Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dda3515a48 | ||
|
|
93f0f96b3f | ||
|
|
02594421d2 | ||
|
|
18aadeff7c | ||
|
|
dcae11d6fb | ||
|
|
2682f8aafc | ||
|
|
827469be4d | ||
|
|
0555604ded | ||
|
|
36fe3b31a3 | ||
|
|
9b1a64e4a9 | ||
|
|
38cfc25e54 | ||
|
|
41a430a88e | ||
|
|
ece05087a7 | ||
|
|
a7ee3092c3 | ||
|
|
f7cc776488 | ||
|
|
15e875a2d9 | ||
|
|
5d173547ff | ||
|
|
202e5609ff | ||
|
|
bb38c3320d | ||
|
|
6b9a5987f6 | ||
|
|
fc3f78f5d9 | ||
|
|
2f41c073a2 | ||
|
|
51672b6ecb | ||
|
|
67a7b1a1d3 | ||
|
|
ce467da9cf | ||
|
|
6ef7aa8399 | ||
|
|
193e3c62e6 | ||
|
|
91dfe60a99 | ||
|
|
edb12401e5 | ||
|
|
79fe11bc1c | ||
|
|
b3e51317e4 | ||
|
|
ddd5a46f39 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
description: Launch, retain, and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, cross-turn dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, iteratively test UI behavior with a human, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
---
|
||||
|
||||
# Test T3 App
|
||||
@@ -13,13 +13,36 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
|
||||
2. Choose a base directory that belongs only to the current worktree or test:
|
||||
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
|
||||
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
|
||||
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
|
||||
3. Start the full web stack with `vp run dev --home-dir <base-dir>`. Add `--share`
|
||||
to also publish it on the tailnet so the user can open it from another device
|
||||
(see "Share a dev server with the user" below).
|
||||
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
|
||||
|
||||
Ports are derived from the worktree path, so a worktree prefers the same pair on
|
||||
every run rather than racing others for the default. That is a preference, not a
|
||||
guarantee — the runner shifts both ports when either is already taken. Read the
|
||||
actual values from the dev-runner line rather than assuming `5733`/`13773`, and
|
||||
re-read them after a restart; `node scripts/dev-runner.ts dev --dry-run` prints
|
||||
them without starting anything.
|
||||
|
||||
Inside a worktree, the dev runner defaults to that worktree's own gitignored `.t3` rather than the shared `~/.t3` — including when `T3CODE_HOME` is exported in the environment, which would otherwise resolve to `~/.t3/userdata`: the live database the user's installed T3 Code is running against. Do not override that default to the shared home.
|
||||
|
||||
A fresh isolated database is empty, which is fine for flows you drive yourself but useless for anything that renders a list of existing work. To populate it, stop the dev server and run `bun run dev:seed` (`--threads N` to change the count), then restart. It copies recent projects and threads from the shared home read-only and refuses to write to it. Prefer this over hand-writing fixtures when you just need the UI to look real; use `references/sqlite-fixtures.md` when a test needs specific, controlled rows.
|
||||
|
||||
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 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.
|
||||
|
||||
## 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=...`.
|
||||
@@ -28,24 +51,63 @@ The dev runner disables browser auto-open by default. Do not pass `--browser` du
|
||||
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
|
||||
5. Continue in the same browser context so its stored bearer session remains available.
|
||||
|
||||
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
|
||||
Treat pairing URLs as secrets: they grant access to the environment. Never put one anywhere it outlives the moment — screenshots, committed files, durable logs, or a PR description.
|
||||
|
||||
The one exception is handing access to the user who asked for it: when they want to open the app themselves (see "Share a dev server with the user"), the URL is the deliverable, so give it to them directly in the response. Do not volunteer one otherwise. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
|
||||
|
||||
## Recover a consumed or expired pairing token
|
||||
|
||||
Create another token against the same database and web URL as the running dev server:
|
||||
Ask the running server for a fresh pairing URL:
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--dev-url <web-url> \
|
||||
--base-url <web-url> \
|
||||
--ttl 15m \
|
||||
--label agent-ui-test
|
||||
bun run dev:pair # implicit ~/.t3 home
|
||||
bun run dev:pair -- --base-dir <base-dir> # explicit --home-dir environment
|
||||
```
|
||||
|
||||
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.
|
||||
It finds the running server's own `server-runtime.json` under the base directory
|
||||
— checking both the `dev` and `userdata` state directories and verifying the
|
||||
recorded process is alive — so it needs no port and builds the URL against the
|
||||
web origin already in use, including a `--share` tailnet URL. Pass `--base-dir`
|
||||
only when the dev server was started with `--home-dir`. Add `--ttl 1h` for a
|
||||
longer window or `--json` for machine-readable output.
|
||||
|
||||
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.
|
||||
Use the printed `Pair URL` once. If the command reports no running server, the
|
||||
dev process has exited — restart it and use the URL from its own startup log.
|
||||
|
||||
Use `auth pairing list` to inspect active token metadata; it intentionally cannot
|
||||
reveal token secrets. `auth pairing create` remains available for scripted cases
|
||||
that need explicit control over every flag.
|
||||
|
||||
## Share a dev server with the user
|
||||
|
||||
When the user wants to try the change themselves — from their laptop, their
|
||||
phone, or anything else on their tailnet — start the stack with `--share`:
|
||||
|
||||
```bash
|
||||
bun run dev:share # or: vp run dev --share --home-dir <base-dir>
|
||||
```
|
||||
|
||||
This publishes the web port over HTTPS on the machine's tailnet and prints
|
||||
`[dev-runner] shared on tailnet: https://<host>:<port>/`. The pairing URL logged
|
||||
right after is already built against that origin, so give the user that URL
|
||||
verbatim — it is the deliverable, and it works unchanged on any of their devices.
|
||||
This is the one case where a pairing URL belongs in a response: it is going to
|
||||
the person who asked for it. It still must not go anywhere durable.
|
||||
|
||||
Dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to
|
||||
the backend, so one shared port covers the whole app. Do not map backend paths by
|
||||
hand, and do not set `VITE_HTTP_URL`/`VITE_WS_URL` for a shared server — absolute
|
||||
localhost URLs get compiled into the bundle and send the remote browser to its
|
||||
own machine.
|
||||
|
||||
The mapping is removed when the dev server exits, and re-running `--share`
|
||||
replaces any mapping left behind by a run that was killed. If the tailnet is
|
||||
unavailable the dev server still starts and serves locally; the warning explains
|
||||
what to fix.
|
||||
|
||||
Expect one failed `ws://localhost:<port>` HMR attempt in the remote console
|
||||
before Vite falls back to the page origin. That is Vite's own hot-reload socket,
|
||||
not the app's connection — ignore it.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
@@ -58,14 +120,24 @@ Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before chang
|
||||
|
||||
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
|
||||
|
||||
## Finish the test
|
||||
## Tear down only when the testing loop is finished
|
||||
|
||||
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
Tear down when the user explicitly asks, confirms the iteration is finished, or the overall task is genuinely complete with no pending human review. Do not infer completion from the end of an assistant turn.
|
||||
|
||||
When teardown is appropriate:
|
||||
|
||||
1. Stop the dev process with its terminal interrupt.
|
||||
2. Preserve the isolated base directory when it contains useful reproduction evidence or state for a likely follow-up.
|
||||
3. Otherwise remove only a path created for this test after resolving and verifying the exact target.
|
||||
|
||||
If completion is uncertain, keep the environment alive and mention that it is retained for further iteration. A fresh isolated base directory remains the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
|
||||
## Troubleshoot predictably
|
||||
|
||||
- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
|
||||
- If the pairing URL is no longer visible, create a replacement token with both `--dev-url` and `--base-url`.
|
||||
- If the replacement token is rejected, verify that the CLI and server use the identical absolute base directory and web URL.
|
||||
- If the pairing URL is no longer visible, run `bun run dev:pair`.
|
||||
- If the replacement token is rejected, verify that the CLI and server resolve the same state directory — pass `--base-dir` only when the server was started with `--home-dir`, and use the same path.
|
||||
- If the UI shows unexpected data, verify that every command uses the identical explicit base directory before editing anything.
|
||||
- If ports move because another instance is running, trust the current dev-runner output rather than assuming ports `13773` and `5733`.
|
||||
- If a remote browser reaches the page but the app cannot connect, check that the served bundle has no absolute `localhost` backend URL baked in: `VITE_HTTP_URL` and `VITE_WS_URL` must be unset for `dev`/`dev:web`.
|
||||
- If a shared URL returns 403 with "host is not allowed", the hostname is outside `*.ts.net`; add it to `T3CODE_DEV_ALLOWED_HOSTS` (comma-separated).
|
||||
@@ -1,4 +1,4 @@
|
||||
interface:
|
||||
display_name: "T3 App Testing"
|
||||
short_description: "Launch and seed isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
|
||||
short_description: "Launch and retain isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 environment and iteratively test it in the browser while preserving state."
|
||||
@@ -13,6 +13,16 @@
|
||||
- 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
|
||||
|
||||
- Start the web stack with `bun run dev` (equivalently `vp run dev`). Never run `vp dev` from the repo root — that starts a bare Vite with no backend.
|
||||
- Ports are derived from the worktree path, so a worktree prefers the same pair every run instead of everyone racing for the default. They still shift when something already holds them, so read the actual values from the `[dev-runner] …` line rather than assuming them. `--dry-run` prints them without starting anything.
|
||||
- To let the user try a change on their own device, use `bun run dev:share`. It publishes the web port on the tailnet and logs a pairing URL already built against that origin — hand them that URL as-is. Details and troubleshooting live in the `test-t3-app` skill.
|
||||
- Dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL`/`VITE_WS_URL` for `dev`/`dev:web` — they compile absolute localhost URLs into the bundle and break every non-localhost origin.
|
||||
- Need a pairing URL for a server that is already running? `bun run dev:pair`. It finds the server itself; no ports or flags to get wrong.
|
||||
- In a worktree, dev state goes to that worktree's own gitignored `.t3` — never the shared `~/.t3` the user's installed app runs against. Do not point a dev server at `~/.t3`, and do not "fix" an ambient `T3CODE_HOME` by passing it through.
|
||||
- That database starts empty. `bun run dev:seed` copies recent projects and threads from the shared home into it, so list and thread UI has something real to render. Stop the dev server first, then restart it.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -50,6 +50,7 @@ export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
|
||||
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
|
||||
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
|
||||
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
|
||||
export const PREVIEW_SET_COLOR_SCHEME_CHANNEL = "desktop:preview-set-color-scheme";
|
||||
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
|
||||
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
|
||||
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
DesktopPreviewRecordingSaveInputSchema,
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
@@ -138,6 +139,15 @@ export const hardReload = tabMethod(
|
||||
"desktop.ipc.preview.hardReload",
|
||||
(manager, tabId) => manager.hardReload(tabId),
|
||||
);
|
||||
export const setColorScheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL,
|
||||
payload: DesktopPreviewSetColorSchemeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.setColorScheme")(function* ({ tabId, colorScheme }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.setColorScheme(tabId, colorScheme);
|
||||
}),
|
||||
});
|
||||
export const openDevTools = tabMethod(
|
||||
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
|
||||
"desktop.ipc.preview.openDevTools",
|
||||
@@ -346,6 +356,7 @@ export const methods = [
|
||||
zoomOut,
|
||||
resetZoom,
|
||||
hardReload,
|
||||
setColorScheme,
|
||||
openDevTools,
|
||||
clearCookies,
|
||||
clearCache,
|
||||
|
||||
@@ -160,6 +160,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }),
|
||||
resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }),
|
||||
hardReload: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, { tabId }),
|
||||
setColorScheme: (tabId, colorScheme) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, { tabId, colorScheme }),
|
||||
openDevTools: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
|
||||
clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
|
||||
|
||||
@@ -365,6 +365,79 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("emulates prefers-color-scheme and re-applies it across webview swaps", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const makeWebContents = (id: number) => {
|
||||
const sendCommand = vi.fn(async () => undefined);
|
||||
return {
|
||||
sendCommand,
|
||||
wc: {
|
||||
id,
|
||||
isDestroyed: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never,
|
||||
};
|
||||
};
|
||||
const first = makeWebContents(42);
|
||||
fromId.mockReturnValue(first.wc);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_scheme");
|
||||
yield* manager.registerWebview("tab_scheme", 42);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* manager.setColorScheme("tab_scheme", "dark");
|
||||
|
||||
expect(first.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "dark" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("dark");
|
||||
|
||||
const replacement = makeWebContents(43);
|
||||
fromId.mockReturnValue(replacement.wc);
|
||||
yield* manager.registerWebview("tab_scheme", 43);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "dark" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("dark");
|
||||
|
||||
yield* manager.setColorScheme("tab_scheme", "system");
|
||||
|
||||
expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("system");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
import type {
|
||||
DesktopPreviewAnnotationTheme,
|
||||
DesktopPreviewColorScheme,
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
@@ -84,6 +85,7 @@ export interface PreviewTabState {
|
||||
canGoBack: boolean;
|
||||
canGoForward: boolean;
|
||||
zoomFactor: number;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -1288,6 +1290,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1320,6 +1323,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1386,7 +1390,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
runFork(restoreControlSession(tabId, wc));
|
||||
const registeredAt = yield* currentIso;
|
||||
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
@@ -1457,6 +1461,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: current?.canGoBack ?? false,
|
||||
canGoForward: current?.canGoForward ?? false,
|
||||
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: current?.colorScheme ?? "system",
|
||||
controller: current?.controller ?? "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1525,7 +1530,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* detachControlSession(wc.id);
|
||||
yield* attempt({ operation: "openDevTools", tabId, webContentsId: wc.id }, () => {
|
||||
wc.once("devtools-closed", () => {
|
||||
if (!wc.isDestroyed()) runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
if (!wc.isDestroyed()) runFork(restoreControlSession(tabId, wc));
|
||||
});
|
||||
wc.openDevTools({ mode: "detach" });
|
||||
});
|
||||
@@ -1684,6 +1689,65 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* update(tabId, { zoomFactor: next });
|
||||
});
|
||||
|
||||
// Emulated media lives on the CDP debugger session, not the WebContents, so
|
||||
// it is lost whenever the session detaches (webview swap, DevTools
|
||||
// open/close) and must be re-applied after every (re)attach.
|
||||
const applyColorScheme = Effect.fn("PreviewManager.applyColorScheme")(function* (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) {
|
||||
yield* ensureControlSession(wc);
|
||||
yield* attemptPromise({ operation: "applyColorScheme", tabId, webContentsId: wc.id }, () =>
|
||||
wc.debugger.sendCommand("Emulation.setEmulatedMedia", {
|
||||
features: [
|
||||
{
|
||||
name: "prefers-color-scheme",
|
||||
// An empty value clears the override so the page follows the OS.
|
||||
value: colorScheme === "system" ? "" : colorScheme,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Re-establish the control session after a detach, restoring any
|
||||
// color-scheme override the tab carries. The scheme is read after the
|
||||
// session attaches so a concurrent setColorScheme is not overwritten with
|
||||
// a stale snapshot.
|
||||
const restoreControlSession = (tabId: string, wc: Electron.WebContents) =>
|
||||
ensureControlSession(wc).pipe(
|
||||
Effect.andThen(SynchronizedRef.get(tabsRef)),
|
||||
Effect.flatMap((tabs) => {
|
||||
const colorScheme = tabs.get(tabId)?.colorScheme ?? "system";
|
||||
return colorScheme === "system" ? Effect.void : applyColorScheme(tabId, wc, colorScheme);
|
||||
}),
|
||||
Effect.ignore,
|
||||
);
|
||||
|
||||
const setColorScheme = Effect.fn("PreviewManager.setColorScheme")(function* (
|
||||
tabId: string,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) {
|
||||
const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
if (!tab) {
|
||||
return yield* new PreviewTabNotFoundError({ tabId });
|
||||
}
|
||||
if (tab.colorScheme !== colorScheme) {
|
||||
// Record the choice even when the CDP call below can't run yet (no
|
||||
// webview, DevTools holding the debugger) — it is re-applied on the
|
||||
// next control-session (re)attach.
|
||||
yield* update(tabId, { colorScheme });
|
||||
}
|
||||
// Re-read after the update: registerWebview may have swapped the guest
|
||||
// in the meantime and the override must land on the current one.
|
||||
const webContentsId = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.webContentsId;
|
||||
if (webContentsId == null) return;
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
if (!wc || wc.isDestroyed()) return;
|
||||
yield* applyColorScheme(tabId, wc, colorScheme);
|
||||
});
|
||||
|
||||
const captureScreenshot = Effect.fn("PreviewManager.captureScreenshot")(function* (
|
||||
tabId: string,
|
||||
) {
|
||||
@@ -2526,6 +2590,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
revealArtifact,
|
||||
saveRecording,
|
||||
setAnnotationTheme,
|
||||
setColorScheme,
|
||||
setMainWindow,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
@@ -2830,6 +2895,10 @@ export class PreviewManager extends Context.Service<
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly setColorScheme: (
|
||||
tabId: string,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
@@ -2921,6 +2990,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
zoomOut: operations.zoomOut,
|
||||
resetZoom: operations.resetZoom,
|
||||
hardReload: operations.hardReload,
|
||||
setColorScheme: operations.setColorScheme,
|
||||
openDevTools: operations.openDevTools,
|
||||
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* () {
|
||||
yield* browserSession
|
||||
|
||||
@@ -385,10 +385,6 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
title="Thread list options"
|
||||
separateBackground
|
||||
>
|
||||
<NativeHeaderToolbar.MenuAction onPress={props.onOpenSettings}>
|
||||
<NativeHeaderToolbar.Label>Settings</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Environment">
|
||||
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
|
||||
@@ -4,7 +4,6 @@ import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -16,6 +15,7 @@ import { AndroidHomeFabLayout } from "./AndroidHomeFab";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
import { useHomeListOptions } from "./home-list-options";
|
||||
import { buildHomeProjectScopes } from "./homeThreadList";
|
||||
import { usePendingTaskListActions } from "./usePendingTaskListActions";
|
||||
import { useThreadListActions } from "./useThreadListActions";
|
||||
|
||||
@@ -61,16 +61,15 @@ export function HomeRouteScreen() {
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
projects
|
||||
.filter(
|
||||
(project) =>
|
||||
selectedEnvironmentId === null || project.environmentId === selectedEnvironmentId,
|
||||
)
|
||||
.map((project) => ({
|
||||
key: scopedProjectKey(project.environmentId, project.id),
|
||||
label: project.title,
|
||||
})),
|
||||
[projects, selectedEnvironmentId],
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: selectedEnvironmentId,
|
||||
projectGroupingMode: listOptions.projectGroupingMode,
|
||||
}).map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[listOptions.projectGroupingMode, projects, selectedEnvironmentId],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
|
||||
@@ -245,43 +245,69 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
|
||||
const scopedProject = useMemo(
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects: props.projects,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
|
||||
);
|
||||
const selectedProjectScope = useMemo(
|
||||
() =>
|
||||
props.selectedProjectKey === null
|
||||
? null
|
||||
: (props.projects.find(
|
||||
(project) =>
|
||||
scopedProjectKey(project.environmentId, project.id) === props.selectedProjectKey &&
|
||||
(props.selectedEnvironmentId === null ||
|
||||
project.environmentId === props.selectedEnvironmentId),
|
||||
: (projectScopes.find(
|
||||
(scope) =>
|
||||
scope.key === props.selectedProjectKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
props.selectedProjectKey,
|
||||
),
|
||||
) ?? null),
|
||||
[props.projects, props.selectedEnvironmentId, props.selectedProjectKey],
|
||||
[projectScopes, props.selectedProjectKey],
|
||||
);
|
||||
const selectedProjectRefKeys = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() => (scopedProject === null ? props.projects : [scopedProject]),
|
||||
[props.projects, scopedProject],
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.projects
|
||||
: props.projects.filter((project) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[props.projects, selectedProjectRefKeys],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
scopedProject === null
|
||||
selectedProjectRefKeys === null
|
||||
? props.threads
|
||||
: props.threads.filter(
|
||||
(thread) =>
|
||||
thread.environmentId === scopedProject.environmentId &&
|
||||
thread.projectId === scopedProject.id,
|
||||
: props.threads.filter((thread) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
),
|
||||
[props.threads, scopedProject],
|
||||
[props.threads, selectedProjectRefKeys],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
scopedProject === null
|
||||
selectedProjectRefKeys === null
|
||||
? props.pendingTasks
|
||||
: props.pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
pendingTask.message.environmentId === scopedProject.environmentId &&
|
||||
pendingTask.creation.projectId === scopedProject.id,
|
||||
: props.pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
),
|
||||
[props.pendingTasks, scopedProject],
|
||||
[props.pendingTasks, selectedProjectRefKeys],
|
||||
);
|
||||
|
||||
const projectGroups = useMemo(
|
||||
@@ -339,22 +365,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const v2ScopeProjects = useMemo(
|
||||
() =>
|
||||
sortHomeProjectScopes({
|
||||
scopes: buildHomeProjectScopes({
|
||||
projects: props.projects,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
scopes: projectScopes,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projectGroupingMode,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
projectScopes,
|
||||
],
|
||||
);
|
||||
const v2ScopedProjectGroup = useMemo(
|
||||
@@ -372,6 +394,21 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
) ?? null),
|
||||
[v2ProjectScopeKey, v2ScopeProjects],
|
||||
);
|
||||
const v2ProjectTitleByProjectKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
v2ScopeProjects.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.title,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
[v2ScopeProjects],
|
||||
);
|
||||
const v2ScopedProjectKeys = useMemo(
|
||||
() =>
|
||||
v2ScopedProjectGroup === null
|
||||
@@ -435,6 +472,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -456,8 +497,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
@@ -467,20 +518,38 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProjectGroup,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
@@ -493,6 +562,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
projectTitle={v2ProjectTitleByProjectKey.get(
|
||||
scopedProjectKey(item.thread.environmentId, item.thread.projectId),
|
||||
)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(item.thread.environmentId)
|
||||
@@ -536,6 +608,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
@@ -755,9 +828,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : scopedProject !== null ? (
|
||||
) : selectedProjectScope !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${scopedProject.title}`}
|
||||
title={`No threads in ${selectedProjectScope.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : selectedEnvironmentLabel ? (
|
||||
@@ -772,11 +845,31 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. Pending tasks render in the header, so the
|
||||
// list showing them isn't empty in the user's eyes.
|
||||
// fact when a query is active. Snoozed threads outrank the rest: "No
|
||||
// threads yet" over an inbox that is merely all-snoozed reads as data
|
||||
// loss. Pending tasks render in the header, so the list showing them
|
||||
// isn't empty in the user's eyes.
|
||||
const v2SnoozedCount = threadListV2Layout.snoozedCount;
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={
|
||||
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
|
||||
}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
|
||||
@@ -24,6 +24,7 @@ describe("buildHomeListFilterMenu", () => {
|
||||
const projectMenu = menu.items.find(
|
||||
(item) => item.type === "submenu" && item.title === "Project",
|
||||
);
|
||||
expect(menu.items.some((item) => item.title === "Settings")).toBe(false);
|
||||
expect(projectMenu).toMatchObject({
|
||||
type: "submenu",
|
||||
items: [
|
||||
|
||||
@@ -43,7 +43,6 @@ export function buildHomeListFilterMenu(props: {
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onOpenSettings?: () => void;
|
||||
/** False hides the sort/group submenus. Thread List v2 uses a fixed
|
||||
creation-order layout, so offering those controls while it silently
|
||||
ignores them would be a lie; the environment filter still applies. */
|
||||
@@ -51,14 +50,6 @@ export function buildHomeListFilterMenu(props: {
|
||||
}): HomeListFilterMenu {
|
||||
const items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu> = [];
|
||||
|
||||
if (props.onOpenSettings) {
|
||||
items.push({
|
||||
type: "action",
|
||||
title: "Settings",
|
||||
onPress: props.onOpenSettings,
|
||||
});
|
||||
}
|
||||
|
||||
items.push({
|
||||
type: "submenu",
|
||||
title: "Environment",
|
||||
|
||||
@@ -104,6 +104,7 @@ describe("buildHomeThreadGroups", () => {
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.title).toBe("t3code");
|
||||
expect(scopes[0]?.projects).toEqual(projects);
|
||||
expect(scopes[0]?.projectRefs).toEqual(
|
||||
projects.map((project) => ({
|
||||
@@ -373,6 +374,43 @@ describe("buildHomeThreadGroups", () => {
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("uses the repository label for a singleton repository scope", () => {
|
||||
const project = makeProject({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "local-worktree-name",
|
||||
repositoryIdentity: {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
displayName: "codething-mvp",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [project],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
const groups = buildGroups(
|
||||
[project],
|
||||
[
|
||||
makeThread({
|
||||
environmentId: project.environmentId,
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: project.id,
|
||||
title: "Thread",
|
||||
}),
|
||||
],
|
||||
);
|
||||
|
||||
expect(scopes[0]?.title).toBe("codething-mvp");
|
||||
expect(groups[0]?.title).toBe("codething-mvp");
|
||||
});
|
||||
|
||||
it("sorts the newest thread first regardless of snapshot order", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
|
||||
@@ -113,10 +113,7 @@ export function buildHomeProjectScopes(input: {
|
||||
const representative = projects[0]!;
|
||||
return {
|
||||
key,
|
||||
title:
|
||||
projects.length > 1
|
||||
? deriveProjectGroupLabel({ representative, members: projects })
|
||||
: representative.title,
|
||||
title: deriveProjectGroupLabel({ representative, members: projects }),
|
||||
representative,
|
||||
projects,
|
||||
projectRefs: projectRefsByGroup.get(key) ?? [],
|
||||
@@ -346,10 +343,7 @@ export function buildHomeThreadGroups(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const title =
|
||||
group.projects.length > 1
|
||||
? deriveProjectGroupLabel({ representative, members: group.projects })
|
||||
: representative.title;
|
||||
const title = deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
title.toLocaleLowerCase().includes(query) ||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { ActivityIndicator, Pressable, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { ActivityIndicator, Pressable, StyleSheet, useColorScheme, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -10,6 +11,9 @@ import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { GitActionProgress } from "../../state/use-vcs-action-state";
|
||||
|
||||
const OVERLAY_LAYOUT_TRANSITION = LinearTransition.duration(220);
|
||||
const AnimatedLiquidGlassView = Animated.createAnimatedComponent(LiquidGlassView);
|
||||
|
||||
export function GitActionProgressOverlay(props: {
|
||||
readonly progress: GitActionProgress;
|
||||
readonly onDismiss: () => void;
|
||||
@@ -45,7 +49,7 @@ export function GitActionProgressOverlay(props: {
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
entering={FadeIn.duration(200)}
|
||||
entering={isLiquidGlassSupported ? undefined : FadeIn.duration(200)}
|
||||
exiting={FadeOut.duration(150)}
|
||||
className="absolute inset-x-3 z-[100]"
|
||||
style={{ top: insets.top + 48 }}
|
||||
@@ -61,16 +65,11 @@ export function GitActionProgressOverlay(props: {
|
||||
function OverlayContent(props: { readonly progress: GitActionProgress }) {
|
||||
const { progress } = props;
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
|
||||
const bgClass =
|
||||
progress.phase === "error"
|
||||
? "bg-red-50 dark:bg-red-950/80 border-red-200 dark:border-red-800"
|
||||
: "bg-card border-border";
|
||||
|
||||
return (
|
||||
<View
|
||||
className={`flex-row items-center gap-2.5 rounded-2xl border px-3.5 py-3 shadow-lg shadow-black/10 ${bgClass}`}
|
||||
>
|
||||
const glassBorder = useThemeColor("--color-header-border");
|
||||
const glassTint = useThemeColor("--color-glass-tint");
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const content = (
|
||||
<>
|
||||
<OverlayIcon phase={progress.phase} iconColor={iconColor} />
|
||||
|
||||
<View className="flex-1 gap-0.5">
|
||||
@@ -89,7 +88,56 @@ function OverlayContent(props: { readonly progress: GitActionProgress }) {
|
||||
{progress.prUrl ? (
|
||||
<SymbolView name="arrow.up.right" size={13} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
|
||||
if (isLiquidGlassSupported) {
|
||||
return (
|
||||
<Animated.View
|
||||
layout={OVERLAY_LAYOUT_TRANSITION}
|
||||
style={{
|
||||
backgroundColor: glassTint,
|
||||
borderColor: glassBorder,
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 26,
|
||||
borderWidth: StyleSheet.hairlineWidth,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<AnimatedLiquidGlassView
|
||||
colorScheme={isDarkMode ? "dark" : "light"}
|
||||
effect="regular"
|
||||
interactive
|
||||
layout={OVERLAY_LAYOUT_TRANSITION}
|
||||
style={{
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 26,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<Animated.View
|
||||
entering={FadeIn.delay(60).duration(140)}
|
||||
className="flex-row items-center gap-2.5 px-3.5 py-3"
|
||||
>
|
||||
{content}
|
||||
</Animated.View>
|
||||
</AnimatedLiquidGlassView>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
const bgClass =
|
||||
progress.phase === "error"
|
||||
? "bg-red-50 dark:bg-red-950/80 border-red-200 dark:border-red-800"
|
||||
: "bg-card border-border";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
layout={OVERLAY_LAYOUT_TRANSITION}
|
||||
className={`flex-row items-center gap-2.5 rounded-[26px] border border-continuous px-3.5 py-3 shadow-lg shadow-black/10 ${bgClass}`}
|
||||
>
|
||||
{content}
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -236,6 +236,21 @@ function ThreadNavigationSidebarPane(
|
||||
})),
|
||||
[projectScopes],
|
||||
);
|
||||
const projectTitleByProjectKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
projectScopes.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.title,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
[projectScopes],
|
||||
);
|
||||
const selectedProjectScope = useMemo(
|
||||
() =>
|
||||
selectedProjectKey === null
|
||||
@@ -384,6 +399,10 @@ function ThreadNavigationSidebarPane(
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -405,8 +424,18 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
@@ -414,20 +443,38 @@ function ThreadNavigationSidebarPane(
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Enabled,
|
||||
threads,
|
||||
selectedProjectScope,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const listItems = useMemo<readonly SidebarListItem[]>(() => {
|
||||
if (!threadListV2Enabled) return listLayout.items;
|
||||
// Queued offline tasks render above the thread rows (mirrors the
|
||||
@@ -728,6 +775,7 @@ function ThreadNavigationSidebarPane(
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
projectTitle={projectTitleByProjectKey.get(scopeKey)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(thread.environmentId)
|
||||
@@ -857,6 +905,7 @@ function ThreadNavigationSidebarPane(
|
||||
openPendingTask,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
props.onNewThreadInProject,
|
||||
props.selectedThreadKey,
|
||||
props.width,
|
||||
@@ -913,15 +962,28 @@ function ThreadNavigationSidebarPane(
|
||||
}),
|
||||
[filterIcon, filterMenu, props.onOpenSettings],
|
||||
);
|
||||
// "No threads yet" over an inbox that is merely all-snoozed reads as
|
||||
// data loss; name the snoozed threads instead.
|
||||
const snoozedCount = threadListV2Layout.snoozedCount;
|
||||
const listEmpty = (
|
||||
<Text className="px-2 py-4 text-sm text-foreground-muted">
|
||||
{catalogState.isLoadingConnections
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
? snoozedCount > 0
|
||||
? // Snoozed matches passed this same search filter — "No
|
||||
// matching threads" would misreport them as nonexistent.
|
||||
snoozedCount === 1
|
||||
? "1 matching thread snoozed"
|
||||
: "All matching threads snoozed"
|
||||
: "No matching threads"
|
||||
: snoozedCount > 0
|
||||
? snoozedCount === 1
|
||||
? "1 thread snoozed"
|
||||
: `${snoozedCount} threads snoozed`
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly variant: "card" | "slim";
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly providerDriver: string | null;
|
||||
/** Which machine hosts the thread. Null when only one environment is
|
||||
connected — repeating the same label on every row is noise. Mirrors
|
||||
@@ -219,7 +220,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.project.title}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
@@ -230,7 +231,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.project?.title ?? ""}
|
||||
{props.projectTitle ?? props.project?.title ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
@@ -393,7 +394,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.project.title}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -77,6 +77,85 @@ describe("sortThreadsForListV2", () => {
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("hides snoozed threads and counts them — visibility parity with web", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("woken"),
|
||||
title: "Woken",
|
||||
// Wake time already passed: back in the active list.
|
||||
snoozedUntil: "2026-06-01T18:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
// Same createdAt → static sort tiebreaks by id; the point is the woken
|
||||
// thread is BACK in the card block and the snoozed one is gone.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("classifies snooze with the second-precise clock and reports the next wake", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("just-woke"),
|
||||
title: "Just woke",
|
||||
// Woke 30s ago: hidden under the minute-floored clock, visible
|
||||
// under the precise one.
|
||||
snoozedUntil: "2026-06-02T00:00:30.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("still-snoozed"),
|
||||
title: "Still snoozed",
|
||||
snoozedUntil: "2026-06-02T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
// Minute-floored partition clock vs precise snooze clock.
|
||||
now: "2026-06-02T00:01:00.000Z",
|
||||
snoozeNow: "2026-06-02T00:01:07.500Z",
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["just-woke"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
|
||||
});
|
||||
|
||||
it("keeps snoozed threads visible on environments without the snooze capability", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
snoozeEnvironmentIds: new Set(),
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
|
||||
expect(layout.snoozedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("partitions settled threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
@@ -84,6 +84,13 @@ export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
/** Snoozed threads hidden from the list (visibility parity with web's
|
||||
collapsed Snoozed shelf; mobile has no shelf UI yet). */
|
||||
readonly snoozedCount: number;
|
||||
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
|
||||
a timeout at this boundary so the list re-partitions the moment a
|
||||
snooze expires instead of on the next minute tick. */
|
||||
readonly nextSnoozeWakeAt: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,13 +113,22 @@ export function buildThreadListV2Items(input: {
|
||||
other environments never classify as settled — the user could neither
|
||||
un-settle nor pin them. Absent = no gating (tests). */
|
||||
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
/** Environments whose server supports thread.snooze/unsnooze. Same
|
||||
contract as settlementEnvironmentIds. */
|
||||
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
readonly now?: string;
|
||||
/** Second-precise clock for snooze classification. Callers pass a
|
||||
minute-quantized `now` for memoization; snooze wake times are
|
||||
second-precise, so classifying with the floored minute would hold a
|
||||
woken thread hidden for up to a minute. Defaults to `now`. */
|
||||
readonly snoozeNow?: string;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const projectKeys = input.projectRefs
|
||||
@@ -121,6 +137,8 @@ export function buildThreadListV2Items(input: {
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
let snoozedCount = 0;
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
@@ -130,8 +148,23 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: a snoozed thread leaves the list until it
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozedCount += 1;
|
||||
if (
|
||||
thread.snoozedUntil != null &&
|
||||
(nextSnoozeWakeAt === null ||
|
||||
parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
|
||||
) {
|
||||
nextSnoozeWakeAt = thread.snoozedUntil;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
@@ -168,5 +201,10 @@ export function buildThreadListV2Items(input: {
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
}
|
||||
@@ -60,6 +60,8 @@ function threadDetailToShell(
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
snoozedUntil: thread.snoozedUntil ?? null,
|
||||
snoozedAt: thread.snoozedAt ?? null,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: latestUserMessageAt(thread),
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -31,7 +31,8 @@
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0"
|
||||
"node-pty": "^1.1.0",
|
||||
"yaml": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
|
||||
+40
-55
@@ -12,7 +12,8 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
DEVELOPMENT_ICON_OVERRIDES,
|
||||
PUBLISH_ICON_OVERRIDES,
|
||||
resolveWebAssetBrandForPackageVersion,
|
||||
resolveWebIconOverrides,
|
||||
} from "../../../scripts/lib/brand-assets.ts";
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
@@ -81,50 +82,34 @@ const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Stan
|
||||
}
|
||||
});
|
||||
|
||||
interface PublishIconBackup {
|
||||
readonly targetPath: string;
|
||||
readonly backupPath: string;
|
||||
}
|
||||
|
||||
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
|
||||
const preparePublishIcons = Effect.fn("preparePublishIcons")(function* (
|
||||
repoRoot: string,
|
||||
serverDir: string,
|
||||
version: string,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const backups: PublishIconBackup[] = [];
|
||||
const brand = resolveWebAssetBrandForPackageVersion(version);
|
||||
const icons = resolveWebIconOverrides(brand, "dist/client").map((override) => ({
|
||||
sourcePath: path.join(repoRoot, override.sourceRelativePath),
|
||||
targetPath: path.join(serverDir, override.targetRelativePath),
|
||||
}));
|
||||
|
||||
for (const override of PUBLISH_ICON_OVERRIDES) {
|
||||
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
|
||||
const targetPath = path.join(serverDir, override.targetRelativePath);
|
||||
const backupPath = `${targetPath}.publish-bak`;
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath });
|
||||
for (const icon of icons) {
|
||||
if (!(yield* fs.exists(icon.sourcePath))) {
|
||||
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath: icon.sourcePath });
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath });
|
||||
if (!(yield* fs.exists(icon.targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath: icon.targetPath });
|
||||
}
|
||||
|
||||
yield* fs.copyFile(targetPath, backupPath);
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
backups.push({ targetPath, backupPath });
|
||||
}
|
||||
|
||||
yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
|
||||
return backups as ReadonlyArray<PublishIconBackup>;
|
||||
});
|
||||
|
||||
const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
|
||||
backups: ReadonlyArray<PublishIconBackup>,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
for (const backup of backups) {
|
||||
if (!(yield* fs.exists(backup.backupPath))) {
|
||||
continue;
|
||||
}
|
||||
yield* fs.rename(backup.backupPath, backup.targetPath);
|
||||
}
|
||||
return yield* Effect.forEach(icons, (icon) =>
|
||||
Effect.all({
|
||||
original: fs.readFile(icon.targetPath),
|
||||
publish: fs.readFile(icon.sourcePath),
|
||||
}).pipe(Effect.map((contents) => ({ ...icon, ...contents }))),
|
||||
);
|
||||
});
|
||||
|
||||
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
|
||||
@@ -236,7 +221,6 @@ const publishCmd = Command.make(
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
|
||||
@@ -247,7 +231,7 @@ const publishCmd = Command.make(
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
|
||||
// Acquire: resolve publish metadata and read every original before mutation.
|
||||
Effect.gen(function* () {
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const workspaceConfig = yield* readWorkspaceConfig();
|
||||
@@ -273,19 +257,22 @@ const publishCmd = Command.make(
|
||||
),
|
||||
};
|
||||
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
const packageJsonString = yield* encodePackageJson(pkg);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
yield* fs.writeFileString(packageJsonPath, `${packageJsonString}\n`);
|
||||
yield* Effect.log("[cli] Prepared package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
return {
|
||||
packageJsonString: yield* encodePackageJson(pkg),
|
||||
originalPackageJson: yield* fs.readFile(packageJsonPath),
|
||||
icons: yield* preparePublishIcons(repoRoot, serverDir, version),
|
||||
};
|
||||
}),
|
||||
// Use: pnpm publish from the workspace root so pnpm-only workspace
|
||||
// config, including override selectors, is interpreted correctly.
|
||||
() =>
|
||||
(resource) =>
|
||||
Effect.gen(function* () {
|
||||
yield* fs.writeFileString(packageJsonPath, `${resource.packageJsonString}\n`);
|
||||
for (const icon of resource.icons) {
|
||||
yield* fs.writeFile(icon.targetPath, icon.publish);
|
||||
}
|
||||
yield* Effect.log("[cli] Applied package metadata and publish icon overrides");
|
||||
|
||||
const args = createVpPmPublishArgs(config);
|
||||
const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
|
||||
|
||||
@@ -299,16 +286,14 @@ const publishCmd = Command.make(
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore
|
||||
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
|
||||
// Release: restore every file even if applying overrides or publishing fails.
|
||||
(resource) =>
|
||||
Effect.gen(function* () {
|
||||
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
|
||||
),
|
||||
);
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
yield* fs.writeFile(packageJsonPath, resource.originalPackageJson);
|
||||
for (const icon of resource.icons) {
|
||||
yield* fs.writeFile(icon.targetPath, icon.original);
|
||||
}
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original publish assets");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -8,9 +8,13 @@ import * as ServerConfig from "../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as PairingGrantStore from "./PairingGrantStore.ts";
|
||||
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
|
||||
import { resolveSessionCookieName } from "./utils.ts";
|
||||
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
/** Pinned so the session cookie name (which is port-scoped) is predictable. */
|
||||
const TEST_SERVER_PORT = 13_773;
|
||||
|
||||
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
|
||||
Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
@@ -18,6 +22,7 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
port: TEST_SERVER_PORT,
|
||||
...overrides,
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
}),
|
||||
@@ -35,7 +40,9 @@ const makeCookieRequest = (
|
||||
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
t3_session: sessionToken,
|
||||
// Derived, not hardcoded: the name is port-scoped so concurrent servers
|
||||
// on one hostname don't share a cookie.
|
||||
[resolveSessionCookieName({ port: TEST_SERVER_PORT })]: sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<
|
||||
|
||||
@@ -438,6 +438,7 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput,
|
||||
@@ -746,11 +747,13 @@ export const make = Effect.gen(function* () {
|
||||
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) =>
|
||||
createPairingLink({
|
||||
scopes: input.scopes,
|
||||
subject: input.subject,
|
||||
...(input.label ? { label: input.label } : {}),
|
||||
...(input.purpose ? { purpose: input.purpose } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
@@ -774,6 +777,7 @@ export const make = Effect.gen(function* () {
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
...(input?.purpose ? { purpose: input.purpose } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
@@ -872,6 +876,7 @@ export const make = Effect.gen(function* () {
|
||||
issuePairingCredentialForSubject({
|
||||
scopes: AuthAdministrativeScopes,
|
||||
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
|
||||
purpose: "startup",
|
||||
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
|
||||
|
||||
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
|
||||
|
||||
@@ -69,12 +69,15 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("loopback-browser");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session");
|
||||
// Port-scoped in web mode too: cookies ignore ports, so two dev servers
|
||||
// on one hostname would otherwise clobber each other's session.
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
port: 13773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -38,10 +38,7 @@ export const make = Effect.gen(function* () {
|
||||
policy,
|
||||
bootstrapMethods,
|
||||
sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
}),
|
||||
sessionCookieName: resolveSessionCookieName({ port: config.port }),
|
||||
};
|
||||
|
||||
return EnvironmentAuthPolicy.of({
|
||||
|
||||
@@ -202,6 +202,11 @@ export class PairingGrantStore extends Context.Service<
|
||||
readonly subject?: string;
|
||||
readonly label?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
/**
|
||||
* "startup" marks the credential the server mints for itself at boot,
|
||||
* which gets the long dev TTL when a dev URL is configured.
|
||||
*/
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthPairingLink>,
|
||||
@@ -243,6 +248,15 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
||||
// window can still recover by re-bootstrapping rather than locking
|
||||
// the user out of the backend.
|
||||
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
|
||||
// A dev server's startup token is read off a log by whoever (or whatever) is
|
||||
// driving the session, often minutes later — after a `node --watch` restart, a
|
||||
// detour into another task, or a hand-off to the person actually doing the
|
||||
// testing. Five minutes turns that into a restart-the-server loop for no
|
||||
// security benefit: the token only unlocks a local dev backend, and its holder
|
||||
// could read the log anyway. Same reasoning (and duration) as the desktop
|
||||
// bootstrap grant above. Only applies when a dev URL is configured; user-issued
|
||||
// pairing links and real servers keep the 5-minute default.
|
||||
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
|
||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
const PAIRING_TOKEN_LENGTH = 12;
|
||||
const PAIRING_TOKEN_REJECTION_LIMIT =
|
||||
@@ -371,7 +385,10 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const credential = yield* generatePairingToken;
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
|
||||
const ttl =
|
||||
input?.ttl ??
|
||||
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
|
||||
@@ -467,10 +467,7 @@ export const make = Effect.gen(function* () {
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
});
|
||||
const cookieName = resolveSessionCookieName({ port: serverConfig.port });
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
|
||||
@@ -10,14 +10,15 @@ import * as Result from "effect/Result";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cookies are scoped by host but *not* by port, so every server reachable at a
|
||||
* given hostname shares one cookie jar. Suffixing the port keeps concurrent
|
||||
* instances from overwriting each other's session — otherwise two dev servers
|
||||
* (different worktrees, or several ports behind one tailnet name) fight over
|
||||
* `t3_session`, and whichever wrote last makes every other one reject the
|
||||
* cookie with "Invalid session token signature" until it's cleared by hand.
|
||||
*/
|
||||
export function resolveSessionCookieName(input: { readonly port: number }): string {
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
return "full thread diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -178,7 +177,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -262,7 +260,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -304,102 +301,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("filters git-attributed sections and reports gitFileCount from patch sections", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-attribution");
|
||||
const threadId = ThreadId.make("thread-attribution");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const patch = [
|
||||
"diff --git a/agent.ts b/agent.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/agent.ts",
|
||||
"+++ b/agent.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/pulled.ts b/pulled.ts",
|
||||
"index 3333333..4444444 100644",
|
||||
"--- a/pulled.ts",
|
||||
"+++ b/pulled.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
// Attribution also tags a path that has no section in this patch
|
||||
// (e.g. whitespace-only change elided by ignoreWhitespace) — it must
|
||||
// not count toward gitFileCount.
|
||||
const attribution = new Map<string, "agent" | "git">([
|
||||
["agent.ts", "agent"],
|
||||
["pulled.ts", "git"],
|
||||
["whitespace-only.ts", "git"],
|
||||
]);
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(patch),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(attribution),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const { filtered, revealed } = yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
const filtered = yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
const revealed = yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
includeGitChanges: true,
|
||||
});
|
||||
return { filtered, revealed };
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(filtered.diff).toContain("agent.ts");
|
||||
expect(filtered.diff).not.toContain("pulled.ts");
|
||||
expect(filtered.gitFileCount).toBe(1);
|
||||
expect(revealed.diff).toBe(patch);
|
||||
expect(revealed.gitFileCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not preflight checkpoint refs before diffing", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-no-preflight");
|
||||
@@ -427,7 +328,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed("diff patch"),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -481,7 +381,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(""),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
} from "./Errors.ts";
|
||||
import type { CheckpointServiceError } from "./Errors.ts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import { filterUnifiedDiffFiles, listUnifiedDiffPaths } from "./Diffs.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
|
||||
/** Service tag for checkpoint diff queries. */
|
||||
@@ -67,14 +66,12 @@ function buildTurnDiffResult(
|
||||
readonly toTurnCount: number;
|
||||
},
|
||||
diff: string,
|
||||
gitFileCount?: number,
|
||||
): OrchestrationGetTurnDiffResultType {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff,
|
||||
...(gitFileCount !== undefined ? { gitFileCount } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -82,51 +79,6 @@ export const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
|
||||
// Drop file sections attributed to pre-existing git history from a patch
|
||||
// unless the caller opted in. Attribution failures degrade to the
|
||||
// unfiltered patch — never block the diff on attribution. The returned
|
||||
// gitFileCount comes from the SAME attribution pass that produced the
|
||||
// patch, so UI driven by it always agrees with what is rendered;
|
||||
// undefined means attribution was unavailable and nothing was filtered.
|
||||
const applyAttributionFilter = Effect.fn("applyAttributionFilter")(function* (input: {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly diff: string;
|
||||
readonly includeGitChanges: boolean;
|
||||
}): Effect.fn.Return<{ readonly diff: string; readonly gitFileCount: number | undefined }> {
|
||||
if (input.diff.trim().length === 0) {
|
||||
return { diff: input.diff, gitFileCount: undefined };
|
||||
}
|
||||
const attribution = yield* checkpointStore
|
||||
.attributeCheckpointDiff({
|
||||
cwd: input.cwd,
|
||||
fromCheckpointRef: input.fromCheckpointRef,
|
||||
toCheckpointRef: input.toCheckpointRef,
|
||||
})
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (attribution === null) {
|
||||
return { diff: input.diff, gitFileCount: undefined };
|
||||
}
|
||||
// Count only git-attributed paths with a section in THIS patch. The
|
||||
// attribution map can include paths absent from the patch (e.g.
|
||||
// whitespace-only changes elided by ignoreWhitespace) — counting those
|
||||
// would advertise hidden files the toggle can never reveal.
|
||||
let gitFileCount = 0;
|
||||
for (const path of listUnifiedDiffPaths(input.diff)) {
|
||||
if (attribution.get(path) === "git") {
|
||||
gitFileCount += 1;
|
||||
}
|
||||
}
|
||||
if (input.includeGitChanges || gitFileCount === 0) {
|
||||
return { diff: input.diff, gitFileCount };
|
||||
}
|
||||
return {
|
||||
diff: filterUnifiedDiffFiles(input.diff, (path) => attribution.get(path) !== "git"),
|
||||
gitFileCount,
|
||||
};
|
||||
});
|
||||
|
||||
const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
@@ -212,7 +164,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const rawDiff = yield* checkpointStore
|
||||
const diff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
@@ -221,15 +173,8 @@ export const make = Effect.gen(function* () {
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
|
||||
const filtered = yield* applyAttributionFilter({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
diff: rawDiff,
|
||||
includeGitChanges: input.includeGitChanges ?? false,
|
||||
});
|
||||
|
||||
const turnDiff = buildTurnDiffResult(input, filtered.diff, filtered.gitFileCount);
|
||||
const turnDiff = buildTurnDiffResult(input, diff);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
operation,
|
||||
@@ -309,24 +254,15 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, 0);
|
||||
const toCheckpointRef = threadContext.value.toCheckpointRef as CheckpointRef;
|
||||
const rawDiff = yield* checkpointStore
|
||||
const diff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
|
||||
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
|
||||
const filtered = yield* applyAttributionFilter({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
diff: rawDiff,
|
||||
includeGitChanges: input.includeGitChanges ?? false,
|
||||
});
|
||||
|
||||
const turnDiff = buildTurnDiffResult(
|
||||
{
|
||||
@@ -334,8 +270,7 @@ export const make = Effect.gen(function* () {
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
},
|
||||
filtered.diff,
|
||||
filtered.gitFileCount,
|
||||
diff,
|
||||
);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
|
||||
@@ -55,7 +55,6 @@ function writeTextFile(
|
||||
function git(
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
env?: NodeJS.ProcessEnv,
|
||||
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
|
||||
return Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
@@ -64,19 +63,12 @@ function git(
|
||||
command: "git",
|
||||
cwd,
|
||||
args,
|
||||
...(env ? { env: { ...global.process.env, ...env } } : {}),
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
return result.stdout.trim();
|
||||
});
|
||||
}
|
||||
|
||||
/** Author and committer dates both in the past: a genuinely pre-existing commit. */
|
||||
const PRE_EXISTING_COMMIT_ENV: NodeJS.ProcessEnv = {
|
||||
GIT_AUTHOR_DATE: "2020-01-01T00:00:00Z",
|
||||
GIT_COMMITTER_DATE: "2020-01-01T00:00:00Z",
|
||||
};
|
||||
|
||||
function initRepoWithCommit(
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
@@ -230,237 +222,4 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("attributeCheckpointDiff", () => {
|
||||
it.effect("returns an empty map when HEAD did not move", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-no-head-move");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.size).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("attributes a branch switch to git while keeping tool edits as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
// A second branch with a pre-existing commit, created before the turn.
|
||||
yield* git(tmp, ["checkout", "-b", "feature"]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "feature.ts"), "export const feature = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "feature work"], PRE_EXISTING_COMMIT_ENV);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-branch-switch");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": switch branches (history-driven) and also edit a file.
|
||||
yield* git(tmp, ["checkout", "feature"]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("feature.ts")).toBe("git");
|
||||
expect(attribution!.get("edited.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps files committed during the turn as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-own-commit");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": edit and commit — HEAD moves, but by a turn-authored commit.
|
||||
yield* writeTextFile(NodePath.join(tmp, "committed.ts"), "export const done = true;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "agent commit"]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("committed.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("attributes a cherry-pick of a pre-existing commit to git", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
// Pre-existing commit on another branch, authored before the turn.
|
||||
yield* git(tmp, ["checkout", "-b", "source"]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "picked.ts"), "export const picked = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(
|
||||
tmp,
|
||||
[
|
||||
"-c",
|
||||
"[email protected]",
|
||||
"-c",
|
||||
"user.name=Other",
|
||||
"commit",
|
||||
"-m",
|
||||
"source work",
|
||||
],
|
||||
PRE_EXISTING_COMMIT_ENV,
|
||||
);
|
||||
const pickedOid = yield* git(tmp, ["rev-parse", "HEAD"]);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-cherry-pick");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
yield* git(tmp, ["cherry-pick", pickedOid]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("picked.ts")).toBe("git");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps an amend of a pre-turn commit as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
// Pre-turn commit with an old author date, as amend preserves it.
|
||||
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "pre-turn work", "--date", "2020-01-01T00:00:00Z"]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-amend");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": edit the file and amend it into the pre-turn commit.
|
||||
// The author date stays 2020, but the content is new agent work.
|
||||
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 2;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "--amend", "--no-edit"]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("amended.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a whitespace-only amend of a pre-turn commit as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
// Pre-turn commit; its pre-amend state stays reachable via reflog,
|
||||
// which is exactly the patch-id collision candidate.
|
||||
yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "pre-turn work"], PRE_EXISTING_COMMIT_ENV);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-ws-amend");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": whitespace-only reformat amended into the pre-turn
|
||||
// commit. `git patch-id --stable` would hash this identically to the
|
||||
// original (it strips whitespace); --verbatim must not.
|
||||
yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "--amend", "--no-edit"]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("style.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null for legacy checkpoints without head metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-legacy");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
// Simulate a pre-attribution checkpoint: commit the tree with the old
|
||||
// single-line message format.
|
||||
const treeOid = yield* git(tmp, ["write-tree"]);
|
||||
const legacyCommit = yield* git(tmp, [
|
||||
"commit-tree",
|
||||
treeOid,
|
||||
"-m",
|
||||
`t3 checkpoint ref=${fromCheckpointRef}`,
|
||||
]);
|
||||
yield* git(tmp, ["update-ref", fromCheckpointRef, legacyCommit]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).toBe(null);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -46,18 +46,6 @@ export interface DeleteCheckpointRefsInput {
|
||||
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
|
||||
}
|
||||
|
||||
export interface AttributeCheckpointDiffInput {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-path origin classification of a checkpoint tree delta, or null when
|
||||
* attribution is unavailable (see VcsCheckpointAttribution).
|
||||
*/
|
||||
export type CheckpointAttribution = ReadonlyMap<string, "agent" | "git"> | null;
|
||||
|
||||
/** Service tag for checkpoint persistence and restore operations. */
|
||||
export class CheckpointStore extends Context.Service<
|
||||
CheckpointStore,
|
||||
@@ -105,17 +93,6 @@ export class CheckpointStore extends Context.Service<
|
||||
readonly deleteCheckpointRefs: (
|
||||
input: DeleteCheckpointRefsInput,
|
||||
) => Effect.Effect<void, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Classify each path in a checkpoint-to-checkpoint tree delta as
|
||||
* agent-authored or explained by pre-existing git history.
|
||||
*
|
||||
* Returns null when attribution is unavailable (legacy checkpoints
|
||||
* without HEAD metadata, or truncated git output).
|
||||
*/
|
||||
readonly attributeCheckpointDiff: (
|
||||
input: AttributeCheckpointDiffInput,
|
||||
) => Effect.Effect<CheckpointAttribution, CheckpointStoreError>;
|
||||
}
|
||||
>()("t3/checkpointing/CheckpointStore") {}
|
||||
|
||||
@@ -180,16 +157,6 @@ export const make = Effect.gen(function* () {
|
||||
return yield* checkpoints.deleteCheckpointRefs(input);
|
||||
});
|
||||
|
||||
const attributeCheckpointDiff: CheckpointStore["Service"]["attributeCheckpointDiff"] = Effect.fn(
|
||||
"attributeCheckpointDiff",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints(
|
||||
"CheckpointStore.attributeCheckpointDiff",
|
||||
input.cwd,
|
||||
);
|
||||
return yield* checkpoints.attributeCheckpointDiff(input);
|
||||
});
|
||||
|
||||
return CheckpointStore.of({
|
||||
isGitRepository,
|
||||
captureCheckpoint,
|
||||
@@ -197,7 +164,6 @@ export const make = Effect.gen(function* () {
|
||||
restoreCheckpoint,
|
||||
diffCheckpoints,
|
||||
deleteCheckpointRefs,
|
||||
attributeCheckpointDiff,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { filterUnifiedDiffFiles, parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
|
||||
|
||||
describe("parseTurnDiffFilesFromUnifiedDiff", () => {
|
||||
it("returns empty list for empty diff", () => {
|
||||
@@ -66,159 +66,3 @@ describe("parseTurnDiffFilesFromUnifiedDiff", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterUnifiedDiffFiles", () => {
|
||||
const twoFileDiff = [
|
||||
"diff --git a/kept.ts b/kept.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/kept.ts",
|
||||
"+++ b/kept.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/dropped.ts b/dropped.ts",
|
||||
"index 3333333..4444444 100644",
|
||||
"--- a/dropped.ts",
|
||||
"+++ b/dropped.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
it("removes sections whose path is rejected", () => {
|
||||
const filtered = filterUnifiedDiffFiles(twoFileDiff, (path) => path !== "dropped.ts");
|
||||
expect(filtered).toContain("kept.ts");
|
||||
expect(filtered).not.toContain("dropped.ts");
|
||||
expect(parseTurnDiffFilesFromUnifiedDiff(filtered)).toEqual([
|
||||
{ path: "kept.ts", additions: 1, deletions: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns the diff unchanged when everything is kept", () => {
|
||||
expect(filterUnifiedDiffFiles(twoFileDiff, () => true)).toBe(twoFileDiff);
|
||||
});
|
||||
|
||||
it("filters deleted files via the --- a/ path", () => {
|
||||
const deletionDiff = [
|
||||
"diff --git a/removed.ts b/removed.ts",
|
||||
"deleted file mode 100644",
|
||||
"index 1111111..0000000",
|
||||
"--- a/removed.ts",
|
||||
"+++ /dev/null",
|
||||
"@@ -1,1 +0,0 @@",
|
||||
"-gone",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(deletionDiff, (path) => path !== "removed.ts").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("filters simple header-only sections via the diff --git header", () => {
|
||||
const oddDiff = ["diff --git a/x b/x", "Binary files differ", ""].join("\n");
|
||||
expect(filterUnifiedDiffFiles(oddDiff, (path) => path !== "x").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("keeps unparseable sections", () => {
|
||||
const oddDiff = ["diff --git malformed-header", "Binary files differ", ""].join("\n");
|
||||
expect(filterUnifiedDiffFiles(oddDiff, () => false)).toBe(oddDiff);
|
||||
});
|
||||
|
||||
it("returns empty diff unchanged", () => {
|
||||
expect(filterUnifiedDiffFiles("", () => false)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDiffSectionPath via renames", () => {
|
||||
it("filters rename sections by the post-image path", () => {
|
||||
const renameDiff = [
|
||||
"diff --git a/old/name.ts b/new/name.ts",
|
||||
"similarity index 90%",
|
||||
"rename from old/name.ts",
|
||||
"rename to new/name.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/old/name.ts",
|
||||
"+++ b/new/name.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
// The attribution map is keyed by post-image paths; a filter that only
|
||||
// knows the new path must still match this section.
|
||||
expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "new/name.ts").trim()).toBe("");
|
||||
expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "old/name.ts")).toBe(renameDiff);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterUnifiedDiffFiles fallback paths", () => {
|
||||
it("filters binary sections via the diff --git header", () => {
|
||||
const binaryDiff = [
|
||||
"diff --git a/assets/logo.png b/assets/logo.png",
|
||||
"index 1111111..2222222 100644",
|
||||
"Binary files a/assets/logo.png and b/assets/logo.png differ",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(binaryDiff, (path) => path !== "assets/logo.png").trim()).toBe(
|
||||
"",
|
||||
);
|
||||
expect(filterUnifiedDiffFiles(binaryDiff, () => true)).toBe(binaryDiff);
|
||||
});
|
||||
|
||||
it("filters mode-only sections via the diff --git header", () => {
|
||||
const modeDiff = [
|
||||
"diff --git a/scripts/run.sh b/scripts/run.sh",
|
||||
"old mode 100644",
|
||||
"new mode 100755",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(modeDiff, (path) => path !== "scripts/run.sh").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("filters binary sections with spaces in the path", () => {
|
||||
const binaryDiff = [
|
||||
"diff --git a/my assets/logo file.png b/my assets/logo file.png",
|
||||
"Binary files differ",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(
|
||||
filterUnifiedDiffFiles(binaryDiff, (path) => path !== "my assets/logo file.png").trim(),
|
||||
).toBe("");
|
||||
});
|
||||
|
||||
it("decodes git C-style quoted paths", () => {
|
||||
const quotedDiff = [
|
||||
'diff --git "a/sp\\303\\244ce.ts" "b/sp\\303\\244ce.ts"',
|
||||
"index 1111111..2222222 100644",
|
||||
'--- "a/sp\\303\\244ce.ts"',
|
||||
'+++ "b/sp\\303\\244ce.ts"',
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"",
|
||||
].join("\n");
|
||||
// git octal-escapes the raw UTF-8 bytes (`ä` = \303\244); the decoder
|
||||
// must reassemble them into the real character, not per-byte mojibake.
|
||||
expect(filterUnifiedDiffFiles(quotedDiff, (path) => path !== "späce.ts").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("filters rename-only sections without hunks via rename metadata", () => {
|
||||
const renameOnlyDiff = [
|
||||
"diff --git a/old.ts b/new.ts",
|
||||
"similarity index 100%",
|
||||
"rename from old.ts",
|
||||
"rename to new.ts",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "new.ts").trim()).toBe("");
|
||||
expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "old.ts")).toBe(
|
||||
renameOnlyDiff,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps ambiguous unquoted rename headers", () => {
|
||||
// Rename of a space-containing path is ambiguous in the header when git
|
||||
// does not quote; with no other metadata the section must be kept.
|
||||
const ambiguous = ["diff --git a/x y b/y z", "Binary files differ", ""].join("\n");
|
||||
expect(filterUnifiedDiffFiles(ambiguous, () => false)).toBe(ambiguous);
|
||||
});
|
||||
});
|
||||
@@ -25,179 +25,3 @@ export function parseTurnDiffFilesFromUnifiedDiff(
|
||||
|
||||
return files.toSorted((left, right) => left.path.localeCompare(right.path));
|
||||
}
|
||||
|
||||
const SIMPLE_ESCAPES: Record<string, number> = {
|
||||
"\\": 0x5c,
|
||||
'"': 0x22,
|
||||
a: 0x07,
|
||||
b: 0x08,
|
||||
f: 0x0c,
|
||||
n: 0x0a,
|
||||
r: 0x0d,
|
||||
t: 0x09,
|
||||
v: 0x0b,
|
||||
};
|
||||
|
||||
function stripGitPathQuoting(value: string): string {
|
||||
if (!(value.startsWith('"') && value.endsWith('"') && value.length >= 2)) {
|
||||
return value;
|
||||
}
|
||||
// Git C-style quoting: octal escapes are raw UTF-8 BYTES (e.g. `ä` is
|
||||
// `\303\244`), so decode into a byte buffer first and UTF-8-decode the
|
||||
// whole path at the end — per-escape String.fromCharCode would yield
|
||||
// mojibake that never matches attribution map keys.
|
||||
const inner = value.slice(1, -1);
|
||||
const bytes: Array<number> = [];
|
||||
const encoder = new TextEncoder();
|
||||
for (let index = 0; index < inner.length; index += 1) {
|
||||
const char = inner[index]!;
|
||||
if (char !== "\\" || index === inner.length - 1) {
|
||||
bytes.push(...encoder.encode(char));
|
||||
continue;
|
||||
}
|
||||
const next = inner[index + 1]!;
|
||||
const simple = SIMPLE_ESCAPES[next];
|
||||
if (simple !== undefined) {
|
||||
bytes.push(simple);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
const octal = /^[0-7]{1,3}/.exec(inner.slice(index + 1))?.[0];
|
||||
if (octal) {
|
||||
bytes.push(parseInt(octal, 8) & 0xff);
|
||||
index += octal.length;
|
||||
continue;
|
||||
}
|
||||
bytes.push(...encoder.encode(char));
|
||||
}
|
||||
return new TextDecoder("utf-8", { fatal: false }).decode(new Uint8Array(bytes));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the post-image path out of a `diff --git a/<path> b/<path>` header.
|
||||
*
|
||||
* Only trustworthy when both paths are quoted or the two paths are equal
|
||||
* (no rename): for unquoted renamed paths containing spaces the split is
|
||||
* ambiguous, so return null and let the caller keep the section.
|
||||
*/
|
||||
function resolveDiffGitHeaderPath(headerLine: string): string | null {
|
||||
const spec = headerLine.slice("diff --git ".length).trim();
|
||||
const quotedMatch = /^("(?:[^"\\]|\\.)*"|\S+) ("(?:[^"\\]|\\.)*"|\S+)$/.exec(spec);
|
||||
if (quotedMatch) {
|
||||
const source = stripGitPathQuoting(quotedMatch[1]!);
|
||||
const target = stripGitPathQuoting(quotedMatch[2]!);
|
||||
if (source.startsWith("a/") && target.startsWith("b/")) {
|
||||
return target.slice(2);
|
||||
}
|
||||
}
|
||||
// Paths with spaces are unquoted in this header; recover the symmetric
|
||||
// a/X b/X form (covers everything but renames of space-containing paths).
|
||||
if (spec.length % 2 === 1) {
|
||||
const midpoint = (spec.length - 1) / 2;
|
||||
const source = spec.slice(0, midpoint);
|
||||
const target = spec.slice(midpoint + 1);
|
||||
if (source.startsWith("a/") && target.startsWith("b/") && source.slice(2) === target.slice(2)) {
|
||||
return target.slice(2);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the post-image path of one `diff --git` section, preferring the
|
||||
* `+++ b/` line and falling back to `--- a/` for deletions. Binary and
|
||||
* mode-only sections have neither, so fall back to rename/copy metadata and
|
||||
* finally the `diff --git` header itself. Returns null when the section is
|
||||
* unparseable; callers should keep such sections.
|
||||
*/
|
||||
function resolveDiffSectionPath(section: string): string | null {
|
||||
// `--- a/` precedes `+++ b/` in a section, so resolve the post-image path
|
||||
// in a full pass before falling back — for renames the two differ, and the
|
||||
// attribution map is keyed by the post-image path.
|
||||
let fallbackSource: string | null = null;
|
||||
let renameTarget: string | null = null;
|
||||
let headerPath: string | null = null;
|
||||
for (const line of section.split("\n")) {
|
||||
if (line.startsWith("+++ ")) {
|
||||
const target = stripGitPathQuoting(line.slice(4).trim());
|
||||
if (target !== "/dev/null") {
|
||||
return target.startsWith("b/") ? target.slice(2) : target;
|
||||
}
|
||||
} else if (line.startsWith("--- ") && fallbackSource === null) {
|
||||
const source = stripGitPathQuoting(line.slice(4).trim());
|
||||
if (source !== "/dev/null" && source.startsWith("a/")) {
|
||||
fallbackSource = source.slice(2);
|
||||
}
|
||||
} else if (
|
||||
(line.startsWith("rename to ") || line.startsWith("copy to ")) &&
|
||||
renameTarget === null
|
||||
) {
|
||||
renameTarget = stripGitPathQuoting(line.slice(line.indexOf(" to ") + 4));
|
||||
} else if (line.startsWith("diff --git ") && headerPath === null) {
|
||||
headerPath = resolveDiffGitHeaderPath(line);
|
||||
}
|
||||
}
|
||||
return fallbackSource ?? renameTarget ?? headerPath;
|
||||
}
|
||||
|
||||
function splitUnifiedDiffSections(diff: string): ReadonlyArray<string> {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
if (normalized.trim().length === 0) {
|
||||
return [];
|
||||
}
|
||||
const sections: Array<string> = [];
|
||||
let currentStart = -1;
|
||||
const lines = normalized.split("\n");
|
||||
const flush = (endExclusive: number) => {
|
||||
if (currentStart >= 0) {
|
||||
sections.push(lines.slice(currentStart, endExclusive).join("\n"));
|
||||
}
|
||||
};
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
if (lines[index]!.startsWith("diff --git ")) {
|
||||
flush(index);
|
||||
currentStart = index;
|
||||
}
|
||||
}
|
||||
flush(lines.length);
|
||||
return sections;
|
||||
}
|
||||
|
||||
/**
|
||||
* List the resolvable post-image paths of a unified diff's file sections.
|
||||
* Unparseable sections are omitted.
|
||||
*/
|
||||
export function listUnifiedDiffPaths(diff: string): ReadonlyArray<string> {
|
||||
const paths: Array<string> = [];
|
||||
for (const section of splitUnifiedDiffSections(diff)) {
|
||||
const path = resolveDiffSectionPath(section);
|
||||
if (path !== null) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove file sections from a unified diff by path.
|
||||
*
|
||||
* Sections whose path cannot be determined are kept (fail toward showing).
|
||||
*/
|
||||
export function filterUnifiedDiffFiles(
|
||||
diff: string,
|
||||
shouldKeepPath: (path: string) => boolean,
|
||||
): string {
|
||||
const sections = splitUnifiedDiffSections(diff);
|
||||
if (sections.length === 0) {
|
||||
return diff;
|
||||
}
|
||||
|
||||
const kept = sections.filter((section) => {
|
||||
const path = resolveDiffSectionPath(section);
|
||||
return path === null || shouldKeepPath(path);
|
||||
});
|
||||
if (kept.length === sections.length) {
|
||||
return diff;
|
||||
}
|
||||
return kept.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import { persistServerRuntimeState } from "../serverRuntimeState.ts";
|
||||
import { findLiveServerRuntimeState } from "./auth.ts";
|
||||
|
||||
/** A pid that cannot belong to a live process (above the usual pid_max). */
|
||||
const DEAD_PID = 0x7ffffffe;
|
||||
|
||||
const writeRuntimeState = Effect.fn(function* (input: {
|
||||
readonly baseDir: string;
|
||||
readonly stateDir: "dev" | "userdata";
|
||||
readonly pid: number;
|
||||
readonly port: number;
|
||||
readonly devUrl?: string;
|
||||
}) {
|
||||
const path = yield* Path.Path;
|
||||
yield* persistServerRuntimeState({
|
||||
path: path.join(input.baseDir, input.stateDir, "server-runtime.json"),
|
||||
state: {
|
||||
version: 1,
|
||||
pid: input.pid,
|
||||
port: input.port,
|
||||
origin: `http://127.0.0.1:${String(input.port)}`,
|
||||
...(input.devUrl ? { devUrl: input.devUrl } : {}),
|
||||
startedAt: "2026-07-20T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const makeBaseDir = Effect.fn(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-auth-cli-test-" });
|
||||
return {
|
||||
baseDir,
|
||||
// What the flag heuristic resolves to without --dev-url: the userdata dir.
|
||||
serverRuntimeStatePath: path.join(baseDir, "userdata", "server-runtime.json"),
|
||||
};
|
||||
});
|
||||
|
||||
describe("findLiveServerRuntimeState", () => {
|
||||
it.effect("prefers the dev server when both state directories are live", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* makeBaseDir();
|
||||
// The configured path points at userdata, but this command is about dev.
|
||||
yield* writeRuntimeState({
|
||||
baseDir: config.baseDir,
|
||||
stateDir: "userdata",
|
||||
pid: process.pid,
|
||||
port: 16_601,
|
||||
});
|
||||
yield* writeRuntimeState({
|
||||
baseDir: config.baseDir,
|
||||
stateDir: "dev",
|
||||
pid: process.pid,
|
||||
port: 16_602,
|
||||
devUrl: "http://localhost:8888/",
|
||||
});
|
||||
|
||||
const found = yield* findLiveServerRuntimeState(config);
|
||||
|
||||
const live = Option.getOrThrow(found);
|
||||
assert.equal(live.stateDir, path.join(config.baseDir, "dev"));
|
||||
assert.equal(live.state.devUrl, "http://localhost:8888/");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("falls back to a live non-dev server when no dev server is running", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* makeBaseDir();
|
||||
yield* writeRuntimeState({
|
||||
baseDir: config.baseDir,
|
||||
stateDir: "userdata",
|
||||
pid: process.pid,
|
||||
port: 16_601,
|
||||
});
|
||||
|
||||
const found = yield* findLiveServerRuntimeState(config);
|
||||
|
||||
const live = Option.getOrThrow(found);
|
||||
assert.equal(live.stateDir, path.join(config.baseDir, "userdata"));
|
||||
assert.equal(live.state.port, 16_601);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
// A server killed with SIGKILL never clears its state file.
|
||||
it.effect("ignores state files whose process is gone", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* makeBaseDir();
|
||||
yield* writeRuntimeState({
|
||||
baseDir: config.baseDir,
|
||||
stateDir: "dev",
|
||||
pid: DEAD_PID,
|
||||
port: 16_602,
|
||||
devUrl: "http://localhost:8888/",
|
||||
});
|
||||
|
||||
assert.isTrue(Option.isNone(yield* findLiveServerRuntimeState(config)));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("skips a stale dev server in favor of a live one elsewhere", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* makeBaseDir();
|
||||
yield* writeRuntimeState({
|
||||
baseDir: config.baseDir,
|
||||
stateDir: "dev",
|
||||
pid: DEAD_PID,
|
||||
port: 16_602,
|
||||
devUrl: "http://localhost:8888/",
|
||||
});
|
||||
yield* writeRuntimeState({
|
||||
baseDir: config.baseDir,
|
||||
stateDir: "userdata",
|
||||
pid: process.pid,
|
||||
port: 16_601,
|
||||
});
|
||||
|
||||
const live = Option.getOrThrow(yield* findLiveServerRuntimeState(config));
|
||||
assert.equal(live.stateDir, path.join(config.baseDir, "userdata"));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports nothing when no state files exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* makeBaseDir();
|
||||
assert.isTrue(Option.isNone(yield* findLiveServerRuntimeState(config)));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
+142
-10
@@ -3,11 +3,14 @@ import {
|
||||
AuthSessionId,
|
||||
AuthStandardClientScopes,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
@@ -19,6 +22,11 @@ import {
|
||||
formatSessionList,
|
||||
} from "../cliAuthFormat.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import {
|
||||
isPersistedServerRuntimeStateLive,
|
||||
type PersistedServerRuntimeState,
|
||||
readPersistedServerRuntimeState,
|
||||
} from "../serverRuntimeState.ts";
|
||||
import {
|
||||
authLocationFlags,
|
||||
type CliAuthLocationFlags,
|
||||
@@ -26,6 +34,24 @@ import {
|
||||
resolveCliAuthConfig,
|
||||
} from "./config.ts";
|
||||
|
||||
class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServerError>()(
|
||||
"NoRunningServerError",
|
||||
{ baseDir: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return [
|
||||
`No running T3 Code server was found under ${this.baseDir}.`,
|
||||
"Start one with `bun run dev`, or point at another directory with --base-dir.",
|
||||
].join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
const environmentAuthLayer = (config: ServerConfig.ServerConfig["Service"], quietLogs: boolean) =>
|
||||
EnvironmentAuth.runtimeLayer.pipe(
|
||||
Layer.provide(ServerConfig.layer(config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, quietLogs ? "Error" : config.logLevel)),
|
||||
);
|
||||
|
||||
const runWithEnvironmentAuth = <A, E>(
|
||||
flags: CliAuthLocationFlags,
|
||||
run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
|
||||
@@ -36,18 +62,10 @@ const runWithEnvironmentAuth = <A, E>(
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
|
||||
return yield* Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
return yield* run(environmentAuth);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(EnvironmentAuth.runtimeLayer).pipe(
|
||||
Layer.provide(ServerConfig.layer(config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(environmentAuthLayer(config, options?.quietLogs ?? false)));
|
||||
});
|
||||
|
||||
const ttlFlag = Flag.string("ttl").pipe(
|
||||
@@ -113,6 +131,115 @@ const pairingCreateCommand = Command.make("create", {
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* The state directory is `<base>/dev` for an implicit dev home and
|
||||
* `<base>/userdata` otherwise — a split that depends on flags the caller of
|
||||
* this command should not have to reason about, and which silently mints
|
||||
* tokens into a database the running server never reads when guessed wrong.
|
||||
* So check both, and let the live server decide which one is right.
|
||||
*/
|
||||
export const findLiveServerRuntimeState = Effect.fn("auth.findLiveServerRuntimeState")(function* (
|
||||
config: Pick<ServerConfig.ServerConfig["Service"], "baseDir" | "serverRuntimeStatePath">,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const candidatePaths = [
|
||||
...new Set([
|
||||
config.serverRuntimeStatePath,
|
||||
...(["dev", "userdata"] as const).map((stateDir) =>
|
||||
path.join(config.baseDir, stateDir, "server-runtime.json"),
|
||||
),
|
||||
]),
|
||||
];
|
||||
|
||||
const live: Array<{
|
||||
readonly stateDir: string;
|
||||
readonly state: PersistedServerRuntimeState;
|
||||
}> = [];
|
||||
|
||||
for (const statePath of candidatePaths) {
|
||||
const state = yield* readPersistedServerRuntimeState(statePath);
|
||||
if (Option.isNone(state)) {
|
||||
continue;
|
||||
}
|
||||
// A file left behind by a killed or crashed server describes a port
|
||||
// nothing is listening on. Minting against it produces a token the live
|
||||
// server rejects with `invalid_credential`.
|
||||
if (yield* isPersistedServerRuntimeStateLive(state.value)) {
|
||||
live.push({ stateDir: path.dirname(statePath), state: state.value });
|
||||
}
|
||||
}
|
||||
|
||||
// `devUrl` is only recorded by a server fronted by a web dev server, so it
|
||||
// distinguishes the dev instance from a production-style one when both are
|
||||
// running under the same base directory. This command is about dev, so a dev
|
||||
// server wins regardless of which state directory the flags happened to
|
||||
// resolve to.
|
||||
return Option.fromNullishOr(
|
||||
live.find((candidate) => candidate.state.devUrl !== undefined) ?? live[0],
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* `t3 auth pairing url` — print a ready-to-open pairing link for a dev server
|
||||
* that is already running, without having to know its port, its state
|
||||
* directory, or which of those two the `--base-dir`/`--dev-url` combination
|
||||
* happens to select. The running server records all of it in
|
||||
* `server-runtime.json`; this reads that back.
|
||||
*
|
||||
* The startup link printed in the server's own log is usually enough. This is
|
||||
* for when it has been consumed, scrolled away, or the log isn't at hand.
|
||||
*/
|
||||
const pairingUrlCommand = Command.make("url", {
|
||||
...authLocationFlags,
|
||||
ttl: ttlFlag,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription(
|
||||
"Print a pairing URL for the dev server running against this data directory.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
// Run from a worktree, this command means "the dev server I just started
|
||||
// here" — which the dev runner puts in the worktree's own `.t3`. Falling
|
||||
// through to the shared home would mint a credential into the database
|
||||
// the user's installed T3 Code is running against.
|
||||
const worktreeBaseDir = yield* resolveWorktreeT3Home(process.cwd());
|
||||
const resolvedFlags =
|
||||
Option.isSome(flags.baseDir) || worktreeBaseDir === undefined
|
||||
? flags
|
||||
: { ...flags, baseDir: Option.some(worktreeBaseDir) };
|
||||
const config = yield* resolveCliAuthConfig(resolvedFlags, logLevel);
|
||||
const live = yield* findLiveServerRuntimeState(config);
|
||||
|
||||
if (Option.isNone(live)) {
|
||||
return yield* new NoRunningServerError({ baseDir: config.baseDir });
|
||||
}
|
||||
|
||||
// Issue against the same state directory the server is using, whichever
|
||||
// of the two it turned out to be.
|
||||
const derivedPaths = yield* ServerConfig.deriveServerPaths(config.baseDir, config.devUrl, {
|
||||
stateDir: live.value.stateDir,
|
||||
});
|
||||
|
||||
// Prefer the web origin the user actually opens; a server with no dev URL
|
||||
// serves the app itself, so its own origin is the right target.
|
||||
const baseUrl = live.value.state.devUrl ?? live.value.state.origin;
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const issued = yield* environmentAuth.createPairingLink({
|
||||
scopes: AuthStandardClientScopes,
|
||||
subject: "one-time-token",
|
||||
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
|
||||
label: "cli-issued pairing url",
|
||||
});
|
||||
yield* Console.log(formatIssuedPairingCredential(issued, { json: flags.json, baseUrl }));
|
||||
}).pipe(Effect.provide(environmentAuthLayer({ ...config, ...derivedPaths }, flags.json)));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingListCommand = Command.make("list", {
|
||||
...authLocationFlags,
|
||||
json: jsonFlag,
|
||||
@@ -156,7 +283,12 @@ const pairingRevokeCommand = Command.make("revoke", {
|
||||
|
||||
const pairingCommand = Command.make("pairing").pipe(
|
||||
Command.withDescription("Manage one-time client pairing tokens."),
|
||||
Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
|
||||
Command.withSubcommands([
|
||||
pairingCreateCommand,
|
||||
pairingUrlCommand,
|
||||
pairingListCommand,
|
||||
pairingRevokeCommand,
|
||||
]),
|
||||
);
|
||||
|
||||
const sessionIssueCommand = Command.make("issue", {
|
||||
|
||||
@@ -47,6 +47,13 @@ export interface ServerDerivedPaths {
|
||||
|
||||
export interface DeriveServerPathsOptions {
|
||||
readonly baseDirIsExplicit?: boolean;
|
||||
/**
|
||||
* Use this state directory verbatim instead of deriving `dev` vs `userdata`.
|
||||
* For tooling that has already located a running server's state directory and
|
||||
* must target it exactly, rather than re-running the heuristic and risking a
|
||||
* different answer.
|
||||
*/
|
||||
readonly stateDir?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,10 +105,9 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
options: DeriveServerPathsOptions = {},
|
||||
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
|
||||
const { join } = yield* Path.Path;
|
||||
const stateDir = join(
|
||||
baseDir,
|
||||
devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
|
||||
);
|
||||
const stateDir =
|
||||
options.stateDir ??
|
||||
join(baseDir, devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata");
|
||||
const dbPath = join(stateDir, "state.sqlite");
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
|
||||
@@ -141,6 +141,7 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
+18
-1
@@ -4,6 +4,7 @@ import {
|
||||
AuthOrchestrationReadScope,
|
||||
EnvironmentHttpApi,
|
||||
} from "@t3tools/contracts";
|
||||
import { isDevProxiedPath } from "@t3tools/shared/devProxy";
|
||||
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -48,9 +49,21 @@ 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.
|
||||
const extraDevOrigins = (process.env.T3CODE_DEV_ALLOWED_ORIGINS ?? "")
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0);
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
? {
|
||||
allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...extraDevOrigins],
|
||||
credentials: true,
|
||||
}
|
||||
: {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
@@ -216,6 +229,10 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
|
||||
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
|
||||
status: 302,
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewTabId,
|
||||
@@ -58,6 +59,8 @@ const handlers = {
|
||||
invokeTargeted<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
|
||||
preview_resize: (input) =>
|
||||
invokeTargeted<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
|
||||
preview_set_appearance: (input) =>
|
||||
invokeTargeted<PreviewAutomationSetColorSchemeResult>("setColorScheme", input),
|
||||
preview_snapshot: (input) => invokeTargeted<PreviewAutomationSnapshot>("snapshot", input ?? {}),
|
||||
preview_click: (input) =>
|
||||
invokeTargeted<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSetColorSchemeInput,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewAutomationTabTargetInput,
|
||||
@@ -86,6 +88,19 @@ export const PreviewResizeTool = safeBrowserTool(
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSetAppearanceTool = safeBrowserTool(
|
||||
Tool.make("preview_set_appearance", {
|
||||
description:
|
||||
"Emulate prefers-color-scheme in a collaborative browser tab, optionally selected by tabId. Use {colorScheme:'dark'} or {colorScheme:'light'} to preview the page in that appearance, and {colorScheme:'system'} to clear the override and follow the OS appearance.",
|
||||
parameters: PreviewAutomationSetColorSchemeInput,
|
||||
success: PreviewAutomationSetColorSchemeResult,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Set preview appearance")
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
Tool.make("preview_snapshot", {
|
||||
description:
|
||||
@@ -189,6 +204,7 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSetAppearanceTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -205,6 +221,7 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSetAppearanceTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -256,27 +256,6 @@ const make = Effect.gen(function* () {
|
||||
// reflects files created or deleted during this turn.
|
||||
yield* workspaceEntries.refresh(input.cwd);
|
||||
|
||||
// Best-effort per-path attribution: paths whose change is fully explained
|
||||
// by pre-existing history moving through HEAD (pull, checkout,
|
||||
// cherry-pick, rebase) are tagged origin "git" so the UI can demote them.
|
||||
// Attribution must never block the checkpoint pipeline — any failure
|
||||
// degrades to unattributed files (all shown as agent work).
|
||||
const attribution = yield* checkpointStore
|
||||
.attributeCheckpointDiff({
|
||||
cwd: input.cwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to attribute checkpoint diff", {
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: input.cwd,
|
||||
@@ -292,7 +271,6 @@ const make = Effect.gen(function* () {
|
||||
kind: "modified" as const,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
...(attribution ? { origin: attribution.get(file.path) ?? "agent" } : {}),
|
||||
})),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
|
||||
@@ -609,6 +609,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -679,6 +681,38 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.snoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: event.payload.snoozedUntil,
|
||||
snoozedAt: event.payload.snoozedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unsnoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -310,6 +310,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -422,6 +424,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
|
||||
@@ -336,6 +336,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
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",
|
||||
@@ -366,6 +368,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
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",
|
||||
@@ -398,6 +402,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
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",
|
||||
@@ -762,6 +768,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
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",
|
||||
@@ -1196,6 +1204,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1396,6 +1406,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1527,6 +1539,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1663,6 +1677,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1905,6 +1921,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
@@ -2001,6 +2019,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
|
||||
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -38,6 +40,8 @@ export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSet
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
|
||||
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationThread,
|
||||
} 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";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
// The decider's clock is the Effect test clock, pinned to the epoch, so
|
||||
// "future" wake times are relative to 1970-01-01T00:00:00.000Z.
|
||||
const FUTURE_WAKE = "1970-01-02T09:00:00.000Z";
|
||||
const PAST_WAKE = "1969-12-31T09:00:00.000Z";
|
||||
const SNOOZED_AT = "1969-12-30T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(input: {
|
||||
readonly snoozedUntil?: string | null;
|
||||
readonly snoozedAt?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
readonly activities?: OrchestrationThread["activities"];
|
||||
readonly messages?: OrchestrationThread["messages"];
|
||||
}): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: input.archivedAt ?? null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: input.snoozedUntil ?? null,
|
||||
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
|
||||
deletedAt: null,
|
||||
messages: input.messages ?? [],
|
||||
proposedPlans: [],
|
||||
activities: input.activities ?? [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("snoozed thread decider", (it) => {
|
||||
it.effect("snoozes a thread to a future wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.snoozed");
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe(FUTURE_WAKE);
|
||||
expect(events[0].payload.snoozedAt).toBe(events[0].payload.updatedAt);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a wake time that is not in the future", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-past"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: PAST_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects an unparseable wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
// IsoDateTime is structurally a string, so garbage can reach the
|
||||
// decider; a NaN wake time must never persist as snooze state.
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-garbage"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "not-a-date",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing blocked-on-you work", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestActivity = {
|
||||
id: EventId.make("activity-req-1"),
|
||||
tone: "approval" as const,
|
||||
kind: "approval.requested",
|
||||
summary: "approval.requested",
|
||||
payload: { requestId: "req-1" },
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
} as OrchestrationThread["activities"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-blocked"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ activities: [requestActivity] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-emits idempotently for a duplicate snooze to the same wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const reEmit = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(reEmit) ? reEmit : [reEmit];
|
||||
expect(events).toHaveLength(1);
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
// Original snoozedAt preserved; updatedAt must not churn.
|
||||
expect(events[0].payload.snoozedAt).toBe(SNOOZED_AT);
|
||||
expect(events[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-snoozing to a DIFFERENT wake time stamps fresh", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-extend"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "1970-01-03T09:00:00.000Z",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe("1970-01-03T09:00:00.000Z");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unsnoozes with reason user and re-emits idempotently when awake", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events[0]?.type).toBe("thread.unsnoozed");
|
||||
if (events[0]?.type === "thread.unsnoozed") {
|
||||
expect(events[0].payload.reason).toBe("user");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
|
||||
const awake = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze-awake"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const awakeEvents = Array.isArray(awake) ? awake : [awake];
|
||||
expect(awakeEvents[0]?.type).toBe("thread.unsnoozed");
|
||||
if (awakeEvents[0]?.type === "thread.unsnoozed") {
|
||||
// No state change — keep the existing updatedAt.
|
||||
expect(awakeEvents[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing a thread with a queued turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
// The decider clock is the Effect test clock pinned to the epoch: a
|
||||
// user message 30s before it with no adopting turn is queued work.
|
||||
const queuedMessage = {
|
||||
id: MessageId.make("message-queued"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "1969-12-31T23:59:30.000Z",
|
||||
updatedAt: "1969-12-31T23:59:30.000Z",
|
||||
} as OrchestrationThread["messages"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-queued"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ messages: [queuedMessage] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing an archived thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ archivedAt: NOW }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("a user message spends the snooze return ticket (activity wake)", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-1"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
|
||||
expect(unsnoozed).toBeDefined();
|
||||
if (unsnoozed?.type === "thread.unsnoozed") {
|
||||
expect(unsnoozed.payload.reason).toBe("activity");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -53,6 +53,13 @@ function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): b
|
||||
);
|
||||
}
|
||||
|
||||
// Scans the read model's activities, which the projector caps at the most
|
||||
// recent 500. That bound is safe here: an OPEN approval/user-input request
|
||||
// blocks its turn, so the thread cannot accumulate hundreds of later
|
||||
// activities while one is outstanding — a request that has scrolled out of
|
||||
// the window is one whose turn kept running, i.e. it was resolved or went
|
||||
// stale. (The projection pipeline's pendingApprovalCount reads the same
|
||||
// capped stream and stays consistent with this view.)
|
||||
function hasOpenBlockingRequest(thread: {
|
||||
readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
|
||||
}): boolean {
|
||||
@@ -79,6 +86,62 @@ function hasOpenBlockingRequest(thread: {
|
||||
return openRequestIds.size > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A queued turn start — a user message no turn has picked up yet — is work
|
||||
* in flight even though session is still null (turn.start emits
|
||||
* message-sent + turn-start-requested; the session arrives later). Detection
|
||||
* mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
* strictly newer than every latestTurn timestamp (adoption stamps the new
|
||||
* turn's requestedAt with the message time, clearing this), and only within
|
||||
* the adoption grace window — historical threads whose last user message
|
||||
* postdates their turn timestamps (older-server data, mid-turn messages)
|
||||
* must not be blocked forever. A failed session start (status "error")
|
||||
* clears the block immediately.
|
||||
*
|
||||
* The age check is bounded on BOTH sides: message timestamps are
|
||||
* client-supplied, so a client clock ahead of the server yields a negative
|
||||
* age. Without the lower bound that negative age satisfies `<= grace` for
|
||||
* as long as the skew lasts, extending the block far past the intended two
|
||||
* minutes.
|
||||
*/
|
||||
function threadHasQueuedTurnStart(
|
||||
thread: {
|
||||
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
|
||||
readonly latestTurn: {
|
||||
readonly requestedAt: string;
|
||||
readonly startedAt: string | null;
|
||||
readonly completedAt: string | null;
|
||||
} | null;
|
||||
readonly session: { readonly status: string } | null;
|
||||
},
|
||||
occurredAt: string,
|
||||
): boolean {
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
return (
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS
|
||||
);
|
||||
}
|
||||
|
||||
function withEventBase(
|
||||
input: Pick<OrchestrationCommand, "commandId"> & {
|
||||
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
|
||||
@@ -411,46 +474,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
);
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
// A queued turn start — a user message no turn has picked up yet — is
|
||||
// work in flight even though session is still null (turn.start emits
|
||||
// message-sent + turn-start-requested; the session arrives later).
|
||||
// Settling in that window would hide just-requested work. Detection
|
||||
// mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
// strictly newer than every latestTurn timestamp (adoption stamps the
|
||||
// new turn's requestedAt with the message time, clearing this), and
|
||||
// only within the adoption grace window — historical threads whose
|
||||
// last user message postdates their turn timestamps (older-server
|
||||
// data, mid-turn messages) must stay settleable. A failed session
|
||||
// start (status "error") clears the block immediately.
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
// The age check is bounded on BOTH sides: message timestamps are
|
||||
// client-supplied, so a client clock ahead of the server yields a
|
||||
// negative age. Without the lower bound that negative age satisfies
|
||||
// `<= grace` for as long as the skew lasts, extending the settle
|
||||
// block far past the intended two minutes.
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
const hasQueuedTurnStart =
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS;
|
||||
if (hasQueuedTurnStart) {
|
||||
// Settling inside the adoption window would hide just-requested work.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
@@ -508,6 +533,103 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.snooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
// A wake time in the past would create a thread that is snoozed and
|
||||
// woken at once — the row would never leave the inbox but still carry
|
||||
// snooze state. Reject instead of silently normalizing. The negated
|
||||
// comparison also catches unparseable wake times (IsoDateTime is
|
||||
// structurally just a string): NaN fails every comparison, and an
|
||||
// unparseable snoozedUntil must never persist.
|
||||
if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Blocked-on-you work must not be snoozed away: a pending approval or
|
||||
// user-input request is the agent waiting on the user, and hiding it
|
||||
// defeats the request. (A running session IS snoozable — snooze only
|
||||
// affects visibility, never the agent.)
|
||||
if (hasOpenBlockingRequest(thread)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// A queued turn start — a user message no turn has adopted yet — is
|
||||
// invisible pending work: no session, no pending flags. Snoozing in
|
||||
// that window would hide a just-requested turn exactly the way settle
|
||||
// would.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Re-snoozing an already-snoozed thread to the SAME wake time is a
|
||||
// duplicate (double-click, raced clients): re-emit with the original
|
||||
// timestamps so the projection is a no-op. A different wake time is a
|
||||
// real change and stamps fresh.
|
||||
const existingSnoozedAt =
|
||||
thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
|
||||
? thread.snoozedAt
|
||||
: null;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.snoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
snoozedUntil: command.snoozedUntil,
|
||||
snoozedAt: existingSnoozedAt ?? occurredAt,
|
||||
updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unsnooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Idempotent by re-emission (see thread.settle): waking a thread that
|
||||
// is not snoozed lands on the same null state without churning
|
||||
// updatedAt.
|
||||
const alreadyAwake = thread.snoozedUntil == null;
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: command.reason,
|
||||
updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
@@ -663,24 +785,42 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
// Real activity resets ANY override: it wakes an explicitly settled
|
||||
// thread, and it clears a keep-active pin back to neutral so the
|
||||
// thread can auto-settle again after this burst of work goes stale.
|
||||
if (targetThread.settledOverride === null) {
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
// A snooze clears the same way — sending a message to a snoozed
|
||||
// thread is the user re-engaging, so the return ticket is spent.
|
||||
const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
if (targetThread.settledOverride !== null) {
|
||||
lifecycleResetEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
|
||||
if (targetThread.snoozedUntil != null) {
|
||||
lifecycleResetEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
|
||||
case "thread.turn.interrupt": {
|
||||
@@ -822,7 +962,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
// Only a session coming alive is activity worth waking a settled thread
|
||||
// for — status writes like ready/stopped/error arrive after the fact and
|
||||
// must not fight a user's explicit settle.
|
||||
// must not fight a user's explicit settle. Snooze is deliberately NOT
|
||||
// cleared here: snooze never pauses the agent, so its session starting
|
||||
// or erroring is not the user re-engaging. Blocked/failed work still
|
||||
// surfaces immediately — effectiveSnoozed refuses to classify a thread
|
||||
// with a raised hand (approval / input / failure / fresh completion)
|
||||
// as snoozed, without spending the return ticket.
|
||||
const isSessionActivity =
|
||||
command.session.status === "starting" || command.session.status === "running";
|
||||
// Real activity resets ANY override (settled wakes, active unpins).
|
||||
|
||||
@@ -91,6 +91,8 @@ describe("orchestration projector", () => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -23,8 +23,10 @@ import {
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadSnoozedPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadUnsnoozedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -290,6 +292,8 @@ export function projectEvent(
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -365,6 +369,30 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.snoozed":
|
||||
return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: payload.snoozedUntil,
|
||||
snoozedAt: payload.snoozedAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unsnoozed":
|
||||
return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
@@ -93,6 +93,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -153,6 +155,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-03-25T00:00:00.000Z",
|
||||
snoozedUntil: "2026-03-26T09:00:00.000Z",
|
||||
snoozedAt: "2026-03-25T00:00:00.000Z",
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -169,12 +173,17 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
}
|
||||
assert.strictEqual(row.settledOverride, "settled");
|
||||
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
|
||||
|
||||
// Un-settle to the keep-active pin and confirm the flip persists.
|
||||
// Un-settle to the keep-active pin and wake the snooze; confirm the
|
||||
// flips persist.
|
||||
yield* threads.upsert({
|
||||
...row,
|
||||
settledOverride: "active",
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
});
|
||||
const repersisted = yield* threads.getById({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
@@ -182,6 +191,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
const updated = Option.getOrNull(repersisted);
|
||||
assert.strictEqual(updated?.settledOverride, "active");
|
||||
assert.strictEqual(updated?.settledAt, null);
|
||||
assert.strictEqual(updated?.snoozedUntil, null);
|
||||
assert.strictEqual(updated?.snoozedAt, null);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -45,6 +45,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
snoozed_until,
|
||||
snoozed_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
@@ -66,6 +68,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.archivedAt},
|
||||
${row.settledOverride},
|
||||
${row.settledAt},
|
||||
${row.snoozedUntil},
|
||||
${row.snoozedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -87,6 +91,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at = excluded.archived_at,
|
||||
settled_override = excluded.settled_override,
|
||||
settled_at = excluded.settled_at,
|
||||
snoozed_until = excluded.snoozed_until,
|
||||
snoozed_at = excluded.snoozed_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
@@ -115,6 +121,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
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",
|
||||
@@ -145,6 +153,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
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",
|
||||
|
||||
@@ -46,6 +46,7 @@ import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.
|
||||
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";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -91,6 +92,7 @@ export const migrationEntries = [
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
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 === "snoozed_until")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_until TEXT
|
||||
`;
|
||||
}
|
||||
|
||||
if (!columns.some((column) => column.name === "snoozed_at")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_at TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -38,6 +38,8 @@ export const ProjectionThread = Schema.Struct({
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
|
||||
settledAt: Schema.NullOr(IsoDateTime),
|
||||
snoozedUntil: Schema.NullOr(IsoDateTime),
|
||||
snoozedAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
|
||||
@@ -118,6 +118,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { cwd } = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
@@ -165,9 +166,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
effectiveConfig,
|
||||
() => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
|
||||
processEnv,
|
||||
cwd,
|
||||
).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import { discoverClaudeSkills } from "./ClaudeSkills.ts";
|
||||
|
||||
const writeSkill = Effect.fn(function* (
|
||||
skillsDir: string,
|
||||
directoryName: string,
|
||||
contents: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const skillDir = path.join(skillsDir, directoryName);
|
||||
yield* fs.makeDirectory(skillDir, { recursive: true });
|
||||
yield* fs.writeFileString(path.join(skillDir, "SKILL.md"), contents);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
|
||||
it.effect("discovers user and project skills with frontmatter metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const configDir = path.join(tempDir, "claude-home");
|
||||
const workspace = path.join(tempDir, "workspace");
|
||||
|
||||
yield* writeSkill(
|
||||
path.join(configDir, "skills"),
|
||||
"codex-review",
|
||||
[
|
||||
"---",
|
||||
"name: codex-review",
|
||||
"description: Ask Codex for a review.",
|
||||
"---",
|
||||
"",
|
||||
"# Body",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* writeSkill(
|
||||
path.join(workspace, ".claude", "skills"),
|
||||
"deploy",
|
||||
["---", "name: deploy", "description: Deploy the app.", "---", "", "# Deploy"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
|
||||
|
||||
assert.deepEqual(skills, [
|
||||
{
|
||||
name: "codex-review",
|
||||
path: path.join(configDir, "skills", "codex-review", "SKILL.md"),
|
||||
enabled: true,
|
||||
scope: "user",
|
||||
description: "Ask Codex for a review.",
|
||||
},
|
||||
{
|
||||
name: "deploy",
|
||||
path: path.join(workspace, ".claude", "skills", "deploy", "SKILL.md"),
|
||||
enabled: true,
|
||||
scope: "project",
|
||||
description: "Deploy the app.",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers project skills over user skills on name collisions", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const configDir = path.join(tempDir, "claude-home");
|
||||
const workspace = path.join(tempDir, "workspace");
|
||||
|
||||
yield* writeSkill(
|
||||
path.join(configDir, "skills"),
|
||||
"deploy",
|
||||
["---", "name: deploy", "description: User deploy.", "---"].join("\n"),
|
||||
);
|
||||
yield* writeSkill(
|
||||
path.join(workspace, ".claude", "skills"),
|
||||
"deploy",
|
||||
["---", "name: deploy", "description: Project deploy.", "---"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
|
||||
|
||||
assert.equal(skills.length, 1);
|
||||
assert.equal(skills[0]?.scope, "project");
|
||||
assert.equal(skills[0]?.description, "Project deploy.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the directory name and skips malformed frontmatter", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const configDir = path.join(tempDir, "claude-home");
|
||||
const skillsDir = path.join(configDir, "skills");
|
||||
|
||||
yield* writeSkill(skillsDir, "no-frontmatter", "# Just a heading\n");
|
||||
yield* writeSkill(skillsDir, "broken-yaml", "---\nname: [unclosed\n---\n");
|
||||
// A stray file (not a directory with SKILL.md) must be skipped.
|
||||
yield* fs.makeDirectory(skillsDir, { recursive: true });
|
||||
yield* fs.writeFileString(path.join(skillsDir, "README.md"), "not a skill");
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: configDir }, undefined);
|
||||
|
||||
// A skill with no frontmatter falls back to its directory name; a skill
|
||||
// whose frontmatter fails to parse is skipped entirely (Claude Code
|
||||
// won't load it either).
|
||||
assert.deepEqual(
|
||||
skills.map((skill) => skill.name),
|
||||
["no-frontmatter"],
|
||||
);
|
||||
assert.equal(skills[0]?.description, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("honors CLAUDE_CONFIG_DIR from the environment when homePath is unset", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const environmentConfigDir = path.join(tempDir, "env-config");
|
||||
|
||||
yield* writeSkill(
|
||||
path.join(environmentConfigDir, "skills"),
|
||||
"env-skill",
|
||||
["---", "name: env-skill", "description: From env config dir.", "---"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: "" }, undefined, {
|
||||
CLAUDE_CONFIG_DIR: environmentConfigDir,
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
skills.map((skill) => skill.name),
|
||||
["env-skill"],
|
||||
);
|
||||
|
||||
// An explicit homePath wins over the environment variable, matching
|
||||
// makeClaudeEnvironment which overwrites CLAUDE_CONFIG_DIR for the CLI.
|
||||
const explicitHome = path.join(tempDir, "explicit-home");
|
||||
yield* writeSkill(
|
||||
path.join(explicitHome, "skills"),
|
||||
"explicit-skill",
|
||||
["---", "name: explicit-skill", "---"].join("\n"),
|
||||
);
|
||||
const explicitSkills = yield* discoverClaudeSkills({ homePath: explicitHome }, undefined, {
|
||||
CLAUDE_CONFIG_DIR: environmentConfigDir,
|
||||
});
|
||||
assert.deepEqual(
|
||||
explicitSkills.map((skill) => skill.name),
|
||||
["explicit-skill"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves a relative CLAUDE_CONFIG_DIR against the workspace cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const workspace = path.join(tempDir, "workspace");
|
||||
yield* fs.makeDirectory(workspace, { recursive: true });
|
||||
|
||||
// The spawned CLI resolves a relative CLAUDE_CONFIG_DIR against its own
|
||||
// cwd (the workspace), so discovery must do the same.
|
||||
yield* writeSkill(
|
||||
path.join(workspace, "relative-config", "skills"),
|
||||
"relative-skill",
|
||||
["---", "name: relative-skill", "---"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: "" }, workspace, {
|
||||
CLAUDE_CONFIG_DIR: "relative-config",
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
skills.map((skill) => skill.name),
|
||||
["relative-skill"],
|
||||
);
|
||||
assert.equal(skills[0]?.scope, "user");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns an empty list when no skill roots exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
|
||||
const skills = yield* discoverClaudeSkills(
|
||||
{ homePath: path.join(tempDir, "missing-home") },
|
||||
path.join(tempDir, "missing-workspace"),
|
||||
);
|
||||
|
||||
assert.deepEqual(skills, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* ClaudeSkills — filesystem discovery of Claude Code skills for the `$` picker.
|
||||
*
|
||||
* Claude Code loads skills from `<config dir>/skills` (user scope) and
|
||||
* `<cwd>/.claude/skills` (project scope), one directory per skill with a
|
||||
* `SKILL.md` carrying YAML frontmatter. The Agent SDK init handshake surfaces
|
||||
* skills only as slash commands without their filesystem paths, so the
|
||||
* provider snapshot scans the same locations directly, mirroring how the
|
||||
* Codex app-server reports its skills.
|
||||
*
|
||||
* @module provider/Drivers/ClaudeSkills
|
||||
*/
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import { parse as parseYamlDocument } from "yaml";
|
||||
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
|
||||
type ClaudeSkillScope = "user" | "project";
|
||||
|
||||
const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
|
||||
|
||||
type SkillFrontmatter =
|
||||
| { readonly kind: "missing" }
|
||||
| { readonly kind: "malformed" }
|
||||
| { readonly kind: "parsed"; readonly name?: string; readonly description?: string };
|
||||
|
||||
function parseSkillFrontmatter(contents: string): SkillFrontmatter {
|
||||
const match = FRONTMATTER_PATTERN.exec(contents);
|
||||
if (!match) {
|
||||
return { kind: "missing" };
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = parseYamlDocument(match[1] ?? "");
|
||||
} catch {
|
||||
return { kind: "malformed" };
|
||||
}
|
||||
if (typeof parsed !== "object" || parsed === null) {
|
||||
return { kind: "malformed" };
|
||||
}
|
||||
|
||||
const record = parsed as Record<string, unknown>;
|
||||
const name = typeof record.name === "string" ? record.name.trim() : "";
|
||||
const description = typeof record.description === "string" ? record.description.trim() : "";
|
||||
return {
|
||||
kind: "parsed",
|
||||
...(name ? { name } : {}),
|
||||
...(description ? { description } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the Claude config directory the CLI would use, matching the
|
||||
* precedence the spawned CLI sees: the instance's `homePath` (exported as
|
||||
* `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`
|
||||
* already present in the process environment, then `~/.claude`.
|
||||
*/
|
||||
const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
|
||||
config: Pick<ClaudeSettings, "homePath">,
|
||||
environment: NodeJS.ProcessEnv,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<string, never, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const homePath = config.homePath.trim();
|
||||
if (homePath.length > 0) {
|
||||
return path.resolve(expandHomePath(homePath));
|
||||
}
|
||||
// No tilde expansion here: the spawned CLI receives this env var verbatim
|
||||
// (env vars are never shell-expanded), so a literal `~` must stay literal
|
||||
// for discovery to scan the same directory the runtime would. A relative
|
||||
// value is resolved against the workspace cwd — the subprocess's own cwd —
|
||||
// for the same reason.
|
||||
const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
|
||||
if (environmentConfigDir.length > 0) {
|
||||
return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
|
||||
}
|
||||
return path.join(NodeOS.homedir(), ".claude");
|
||||
});
|
||||
|
||||
/**
|
||||
* Enumerate Claude Code skills from the user config dir and the workspace.
|
||||
* Discovery is best-effort: unreadable roots and malformed skill entries are
|
||||
* skipped so a broken skill never degrades the provider snapshot. On name
|
||||
* collisions the project-scoped skill wins, matching Claude Code's
|
||||
* most-specific-wins resolution.
|
||||
*/
|
||||
export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
|
||||
config: Pick<ClaudeSettings, "homePath">,
|
||||
cwd?: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
|
||||
|
||||
const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [
|
||||
{ directory: path.join(configDirPath, "skills"), scope: "user" },
|
||||
...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
|
||||
];
|
||||
|
||||
const skillsByName = new Map<string, ServerProviderSkill>();
|
||||
for (const root of roots) {
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(root.directory)
|
||||
.pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
|
||||
|
||||
for (const entry of [...entries].sort()) {
|
||||
const skillPath = path.join(root.directory, entry, "SKILL.md");
|
||||
const contents = yield* fileSystem
|
||||
.readFileString(skillPath)
|
||||
.pipe(Effect.orElseSucceed(() => undefined));
|
||||
if (contents === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const frontmatter = parseSkillFrontmatter(contents);
|
||||
// Malformed frontmatter means the skill won't load in Claude Code
|
||||
// either — skip it rather than surfacing a broken entry under its
|
||||
// directory name.
|
||||
if (frontmatter.kind === "malformed") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = (frontmatter.kind === "parsed" ? frontmatter.name : undefined) ?? entry.trim();
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
skillsByName.set(name, {
|
||||
name,
|
||||
path: skillPath,
|
||||
enabled: true,
|
||||
scope: root.scope,
|
||||
...(frontmatter.kind === "parsed" && frontmatter.description
|
||||
? { description: frontmatter.description }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
|
||||
});
|
||||
@@ -530,6 +530,29 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("preserves xhigh effort for Claude Opus 5", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
"claude-opus-5",
|
||||
[{ id: "effort", value: "xhigh" }],
|
||||
),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, "xhigh");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Result from "effect/Result";
|
||||
@@ -40,6 +41,7 @@ import {
|
||||
} from "../providerSnapshot.ts";
|
||||
import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
|
||||
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
|
||||
import { discoverClaudeSkills } from "../Drivers/ClaudeSkills.ts";
|
||||
|
||||
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [],
|
||||
@@ -49,6 +51,7 @@ const CLAUDE_PRESENTATION = {
|
||||
displayName: "Claude",
|
||||
showInteractionModeToggle: true,
|
||||
} as const;
|
||||
const MINIMUM_CLAUDE_OPUS_5_VERSION = "2.1.219";
|
||||
const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
|
||||
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
|
||||
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
|
||||
@@ -85,6 +88,42 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-5",
|
||||
name: "Claude Opus 5",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultracode", label: "Ultracode" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
// Claude Code selects the 1M variant explicitly (`claude-opus-5[1m]`).
|
||||
options: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-8",
|
||||
name: "Claude Opus 4.8",
|
||||
@@ -270,6 +309,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
},
|
||||
];
|
||||
|
||||
function supportsClaudeOpus5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;
|
||||
}
|
||||
|
||||
function supportsClaudeFable5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
|
||||
}
|
||||
@@ -286,6 +329,9 @@ function getBuiltInClaudeModelsForVersion(
|
||||
version: string | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
return BUILT_IN_MODELS.filter((model) => {
|
||||
if (model.slug === "claude-opus-5") {
|
||||
return supportsClaudeOpus5(version);
|
||||
}
|
||||
if (model.slug === "claude-fable-5") {
|
||||
return supportsClaudeFable5(version);
|
||||
}
|
||||
@@ -299,6 +345,11 @@ function getBuiltInClaudeModelsForVersion(
|
||||
});
|
||||
}
|
||||
|
||||
function formatClaudeOpus5UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Opus 5. Upgrade to v${MINIMUM_CLAUDE_OPUS_5_VERSION} or newer to access it.`;
|
||||
}
|
||||
|
||||
function formatClaudeFable5UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;
|
||||
@@ -358,6 +409,7 @@ export function normalizeClaudeCliEffort(
|
||||
if (
|
||||
effort === "xhigh" &&
|
||||
model !== "claude-fable-5" &&
|
||||
model !== "claude-opus-5" &&
|
||||
model !== "claude-opus-4-8" &&
|
||||
model !== "claude-sonnet-5"
|
||||
) {
|
||||
@@ -732,10 +784,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings: ClaudeSettings,
|
||||
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Path.Path
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
@@ -834,17 +887,20 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const versionUpgradeMessage = supportsClaudeFable5(parsedVersion)
|
||||
const versionUpgradeMessage = supportsClaudeOpus5(parsedVersion)
|
||||
? undefined
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
: supportsClaudeFable5(parsedVersion)
|
||||
? formatClaudeOpus5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
|
||||
const capabilities = resolveCapabilities
|
||||
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
|
||||
: undefined;
|
||||
const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
|
||||
const slashCommands = capabilities?.slashCommands ?? [];
|
||||
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
|
||||
|
||||
@@ -855,6 +911,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -876,6 +933,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
|
||||
@@ -1842,6 +1842,62 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes Claude Opus 5 on supported Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
const opus5 = status.models.find((model) => model.slug === "claude-opus-5");
|
||||
assert.strictEqual(opus5?.name, "Claude Opus 5");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.219\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides Claude Opus 5 on older Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.models.some((model) => model.slug === "claude-opus-5"),
|
||||
false,
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Code v2.1.218 is too old for Claude Opus 5. Upgrade to v2.1.219 or newer to access it.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.218\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes Claude Fable 5 on supported Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
|
||||
@@ -43,6 +43,35 @@ describe("serverRuntimeState", () => {
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
// A server killed with SIGKILL never runs its release finalizer, so the file
|
||||
// survives it. Trusting a leftover file points callers at a dead port.
|
||||
describe("isPersistedServerRuntimeStateLive", () => {
|
||||
const stateForPid = (pid: number): ServerRuntimeState.PersistedServerRuntimeState => ({
|
||||
version: 1,
|
||||
pid,
|
||||
port: 4_971,
|
||||
origin: "http://127.0.0.1:4971",
|
||||
startedAt: "2026-06-20T00:00:00.000Z",
|
||||
});
|
||||
|
||||
it.effect("recognizes the current process as live", () =>
|
||||
Effect.gen(function* () {
|
||||
assert.isTrue(
|
||||
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(process.pid)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a pid that no longer exists as dead", () =>
|
||||
Effect.gen(function* () {
|
||||
// Above the default pid_max, so it cannot be a live process.
|
||||
assert.isFalse(
|
||||
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(0x7ffffffe)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("treats a missing runtime state file as absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -14,6 +14,12 @@ export const PersistedServerRuntimeState = Schema.Struct({
|
||||
host: Schema.optional(Schema.String),
|
||||
port: Schema.Int,
|
||||
origin: Schema.String,
|
||||
/**
|
||||
* The web origin users actually open in dev — the Vite server, or the shared
|
||||
* tailnet URL when the dev runner published one. Recorded so tooling can mint
|
||||
* a pairing URL for a running server without being told where it lives.
|
||||
*/
|
||||
devUrl: Schema.optional(Schema.String),
|
||||
startedAt: Schema.String,
|
||||
});
|
||||
export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
|
||||
@@ -45,7 +51,7 @@ const runtimeOriginForConfig = (
|
||||
};
|
||||
|
||||
export const makePersistedServerRuntimeState = (input: {
|
||||
readonly config: Pick<ServerConfig.ServerConfig["Service"], "host">;
|
||||
readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
|
||||
readonly port: number;
|
||||
}): Effect.Effect<PersistedServerRuntimeState> =>
|
||||
Effect.map(DateTime.now, (now) => ({
|
||||
@@ -54,6 +60,7 @@ export const makePersistedServerRuntimeState = (input: {
|
||||
...(input.config.host ? { host: input.config.host } : {}),
|
||||
port: input.port,
|
||||
origin: runtimeOriginForConfig(input.config, input.port),
|
||||
...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
|
||||
startedAt: DateTime.formatIso(now),
|
||||
}));
|
||||
|
||||
@@ -100,6 +107,31 @@ export const clearPersistedServerRuntimeState = (path: string) =>
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Whether the process that wrote a runtime-state file is still alive.
|
||||
*
|
||||
* The file is removed by a release finalizer, so a server killed with SIGKILL —
|
||||
* or one that crashed — leaves it behind. Treating a leftover file as "the
|
||||
* server is up" points callers at a port nothing is listening on. Signal 0
|
||||
* performs the permission and existence checks without delivering a signal.
|
||||
*
|
||||
* PIDs are reused eventually, so a false positive is possible in principle;
|
||||
* that is acceptable for local dev tooling, where the alternative is an
|
||||
* HTTP probe that has to guess how long to wait for a starting server.
|
||||
*/
|
||||
export const isPersistedServerRuntimeStateLive = (
|
||||
state: PersistedServerRuntimeState,
|
||||
): Effect.Effect<boolean> =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
process.kill(state.pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
// EPERM means the process exists but belongs to another user.
|
||||
return (cause as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
});
|
||||
|
||||
export const readPersistedServerRuntimeState = (path: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
classifyCheckpointPaths,
|
||||
formatCheckpointCommitMessage,
|
||||
parseCheckpointCommitMessage,
|
||||
parseRawDiffEntries,
|
||||
type RawDiffEntry,
|
||||
} from "./CheckpointAttribution.ts";
|
||||
|
||||
const ZERO_OID = "0".repeat(40);
|
||||
|
||||
function entry(overrides: Partial<RawDiffEntry> & { path: string }): RawDiffEntry {
|
||||
return {
|
||||
srcMode: "100644",
|
||||
dstMode: "100644",
|
||||
srcOid: "a".repeat(40),
|
||||
dstOid: "b".repeat(40),
|
||||
status: "M",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("checkpoint commit message metadata", () => {
|
||||
it("round-trips head and branch", () => {
|
||||
const message = formatCheckpointCommitMessage({
|
||||
checkpointRef: "refs/t3/checkpoints/x/turn/3",
|
||||
headOid: "c".repeat(40),
|
||||
branch: "feature/attribution",
|
||||
});
|
||||
expect(parseCheckpointCommitMessage(message)).toEqual({
|
||||
headOid: "c".repeat(40),
|
||||
branch: "feature/attribution",
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips null head (unborn HEAD)", () => {
|
||||
const message = formatCheckpointCommitMessage({
|
||||
checkpointRef: "refs/t3/checkpoints/x/turn/0",
|
||||
headOid: null,
|
||||
branch: null,
|
||||
});
|
||||
expect(parseCheckpointCommitMessage(message)).toEqual({ headOid: null, branch: null });
|
||||
});
|
||||
|
||||
it("returns null for legacy messages without metadata", () => {
|
||||
expect(parseCheckpointCommitMessage("t3 checkpoint ref=refs/t3/checkpoints/x/turn/1")).toBe(
|
||||
null,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseRawDiffEntries", () => {
|
||||
it("parses NUL-separated raw records", () => {
|
||||
const src = "a".repeat(40);
|
||||
const dst = "b".repeat(40);
|
||||
const output = `:100644 100644 ${src} ${dst} M\0src/index.ts\0:000000 100644 ${ZERO_OID} ${dst} A\0new file.ts\0`;
|
||||
expect(parseRawDiffEntries(output)).toEqual([
|
||||
{
|
||||
srcMode: "100644",
|
||||
dstMode: "100644",
|
||||
srcOid: src,
|
||||
dstOid: dst,
|
||||
status: "M",
|
||||
path: "src/index.ts",
|
||||
},
|
||||
{
|
||||
srcMode: "000000",
|
||||
dstMode: "100644",
|
||||
srcOid: ZERO_OID,
|
||||
dstOid: dst,
|
||||
status: "A",
|
||||
path: "new file.ts",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns empty for empty output", () => {
|
||||
expect(parseRawDiffEntries("")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyCheckpointPaths", () => {
|
||||
it("attributes a pull-only change to git", () => {
|
||||
const pulled = entry({ path: "upstream.ts" });
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [pulled],
|
||||
historyDelta: [pulled],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("upstream.ts")).toBe("git");
|
||||
});
|
||||
|
||||
it("attributes tool edits to agent (no history match)", () => {
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [entry({ path: "edited.ts" })],
|
||||
historyDelta: [],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("edited.ts")).toBe("agent");
|
||||
});
|
||||
|
||||
it("keeps a file the agent committed during the turn as agent work", () => {
|
||||
const committed = entry({ path: "committed.ts" });
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [committed],
|
||||
historyDelta: [committed],
|
||||
turnAuthoredPaths: new Set(["committed.ts"]),
|
||||
});
|
||||
expect(origins.get("committed.ts")).toBe("agent");
|
||||
});
|
||||
|
||||
it("attributes a pulled-then-edited file to agent (blob transition differs)", () => {
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [entry({ path: "both.ts", dstOid: "d".repeat(40) })],
|
||||
historyDelta: [entry({ path: "both.ts", dstOid: "e".repeat(40) })],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("both.ts")).toBe("agent");
|
||||
});
|
||||
|
||||
it("attributes mode-only mismatches to agent", () => {
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [entry({ path: "script.sh", dstMode: "100755" })],
|
||||
historyDelta: [entry({ path: "script.sh", dstMode: "100644" })],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("script.sh")).toBe("agent");
|
||||
});
|
||||
|
||||
it("attributes checkout deletions and additions to git", () => {
|
||||
const removed = entry({
|
||||
path: "only-on-old-branch.ts",
|
||||
dstMode: "000000",
|
||||
dstOid: ZERO_OID,
|
||||
status: "D",
|
||||
});
|
||||
const added = entry({
|
||||
path: "only-on-new-branch.ts",
|
||||
srcMode: "000000",
|
||||
srcOid: ZERO_OID,
|
||||
status: "A",
|
||||
});
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [removed, added],
|
||||
historyDelta: [removed, added],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("only-on-old-branch.ts")).toBe("git");
|
||||
expect(origins.get("only-on-new-branch.ts")).toBe("git");
|
||||
});
|
||||
});
|
||||
Binary file not shown.
@@ -29,12 +29,6 @@ import {
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
|
||||
import {
|
||||
classifyCheckpointPaths,
|
||||
formatCheckpointCommitMessage,
|
||||
parseCheckpointCommitMessage,
|
||||
parseRawDiffEntries,
|
||||
} from "./CheckpointAttribution.ts";
|
||||
import * as VcsDriver from "./VcsDriver.ts";
|
||||
import * as VcsProcess from "./VcsProcess.ts";
|
||||
|
||||
@@ -642,22 +636,6 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
}),
|
||||
);
|
||||
|
||||
const resolveHeadBranch = (cwd: string) =>
|
||||
execute({
|
||||
operation: "GitVcsDriver.checkpoints.resolveHeadBranch",
|
||||
cwd,
|
||||
args: ["symbolic-ref", "--short", "--quiet", "HEAD"],
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
return null;
|
||||
}
|
||||
const branch = result.stdout.trim();
|
||||
return branch.length > 0 ? branch : null;
|
||||
}),
|
||||
);
|
||||
|
||||
const resolveGitCommonDir = (cwd: string) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* execute({
|
||||
@@ -691,9 +669,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
.pipe(Effect.ignore);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const headCommit = yield* resolveHeadCommit(input.cwd);
|
||||
const headBranch = yield* resolveHeadBranch(input.cwd);
|
||||
if (headCommit) {
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
@@ -726,11 +703,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
});
|
||||
}
|
||||
|
||||
const message = formatCheckpointCommitMessage({
|
||||
checkpointRef: input.checkpointRef,
|
||||
headOid: headCommit,
|
||||
branch: headBranch,
|
||||
});
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
@@ -875,262 +848,6 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
attributeCheckpointDiff: Effect.fn("GitVcsDriver.checkpoints.attributeCheckpointDiff")(
|
||||
function* (input) {
|
||||
const operation = "GitVcsDriver.checkpoints.attributeCheckpointDiff";
|
||||
|
||||
const readCommitField = (revision: string, format: string) =>
|
||||
execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["log", "-1", `--format=${format}`, revision, "--"],
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trimEnd() : null)));
|
||||
|
||||
const fromMessage = yield* readCommitField(`${input.fromCheckpointRef}^{commit}`, "%B");
|
||||
const toMessage = yield* readCommitField(`${input.toCheckpointRef}^{commit}`, "%B");
|
||||
if (fromMessage === null || toMessage === null) {
|
||||
return null;
|
||||
}
|
||||
const fromMetadata = parseCheckpointCommitMessage(fromMessage);
|
||||
const toMetadata = parseCheckpointCommitMessage(toMessage);
|
||||
// Checkpoints captured before attribution metadata existed: unavailable.
|
||||
if (fromMetadata === null || toMetadata === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// HEAD did not move during the turn (or the repo has no commits):
|
||||
// every tree change is agent-authored. An empty map means "classified,
|
||||
// no git-origin paths".
|
||||
if (fromMetadata.headOid === toMetadata.headOid || fromMetadata.headOid === null) {
|
||||
return new Map<string, "agent" | "git">();
|
||||
}
|
||||
if (toMetadata.headOid === null) {
|
||||
// HEAD disappeared mid-turn (e.g. re-init); fail toward "agent".
|
||||
return new Map<string, "agent" | "git">();
|
||||
}
|
||||
|
||||
const rawDiff = (fromRevision: string, toRevision: string) =>
|
||||
execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"diff-tree",
|
||||
"-r",
|
||||
"-z",
|
||||
"--no-abbrev",
|
||||
"--no-renames",
|
||||
fromRevision,
|
||||
toRevision,
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
}).pipe(
|
||||
Effect.map((result) =>
|
||||
result.exitCode === 0 && !result.stdoutTruncated
|
||||
? parseRawDiffEntries(result.stdout)
|
||||
: null,
|
||||
),
|
||||
);
|
||||
|
||||
const treeDelta = yield* rawDiff(
|
||||
`${input.fromCheckpointRef}^{commit}`,
|
||||
`${input.toCheckpointRef}^{commit}`,
|
||||
);
|
||||
const historyDelta = yield* rawDiff(fromMetadata.headOid, toMetadata.headOid);
|
||||
if (treeDelta === null || historyDelta === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The baseline checkpoint commit is created at turn start, so its
|
||||
// committer timestamp is the turn-start time. Commits in the HEAD
|
||||
// range split three ways:
|
||||
// - authored at/after turn start: made during the turn → agent work.
|
||||
// - authored before AND committed before: pre-existing content that
|
||||
// moved into the range wholesale (pull, checkout, merge fast path).
|
||||
// - authored before but COMMITTED during the turn: rewritten by a
|
||||
// history-editing command. Cherry-pick and rebase preserve author
|
||||
// dates while re-committing, and so does `commit --amend` — but an
|
||||
// amend carries NEW agent content while a replay carries old
|
||||
// content. Disambiguated below by patch-id (--verbatim, so
|
||||
// whitespace-only amends don't collide with their pre-amend
|
||||
// original): a rewritten commit whose byte-exact patch exists
|
||||
// elsewhere in the repo (branches, remotes, or reflog — the
|
||||
// latter catches pre-rebase originals) is a replay → demote;
|
||||
// otherwise treat as agent work → show.
|
||||
const fromCommitTimeRaw = yield* readCommitField(
|
||||
`${input.fromCheckpointRef}^{commit}`,
|
||||
"%ct",
|
||||
);
|
||||
const fromCommitTime = fromCommitTimeRaw === null ? NaN : Number(fromCommitTimeRaw);
|
||||
if (!Number.isFinite(fromCommitTime)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const headRangeResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"log",
|
||||
"--format=%H %at %ct %p",
|
||||
`${fromMetadata.headOid}..${toMetadata.headOid}`,
|
||||
"--",
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (headRangeResult.exitCode !== 0 || headRangeResult.stdoutTruncated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
interface RangeCommit {
|
||||
readonly oid: string;
|
||||
readonly isMerge: boolean;
|
||||
}
|
||||
const turnAuthoredCommits: Array<RangeCommit> = [];
|
||||
const rewrittenCommits: Array<RangeCommit> = [];
|
||||
for (const line of headRangeResult.stdout.split("\n")) {
|
||||
const [oid, authorTime, commitTime, ...parents] = line.trim().split(" ");
|
||||
if (!oid || !authorTime || !commitTime) {
|
||||
continue;
|
||||
}
|
||||
const authoredAt = Number(authorTime);
|
||||
const committedAt = Number(commitTime);
|
||||
if (!Number.isFinite(authoredAt) || !Number.isFinite(committedAt)) {
|
||||
continue;
|
||||
}
|
||||
const commit: RangeCommit = { oid, isMerge: parents.length > 1 };
|
||||
if (authoredAt >= fromCommitTime) {
|
||||
turnAuthoredCommits.push(commit);
|
||||
} else if (committedAt >= fromCommitTime) {
|
||||
rewrittenCommits.push(commit);
|
||||
}
|
||||
}
|
||||
if (rewrittenCommits.length > 100) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Batch patch-id computation: diff-tree --stdin -p streams every
|
||||
// commit's patch prefixed by its oid, which `git patch-id` consumes
|
||||
// directly. Failures degrade to an empty map, which classifies the
|
||||
// affected rewritten commits as agent work (shown).
|
||||
const patchIdsForCommits = (oids: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
if (oids.length === 0) {
|
||||
return new Map<string, string>();
|
||||
}
|
||||
const patches = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["diff-tree", "--stdin", "-p", "--no-renames", "--root"],
|
||||
stdin: `${oids.join("\n")}\n`,
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (patches.exitCode !== 0 || patches.stdoutTruncated) {
|
||||
return new Map<string, string>();
|
||||
}
|
||||
const ids = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["patch-id", "--verbatim"],
|
||||
stdin: patches.stdout,
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (ids.exitCode !== 0 || ids.stdoutTruncated) {
|
||||
return new Map<string, string>();
|
||||
}
|
||||
const byCommit = new Map<string, string>();
|
||||
for (const line of ids.stdout.split("\n")) {
|
||||
const [patchId, commitId] = line.trim().split(" ");
|
||||
if (patchId && commitId) {
|
||||
byCommit.set(commitId, patchId);
|
||||
}
|
||||
}
|
||||
return byCommit;
|
||||
});
|
||||
|
||||
if (rewrittenCommits.length > 0) {
|
||||
const candidatesResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"rev-list",
|
||||
"-n",
|
||||
"500",
|
||||
"--branches",
|
||||
"--tags",
|
||||
"--remotes",
|
||||
"--reflog",
|
||||
"--not",
|
||||
toMetadata.headOid,
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
const candidateOids =
|
||||
candidatesResult.exitCode === 0 && !candidatesResult.stdoutTruncated
|
||||
? candidatesResult.stdout.split("\n").filter((line) => line.length > 0)
|
||||
: [];
|
||||
const candidatePatchIds = new Set((yield* patchIdsForCommits(candidateOids)).values());
|
||||
const rewrittenPatchIds = yield* patchIdsForCommits(
|
||||
rewrittenCommits.map((commit) => commit.oid),
|
||||
);
|
||||
for (const commit of rewrittenCommits) {
|
||||
const patchId = rewrittenPatchIds.get(commit.oid);
|
||||
if (patchId === undefined || !candidatePatchIds.has(patchId)) {
|
||||
turnAuthoredCommits.push(commit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A pathological number of turn-authored commits (e.g. clock skew
|
||||
// misclassifying a pulled range) would mean one diff-tree call per
|
||||
// commit; skip attribution instead — the diff renders unfiltered.
|
||||
if (turnAuthoredCommits.length > 100) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const turnAuthoredPaths = new Set<string>();
|
||||
for (const commit of turnAuthoredCommits) {
|
||||
const pathsResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"diff-tree",
|
||||
"-r",
|
||||
"-z",
|
||||
"--no-commit-id",
|
||||
"--name-only",
|
||||
// Root commits (orphan branches) have no parent; without
|
||||
// --root they would list no paths and their agent-authored
|
||||
// content would be misattributed to history.
|
||||
"--root",
|
||||
// For merges, the combined diff lists only paths whose result
|
||||
// differs from every parent — i.e. conflict resolutions the
|
||||
// agent authored. Paths taken wholesale from one side are
|
||||
// pre-existing content and stay attributable to history.
|
||||
...(commit.isMerge ? ["-c"] : []),
|
||||
commit.oid,
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (pathsResult.exitCode !== 0 || pathsResult.stdoutTruncated) {
|
||||
return null;
|
||||
}
|
||||
for (const pathValue of pathsResult.stdout.split("\0")) {
|
||||
if (pathValue.length > 0) {
|
||||
turnAuthoredPaths.add(pathValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return classifyCheckpointPaths({ treeDelta, historyDelta, turnAuthoredPaths });
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -38,24 +38,6 @@ export interface VcsDeleteCheckpointRefsInput {
|
||||
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
|
||||
}
|
||||
|
||||
export interface VcsAttributeCheckpointDiffInput {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-path attribution of a checkpoint-to-checkpoint tree delta.
|
||||
*
|
||||
* Paths mapped to "git" are byte-for-byte explained by pre-existing commits
|
||||
* that moved through HEAD during the turn (pull, checkout, cherry-pick,
|
||||
* rebase). Paths mapped to "agent" — and paths absent from the map — were
|
||||
* authored during the turn. `null` means attribution is unavailable (HEAD
|
||||
* metadata missing on either snapshot); callers must treat every path as
|
||||
* agent-authored.
|
||||
*/
|
||||
export type VcsCheckpointAttribution = ReadonlyMap<string, "agent" | "git"> | null;
|
||||
|
||||
export interface VcsCheckpointOps {
|
||||
readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect<void, VcsError>;
|
||||
readonly hasCheckpointRef: (
|
||||
@@ -68,9 +50,6 @@ export interface VcsCheckpointOps {
|
||||
readonly deleteCheckpointRefs: (
|
||||
input: VcsDeleteCheckpointRefsInput,
|
||||
) => Effect.Effect<void, VcsError>;
|
||||
readonly attributeCheckpointDiff: (
|
||||
input: VcsAttributeCheckpointDiffInput,
|
||||
) => Effect.Effect<VcsCheckpointAttribution, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsDriver extends Context.Service<
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolveLocalCheckoutBranchMismatch,
|
||||
resolvePreviousWorktreeLabel,
|
||||
resolvePreviousWorktreeSeed,
|
||||
shouldIncludeBranchPickerItem,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
@@ -19,6 +21,91 @@ import {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
|
||||
describe("resolvePreviousWorktreeSeed", () => {
|
||||
it("picks the most recently updated worktree thread", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [
|
||||
{
|
||||
branch: "t3/older",
|
||||
worktreePath: "/repo/.t3/worktrees/older",
|
||||
updatedAt: "2026-07-20T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
branch: "t3/newer",
|
||||
worktreePath: "/repo/.t3/worktrees/newer",
|
||||
updatedAt: "2026-07-22T00:00:00.000Z",
|
||||
},
|
||||
{ branch: "main", worktreePath: null, updatedAt: "2026-07-23T00:00:00.000Z" },
|
||||
],
|
||||
currentWorktreePath: null,
|
||||
}),
|
||||
).toEqual({ branch: "t3/newer", worktreePath: "/repo/.t3/worktrees/newer" });
|
||||
});
|
||||
|
||||
it("skips the worktree the composer already points at", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [
|
||||
{
|
||||
branch: "t3/current",
|
||||
worktreePath: "/repo/.t3/worktrees/current",
|
||||
updatedAt: "2026-07-22T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
currentWorktreePath: "/repo/.t3/worktrees/current",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when no thread has a worktree", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [{ branch: "main", worktreePath: null, updatedAt: "2026-07-22T00:00:00.000Z" }],
|
||||
currentWorktreePath: null,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores archived threads and threads with unparseable timestamps", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [
|
||||
{
|
||||
branch: "t3/archived",
|
||||
worktreePath: "/repo/.t3/worktrees/archived",
|
||||
updatedAt: "2026-07-23T00:00:00.000Z",
|
||||
archivedAt: "2026-07-23T01:00:00.000Z",
|
||||
},
|
||||
{
|
||||
branch: "t3/garbage-timestamp",
|
||||
worktreePath: "/repo/.t3/worktrees/garbage",
|
||||
updatedAt: "not-a-date",
|
||||
},
|
||||
{
|
||||
branch: "t3/live",
|
||||
worktreePath: "/repo/.t3/worktrees/live",
|
||||
updatedAt: "2026-07-21T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
},
|
||||
],
|
||||
currentWorktreePath: null,
|
||||
}),
|
||||
).toEqual({ branch: "t3/live", worktreePath: "/repo/.t3/worktrees/live" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePreviousWorktreeLabel", () => {
|
||||
it("includes the branch when known", () => {
|
||||
expect(resolvePreviousWorktreeLabel({ branch: "t3/fix-thing", worktreePath: "/wt" })).toBe(
|
||||
"Previous worktree (t3/fix-thing)",
|
||||
);
|
||||
expect(resolvePreviousWorktreeLabel({ branch: null, worktreePath: "/wt" })).toBe(
|
||||
"Previous worktree",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
|
||||
expect(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { toSortableTimestamp } from "../lib/threadSort";
|
||||
export {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
@@ -65,6 +66,53 @@ export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null):
|
||||
return activeWorktreePath ? "Worktree" : "Local checkout";
|
||||
}
|
||||
|
||||
export interface PreviousWorktreeSeed {
|
||||
branch: string | null;
|
||||
worktreePath: string;
|
||||
}
|
||||
|
||||
// The most recently touched worktree in the project that the composer isn't
|
||||
// already pointing at. Backs the "Previous worktree" entry in the workspace
|
||||
// selector so a follow-up thread can hop back into the worktree you just
|
||||
// worked in without hunting for its branch. Archived threads don't compete —
|
||||
// the rest of the UI hides them, so their worktrees shouldn't resurface here.
|
||||
export function resolvePreviousWorktreeSeed(input: {
|
||||
threads: ReadonlyArray<{
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
updatedAt: string;
|
||||
archivedAt?: string | null;
|
||||
}>;
|
||||
currentWorktreePath: string | null;
|
||||
}): PreviousWorktreeSeed | null {
|
||||
let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
|
||||
for (const thread of input.threads) {
|
||||
if (
|
||||
!thread.worktreePath ||
|
||||
thread.worktreePath === input.currentWorktreePath ||
|
||||
(thread.archivedAt ?? null) !== null
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const updatedAt = toSortableTimestamp(thread.updatedAt);
|
||||
if (updatedAt === null) {
|
||||
continue;
|
||||
}
|
||||
if (latest === null || updatedAt > latest.updatedAt) {
|
||||
latest = {
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
|
||||
}
|
||||
|
||||
export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
|
||||
return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
|
||||
}
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
hasServerThread: boolean;
|
||||
|
||||
@@ -6,12 +6,13 @@ import {
|
||||
FolderGit2Icon,
|
||||
FolderGitIcon,
|
||||
FolderIcon,
|
||||
HistoryIcon,
|
||||
MonitorIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useMemo } from "react";
|
||||
import { memo, useCallback, useMemo } from "react";
|
||||
|
||||
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
|
||||
import { useIsMobile } from "../hooks/useMediaQuery";
|
||||
import {
|
||||
type EnvMode,
|
||||
@@ -20,6 +21,8 @@ import {
|
||||
resolveEnvModeLabel,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolvePreviousWorktreeLabel,
|
||||
resolvePreviousWorktreeSeed,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
@@ -66,6 +69,8 @@ interface MobileRunContextSelectorProps {
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
previousWorktreeLabel: string | null;
|
||||
onUsePreviousWorktree: () => void;
|
||||
}
|
||||
|
||||
const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
@@ -79,6 +84,8 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
onEnvModeChange,
|
||||
previousWorktreeLabel,
|
||||
onUsePreviousWorktree,
|
||||
}: MobileRunContextSelectorProps) {
|
||||
const activeEnvironment = useMemo(
|
||||
() => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null,
|
||||
@@ -166,7 +173,13 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<MenuGroupLabel>Workspace</MenuGroupLabel>
|
||||
<MenuRadioGroup
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
onValueChange={(value) => {
|
||||
if (value === "previous-worktree") {
|
||||
onUsePreviousWorktree();
|
||||
return;
|
||||
}
|
||||
onEnvModeChange(value as EnvMode);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem disabled={envModeLocked} value="local">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
@@ -186,6 +199,14 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
{previousWorktreeLabel ? (
|
||||
<MenuRadioItem disabled={envModeLocked} value="previous-worktree">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
<HistoryIcon className="size-3" />
|
||||
<span className="min-w-0 truncate">{previousWorktreeLabel}</span>
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
) : null}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</MenuPopup>
|
||||
@@ -217,6 +238,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const activeProjectRef = serverThread
|
||||
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
|
||||
: draftThread
|
||||
@@ -234,6 +256,40 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
});
|
||||
const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
|
||||
|
||||
// "Previous worktree" hops a draft into the most recently active worktree
|
||||
// of this project — the "keep going where I just was" follow-up flow. Only
|
||||
// drafts can hop; started server threads have their workspace pinned.
|
||||
const canUsePreviousWorktree = draftThread !== null && serverThread === null && !envModeLocked;
|
||||
const projectRefsForWorktreeLookup = useMemo(
|
||||
() => (canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []),
|
||||
[canUsePreviousWorktree, activeProjectRef],
|
||||
);
|
||||
const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
|
||||
const previousWorktreeSeed = useMemo(
|
||||
() =>
|
||||
canUsePreviousWorktree
|
||||
? resolvePreviousWorktreeSeed({
|
||||
threads: projectThreads,
|
||||
currentWorktreePath: activeWorktreePath,
|
||||
})
|
||||
: null,
|
||||
[activeWorktreePath, canUsePreviousWorktree, projectThreads],
|
||||
);
|
||||
const previousWorktreeLabel = previousWorktreeSeed
|
||||
? resolvePreviousWorktreeLabel(previousWorktreeSeed)
|
||||
: null;
|
||||
const onUsePreviousWorktree = useCallback(() => {
|
||||
if (!previousWorktreeSeed || !activeProjectRef) return;
|
||||
// Same shape the branch selector writes when picking a branch that
|
||||
// already lives in a worktree: point the draft at the existing tree.
|
||||
setDraftThreadContext(draftId ?? threadRef, {
|
||||
branch: previousWorktreeSeed.branch,
|
||||
worktreePath: previousWorktreeSeed.worktreePath,
|
||||
envMode: "worktree",
|
||||
projectRef: activeProjectRef,
|
||||
});
|
||||
}, [activeProjectRef, draftId, previousWorktreeSeed, setDraftThreadContext, threadRef]);
|
||||
|
||||
const showEnvironmentPicker = Boolean(
|
||||
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
|
||||
);
|
||||
@@ -248,7 +304,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
if (!hasActiveThread || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<div className="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-1.5rem)] max-w-[calc(48rem-1.5rem)] items-center gap-2 pt-5 pb-1 ps-1">
|
||||
<div className="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 px-1 pt-5 pb-1">
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
@@ -261,6 +317,8 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
previousWorktreeLabel={previousWorktreeLabel}
|
||||
onUsePreviousWorktree={onUsePreviousWorktree}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
@@ -280,6 +338,8 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
previousWorktreeLabel={previousWorktreeLabel}
|
||||
onUsePreviousWorktree={onUsePreviousWorktree}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -731,7 +731,7 @@ export function BranchToolbarBranchSelector({
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="min-w-0 text-muted-foreground/70 hover:text-foreground/80"
|
||||
className="min-w-0 max-w-full text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={isInitialBranchesLoadPending || isBranchActionPending}
|
||||
>
|
||||
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon } from "lucide-react";
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon, HistoryIcon } from "lucide-react";
|
||||
import { memo, useMemo } from "react";
|
||||
|
||||
import {
|
||||
@@ -17,11 +17,15 @@ import {
|
||||
SelectValue,
|
||||
} from "./ui/select";
|
||||
|
||||
export const PREVIOUS_WORKTREE_SELECT_VALUE = "previous-worktree";
|
||||
|
||||
interface BranchToolbarEnvModeSelectorProps {
|
||||
envLocked: boolean;
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
previousWorktreeLabel?: string | null;
|
||||
onUsePreviousWorktree?: () => void;
|
||||
}
|
||||
|
||||
export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({
|
||||
@@ -29,13 +33,19 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
onEnvModeChange,
|
||||
previousWorktreeLabel,
|
||||
onUsePreviousWorktree,
|
||||
}: BranchToolbarEnvModeSelectorProps) {
|
||||
const showPreviousWorktree = Boolean(previousWorktreeLabel && onUsePreviousWorktree);
|
||||
const envModeItems = useMemo(
|
||||
() => [
|
||||
{ value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) },
|
||||
{ value: "worktree", label: resolveEnvModeLabel("worktree") },
|
||||
...(showPreviousWorktree && previousWorktreeLabel
|
||||
? [{ value: PREVIOUS_WORKTREE_SELECT_VALUE, label: previousWorktreeLabel }]
|
||||
: []),
|
||||
],
|
||||
[activeWorktreePath],
|
||||
[activeWorktreePath, previousWorktreeLabel, showPreviousWorktree],
|
||||
);
|
||||
|
||||
if (envLocked) {
|
||||
@@ -60,7 +70,13 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
<Select
|
||||
modal={false}
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
onValueChange={(value: string | null) => {
|
||||
if (value === PREVIOUS_WORKTREE_SELECT_VALUE) {
|
||||
onUsePreviousWorktree?.();
|
||||
return;
|
||||
}
|
||||
onEnvModeChange(value as EnvMode);
|
||||
}}
|
||||
items={envModeItems}
|
||||
>
|
||||
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Workspace">
|
||||
@@ -92,6 +108,14 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
{resolveEnvModeLabel("worktree")}
|
||||
</span>
|
||||
</SelectItem>
|
||||
{showPreviousWorktree && previousWorktreeLabel ? (
|
||||
<SelectItem value={PREVIOUS_WORKTREE_SELECT_VALUE}>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<HistoryIcon className="size-3" />
|
||||
{previousWorktreeLabel}
|
||||
</span>
|
||||
</SelectItem>
|
||||
) : null}
|
||||
</SelectGroup>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
|
||||
@@ -12,16 +12,20 @@ import type { Thread } from "../types";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
branchMismatchKey,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildThreadTurnInterruptInput,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
dismissBranchMismatchForSession,
|
||||
getStartedThreadModelChangeBlockReason,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
isBranchMismatchDismissedForSession,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
reconcileRetainedMountedThreadIds,
|
||||
resolveThreadMetadataUpdateForNextTurn,
|
||||
resolveSendEnvMode,
|
||||
shouldShowBranchMismatchBanner,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
} from "./ChatView.logic";
|
||||
|
||||
@@ -292,6 +296,61 @@ describe("resolveSendEnvMode", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("branchMismatchKey", () => {
|
||||
it("builds a key from thread id and both branches", () => {
|
||||
expect(branchMismatchKey("thread-1", { threadBranch: "feat/a", currentBranch: "feat/b" })).toBe(
|
||||
"thread-1:feat/a:feat/b",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null without a thread or mismatch", () => {
|
||||
expect(branchMismatchKey(null, { threadBranch: "a", currentBranch: "b" })).toBeNull();
|
||||
expect(branchMismatchKey("thread-1", null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldShowBranchMismatchBanner", () => {
|
||||
const base = {
|
||||
hasMismatch: true,
|
||||
isDismissed: false,
|
||||
composerHasContent: false,
|
||||
wasShownForCurrentMismatch: false,
|
||||
};
|
||||
|
||||
it("stays hidden during passive browsing (even though the composer autofocuses)", () => {
|
||||
expect(shouldShowBranchMismatchBanner(base)).toBe(false);
|
||||
});
|
||||
|
||||
it("shows once the composer has draft content", () => {
|
||||
expect(shouldShowBranchMismatchBanner({ ...base, composerHasContent: true })).toBe(true);
|
||||
});
|
||||
|
||||
it("stays mounted after the draft clears once shown for the current mismatch", () => {
|
||||
expect(shouldShowBranchMismatchBanner({ ...base, wasShownForCurrentMismatch: true })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("never shows when dismissed or without a mismatch", () => {
|
||||
expect(
|
||||
shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, isDismissed: true }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, hasMismatch: false }),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("session branch mismatch dismissal", () => {
|
||||
it("tracks dismissed keys and treats other keys as active", () => {
|
||||
expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(false);
|
||||
dismissBranchMismatchForSession("t1:a:b");
|
||||
expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(true);
|
||||
expect(isBranchMismatchDismissedForSession("t1:a:c")).toBe(false);
|
||||
expect(isBranchMismatchDismissedForSession(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileMountedTerminalThreadIds", () => {
|
||||
it("keeps open threads and makes the active thread most recent", () => {
|
||||
expect(
|
||||
|
||||
@@ -289,6 +289,46 @@ export function buildExpiredTerminalContextToastCopy(
|
||||
};
|
||||
}
|
||||
|
||||
export function branchMismatchKey(
|
||||
threadId: string | null,
|
||||
mismatch: { threadBranch: string; currentBranch: string } | null,
|
||||
): string | null {
|
||||
if (!threadId || !mismatch) {
|
||||
return null;
|
||||
}
|
||||
return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
|
||||
}
|
||||
|
||||
// The mismatch banner only matters when the user is about to send: passive
|
||||
// reading of an old thread carries no risk (the branch picker tint already
|
||||
// covers ambient awareness). Draft content is the intent signal — composer
|
||||
// focus is useless here because ChatView autofocuses the composer on every
|
||||
// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
|
||||
// revealed so it doesn't flicker away when the draft is cleared.
|
||||
export function shouldShowBranchMismatchBanner(input: {
|
||||
hasMismatch: boolean;
|
||||
isDismissed: boolean;
|
||||
composerHasContent: boolean;
|
||||
wasShownForCurrentMismatch: boolean;
|
||||
}): boolean {
|
||||
if (!input.hasMismatch || input.isDismissed) {
|
||||
return false;
|
||||
}
|
||||
return input.composerHasContent || input.wasShownForCurrentMismatch;
|
||||
}
|
||||
|
||||
// Session-scoped (module-level so it survives ChatView remounts, e.g. route
|
||||
// changes). Durable cross-device dismissal is planned as a server-side ack.
|
||||
const sessionDismissedBranchMismatchKeys = new Set<string>();
|
||||
|
||||
export function dismissBranchMismatchForSession(key: string): void {
|
||||
sessionDismissedBranchMismatchKeys.add(key);
|
||||
}
|
||||
|
||||
export function isBranchMismatchDismissedForSession(key: string | null): boolean {
|
||||
return key !== null && sessionDismissedBranchMismatchKeys.has(key);
|
||||
}
|
||||
|
||||
export function threadHasStarted(thread: Thread | null | undefined): boolean {
|
||||
return Boolean(
|
||||
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
@@ -138,7 +139,14 @@ import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
|
||||
import {
|
||||
AlarmClockIcon,
|
||||
CheckCircle2Icon,
|
||||
ChevronDownIcon,
|
||||
GitBranchIcon,
|
||||
TriangleAlertIcon,
|
||||
WifiOffIcon,
|
||||
} from "lucide-react";
|
||||
import { cn, randomHex } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
@@ -153,7 +161,8 @@ import {
|
||||
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
|
||||
import { useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { useNowMinute } from "../hooks/useNowMinute";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { getTerminalFocusOwner } from "../lib/terminalFocus";
|
||||
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
|
||||
@@ -202,6 +211,7 @@ import {
|
||||
useThread,
|
||||
useThreadProposedPlans,
|
||||
useThreadRefs,
|
||||
useThreadShell,
|
||||
} from "../state/entities";
|
||||
import { environmentShell } from "../state/shell";
|
||||
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
|
||||
@@ -220,6 +230,7 @@ import {
|
||||
shouldShowProviderStatusBanner,
|
||||
} from "./chat/ProviderStatusBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import { resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
|
||||
import {
|
||||
DRAFT_HERO_TRANSITION_ANIMATION_ID,
|
||||
@@ -231,13 +242,17 @@ import {
|
||||
} from "./chat/draftHeroTransition";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
branchMismatchKey,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildLocalDraftThread,
|
||||
buildThreadTurnInterruptInput,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
dismissBranchMismatchForSession,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
isBranchMismatchDismissedForSession,
|
||||
shouldShowBranchMismatchBanner,
|
||||
getStartedThreadModelChangeBlockReason,
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
LastInvokedScriptByProjectSchema,
|
||||
@@ -260,6 +275,16 @@ import { RightPanelSheet } from "./RightPanelSheet";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogClose,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogPopup,
|
||||
AlertDialogTitle,
|
||||
} from "./ui/alert-dialog";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { ServerUpdateAction } from "./ServerUpdateAction";
|
||||
import {
|
||||
buildVersionMismatchDismissalKey,
|
||||
@@ -2352,6 +2377,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null;
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const showComposerContextStrip = isGitRepo && activeProject !== null;
|
||||
const initialDiffPanelGitScope =
|
||||
gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch";
|
||||
const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending";
|
||||
@@ -3808,52 +3834,159 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: null,
|
||||
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
|
||||
);
|
||||
const [branchRepairAction, setBranchRepairAction] = useState<
|
||||
"update-thread" | "switch-checkout" | null
|
||||
>(null);
|
||||
const handleUpdateThreadToCheckout = useCallback(async () => {
|
||||
if (!activeThread || !localCheckoutBranchMismatch || branchRepairAction !== null) {
|
||||
return;
|
||||
}
|
||||
setBranchRepairAction("update-thread");
|
||||
const updateResult = await updateThreadMetadata({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: activeThread.id,
|
||||
branch: localCheckoutBranchMismatch.currentBranch,
|
||||
worktreePath: null,
|
||||
},
|
||||
// Settled state of the open thread, resolved exactly like the sidebar
|
||||
// partition (same shell, same capability gate, same PR auto-settle input)
|
||||
// so the banner and the sidebar row never disagree.
|
||||
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
|
||||
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
|
||||
const activeThreadPr = resolveThreadPr({
|
||||
threadBranch: activeThread?.branch ?? null,
|
||||
gitStatus: gitStatusQuery.data ?? null,
|
||||
hasDedicatedWorktree: (activeThread?.worktreePath ?? null) !== null,
|
||||
});
|
||||
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
|
||||
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
|
||||
const nowMinute = useNowMinute();
|
||||
const activeThreadSnoozed =
|
||||
activeThreadShell !== null &&
|
||||
supportsSnooze &&
|
||||
effectiveSnoozed(activeThreadShell, { now: new Date().toISOString() });
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
void snoozeWakeTick;
|
||||
if (!activeThreadSnoozed) return;
|
||||
const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
|
||||
if (!Number.isFinite(wakeAtMs)) return;
|
||||
const id = window.setTimeout(
|
||||
() => bumpSnoozeWakeTick((tick) => tick + 1),
|
||||
Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
|
||||
);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
|
||||
const activeThreadSettled = useMemo(() => {
|
||||
if (activeThreadShell === null || !supportsSettlement) return false;
|
||||
return effectiveSettled(activeThreadShell, {
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
autoSettleAfterDays,
|
||||
changeRequestState: activeThreadPr?.state ?? null,
|
||||
});
|
||||
setBranchRepairAction(null);
|
||||
if (updateResult._tag === "Failure" && !isAtomCommandInterrupted(updateResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to update thread branch",
|
||||
description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
scheduleComposerFocus();
|
||||
}, [
|
||||
activeThread,
|
||||
branchRepairAction,
|
||||
environmentId,
|
||||
localCheckoutBranchMismatch,
|
||||
scheduleComposerFocus,
|
||||
updateThreadMetadata,
|
||||
activeThreadPr?.state,
|
||||
activeThreadShell,
|
||||
autoSettleAfterDays,
|
||||
nowMinute,
|
||||
supportsSettlement,
|
||||
]);
|
||||
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
|
||||
reportFailure: false,
|
||||
});
|
||||
// Keyed by thread, not a boolean: the pending state must follow the thread
|
||||
// it belongs to across navigation, and a request resolving for thread A
|
||||
// must never clear (or re-enable) thread B's button.
|
||||
const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
|
||||
const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
|
||||
const handleUnsettleActiveThread = useCallback(async () => {
|
||||
if (!activeThreadRef) return;
|
||||
const threadKey = scopedThreadKey(activeThreadRef);
|
||||
setUnsettlingThreadKey(threadKey);
|
||||
try {
|
||||
const result = await unsettleThreadMutation({
|
||||
environmentId: activeThreadRef.environmentId,
|
||||
input: { threadId: activeThreadRef.threadId, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to un-settle thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
|
||||
}
|
||||
}, [activeThreadRef, unsettleThreadMutation]);
|
||||
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
|
||||
const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
|
||||
const handleUnsnoozeActiveThread = useCallback(async () => {
|
||||
if (!activeThreadRef) return;
|
||||
const threadKey = scopedThreadKey(activeThreadRef);
|
||||
setUnsnoozingThreadKey(threadKey);
|
||||
try {
|
||||
const result = await unsnoozeThreadMutation({
|
||||
environmentId: activeThreadRef.environmentId,
|
||||
input: { threadId: activeThreadRef.threadId, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to wake thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
|
||||
}
|
||||
}, [activeThreadRef, unsnoozeThreadMutation]);
|
||||
const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
|
||||
const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
|
||||
// Once revealed for a given mismatch, the banner stays mounted until the
|
||||
// mismatch changes or resolves, so clearing the draft doesn't flicker it.
|
||||
const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
|
||||
// Dismissal lives in a module-level set (survives remounts); this tick just
|
||||
// forces a re-render so the banner leaves immediately.
|
||||
const [, setBranchMismatchDismissTick] = useState(0);
|
||||
const composerHasDraftContent = useComposerDraftStore((store) => {
|
||||
const draft = store.getComposerDraft(composerDraftTarget);
|
||||
return Boolean(
|
||||
draft &&
|
||||
(draft.prompt.trim().length > 0 ||
|
||||
draft.images.length > 0 ||
|
||||
draft.terminalContexts.length > 0 ||
|
||||
draft.elementContexts.length > 0 ||
|
||||
draft.previewAnnotations.length > 0 ||
|
||||
draft.reviewComments.length > 0),
|
||||
);
|
||||
});
|
||||
const activeBranchMismatchKey = branchMismatchKey(
|
||||
activeThread?.id ?? null,
|
||||
localCheckoutBranchMismatch,
|
||||
);
|
||||
const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
|
||||
hasMismatch: localCheckoutBranchMismatch !== null,
|
||||
isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
|
||||
composerHasContent: composerHasDraftContent,
|
||||
wasShownForCurrentMismatch:
|
||||
revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
|
||||
});
|
||||
useEffect(() => {
|
||||
setRevealedBranchMismatchKey((revealed) => {
|
||||
if (showBranchMismatchBanner) {
|
||||
return activeBranchMismatchKey;
|
||||
}
|
||||
// Hysteresis is scoped to an uninterrupted mismatch: reset when the
|
||||
// mismatch resolves or changes so a recurrence re-gates on intent.
|
||||
return revealed !== null && revealed !== activeBranchMismatchKey ? null : revealed;
|
||||
});
|
||||
}, [activeBranchMismatchKey, showBranchMismatchBanner]);
|
||||
const handleSwitchCheckoutToThread = useCallback(async () => {
|
||||
if (
|
||||
!activeProjectCwd ||
|
||||
!activeThread ||
|
||||
!localCheckoutBranchMismatch ||
|
||||
branchRepairAction !== null
|
||||
isRestoringThreadBranch
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setBranchRepairAction("switch-checkout");
|
||||
setIsRestoringThreadBranch(true);
|
||||
const checkoutResult = await switchGitRef({
|
||||
environmentId,
|
||||
input: {
|
||||
@@ -3862,7 +3995,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
},
|
||||
});
|
||||
if (checkoutResult._tag === "Failure") {
|
||||
setBranchRepairAction(null);
|
||||
setIsRestoringThreadBranch(false);
|
||||
if (!isAtomCommandInterrupted(checkoutResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
@@ -3882,7 +4015,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
|
||||
});
|
||||
if (updateResult._tag === "Failure") {
|
||||
setBranchRepairAction(null);
|
||||
setIsRestoringThreadBranch(false);
|
||||
if (!isAtomCommandInterrupted(updateResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
@@ -3897,76 +4030,125 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
}
|
||||
gitStatusQuery.refresh();
|
||||
setBranchRepairAction(null);
|
||||
setIsRestoringThreadBranch(false);
|
||||
scheduleComposerFocus();
|
||||
}, [
|
||||
activeProjectCwd,
|
||||
activeThread,
|
||||
branchRepairAction,
|
||||
environmentId,
|
||||
gitStatusQuery,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
scheduleComposerFocus,
|
||||
switchGitRef,
|
||||
updateThreadMetadata,
|
||||
]);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
if (!localCheckoutBranchMismatch) {
|
||||
return systemComposerBannerItems;
|
||||
// The stack renders items[0] front-most and tucks the rest behind hover, so
|
||||
// ordering is priority: system banners, then the branch-mismatch notice,
|
||||
// and the informational parked-thread banner last — it must never cover another.
|
||||
const parkedThreadBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
|
||||
if (!activeThreadSnoozed && !activeThreadSettled) {
|
||||
return null;
|
||||
}
|
||||
const isSnoozed = activeThreadSnoozed;
|
||||
return {
|
||||
id: `thread-${isSnoozed ? "snoozed" : "settled"}:${activeThread?.id ?? "unknown"}`,
|
||||
variant: "info",
|
||||
icon: isSnoozed ? <AlarmClockIcon /> : <CheckCircle2Icon />,
|
||||
title: `This thread is ${isSnoozed ? "snoozed" : "settled"}`,
|
||||
description: isSnoozed
|
||||
? "Sending a message wakes it and moves it back to Active in the sidebar."
|
||||
: "Sending a message moves it back to Active in the sidebar.",
|
||||
actions: (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isSnoozed ? isUnsnoozing : isUnsettling}
|
||||
onClick={() =>
|
||||
void (isSnoozed ? handleUnsnoozeActiveThread() : handleUnsettleActiveThread())
|
||||
}
|
||||
>
|
||||
{isSnoozed
|
||||
? isUnsnoozing
|
||||
? "Waking..."
|
||||
: "Wake now"
|
||||
: isUnsettling
|
||||
? "Un-settling..."
|
||||
: "Un-settle"}
|
||||
</Button>
|
||||
),
|
||||
};
|
||||
}, [
|
||||
activeThread?.id,
|
||||
activeThreadSettled,
|
||||
activeThreadSnoozed,
|
||||
handleUnsnoozeActiveThread,
|
||||
handleUnsettleActiveThread,
|
||||
isUnsnoozing,
|
||||
isUnsettling,
|
||||
]);
|
||||
const handleRestoreThreadBranch = useCallback(() => {
|
||||
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
|
||||
setBranchRestoreConfirmOpen(true);
|
||||
return;
|
||||
}
|
||||
void handleSwitchCheckoutToThread();
|
||||
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
|
||||
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
|
||||
return [...systemComposerBannerItems, ...parkedThreadItems];
|
||||
}
|
||||
const isRepairingBranch = branchRepairAction !== null;
|
||||
return [
|
||||
...systemComposerBannerItems,
|
||||
{
|
||||
id: `branch-mismatch:${activeThread?.id ?? "unknown"}:${localCheckoutBranchMismatch.threadBranch}:${localCheckoutBranchMismatch.currentBranch}`,
|
||||
variant: "warning",
|
||||
icon: <TriangleAlertIcon />,
|
||||
title: "You're on a different branch",
|
||||
className:
|
||||
"text-base sm:text-sm [&>div]:items-start max-sm:[&>div]:flex-wrap max-sm:[&>div>div:last-child]:w-full max-sm:[&>div>div:last-child]:self-start dark:shadow-none",
|
||||
actionClassName:
|
||||
"max-sm:w-full max-sm:border-t max-sm:border-border/60 max-sm:pt-2 max-sm:pl-6 sm:border-l sm:border-border/60 sm:pl-3",
|
||||
description: (
|
||||
<p className="text-pretty">
|
||||
This thread is on{" "}
|
||||
<code className="font-medium text-foreground">
|
||||
{localCheckoutBranchMismatch.threadBranch}
|
||||
</code>
|
||||
, but you're currently checked out at{" "}
|
||||
<code className="font-medium text-foreground">
|
||||
{localCheckoutBranchMismatch.currentBranch}
|
||||
</code>
|
||||
. Sending a message will update the thread.
|
||||
</p>
|
||||
id: `branch-mismatch:${activeBranchMismatchKey}`,
|
||||
variant: "info",
|
||||
icon: <GitBranchIcon />,
|
||||
title: (
|
||||
<span className="flex min-w-0 items-baseline gap-1.5">
|
||||
<span className="shrink-0 font-normal text-muted-foreground">Branch changed — was</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<code className="min-w-0 truncate font-medium text-foreground">
|
||||
{localCheckoutBranchMismatch.threadBranch}
|
||||
</code>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-80">
|
||||
This thread last ran on {localCheckoutBranchMismatch.threadBranch}. Sending will
|
||||
continue on {localCheckoutBranchMismatch.currentBranch}.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</span>
|
||||
),
|
||||
className: "dark:shadow-none",
|
||||
actions: (
|
||||
<>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isRepairingBranch}
|
||||
onClick={() => void handleUpdateThreadToCheckout()}
|
||||
>
|
||||
{branchRepairAction === "update-thread" ? "Moving..." : "Move thread here"}
|
||||
</Button>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={isRepairingBranch}
|
||||
onClick={() => void handleSwitchCheckoutToThread()}
|
||||
>
|
||||
{branchRepairAction === "switch-checkout" ? "Switching..." : "Checkout thread branch"}
|
||||
</Button>
|
||||
</>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={isRestoringThreadBranch}
|
||||
onClick={handleRestoreThreadBranch}
|
||||
>
|
||||
{isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
|
||||
</Button>
|
||||
),
|
||||
dismissLabel: "Dismiss branch change notice",
|
||||
onDismiss: () => {
|
||||
dismissBranchMismatchForSession(activeBranchMismatchKey);
|
||||
setBranchMismatchDismissTick((tick) => tick + 1);
|
||||
},
|
||||
},
|
||||
...parkedThreadItems,
|
||||
];
|
||||
}, [
|
||||
activeThread?.id,
|
||||
branchRepairAction,
|
||||
handleSwitchCheckoutToThread,
|
||||
handleUpdateThreadToCheckout,
|
||||
activeBranchMismatchKey,
|
||||
handleRestoreThreadBranch,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
parkedThreadBannerItem,
|
||||
showBranchMismatchBanner,
|
||||
systemComposerBannerItems,
|
||||
]);
|
||||
|
||||
@@ -5592,119 +5774,128 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div className="chat-composer-glass-host relative z-10 mx-auto w-full max-w-3xl rounded-[22px]">
|
||||
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
|
||||
projectSelectionRequired={isLocalDraftThread && activeProject === null}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={
|
||||
onSelectActivePendingUserInputOption
|
||||
}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"chat-composer-glass-shell relative mx-auto w-full max-w-3xl",
|
||||
showComposerContextStrip && "chat-composer-glass-shell-with-context",
|
||||
)}
|
||||
>
|
||||
<div className="chat-composer-glass-host relative z-10 w-full rounded-[22px]">
|
||||
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
|
||||
projectSelectionRequired={isLocalDraftThread && activeProject === null}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={
|
||||
activeProject?.defaultModelSelection
|
||||
}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={
|
||||
onSelectActivePendingUserInputOption
|
||||
}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-h-0">
|
||||
<div
|
||||
data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
|
||||
className="relative z-0"
|
||||
>
|
||||
{isGitRepo && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange:
|
||||
setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="min-h-0">
|
||||
<div
|
||||
data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
|
||||
className="relative z-0"
|
||||
>
|
||||
{showComposerContextStrip && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange:
|
||||
setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
@@ -5716,6 +5907,36 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={branchRestoreConfirmOpen} onOpenChange={setBranchRestoreConfirmOpen}>
|
||||
<AlertDialogPopup>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
Switch to{" "}
|
||||
<code className="font-medium">
|
||||
{localCheckoutBranchMismatch?.threadBranch ?? ""}
|
||||
</code>
|
||||
?
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
You have uncommitted changes. They'll carry over to the other branch, or block
|
||||
the switch if they conflict.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
setBranchRestoreConfirmOpen(false);
|
||||
void handleSwitchCheckoutToThread();
|
||||
}}
|
||||
>
|
||||
Switch branch
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogPopup>
|
||||
</AlertDialog>
|
||||
|
||||
{pullRequestDialogState ? (
|
||||
<PullRequestThreadDialog
|
||||
key={pullRequestDialogState.key}
|
||||
|
||||
@@ -58,11 +58,7 @@ import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
|
||||
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
import {
|
||||
resolveThreadActionProjectRef,
|
||||
startNewThreadInProjectFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import {
|
||||
appendBrowsePathSegment,
|
||||
canNavigateUp,
|
||||
@@ -837,13 +833,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
projectRef.environmentId === contextualProjectRef.environmentId &&
|
||||
projectRef.projectId === contextualProjectRef.projectId,
|
||||
);
|
||||
await startNewThreadInProjectFromContext(
|
||||
{
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
},
|
||||
await handleNewThread(
|
||||
contextualRefBelongsToGroup
|
||||
? contextualProjectRef
|
||||
: scopeProjectRef(project.environmentId, project.id),
|
||||
@@ -851,15 +841,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
},
|
||||
}),
|
||||
),
|
||||
[
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
contextualProjectRef,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
pickerProjects,
|
||||
projectGroupByTargetKey,
|
||||
],
|
||||
[contextualProjectRef, handleNewThread, pickerProjects, projectGroupByTargetKey],
|
||||
);
|
||||
|
||||
const allThreadItems = useMemo(
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsDownUpIcon,
|
||||
ChevronsUpDownIcon,
|
||||
Columns2Icon,
|
||||
PilcrowIcon,
|
||||
Rows3Icon,
|
||||
@@ -32,6 +34,7 @@ import {
|
||||
resolveDiffThemeName,
|
||||
resolveFileDiffPath,
|
||||
} from "../lib/diffRendering";
|
||||
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
@@ -39,6 +42,7 @@ import { useClientSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
|
||||
import { Button } from "./ui/button";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
import { Switch } from "./ui/switch";
|
||||
import {
|
||||
@@ -194,12 +198,6 @@ export default function DiffPanel({
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
// Scoped per turn selection so revealing git changes on one turn doesn't
|
||||
// leak into other turns or threads.
|
||||
const [includeGitChangesState, setIncludeGitChangesState] = useState<{
|
||||
scopeKey: string | null;
|
||||
value: boolean;
|
||||
}>(() => ({ scopeKey: null, value: false }));
|
||||
const [baseRefQuery, setBaseRefQuery] = useState("");
|
||||
const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
|
||||
scopeKey: null,
|
||||
@@ -317,12 +315,6 @@ export default function DiffPanel({
|
||||
: null,
|
||||
[selectedCheckpointTurnCount],
|
||||
);
|
||||
const includeGitChanges =
|
||||
includeGitChangesState.scopeKey === collapseScopeKey && includeGitChangesState.value;
|
||||
const setIncludeGitChanges = useCallback(
|
||||
(value: boolean) => setIncludeGitChangesState({ scopeKey: collapseScopeKey, value }),
|
||||
[collapseScopeKey],
|
||||
);
|
||||
const activeCheckpointDiff = useCheckpointDiff(
|
||||
{
|
||||
environmentId: activeThread?.environmentId ?? null,
|
||||
@@ -330,17 +322,10 @@ export default function DiffPanel({
|
||||
fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
|
||||
ignoreWhitespace: diffIgnoreWhitespace,
|
||||
includeGitChanges,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : null,
|
||||
},
|
||||
{ enabled: isGitRepo && selectedTurn !== undefined },
|
||||
);
|
||||
// Number of files in the selected turn whose change came from pre-existing
|
||||
// git history; drives the hidden-changes banner. Comes from the diff
|
||||
// response so it reflects the same attribution pass that produced (or
|
||||
// deliberately kept) the rendered patch — the turn summary's origin tags
|
||||
// are computed by a separate pass and could disagree after failures.
|
||||
const selectedTurnGitFileCount = activeCheckpointDiff.data?.gitFileCount ?? 0;
|
||||
const primaryBranchDiffPreview = useEnvironmentQuery(
|
||||
selectedTurnId === null && activeThread && activeCwd
|
||||
? reviewEnvironment.diffPreview({
|
||||
@@ -465,6 +450,8 @@ export default function DiffPanel({
|
||||
}),
|
||||
[collapsedDiffFileKeys, renderableFiles],
|
||||
);
|
||||
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
|
||||
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath) return;
|
||||
@@ -515,6 +502,18 @@ export default function DiffPanel({
|
||||
[collapseScopeKey],
|
||||
);
|
||||
|
||||
const toggleDiffFileCollapse = useCallback(() => {
|
||||
setCollapsedDiffFiles((current) => {
|
||||
const currentKeys =
|
||||
current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
|
||||
|
||||
return {
|
||||
scopeKey: collapseScopeKey,
|
||||
fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
|
||||
};
|
||||
});
|
||||
}, [collapseScopeKey, diffFileKeys]);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!routeThreadRef) return;
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
|
||||
@@ -714,6 +713,30 @@ export default function DiffPanel({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
|
||||
{codeViewFiles.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
|
||||
onClick={toggleDiffFileCollapse}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDiffFilesCollapsed ? (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<ToggleGroup
|
||||
className="shrink-0"
|
||||
variant="outline"
|
||||
@@ -802,36 +825,6 @@ export default function DiffPanel({
|
||||
incomplete.
|
||||
</p>
|
||||
)}
|
||||
{selectedTurn && selectedTurnGitFileCount > 0 && (
|
||||
<p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-[11px] text-muted-foreground">
|
||||
{includeGitChanges ? (
|
||||
<>
|
||||
Showing {selectedTurnGitFileCount} file
|
||||
{selectedTurnGitFileCount === 1 ? "" : "s"} changed via git (pull, checkout,
|
||||
rebase, …).{" "}
|
||||
<button
|
||||
type="button"
|
||||
className="cursor-pointer underline underline-offset-2 hover:text-foreground"
|
||||
onClick={() => setIncludeGitChanges(false)}
|
||||
>
|
||||
Hide them
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{selectedTurnGitFileCount} file{selectedTurnGitFileCount === 1 ? "" : "s"}{" "}
|
||||
changed via git (pull, checkout, rebase, …) are hidden.{" "}
|
||||
<button
|
||||
type="button"
|
||||
className="cursor-pointer underline underline-offset-2 hover:text-foreground"
|
||||
onClick={() => setIncludeGitChanges(true)}
|
||||
>
|
||||
Show them
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{selectedPatchError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{selectedPatchError}</p>
|
||||
@@ -873,7 +866,7 @@ export default function DiffPanel({
|
||||
<AnnotatableCodeView
|
||||
viewerRef={codeViewRef}
|
||||
key={collapseScopeKey ?? reviewSectionId}
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto [&>div>div:last-child]:top-0! [&>div>div:last-child]:bottom-auto!"
|
||||
files={codeViewFiles}
|
||||
sectionId={reviewSectionId}
|
||||
sectionTitle={reviewSectionTitle}
|
||||
|
||||
@@ -14,15 +14,16 @@ import {
|
||||
isTrailingDoubleClick,
|
||||
orderItemsByPreferredIds,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveSidebarV2Status,
|
||||
resolveThreadStatusPill,
|
||||
resolveWorkingStartedAt,
|
||||
formatWorkingDurationLabel,
|
||||
shouldNavigateAfterProjectRemoval,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortLogicalProjectsForSidebar,
|
||||
sortSettledThreadsForSidebarV2,
|
||||
sortThreadsForSidebarV2,
|
||||
sortProjectsForSidebar,
|
||||
sortScopedProjectsForSidebar,
|
||||
@@ -209,8 +210,10 @@ function makeLatestTurn(overrides?: {
|
||||
state: "completed",
|
||||
assistantMessageId: null,
|
||||
requestedAt: "2026-03-09T10:00:00.000Z",
|
||||
startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
|
||||
completedAt: overrides?.completedAt ?? "2026-03-09T10:05:00.000Z",
|
||||
startedAt:
|
||||
overrides?.startedAt !== undefined ? overrides.startedAt : "2026-03-09T10:00:00.000Z",
|
||||
completedAt:
|
||||
overrides?.completedAt !== undefined ? overrides.completedAt : "2026-03-09T10:05:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -366,112 +369,6 @@ describe("isTrailingDoubleClick", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarNewThreadEnvMode", () => {
|
||||
it("uses the app default when the caller does not request a specific mode", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadEnvMode({
|
||||
defaultEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
});
|
||||
|
||||
it("preserves an explicit requested mode over the app default", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadEnvMode({
|
||||
requestedEnvMode: "local",
|
||||
defaultEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("local");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarNewThreadSeedContext", () => {
|
||||
it("prefers the default worktree mode over active thread context", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "worktree",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/existing",
|
||||
worktreePath: "/repo/.t3/worktrees/existing",
|
||||
},
|
||||
activeDraftThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/draft",
|
||||
worktreePath: "/repo/.t3/worktrees/draft",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
|
||||
it("inherits the active server thread context when creating a new thread in the same project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "local",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: null,
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the active draft thread context when it matches the target project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "local",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the default env mode when there is no matching active thread context", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-2",
|
||||
defaultEnvMode: "worktree",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: null,
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("orderItemsByPreferredIds", () => {
|
||||
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
|
||||
const ordered = orderItemsByPreferredIds({
|
||||
@@ -783,6 +680,141 @@ describe("sortThreadsForSidebarV2", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortSettledThreadsForSidebarV2", () => {
|
||||
const settled = (input: {
|
||||
id: string;
|
||||
settledAt?: string | null;
|
||||
latestUserMessageAt?: string | null;
|
||||
latestTurn?: OrchestrationLatestTurn | null;
|
||||
updatedAt?: string;
|
||||
}) => ({
|
||||
id: input.id,
|
||||
settledAt: input.settledAt ?? null,
|
||||
latestUserMessageAt: input.latestUserMessageAt ?? null,
|
||||
latestTurn: input.latestTurn ?? null,
|
||||
updatedAt: input.updatedAt ?? "2026-03-09T09:00:00.000Z",
|
||||
});
|
||||
|
||||
it("orders by settle time, most recently settled first", () => {
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({
|
||||
id: "settled-first",
|
||||
settledAt: "2026-03-09T10:00:00.000Z",
|
||||
// Created/active later than the other thread: settle time must win.
|
||||
latestUserMessageAt: "2026-03-09T09:59:00.000Z",
|
||||
}),
|
||||
settled({
|
||||
id: "settled-last",
|
||||
settledAt: "2026-03-09T12:00:00.000Z",
|
||||
latestUserMessageAt: "2026-03-09T08:00:00.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["settled-last", "settled-first"]);
|
||||
});
|
||||
|
||||
it("falls back to last activity for auto-settled threads without a settledAt stamp", () => {
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({ id: "auto-old", latestUserMessageAt: "2026-03-09T08:00:00.000Z" }),
|
||||
settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }),
|
||||
settled({ id: "auto-recent", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["auto-recent", "explicit", "auto-old"]);
|
||||
});
|
||||
|
||||
it("counts a turn completion as activity for auto-settled threads", () => {
|
||||
// The message came in before the other thread's, but its turn finished
|
||||
// after: completion time is the real "work ended" moment.
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }),
|
||||
settled({
|
||||
id: "completed-later",
|
||||
latestUserMessageAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: makeLatestTurn({ completedAt: "2026-03-09T10:30:00.000Z" }),
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["completed-later", "message-only"]);
|
||||
});
|
||||
|
||||
it("breaks timestamp ties by id so the order is stable", () => {
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }),
|
||||
settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWorkingStartedAt", () => {
|
||||
const session = {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running" as const,
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
activeTurnId: "turn-1" as never,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-09T10:02:00.000Z",
|
||||
};
|
||||
|
||||
it("uses the running turn's start time", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn({ completedAt: null }),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("uses the request time while a turn awaits adoption", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn({ startedAt: null, completedAt: null }),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to the session transition when the latest turn already completed", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn(),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:02:00.000Z");
|
||||
});
|
||||
|
||||
it("skips a malformed startedAt instead of returning it", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn({ startedAt: "not-a-date", completedAt: null }),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("returns null with neither a running turn nor a session", () => {
|
||||
expect(resolveWorkingStartedAt({ latestTurn: null, session: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatWorkingDurationLabel", () => {
|
||||
it("formats seconds, minutes, and hours", () => {
|
||||
expect(formatWorkingDurationLabel(0)).toBe("0s");
|
||||
expect(formatWorkingDurationLabel(42_000)).toBe("42s");
|
||||
expect(formatWorkingDurationLabel(5 * 60_000)).toBe("5m");
|
||||
expect(formatWorkingDurationLabel(90 * 60_000)).toBe("1h 30m");
|
||||
});
|
||||
|
||||
it("clamps negative and non-finite elapsed values to zero", () => {
|
||||
expect(formatWorkingDurationLabel(-5_000)).toBe("0s");
|
||||
expect(formatWorkingDurationLabel(Number.NaN)).toBe("0s");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadStatusPill", () => {
|
||||
const baseThread = {
|
||||
hasActionableProposedPlan: false,
|
||||
|
||||
@@ -18,7 +18,6 @@ export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
|
||||
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
|
||||
// nearby thread usually reuses an already-hot subscription.
|
||||
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -246,62 +245,6 @@ export function isTrailingDoubleClick(detail: number): boolean {
|
||||
return detail > 1;
|
||||
}
|
||||
|
||||
export function resolveSidebarNewThreadEnvMode(input: {
|
||||
requestedEnvMode?: SidebarNewThreadEnvMode;
|
||||
defaultEnvMode: SidebarNewThreadEnvMode;
|
||||
}): SidebarNewThreadEnvMode {
|
||||
return input.requestedEnvMode ?? input.defaultEnvMode;
|
||||
}
|
||||
|
||||
export function resolveSidebarNewThreadSeedContext(input: {
|
||||
projectId: string;
|
||||
defaultEnvMode: SidebarNewThreadEnvMode;
|
||||
activeThread?: {
|
||||
projectId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
} | null;
|
||||
activeDraftThread?: {
|
||||
projectId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin: boolean;
|
||||
} | null;
|
||||
}): {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin?: boolean;
|
||||
} {
|
||||
if (input.defaultEnvMode === "worktree") {
|
||||
return {
|
||||
envMode: "worktree",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeDraftThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeDraftThread.branch,
|
||||
worktreePath: input.activeDraftThread.worktreePath,
|
||||
envMode: input.activeDraftThread.envMode,
|
||||
startFromOrigin: input.activeDraftThread.startFromOrigin,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeThread.branch,
|
||||
worktreePath: input.activeThread.worktreePath,
|
||||
envMode: input.activeThread.worktreePath ? "worktree" : "local",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
envMode: input.defaultEnvMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function orderItemsByPreferredIds<TItem, TId>(input: {
|
||||
items: readonly TItem[];
|
||||
preferredIds: readonly TId[];
|
||||
@@ -502,6 +445,18 @@ export function firstValidTimestampMs(
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** String twin of firstValidTimestampMs for callers that need the ISO string
|
||||
(display labels, tick anchors) rather than epoch ms. */
|
||||
export function firstValidTimestamp(
|
||||
...candidates: ReadonlyArray<string | null | undefined>
|
||||
): string | null {
|
||||
for (const candidate of candidates) {
|
||||
if (candidate == null) continue;
|
||||
if (!Number.isNaN(Date.parse(candidate))) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// v2 sort: static creation order, newest thread on top. Activity NEVER
|
||||
// reorders the list — a row holds its position from open until settled, so
|
||||
// the screen only moves at lifecycle transitions. Status (including pending
|
||||
@@ -516,6 +471,73 @@ export function sortThreadsForSidebarV2<
|
||||
);
|
||||
}
|
||||
|
||||
type SettledTimestampInput = Pick<
|
||||
SidebarThreadSummary,
|
||||
"settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
|
||||
>;
|
||||
|
||||
/** The timestamp a settled row sorts and labels by: settledAt when stamped
|
||||
(explicit settles), otherwise last activity — the same candidates
|
||||
threadLastActivityAt feeds the auto-settle window (user message plus all
|
||||
latestTurn stamps), so a thread whose last activity was a turn completion
|
||||
doesn't sort by an older message time. updatedAt is the final net. */
|
||||
export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
|
||||
const settledAt = firstValidTimestamp(thread.settledAt);
|
||||
if (settledAt !== null) return settledAt;
|
||||
let latest: string | null = null;
|
||||
let latestMs = Number.NEGATIVE_INFINITY;
|
||||
for (const candidate of [
|
||||
thread.latestUserMessageAt,
|
||||
thread.latestTurn?.requestedAt,
|
||||
thread.latestTurn?.startedAt,
|
||||
thread.latestTurn?.completedAt,
|
||||
]) {
|
||||
if (candidate == null) continue;
|
||||
const parsed = Date.parse(candidate);
|
||||
if (!Number.isNaN(parsed) && parsed > latestMs) {
|
||||
latest = candidate;
|
||||
latestMs = parsed;
|
||||
}
|
||||
}
|
||||
return latest ?? firstValidTimestamp(thread.updatedAt);
|
||||
}
|
||||
|
||||
// Settled rows are history, so they order by when the work ENDED, not when
|
||||
// the thread was created or last touched.
|
||||
export function sortSettledThreadsForSidebarV2<
|
||||
T extends SettledTimestampInput & { readonly id: string },
|
||||
>(threads: readonly T[]): T[] {
|
||||
const timestampMs = (thread: T) => {
|
||||
const timestamp = resolveSettledTimestamp(thread);
|
||||
return timestamp === null ? 0 : Date.parse(timestamp);
|
||||
};
|
||||
return [...threads].toSorted(
|
||||
(left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
/** The timestamp a working thread's elapsed label counts from: the running
|
||||
turn's start (request time until adoption), falling back to the session's
|
||||
last transition when the turn projection lags behind. Malformed
|
||||
timestamps fall through to the next candidate, not just missing ones. */
|
||||
export function resolveWorkingStartedAt(
|
||||
thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
|
||||
): string | null {
|
||||
const turn = thread.latestTurn;
|
||||
if (turn && turn.completedAt === null) {
|
||||
return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
|
||||
}
|
||||
return firstValidTimestamp(thread.session?.updatedAt);
|
||||
}
|
||||
|
||||
export function formatWorkingDurationLabel(elapsedMs: number): string {
|
||||
const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
|
||||
if (seconds < 60) return `${seconds}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return `${minutes}m`;
|
||||
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
||||
}
|
||||
|
||||
export function resolveThreadStatusPill(input: {
|
||||
thread: ThreadStatusInput;
|
||||
}): ThreadStatusPill | null {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveSnoozePresets, snoozeWakeDescription, snoozeWakeLabel } from "./Sidebar.snooze";
|
||||
|
||||
// Local-time constructor so preset math is timezone-stable in tests.
|
||||
function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
|
||||
return new Date(year, month - 1, day, hour, minute, 0, 0);
|
||||
}
|
||||
|
||||
describe("resolveSnoozePresets", () => {
|
||||
it("offers hour, evening, tomorrow, next week in the morning", () => {
|
||||
// Wednesday 2026-04-08 10:00 local.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
expect(presets.map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"evening",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
const evening = presets.find((preset) => preset.id === "evening");
|
||||
expect(new Date(evening!.snoozedUntil).getHours()).toBe(18);
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
const tomorrowDate = new Date(tomorrow!.snoozedUntil);
|
||||
expect(tomorrowDate.getDate()).toBe(9);
|
||||
expect(tomorrowDate.getHours()).toBe(9);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
const nextWeekDate = new Date(nextWeek!.snoozedUntil);
|
||||
expect(nextWeekDate.getDay()).toBe(1);
|
||||
expect(nextWeekDate.getDate()).toBe(13);
|
||||
});
|
||||
|
||||
it("whenLabel complements the label instead of repeating it", () => {
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
for (const preset of presets) {
|
||||
// Day words live in the label column; the time column is time-only
|
||||
// (plus a weekday for next week, which names a different day).
|
||||
expect(preset.whenLabel.toLowerCase()).not.toContain("tomorrow");
|
||||
}
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
expect(tomorrow!.whenLabel).toMatch(/9/);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
expect(nextWeek!.whenLabel).toMatch(/Mon/);
|
||||
});
|
||||
|
||||
it("drops the evening preset once evening is near or past", () => {
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 17, 30)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 21)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
});
|
||||
|
||||
it("puts next week a full week out when today is Monday", () => {
|
||||
// Monday 2026-04-06.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 6, 10));
|
||||
const nextWeek = new Date(presets.find((preset) => preset.id === "next-week")!.snoozedUntil);
|
||||
expect(nextWeek.getDay()).toBe(1);
|
||||
expect(nextWeek.getDate()).toBe(13);
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeLabel", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("formats minutes, hours, and days, rounding up", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 30 * 60_000).toISOString(), now)).toBe("30m");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 90 * 60_000).toISOString(), now)).toBe("2h");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 26 * 3_600_000).toISOString(), now)).toBe("2d");
|
||||
});
|
||||
|
||||
it("reports now for past and malformed wake times", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() - 1000).toISOString(), now)).toBe("now");
|
||||
expect(snoozeWakeLabel("not-a-date", now)).toBe("now");
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeDescription", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("uses bare time today, 'tomorrow' next day, weekday within the week", () => {
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now)).not.toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 9, 9).toISOString(), now)).toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 13, 9).toISOString(), now)).toMatch(/Mon/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Snooze preset resolution for the sidebar snooze menu. Pure functions so
|
||||
* the preset math (evening/tomorrow/next-week boundaries) is unit-testable
|
||||
* without a DOM.
|
||||
*
|
||||
* Presets deliberately skew short: agent-thread rhythms are hours (a CI
|
||||
* run, a teammate review, the next work session), not days.
|
||||
*/
|
||||
import { parseTimestampDate } from "../timestampFormat";
|
||||
|
||||
type SnoozePresetId = "hour" | "evening" | "tomorrow" | "next-week";
|
||||
|
||||
export interface SnoozePreset {
|
||||
readonly id: SnoozePresetId;
|
||||
readonly label: string;
|
||||
/** Menu-row time column. Complements the label instead of repeating it:
|
||||
"Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
|
||||
readonly whenLabel: string;
|
||||
/** ISO wake time. */
|
||||
readonly snoozedUntil: string;
|
||||
}
|
||||
|
||||
function timeOfDayLabel(date: Date): string {
|
||||
return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
}
|
||||
|
||||
const EVENING_HOUR = 18;
|
||||
const MORNING_HOUR = 9;
|
||||
const HOUR_MS = 60 * 60 * 1_000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
|
||||
function atHour(base: Date, hour: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setHours(hour, 0, 0, 0);
|
||||
return next;
|
||||
}
|
||||
|
||||
// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
|
||||
// land on the wrong local day across DST transitions (a spring-forward day
|
||||
// is 23 hours, so 23:30 + 24h skips the whole next day).
|
||||
function addDays(base: Date, days: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setDate(next.getDate() + days);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Presets for "snooze until", computed against local time. "This evening"
|
||||
* only appears while it is still meaningfully before evening; after that
|
||||
* the list starts at "Tomorrow".
|
||||
*/
|
||||
export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
|
||||
const inAnHour = new Date(now.getTime() + HOUR_MS);
|
||||
const presets: SnoozePreset[] = [
|
||||
{
|
||||
id: "hour",
|
||||
label: "In 1 hour",
|
||||
whenLabel: timeOfDayLabel(inAnHour),
|
||||
snoozedUntil: inAnHour.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
const evening = atHour(now, EVENING_HOUR);
|
||||
// Suppress the evening preset once it is within an hour (or past): it
|
||||
// would duplicate "In 1 hour" or point at the past.
|
||||
if (evening.getTime() - now.getTime() > HOUR_MS) {
|
||||
presets.push({
|
||||
id: "evening",
|
||||
label: "This evening",
|
||||
whenLabel: timeOfDayLabel(evening),
|
||||
snoozedUntil: evening.toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
const tomorrow = atHour(addDays(now, 1), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "tomorrow",
|
||||
label: "Tomorrow",
|
||||
whenLabel: timeOfDayLabel(tomorrow),
|
||||
snoozedUntil: tomorrow.toISOString(),
|
||||
});
|
||||
|
||||
// Next Monday 9:00 (a week out when today is Monday).
|
||||
const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
|
||||
const nextWeek = atHour(addDays(now, daysUntilMonday), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "next-week",
|
||||
label: "Next week",
|
||||
whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${timeOfDayLabel(nextWeek)}`,
|
||||
snoozedUntil: nextWeek.toISOString(),
|
||||
});
|
||||
|
||||
return presets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
|
||||
* round up so a snooze never reads "0m" while still hidden.
|
||||
*/
|
||||
export function snoozeWakeLabel(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "now";
|
||||
const remainingMs = wake.getTime() - now.getTime();
|
||||
if (remainingMs <= 0) return "now";
|
||||
if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
|
||||
if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
|
||||
return `${Math.ceil(remainingMs / DAY_MS)}d`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human wake time for menus and toasts: "tomorrow 9:00", "Mon 9:00",
|
||||
* "17:30" (today).
|
||||
*/
|
||||
export function snoozeWakeDescription(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "";
|
||||
const time = wake.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
const startOfToday = new Date(now);
|
||||
startOfToday.setHours(0, 0, 0, 0);
|
||||
const dayDelta = Math.floor((wake.getTime() - startOfToday.getTime()) / DAY_MS);
|
||||
if (dayDelta === 0) return time;
|
||||
if (dayDelta === 1) return `tomorrow ${time}`;
|
||||
const weekday = wake.toLocaleDateString(undefined, { weekday: "short" });
|
||||
if (dayDelta < 7) return `${weekday} ${time}`;
|
||||
const date = wake.toLocaleDateString(undefined, { month: "short", day: "numeric" });
|
||||
return `${date}, ${time}`;
|
||||
}
|
||||
@@ -177,8 +177,6 @@ import {
|
||||
isContextMenuPointerDown,
|
||||
isTrailingDoubleClick,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
orderItemsByPreferredIds,
|
||||
@@ -193,7 +191,7 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useIsMobile } from "~/hooks/useMediaQuery";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
|
||||
import { primaryServerKeybindingsAtom, primaryServerSettingsAtom } from "../state/server";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import {
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupingOverrideKey,
|
||||
@@ -1103,7 +1101,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
(settings) => settings.confirmThreadArchive,
|
||||
);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
|
||||
const deleteProject = useAtomCommand(projectEnvironment.delete, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -1875,61 +1872,14 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
const createThreadForProjectMember = useCallback(
|
||||
(member: SidebarProjectGroupMember) => {
|
||||
const currentRouteParams =
|
||||
router.state.matches[router.state.matches.length - 1]?.params ?? {};
|
||||
const currentRouteTarget = resolveThreadRouteTarget(currentRouteParams);
|
||||
const currentActiveThread =
|
||||
currentRouteTarget?.kind === "server"
|
||||
? readThreadShell(currentRouteTarget.threadRef)
|
||||
: null;
|
||||
const draftStore = useComposerDraftStore.getState();
|
||||
const currentActiveDraftThread =
|
||||
currentRouteTarget?.kind === "server"
|
||||
? (draftStore.getDraftThread(currentRouteTarget.threadRef) ?? null)
|
||||
: currentRouteTarget?.kind === "draft"
|
||||
? (draftStore.getDraftSession(currentRouteTarget.draftId) ?? null)
|
||||
: null;
|
||||
const seedContext = resolveSidebarNewThreadSeedContext({
|
||||
projectId: member.id,
|
||||
// The default env mode is a user preference stored on the primary
|
||||
// environment's settings.json; remote environments never carry it.
|
||||
defaultEnvMode: resolveSidebarNewThreadEnvMode({
|
||||
defaultEnvMode: primaryServerSettings.defaultThreadEnvMode,
|
||||
}),
|
||||
activeThread:
|
||||
currentActiveThread && currentActiveThread.projectId === member.id
|
||||
? {
|
||||
projectId: currentActiveThread.projectId,
|
||||
branch: currentActiveThread.branch,
|
||||
worktreePath: currentActiveThread.worktreePath,
|
||||
}
|
||||
: null,
|
||||
activeDraftThread:
|
||||
currentActiveDraftThread && currentActiveDraftThread.projectId === member.id
|
||||
? {
|
||||
projectId: currentActiveDraftThread.projectId,
|
||||
branch: currentActiveDraftThread.branch,
|
||||
worktreePath: currentActiveDraftThread.worktreePath,
|
||||
envMode: currentActiveDraftThread.envMode,
|
||||
startFromOrigin: currentActiveDraftThread.startFromOrigin,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
if (isMobile) {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void (async () => {
|
||||
// No options: branch, worktree, and env mode come from the user's
|
||||
// configured defaults, never from the currently viewed thread.
|
||||
const result = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(member.environmentId, member.id), {
|
||||
...(seedContext.branch !== undefined ? { branch: seedContext.branch } : {}),
|
||||
...(seedContext.worktreePath !== undefined
|
||||
? { worktreePath: seedContext.worktreePath }
|
||||
: {}),
|
||||
envMode: seedContext.envMode,
|
||||
...(seedContext.startFromOrigin !== undefined
|
||||
? { startFromOrigin: seedContext.startFromOrigin }
|
||||
: {}),
|
||||
}),
|
||||
handleNewThread(scopeProjectRef(member.environmentId, member.id)),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
@@ -1943,7 +1893,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}
|
||||
})();
|
||||
},
|
||||
[handleNewThread, isMobile, primaryServerSettings.defaultThreadEnvMode, router, setOpenMobile],
|
||||
[handleNewThread, isMobile, setOpenMobile],
|
||||
);
|
||||
|
||||
const handleCreateThreadClick = useCallback(
|
||||
@@ -2164,6 +2114,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
...(thread.branch
|
||||
? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }]
|
||||
: []),
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-path", label: "Copy Path" },
|
||||
@@ -2173,6 +2126,30 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
position,
|
||||
);
|
||||
|
||||
if (clicked === "new-thread-on-branch") {
|
||||
// Explicit branch carry-over: reuse the thread's worktree when it
|
||||
// has one, otherwise its branch on the local checkout.
|
||||
const result = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), {
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
envMode: thread.worktreePath ? "worktree" : "local",
|
||||
startFromOrigin: false,
|
||||
}),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not create thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "rename") {
|
||||
startThreadRename(threadKey, thread.title);
|
||||
return;
|
||||
@@ -2229,6 +2206,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
copyPathToClipboard,
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
handleNewThread,
|
||||
markThreadUnread,
|
||||
memberProjectByScopedKey,
|
||||
project.workspaceRoot,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,11 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
import {
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
settledPrHoverColorClass,
|
||||
} from "./ThreadStatusIndicators";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
@@ -70,4 +74,23 @@ describe("prStatusIndicator", () => {
|
||||
tooltipTitle: "PR branch",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses red for closed pull requests", () => {
|
||||
const closedPr = status().pr;
|
||||
if (!closedPr) throw new Error("Expected pull request fixture");
|
||||
|
||||
expect(prStatusIndicator({ ...closedPr, state: "closed" }, undefined)?.colorClass).toContain(
|
||||
"text-red-600",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("settledPrHoverColorClass", () => {
|
||||
it.each([
|
||||
["open", "text-emerald-600"],
|
||||
["merged", "text-violet-600"],
|
||||
["closed", "text-red-600"],
|
||||
] as const)("restores the %s pull request color on row hover", (state, colorClass) => {
|
||||
expect(settledPrHoverColorClass(state)).toContain(`group-hover/v2-row:${colorClass}`);
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,17 @@ export interface TerminalStatusIndicator {
|
||||
|
||||
export type ThreadPr = VcsStatusResult["pr"];
|
||||
|
||||
export function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"]): string {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return "group-hover/v2-row:text-emerald-600 dark:group-hover/v2-row:text-emerald-300/90";
|
||||
case "merged":
|
||||
return "group-hover/v2-row:text-violet-600 dark:group-hover/v2-row:text-violet-300/90";
|
||||
case "closed":
|
||||
return "group-hover/v2-row:text-red-600 dark:group-hover/v2-row:text-red-300/90";
|
||||
}
|
||||
}
|
||||
|
||||
export function prStatusIndicator(
|
||||
pr: ThreadPr,
|
||||
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
|
||||
@@ -65,7 +76,7 @@ export function prStatusIndicator(
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: `${presentation.shortName} closed`,
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
colorClass: "text-red-600 dark:text-red-300/90",
|
||||
tooltip,
|
||||
tooltipLead,
|
||||
tooltipTitle: pr.title,
|
||||
|
||||
@@ -10,23 +10,86 @@ describe("ChangedFilesCard", () => {
|
||||
<ChangedFilesCard
|
||||
turnId={TurnId.make("turn-1")}
|
||||
files={[{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }]}
|
||||
expanded
|
||||
showCompactPreview={false}
|
||||
allDirectoriesExpanded
|
||||
resolvedTheme="light"
|
||||
onExpandedChange={() => {}}
|
||||
onToggleAllDirectories={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('class="sticky top-0 z-10');
|
||||
expect(markup).not.toContain("self-start");
|
||||
expect(markup).toContain('data-changed-files-state="expanded"');
|
||||
expect(markup).toContain('aria-expanded="true"');
|
||||
expect(markup).toContain("whitespace-nowrap");
|
||||
expect(markup).toContain("!size-[22px]");
|
||||
expect(markup).toContain("size-3");
|
||||
expect(markup).toContain('aria-label="Collapse all"');
|
||||
expect(markup).toContain('aria-label="View diff"');
|
||||
expect(markup).toContain('aria-label="Collapse all folders"');
|
||||
expect(markup).toContain('aria-label="Open diff"');
|
||||
expect(markup).toContain('role="group" aria-label="2 additions, 1 deletions"');
|
||||
expect(markup).toContain("1 changed file");
|
||||
expect(markup).not.toContain("1 changed files");
|
||||
});
|
||||
|
||||
it("renders a scope and representative-file preview for a large latest change", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesCard
|
||||
turnId={TurnId.make("turn-1")}
|
||||
files={[
|
||||
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 },
|
||||
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 30, deletions: 2 },
|
||||
{
|
||||
path: "packages/shared/src/git.ts",
|
||||
kind: "modified",
|
||||
additions: 15,
|
||||
deletions: 4,
|
||||
},
|
||||
{ path: "README.md", kind: "modified", additions: 3, deletions: 0 },
|
||||
]}
|
||||
expanded={false}
|
||||
showCompactPreview
|
||||
allDirectoriesExpanded={false}
|
||||
resolvedTheme="light"
|
||||
onExpandedChange={() => {}}
|
||||
onToggleAllDirectories={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-changed-files-state="preview"');
|
||||
expect(markup).toContain('aria-expanded="false"');
|
||||
expect(markup).toContain("apps");
|
||||
expect(markup).toContain("2 files");
|
||||
expect(markup).toContain("packages");
|
||||
expect(markup).toContain("root");
|
||||
expect(markup).toContain("App.tsx");
|
||||
expect(markup).toContain("git.ts");
|
||||
expect(markup).toContain("README.md");
|
||||
expect(markup).toContain("Show all 4 files");
|
||||
expect(markup).not.toContain("App.test.tsx");
|
||||
});
|
||||
|
||||
it("keeps older collapsed changes to a one-line receipt", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesCard
|
||||
turnId={TurnId.make("turn-1")}
|
||||
files={[{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 }]}
|
||||
expanded={false}
|
||||
showCompactPreview={false}
|
||||
allDirectoriesExpanded={false}
|
||||
resolvedTheme="light"
|
||||
onExpandedChange={() => {}}
|
||||
onToggleAllDirectories={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-changed-files-state="collapsed"');
|
||||
expect(markup).toContain("1 changed file");
|
||||
expect(markup).not.toContain("Show all");
|
||||
expect(markup).not.toContain("App.tsx");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ChangedFilesTree", () => {
|
||||
|
||||
@@ -19,95 +19,184 @@ import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { PierreEntryIcon } from "./PierreEntryIcon";
|
||||
import { Button } from "../ui/button";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import {
|
||||
changedFileName,
|
||||
selectChangedFilePreview,
|
||||
summarizeChangedFileScopes,
|
||||
} from "./changedFilesPresentation";
|
||||
|
||||
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
|
||||
|
||||
export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
turnId: TurnId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
expanded: boolean;
|
||||
showCompactPreview: boolean;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onExpandedChange: (expanded: boolean) => void;
|
||||
onToggleAllDirectories: () => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const {
|
||||
turnId,
|
||||
files,
|
||||
expanded,
|
||||
showCompactPreview,
|
||||
allDirectoriesExpanded,
|
||||
resolvedTheme,
|
||||
onExpandedChange,
|
||||
onToggleAllDirectories,
|
||||
onOpenTurnDiff,
|
||||
} = props;
|
||||
const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);
|
||||
const scopeSummary = useMemo(() => summarizeChangedFileScopes(files), [files]);
|
||||
const previewFiles = useMemo(() => selectChangedFilePreview(files), [files]);
|
||||
const compactPreviewVisible = showCompactPreview && !expanded;
|
||||
|
||||
return (
|
||||
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
|
||||
<div className="sticky top-0 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
|
||||
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{files.length} changed file{files.length === 1 ? "" : "s"}
|
||||
<div
|
||||
className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
|
||||
data-changed-files-state={
|
||||
expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
|
||||
}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-2 rounded-xl px-1",
|
||||
expanded &&
|
||||
"sticky top-2 z-10 mb-2 bg-secondary dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
data-scroll-anchor-ignore
|
||||
className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onExpandedChange(!expanded)}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 text-muted-foreground transition-transform",
|
||||
expanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
<span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{files.length} changed file{files.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
<span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
|
||||
{expanded ? "Hide files" : "Show files"}
|
||||
</span>
|
||||
</button>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{expanded ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label={
|
||||
allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
|
||||
}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={onToggleAllDirectories}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={onToggleAllDirectories}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label="View diff"
|
||||
aria-label="Open diff"
|
||||
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
<span className="hidden sm:inline">Open diff</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">View diff</TooltipPopup>
|
||||
<TooltipPopup side="top">Open the full diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
{expanded ? (
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
) : compactPreviewVisible ? (
|
||||
<div className="px-2 pb-1.5 pt-1">
|
||||
<p className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] text-muted-foreground">
|
||||
{scopeSummary.map((scope, index) => (
|
||||
<span key={scope.label} className="inline-flex items-center gap-1">
|
||||
{index > 0 ? <span aria-hidden="true">·</span> : null}
|
||||
<span className="font-mono text-foreground/75">{scope.label}</span>
|
||||
<span>
|
||||
{scope.fileCount} file{scope.fileCount === 1 ? "" : "s"}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||
{previewFiles.map((file) => (
|
||||
<button
|
||||
key={file.path}
|
||||
type="button"
|
||||
title={file.path}
|
||||
className="inline-flex max-w-48 items-center gap-1 rounded-md border border-border/70 bg-background/45 px-1.5 py-1 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onOpenTurnDiff(turnId, file.path)}
|
||||
>
|
||||
<PierreEntryIcon
|
||||
pathValue={file.path}
|
||||
kind="file"
|
||||
theme={resolvedTheme}
|
||||
className="size-3 shrink-0 text-muted-foreground/70"
|
||||
/>
|
||||
<span className="truncate">{changedFileName(file.path)}</span>
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md px-1.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onExpandedChange(true)}
|
||||
>
|
||||
Show all {files.length} files
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -31,6 +31,8 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
|
||||
<>
|
||||
{showParentheses && <span className="text-muted-foreground/70">(</span>}
|
||||
<span
|
||||
role="group"
|
||||
aria-label={`${additions} additions, ${deletions} deletions`}
|
||||
className={cn(
|
||||
layout === "inline"
|
||||
? "inline-flex items-center gap-1 tabular-nums align-middle"
|
||||
@@ -38,8 +40,12 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span className="font-mono text-success">+{formatCompactDiffCount(additions)}</span>
|
||||
<span className="font-mono text-destructive">-{formatCompactDiffCount(deletions)}</span>
|
||||
<span aria-hidden="true" className="font-mono text-success">
|
||||
+{formatCompactDiffCount(additions)}
|
||||
</span>
|
||||
<span aria-hidden="true" className="font-mono text-destructive">
|
||||
-{formatCompactDiffCount(deletions)}
|
||||
</span>
|
||||
</span>
|
||||
{showParentheses && <span className="text-muted-foreground/70">)</span>}
|
||||
</>
|
||||
|
||||
@@ -245,6 +245,12 @@ describe("MessagesTimeline", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
latestTurn={{
|
||||
turnId,
|
||||
state: "completed",
|
||||
startedAt: MESSAGE_CREATED_AT,
|
||||
completedAt: MESSAGE_CREATED_AT,
|
||||
}}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-assistant-with-files",
|
||||
@@ -280,13 +286,13 @@ describe("MessagesTimeline", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('class="sticky top-2 z-10');
|
||||
expect(markup).toContain("sticky top-2 z-10");
|
||||
expect(markup).not.toContain("self-start");
|
||||
expect(markup).toContain("whitespace-nowrap");
|
||||
expect(markup).toContain("!size-[22px]");
|
||||
expect(markup).toContain("size-3");
|
||||
expect(markup).toContain('aria-label="Collapse all"');
|
||||
expect(markup).toContain('aria-label="View diff"');
|
||||
expect(markup).toContain('aria-label="Collapse all folders"');
|
||||
expect(markup).toContain('aria-label="Open diff"');
|
||||
expect(markup).toContain("1 changed file");
|
||||
});
|
||||
|
||||
@@ -428,6 +434,7 @@ describe("MessagesTimeline", () => {
|
||||
|
||||
expect(markup).not.toContain("Show full message");
|
||||
expect(markup).toContain('data-user-message-collapsible="false"');
|
||||
expect(markup).toContain("rounded-2xl bg-accent p-3");
|
||||
});
|
||||
|
||||
it("renders inline terminal labels with the composer chip UI", () => {
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
workLogEntryIsToolLike,
|
||||
} from "../../session-logic";
|
||||
import { type TurnDiffSummary } from "../../types";
|
||||
import { partitionTurnDiffFiles, summarizeTurnDiffStats } from "../../lib/turnDiffTree";
|
||||
import {
|
||||
getRenderablePatch,
|
||||
resolveDiffThemeName,
|
||||
@@ -44,12 +43,8 @@ import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsDownUpIcon,
|
||||
ChevronsUpDownIcon,
|
||||
CircleAlertIcon,
|
||||
EyeIcon,
|
||||
FileDiffIcon,
|
||||
GitBranchIcon,
|
||||
GlobeIcon,
|
||||
HammerIcon,
|
||||
MessageCircleIcon,
|
||||
@@ -66,8 +61,8 @@ import {
|
||||
import { Button } from "../ui/button";
|
||||
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { ProposedPlanCard } from "./ProposedPlanCard";
|
||||
import { ChangedFilesTree } from "./ChangedFilesTree";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { ChangedFilesCard } from "./ChangedFilesTree";
|
||||
import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation";
|
||||
import { MessageCopyButton } from "./MessageCopyButton";
|
||||
import {
|
||||
computeStableMessagesTimelineRows,
|
||||
@@ -146,6 +141,7 @@ interface TimelineRowActivityState {
|
||||
isWorking: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
activeTurnInProgress: boolean;
|
||||
latestTurnId: TurnId | null;
|
||||
}
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
@@ -455,8 +451,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
isWorking,
|
||||
isRevertingCheckpoint,
|
||||
activeTurnInProgress,
|
||||
latestTurnId: latestTurn?.turnId ?? null,
|
||||
}),
|
||||
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
|
||||
[activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId],
|
||||
);
|
||||
|
||||
// Stable renderItem — no closure deps. Row components read shared state
|
||||
@@ -893,7 +890,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
|
||||
return (
|
||||
<div className="group flex flex-col items-end gap-1">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-secondary p-3">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-accent p-3">
|
||||
{regularImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
@@ -1250,17 +1247,13 @@ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection(
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
if (!turnSummary) return null;
|
||||
if (turnSummary.files.length === 0) return null;
|
||||
// Changes explained by pre-existing git history (pull, checkout,
|
||||
// cherry-pick, rebase) collapse into a single summary row instead of
|
||||
// being listed as agent work.
|
||||
const { agentFiles, gitFiles } = partitionTurnDiffFiles(turnSummary.files);
|
||||
const checkpointFiles = turnSummary.files;
|
||||
if (checkpointFiles.length === 0) return null;
|
||||
|
||||
return (
|
||||
<AssistantChangedFilesSectionInner
|
||||
turnSummary={turnSummary}
|
||||
checkpointFiles={agentFiles}
|
||||
gitFiles={gitFiles}
|
||||
checkpointFiles={checkpointFiles}
|
||||
routeThreadKey={routeThreadKey}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
@@ -1273,125 +1266,42 @@ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection(
|
||||
function AssistantChangedFilesSectionInner({
|
||||
turnSummary,
|
||||
checkpointFiles,
|
||||
gitFiles,
|
||||
routeThreadKey,
|
||||
resolvedTheme,
|
||||
onOpenTurnDiff,
|
||||
}: {
|
||||
turnSummary: TurnDiffSummary;
|
||||
checkpointFiles: TurnDiffSummary["files"];
|
||||
gitFiles: TurnDiffSummary["files"];
|
||||
routeThreadKey: string;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const allDirectoriesExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const isLatestTurn = activity.latestTurnId === turnSummary.turnId;
|
||||
const persistedExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId],
|
||||
);
|
||||
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
const gitSummaryStat = summarizeTurnDiffStats(gitFiles);
|
||||
// A git-only turn renders as a compact card with just the git summary row:
|
||||
// the "N changed files" header, expand/collapse, and View diff controls all
|
||||
// operate on agent files and would be dead weight.
|
||||
const hasAgentFiles = checkpointFiles.length > 0;
|
||||
const [autoExpanded] = useState(() =>
|
||||
shouldAutoExpandChangedFiles(checkpointFiles, isLatestTurn),
|
||||
);
|
||||
const [allDirectoriesExpanded, setAllDirectoriesExpanded] = useState(autoExpanded);
|
||||
const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32",
|
||||
hasAgentFiles && "pt-4",
|
||||
)}
|
||||
>
|
||||
{hasAgentFiles && (
|
||||
<div className="sticky top-2 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
|
||||
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() =>
|
||||
setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label="View diff"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">View diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{checkpointFiles.length > 0 && (
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.turnId}`}
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
)}
|
||||
{gitFiles.length > 0 && (
|
||||
<div className="flex items-center gap-1.5 rounded-xl px-2 py-1 text-muted-foreground/80">
|
||||
<GitBranchIcon aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
<span className="truncate font-mono text-[11px]">
|
||||
Updated via git — {gitFiles.length} file{gitFiles.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
{hasNonZeroStat(gitSummaryStat) && (
|
||||
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
|
||||
<DiffStatLabel
|
||||
additions={gitSummaryStat.additions}
|
||||
deletions={gitSummaryStat.deletions}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<ChangedFilesCard
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
expanded={expanded}
|
||||
showCompactPreview={isLatestTurn}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onExpandedChange={(nextExpanded) =>
|
||||
setExpanded(routeThreadKey, turnSummary.turnId, nextExpanded)
|
||||
}
|
||||
onToggleAllDirectories={() => setAllDirectoriesExpanded((current) => !current)}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
contentClassName="flex w-full items-center gap-3"
|
||||
className={cn(
|
||||
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
|
||||
"data-highlighted:bg-muted/56 data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0",
|
||||
"hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-highlighted:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0 [&[data-highlighted][data-selected]]:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))]",
|
||||
props.disabledReason &&
|
||||
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
|
||||
)}
|
||||
|
||||
@@ -521,7 +521,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
<div
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-xl text-popover-foreground"
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
data-model-picker-content="true"
|
||||
>
|
||||
{/* Sidebar */}
|
||||
@@ -568,18 +568,23 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
handleModelSelect(slug, instanceId);
|
||||
}}
|
||||
>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
|
||||
showSidebar && "border-l",
|
||||
)}
|
||||
>
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px rounded-lg bg-accent px-2 py-1">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm placeholder:text-muted-foreground/80"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/80" />
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
|
||||
@@ -97,7 +97,10 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
|
||||
|
||||
return (
|
||||
<div className="w-12 shrink-0 overflow-hidden bg-muted/60" data-model-picker-sidebar="true">
|
||||
<div
|
||||
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
|
||||
data-model-picker-sidebar="true"
|
||||
>
|
||||
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<div
|
||||
ref={sidebarContentRef}
|
||||
@@ -115,14 +118,14 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
) : null}
|
||||
{/* Favorites section */}
|
||||
{showFavorites ? (
|
||||
<div className="mb-1 pb-1">
|
||||
<div className="mb-1 border-b pb-1">
|
||||
<div className="relative w-full">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
)}
|
||||
onClick={() => handleSelect("favorites")}
|
||||
type="button"
|
||||
@@ -169,7 +172,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
<button
|
||||
data-model-picker-provider={entry.instanceId}
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
|
||||
)}
|
||||
data-provider-accent-color={entry.accentColor}
|
||||
|
||||
@@ -187,8 +187,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup
|
||||
align="start"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0]"
|
||||
viewportClassName="!overflow-hidden p-0"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [-webkit-backdrop-filter:none]! [--viewport-inline-padding:0] [backdrop-filter:none]!"
|
||||
viewportClassName="rounded-lg !overflow-hidden p-0"
|
||||
>
|
||||
<ModelPickerContent
|
||||
activeInstanceId={activeInstanceId}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
changedFileName,
|
||||
selectChangedFilePreview,
|
||||
shouldAutoExpandChangedFiles,
|
||||
summarizeChangedFileScopes,
|
||||
} from "./changedFilesPresentation";
|
||||
|
||||
describe("changed-files presentation", () => {
|
||||
it("auto-expands only small, low-churn latest changes", () => {
|
||||
const smallFiles = [
|
||||
{ path: "src/a.ts", kind: "modified", additions: 80, deletions: 20 },
|
||||
{ path: "src/b.ts", kind: "modified", additions: 60, deletions: 20 },
|
||||
];
|
||||
|
||||
expect(shouldAutoExpandChangedFiles(smallFiles, true)).toBe(true);
|
||||
expect(shouldAutoExpandChangedFiles(smallFiles, false)).toBe(false);
|
||||
expect(
|
||||
shouldAutoExpandChangedFiles(
|
||||
[{ path: "src/a.ts", kind: "modified", additions: 201, deletions: 0 }],
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoExpandChangedFiles(
|
||||
Array.from({ length: 6 }, (_, index) => ({
|
||||
path: `src/${index}.ts`,
|
||||
kind: "modified",
|
||||
additions: 1,
|
||||
deletions: 0,
|
||||
})),
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("summarizes the most prominent top-level scopes", () => {
|
||||
const files = [
|
||||
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "apps/server/src/index.ts", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "apps\\mobile\\App.tsx", kind: "modified", additions: 1, deletions: 0 },
|
||||
];
|
||||
|
||||
expect(summarizeChangedFileScopes(files)).toEqual([
|
||||
{ label: "apps", fileCount: 3 },
|
||||
{ label: "root", fileCount: 1 },
|
||||
{ label: "packages", fileCount: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("previews files across different scopes before filling from one scope", () => {
|
||||
const files = [
|
||||
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
|
||||
];
|
||||
|
||||
expect(selectChangedFilePreview(files).map((file) => file.path)).toEqual([
|
||||
"apps/web/src/App.tsx",
|
||||
"packages/shared/src/git.ts",
|
||||
"README.md",
|
||||
]);
|
||||
expect(changedFileName("apps\\web\\src\\App.tsx")).toBe("App.tsx");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { type TurnDiffFileChange } from "../../types";
|
||||
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
|
||||
|
||||
export const CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT = 5;
|
||||
export const CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT = 200;
|
||||
export const CHANGED_FILES_PREVIEW_FILE_LIMIT = 3;
|
||||
export const CHANGED_FILES_PREVIEW_SCOPE_LIMIT = 4;
|
||||
|
||||
export interface ChangedFilesScopeSummary {
|
||||
readonly label: string;
|
||||
readonly fileCount: number;
|
||||
}
|
||||
|
||||
function pathSegments(pathValue: string): string[] {
|
||||
return pathValue
|
||||
.replaceAll("\\", "/")
|
||||
.split("/")
|
||||
.filter((segment) => segment.length > 0);
|
||||
}
|
||||
|
||||
export function changedFileName(pathValue: string): string {
|
||||
return pathSegments(pathValue).at(-1) ?? pathValue;
|
||||
}
|
||||
|
||||
function changedFileScope(pathValue: string): string {
|
||||
const segments = pathSegments(pathValue);
|
||||
return segments.length > 1 ? (segments[0] ?? "root") : "root";
|
||||
}
|
||||
|
||||
export function shouldAutoExpandChangedFiles(
|
||||
files: ReadonlyArray<TurnDiffFileChange>,
|
||||
isLatestTurn: boolean,
|
||||
): boolean {
|
||||
if (!isLatestTurn || files.length > CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT) {
|
||||
return false;
|
||||
}
|
||||
const stat = summarizeTurnDiffStats(files);
|
||||
return stat.additions + stat.deletions <= CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT;
|
||||
}
|
||||
|
||||
export function summarizeChangedFileScopes(
|
||||
files: ReadonlyArray<TurnDiffFileChange>,
|
||||
limit = CHANGED_FILES_PREVIEW_SCOPE_LIMIT,
|
||||
): ChangedFilesScopeSummary[] {
|
||||
const scopes = new Map<string, { fileCount: number; firstIndex: number }>();
|
||||
files.forEach((file, index) => {
|
||||
const label = changedFileScope(file.path);
|
||||
const current = scopes.get(label);
|
||||
scopes.set(label, {
|
||||
fileCount: (current?.fileCount ?? 0) + 1,
|
||||
firstIndex: current?.firstIndex ?? index,
|
||||
});
|
||||
});
|
||||
|
||||
return Array.from(scopes, ([label, scope]) => ({
|
||||
label,
|
||||
fileCount: scope.fileCount,
|
||||
firstIndex: scope.firstIndex,
|
||||
}))
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
right.fileCount - left.fileCount ||
|
||||
left.firstIndex - right.firstIndex ||
|
||||
left.label.localeCompare(right.label),
|
||||
)
|
||||
.slice(0, limit)
|
||||
.map(({ label, fileCount }) => ({ label, fileCount }));
|
||||
}
|
||||
|
||||
export function selectChangedFilePreview(
|
||||
files: ReadonlyArray<TurnDiffFileChange>,
|
||||
limit = CHANGED_FILES_PREVIEW_FILE_LIMIT,
|
||||
): TurnDiffFileChange[] {
|
||||
const selected: TurnDiffFileChange[] = [];
|
||||
const selectedPaths = new Set<string>();
|
||||
const selectedScopes = new Set<string>();
|
||||
|
||||
for (const file of files) {
|
||||
const scope = changedFileScope(file.path);
|
||||
if (selectedScopes.has(scope)) {
|
||||
continue;
|
||||
}
|
||||
selected.push(file);
|
||||
selectedPaths.add(file.path);
|
||||
selectedScopes.add(scope);
|
||||
if (selected.length === limit) {
|
||||
return selected;
|
||||
}
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
if (selectedPaths.has(file.path)) {
|
||||
continue;
|
||||
}
|
||||
selected.push(file);
|
||||
if (selected.length === limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return selected;
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
type PreviewAutomationOpenInput,
|
||||
type PreviewAutomationResizeInput,
|
||||
type PreviewAutomationResizeResult,
|
||||
type PreviewAutomationSetColorSchemeInput,
|
||||
type PreviewAutomationSetColorSchemeResult,
|
||||
type PreviewAutomationHost as PreviewAutomationHostState,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationStatus,
|
||||
@@ -451,6 +453,15 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
viewport,
|
||||
} satisfies PreviewAutomationResizeResult;
|
||||
}
|
||||
case "setColorScheme": {
|
||||
const ready = await requireReadyTab();
|
||||
const input = request.input as PreviewAutomationSetColorSchemeInput;
|
||||
await ready.bridge.setColorScheme(ready.tabId, input.colorScheme);
|
||||
return {
|
||||
tabId: ready.tabId,
|
||||
colorScheme: input.colorScheme,
|
||||
} satisfies PreviewAutomationSetColorSchemeResult;
|
||||
}
|
||||
case "snapshot": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.snapshot(ready.tabId);
|
||||
|
||||
@@ -1,13 +1,34 @@
|
||||
"use client";
|
||||
|
||||
import type { DesktopPreviewColorScheme } from "@t3tools/contracts";
|
||||
import { Minus, MoreVertical, Plus as PlusIcon, RotateCcw } from "lucide-react";
|
||||
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "~/components/ui/menu";
|
||||
import {
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator,
|
||||
MenuSub,
|
||||
MenuSubPopup,
|
||||
MenuSubTrigger,
|
||||
MenuTrigger,
|
||||
} from "~/components/ui/menu";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
|
||||
import { previewBridge } from "./previewBridge";
|
||||
|
||||
const COLOR_SCHEME_OPTIONS: ReadonlyArray<{
|
||||
value: DesktopPreviewColorScheme;
|
||||
label: string;
|
||||
}> = [
|
||||
{ value: "system", label: "System" },
|
||||
{ value: "light", label: "Light" },
|
||||
{ value: "dark", label: "Dark" },
|
||||
];
|
||||
|
||||
interface Props {
|
||||
/** Active preview tab id. Tab-targeting actions are disabled without it. */
|
||||
tabId: string | null;
|
||||
@@ -19,6 +40,8 @@ interface Props {
|
||||
hasWebContents: boolean;
|
||||
/** Current zoom factor as a number (1.0 = 100%). */
|
||||
zoomFactor: number;
|
||||
/** Emulated `prefers-color-scheme` for the guest page. */
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
/** Fixed viewport modes expose the device toolbar and resize rails. */
|
||||
deviceToolbarVisible: boolean;
|
||||
/** Switches between fill-panel mode and a fixed responsive viewport. */
|
||||
@@ -34,6 +57,7 @@ export function PreviewMoreMenu({
|
||||
tabId,
|
||||
hasWebContents,
|
||||
zoomFactor,
|
||||
colorScheme,
|
||||
deviceToolbarVisible,
|
||||
onToggleDeviceToolbar,
|
||||
}: Props) {
|
||||
@@ -72,6 +96,26 @@ export function PreviewMoreMenu({
|
||||
<MenuItem onClick={onToggleDeviceToolbar} disabled={tabDisabled}>
|
||||
{deviceToolbarVisible ? "Hide device toolbar" : "Show device toolbar"}
|
||||
</MenuItem>
|
||||
<MenuSub>
|
||||
<MenuSubTrigger disabled={tabDisabled}>Appearance</MenuSubTrigger>
|
||||
<MenuSubPopup className="min-w-32">
|
||||
<MenuRadioGroup
|
||||
value={colorScheme}
|
||||
onValueChange={(value) => {
|
||||
if (!tabId) return;
|
||||
void bridge
|
||||
.setColorScheme(tabId, value as DesktopPreviewColorScheme)
|
||||
.catch(() => undefined);
|
||||
}}
|
||||
>
|
||||
{COLOR_SCHEME_OPTIONS.map((option) => (
|
||||
<MenuRadioItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuSubPopup>
|
||||
</MenuSub>
|
||||
<MenuSeparator />
|
||||
{/*
|
||||
Zoom row: label + inline control cluster. `closeOnClick=false`
|
||||
|
||||
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user