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 | ||
|
|
88c69ffff6 | ||
|
|
979854895c | ||
|
|
9cbe50d10d | ||
|
|
9d9208cec5 | ||
|
|
57100fba85 | ||
|
|
3afb4a9ef9 | ||
|
|
315b27385d | ||
|
|
719c905eac | ||
|
|
0542abc75e | ||
|
|
7609495bf7 | ||
|
|
b41e89eba9 | ||
|
|
4d83436415 | ||
|
|
e51538b812 | ||
|
|
1c9a6de26e | ||
|
|
fbd77420f2 | ||
|
|
16491a84b9 | ||
|
|
b44ed835c6 | ||
|
|
9c9916aefe | ||
|
|
936394b6f2 | ||
|
|
c38225ef1c | ||
|
|
39cd15b954 | ||
|
|
160d97f403 | ||
|
|
d330759f58 | ||
|
|
5961d36769 | ||
|
|
0b1ce58824 | ||
|
|
10da67b9da | ||
|
|
6e5df67f15 | ||
|
|
29b1abc45e | ||
|
|
14b6bfdf15 | ||
|
|
b6a2563db7 | ||
|
|
c5ff51ec1f | ||
|
|
2d31cb022d | ||
|
|
bc9428a06a | ||
|
|
593289c3c7 | ||
|
|
ab4a88386d | ||
|
|
78a0ea55c1 | ||
|
|
9a0a07167f | ||
|
|
9fe4832a3f | ||
|
|
376c149eac | ||
|
|
7e2bb47504 | ||
|
|
18fa89c4ad | ||
|
|
f74eb62661 | ||
|
|
e5fba263e6 | ||
|
|
18b468871e | ||
|
|
020179c19a | ||
|
|
571a8b44bd | ||
|
|
b6e1b39335 | ||
|
|
c7b21ff172 | ||
|
|
4e09cddb40 | ||
|
|
783692afc1 | ||
|
|
aa5ec80364 | ||
|
|
282ecb3178 | ||
|
|
32c6012dab |
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.
|
||||
|
||||
@@ -54,6 +54,8 @@ There's no public docs site yet, checkout the miscellaneous markdown files in [d
|
||||
## Documentation
|
||||
|
||||
- [Getting started](./docs/getting-started/quick-start.md)
|
||||
- [Remote access](./docs/user/remote-access.md)
|
||||
- [Keeping T3 Code in sync](./docs/user/server-updates.md)
|
||||
- [Architecture overview](./docs/architecture/overview.md)
|
||||
- [Provider guides](./docs/providers/codex.md)
|
||||
- [Operations](./docs/operations/ci.md)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
for (const stream of [process.stdout, process.stderr]) {
|
||||
stream.on("error", (err: NodeJS.ErrnoException) => {
|
||||
if (err.code !== "EPIPE") throw err;
|
||||
});
|
||||
}
|
||||
|
||||
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -19,7 +19,9 @@ const clientSettings: ClientSettings = {
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
favorites: [],
|
||||
glassOpacity: 80,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
@@ -27,6 +29,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"astro": "^7.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { APIRoute } from "astro";
|
||||
|
||||
import { buildT3ProjectFileJsonSchema } from "@t3tools/shared/t3ProjectFile";
|
||||
|
||||
// Rendered at build time; published at https://t3.codes/schema/t3.json so
|
||||
// t3.json files can reference it via "$schema" for editor/LSP support.
|
||||
export const GET: APIRoute = () =>
|
||||
new Response(`${JSON.stringify(buildT3ProjectFileJsonSchema(), null, 2)}\n`, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { VercelConfig } from "@vercel/config/v1";
|
||||
|
||||
export const config: VercelConfig = {
|
||||
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing'",
|
||||
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing...'",
|
||||
buildCommand: "vp run --filter @t3tools/marketing build",
|
||||
outputDirectory: "dist",
|
||||
};
|
||||
+19
-5
@@ -13,7 +13,10 @@ import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
|
||||
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import {
|
||||
AppearancePreferencesProvider,
|
||||
useAppearancePreferences,
|
||||
} from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
import { OverlayPortalHost } from "./components/OverlayPortal";
|
||||
@@ -26,6 +29,10 @@ if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
|
||||
prepareNativeShowcaseCapture();
|
||||
}
|
||||
|
||||
void SplashScreen.preventAutoHideAsync().catch(() => {
|
||||
// The native module can be unavailable in non-native test environments.
|
||||
});
|
||||
|
||||
const appLinking = {
|
||||
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
|
||||
// The Expo dev client launches the app via
|
||||
@@ -40,18 +47,25 @@ const appLinking = {
|
||||
|
||||
const Navigation = createStaticNavigation(RootStack);
|
||||
|
||||
function SplashScreenCoordinator() {
|
||||
const { isReady } = useAppearancePreferences();
|
||||
|
||||
useEffect(() => {
|
||||
if (isReady) void SplashScreen.hide();
|
||||
}, [isReady]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const colorScheme = useColorScheme();
|
||||
const statusBarBg = useThemeColor("--color-status-bar");
|
||||
|
||||
useEffect(() => {
|
||||
SplashScreen.hide();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<AppearancePreferencesProvider>
|
||||
<SplashScreenCoordinator />
|
||||
<GestureHandlerRootView className="flex-1">
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
|
||||
@@ -33,7 +33,7 @@ import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
|
||||
import { connectionStorageLayer } from "./storage";
|
||||
|
||||
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
|
||||
if (state.isConnected === false || state.isInternetReachable === false) {
|
||||
if (state.isConnected === false) {
|
||||
return "offline";
|
||||
}
|
||||
if (state.isConnected === true) {
|
||||
|
||||
@@ -41,6 +41,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
|
||||
@@ -14,6 +12,7 @@ import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
@@ -21,10 +20,10 @@ import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
buildHomeListFilterMenu,
|
||||
type HomeListFilterMenuEnvironment,
|
||||
type HomeListFilterMenuProject,
|
||||
} from "./home-list-filter-menu";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
@@ -33,16 +32,17 @@ export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment;
|
||||
|
||||
export function HomeHeader(props: {
|
||||
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
|
||||
readonly projects: ReadonlyArray<HomeListFilterMenuProject>;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
}) {
|
||||
@@ -59,11 +59,24 @@ function checkedMenuState(checked: boolean) {
|
||||
return checked ? ("on" as const) : undefined;
|
||||
}
|
||||
|
||||
/** Thread List v2 lays the list out in fixed creation order, so the
|
||||
sort/group filter controls would be silently ignored — hide them and
|
||||
key the "customized" icon state off the environment filter alone. */
|
||||
function useThreadListV2FilterGate() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
return (
|
||||
AsyncResult.isSuccess(preferencesResult) && preferencesResult.value.threadListV2Enabled === true
|
||||
);
|
||||
}
|
||||
|
||||
function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const hasCustomListOptions = hasCustomHomeListOptions(props);
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
const menuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{
|
||||
@@ -82,40 +95,57 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
})),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "project-sort",
|
||||
title: "Sort projects",
|
||||
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
id: `project-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.projectSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "thread-sort",
|
||||
title: "Sort threads",
|
||||
subactions: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
id: `thread-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.threadSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "project-grouping",
|
||||
title: "Group projects",
|
||||
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
id: `project-grouping:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.projectGroupingMode === option.value),
|
||||
})),
|
||||
},
|
||||
...(props.projects.length === 0
|
||||
? []
|
||||
: ([
|
||||
{
|
||||
id: "project",
|
||||
title: "Project",
|
||||
subactions: [
|
||||
{
|
||||
id: "project:all",
|
||||
title: "All projects",
|
||||
state: checkedMenuState(props.selectedProjectKey === null),
|
||||
},
|
||||
...props.projects.map((project) => ({
|
||||
id: `project:${project.key}`,
|
||||
title: project.label,
|
||||
state: checkedMenuState(props.selectedProjectKey === project.key),
|
||||
})),
|
||||
],
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
...(threadListV2Enabled
|
||||
? []
|
||||
: ([
|
||||
{
|
||||
id: "project-sort",
|
||||
title: "Sort projects",
|
||||
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
id: `project-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.projectSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "thread-sort",
|
||||
title: "Sort threads",
|
||||
subactions: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
id: `thread-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.threadSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
],
|
||||
[
|
||||
props.environments,
|
||||
props.projectGroupingMode,
|
||||
props.projectSortOrder,
|
||||
props.projects,
|
||||
props.selectedEnvironmentId,
|
||||
props.selectedProjectKey,
|
||||
props.threadSortOrder,
|
||||
threadListV2Enabled,
|
||||
],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
@@ -137,6 +167,19 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (id === "project:all") {
|
||||
props.onProjectChange(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (id.startsWith("project:")) {
|
||||
const projectKey = id.slice("project:".length);
|
||||
if (props.projects.some((project) => project.key === projectKey)) {
|
||||
props.onProjectChange(projectKey);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const projectSort = PROJECT_SORT_OPTIONS.find(
|
||||
(option) => id === `project-sort:${option.value}`,
|
||||
);
|
||||
@@ -150,13 +193,6 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
props.onThreadSortOrderChange(threadSort.value);
|
||||
return;
|
||||
}
|
||||
|
||||
const grouping = PROJECT_GROUPING_OPTIONS.find(
|
||||
(option) => id === `project-grouping:${option.value}`,
|
||||
);
|
||||
if (grouping) {
|
||||
props.onProjectGroupingModeChange(grouping.value);
|
||||
}
|
||||
},
|
||||
[props],
|
||||
);
|
||||
@@ -255,17 +291,24 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
function IosHomeHeader(props: HomeHeaderProps) {
|
||||
const searchBarRef = useRef<SearchBarCommands>(null);
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const hasCustomListOptions = hasCustomHomeListOptions(props);
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
const focusSearch = useCallback(() => {
|
||||
searchBarRef.current?.focus();
|
||||
return searchBarRef.current !== null;
|
||||
}, []);
|
||||
useHardwareKeyboardCommand("focusSearch", focusSearch);
|
||||
const filterMenu = buildHomeListFilterMenu(props);
|
||||
const filterMenu = buildHomeListFilterMenu({
|
||||
...props,
|
||||
listOrganization: !threadListV2Enabled,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
optionsVersion={filterMenu.items}
|
||||
options={{
|
||||
// Static header config (glass, title, fonts) lives in Stack.tsx
|
||||
// (GLASS_HEADER_OPTIONS). Only dynamic values are set here.
|
||||
@@ -342,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
|
||||
@@ -366,6 +405,28 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
{props.projects.length > 0 ? (
|
||||
<NativeHeaderToolbar.Menu title="Project">
|
||||
<NativeHeaderToolbar.Label>Project</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.selectedProjectKey === null}
|
||||
onPress={() => props.onProjectChange(null)}
|
||||
subtitle="Show threads from every project"
|
||||
>
|
||||
<NativeHeaderToolbar.Label>All projects</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
{props.projects.map((project) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={project.key}
|
||||
isOn={props.selectedProjectKey === project.key}
|
||||
onPress={() => props.onProjectChange(project.key)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{project.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
) : null}
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Sort projects">
|
||||
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
|
||||
{PROJECT_SORT_OPTIONS.map((option) => (
|
||||
@@ -391,20 +452,6 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Group projects">
|
||||
<NativeHeaderToolbar.Label>Group projects</NativeHeaderToolbar.Label>
|
||||
{PROJECT_GROUPING_OPTIONS.map((option) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectGroupingMode === option.value}
|
||||
onPress={() => props.onProjectGroupingModeChange(option.value)}
|
||||
subtitle={option.subtitle}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
|
||||
<NativeHeaderToolbar.SearchBarSlot />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
@@ -15,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";
|
||||
|
||||
@@ -28,7 +29,8 @@ export function HomeRouteScreen() {
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -52,11 +54,31 @@ export function HomeRouteScreen() {
|
||||
const {
|
||||
options: listOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
} = useHomeListOptions(availableEnvironmentIds);
|
||||
const selectedEnvironmentId = listOptions.selectedEnvironmentId;
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: selectedEnvironmentId,
|
||||
projectGroupingMode: listOptions.projectGroupingMode,
|
||||
}).map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[listOptions.projectGroupingMode, projects, selectedEnvironmentId],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
selectedProjectKey !== null &&
|
||||
!projectFilterOptions.some((project) => project.key === selectedProjectKey)
|
||||
) {
|
||||
setSelectedProjectKey(null);
|
||||
}
|
||||
}, [projectFilterOptions, selectedProjectKey]);
|
||||
|
||||
// In split layouts the persistent sidebar IS the thread list — Home becomes
|
||||
// an empty detail pane so selecting a thread never transitions layouts.
|
||||
@@ -89,14 +111,15 @@ export function HomeRouteScreen() {
|
||||
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
projects={projectFilterOptions}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
@@ -111,15 +134,19 @@ export function HomeRouteScreen() {
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
// Settled threads are live shells: opening one is plain
|
||||
// navigation, and sending a message un-settles server-side.
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
@@ -146,6 +173,7 @@ export function HomeRouteScreen() {
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
|
||||
@@ -14,18 +14,20 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Platform, View } from "react-native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import {
|
||||
PendingTaskListRow,
|
||||
@@ -33,6 +35,13 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
|
||||
type ThreadListV2Item,
|
||||
} from "../threads/threadListV2";
|
||||
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
|
||||
import {
|
||||
buildHomeListLayout,
|
||||
@@ -43,7 +52,12 @@ import {
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "./homeListItems";
|
||||
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
type HomeProjectSortOrder,
|
||||
} from "./homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
|
||||
@@ -59,14 +73,15 @@ interface HomeScreenProps {
|
||||
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onAddConnection: () => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
@@ -74,6 +89,9 @@ interface HomeScreenProps {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** Resolves true iff the settle was dispatched and succeeded. */
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -163,6 +181,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
>(() => new Map());
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
@@ -224,12 +245,77 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
|
||||
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
|
||||
: (projectScopes.find(
|
||||
(scope) =>
|
||||
scope.key === props.selectedProjectKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
props.selectedProjectKey,
|
||||
),
|
||||
) ?? null),
|
||||
[projectScopes, props.selectedProjectKey],
|
||||
);
|
||||
const selectedProjectRefKeys = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.projects
|
||||
: props.projects.filter((project) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[props.projects, selectedProjectRefKeys],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.threads
|
||||
: props.threads.filter((thread) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
),
|
||||
[props.threads, selectedProjectRefKeys],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.pendingTasks
|
||||
: props.pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
),
|
||||
[props.pendingTasks, selectedProjectRefKeys],
|
||||
);
|
||||
|
||||
const projectGroups = useMemo(
|
||||
() =>
|
||||
buildHomeThreadGroups({
|
||||
projects: props.projects,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
projects: scopedProjects,
|
||||
threads: scopedThreads,
|
||||
pendingTasks: scopedPendingTasks,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
@@ -237,14 +323,14 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projectGroupingMode,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threadSortOrder,
|
||||
props.threads,
|
||||
scopedPendingTasks,
|
||||
scopedProjects,
|
||||
scopedThreads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -267,6 +353,269 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const projectByKey = useMemo(() => {
|
||||
const map = new Map<string, EnvironmentProject>();
|
||||
for (const project of props.projects) {
|
||||
map.set(scopedProjectKey(project.environmentId, project.id), project);
|
||||
}
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const v2ProjectScopeKey = props.selectedProjectKey;
|
||||
const v2ScopeProjects = useMemo(
|
||||
() =>
|
||||
sortHomeProjectScopes({
|
||||
scopes: projectScopes,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
projectScopes,
|
||||
],
|
||||
);
|
||||
const v2ScopedProjectGroup = useMemo(
|
||||
() =>
|
||||
v2ProjectScopeKey === null
|
||||
? null
|
||||
: (v2ScopeProjects.find(
|
||||
(scope) =>
|
||||
scope.key === v2ProjectScopeKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
v2ProjectScopeKey,
|
||||
),
|
||||
) ?? 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
|
||||
? null
|
||||
: new Set(
|
||||
v2ScopedProjectGroup.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[v2ScopedProjectGroup],
|
||||
);
|
||||
// Thread List v2 (beta): one flat list in creation order, no grouping.
|
||||
// Settled threads collapse into a recency tail below the card block.
|
||||
// Settled threads stay in the live shell stream (settled ≠ archived), so
|
||||
// the partition works directly off live shells — no snapshot merging or
|
||||
// optimistic holds.
|
||||
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
|
||||
// closed PR auto-settles its thread on the next partition (mirrors web).
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
const handleChangeRequestState = useCallback(
|
||||
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
|
||||
setChangeRequestStateByKey((current) => {
|
||||
if ((current.get(threadKey) ?? null) === state) return current;
|
||||
const next = new Map(current);
|
||||
if (state === null) {
|
||||
next.delete(threadKey);
|
||||
} else {
|
||||
next.set(threadKey, state);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleSettleThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onSettleThread(thread);
|
||||
},
|
||||
[props.onSettleThread],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
// context changes so environment/search flips never inherit a deep page.
|
||||
const [settledVisibleCount, setSettledVisibleCount] = useState(
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
);
|
||||
const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
|
||||
const lastSettledResetKeyRef = useRef(settledResetKey);
|
||||
if (lastSettledResetKeyRef.current !== settledResetKey) {
|
||||
lastSettledResetKeyRef.current = settledResetKey;
|
||||
setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
|
||||
}
|
||||
const showMoreSettled = useCallback(
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
// now is quantized to the minute and ticks so the inactivity auto-settle
|
||||
// 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
|
||||
// by the time the beta is switched on, which would misclassify the
|
||||
// inactivity auto-settle boundary until the first tick.
|
||||
setNowMinute(new Date().toISOString().slice(0, 16));
|
||||
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
|
||||
return () => clearInterval(id);
|
||||
}, [threadListV2Enabled]);
|
||||
// Threads on servers without the settlement capability never classify as
|
||||
// settled (the user could neither un-settle nor pin them).
|
||||
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
|
||||
const settlementEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSettlement === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
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, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
threads: props.threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
|
||||
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(
|
||||
({ item }: { readonly item: ThreadListV2Item }) => (
|
||||
<ThreadListV2Row
|
||||
thread={item.thread}
|
||||
variant={item.variant}
|
||||
showSettledDivider={item.showSettledDivider}
|
||||
project={
|
||||
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)
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
Object.keys(props.savedConnectionsById).length > 1
|
||||
? (props.savedConnectionsById[item.thread.environmentId]?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(item.thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
),
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handleSettleThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onSelectThread,
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
(item: ThreadListV2Item) => `${item.thread.environmentId}:${item.thread.id}`,
|
||||
[],
|
||||
);
|
||||
|
||||
const extraData = useMemo(
|
||||
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
|
||||
[props.savedConnectionsById, projectCwdByKey],
|
||||
@@ -360,6 +709,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
|
||||
|
||||
/* Empty states */
|
||||
// The signal must ignore the search/environment filters: an active query
|
||||
// that matches nothing needs the in-list "No results" state, not the
|
||||
// full-page "No threads yet". Settled threads are unarchived live shells,
|
||||
// so the v1 check already covers v2.
|
||||
const hasAnyThreads =
|
||||
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
|
||||
const hasResults = projectGroups.length > 0;
|
||||
@@ -436,9 +789,50 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
</>
|
||||
);
|
||||
|
||||
// v2 renders queued offline tasks above the thread cards — they are not
|
||||
// thread shells, so the v2 item builder never sees them, but they must
|
||||
// stay visible and deletable while their environment is offline. They
|
||||
// respect the same environment scope and search filter as the list.
|
||||
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
|
||||
const v2PendingTasks = props.pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
(props.selectedEnvironmentId === null ||
|
||||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
|
||||
(v2ScopedProjectKeys === null ||
|
||||
v2ScopedProjectKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
)) &&
|
||||
(v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
|
||||
);
|
||||
// Project scoping lives in the header filter menu (no inline chip row on
|
||||
// mobile — the menu is the one filter surface).
|
||||
const v2ListHeader = (
|
||||
<>
|
||||
{listHeader}
|
||||
{v2PendingTasks.map((pendingTask, index) => (
|
||||
<PendingTaskListRow
|
||||
key={pendingTask.message.messageId}
|
||||
variant="compact"
|
||||
pendingTask={pendingTask}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[pendingTask.message.environmentId]?.environmentLabel ?? null
|
||||
}
|
||||
isLast={index === v2PendingTasks.length - 1}
|
||||
onSelectPendingTask={props.onSelectPendingTask}
|
||||
onDeletePendingTask={props.onDeletePendingTask}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : selectedProjectScope !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedProjectScope.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : selectedEnvironmentLabel ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedEnvironmentLabel}`}
|
||||
@@ -448,6 +842,93 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
|
||||
)
|
||||
) : null;
|
||||
// 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. 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 ? (
|
||||
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}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : (
|
||||
listEmpty
|
||||
);
|
||||
|
||||
if (threadListV2Enabled) {
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<FlatList
|
||||
data={threadListV2Items}
|
||||
renderItem={renderV2Item}
|
||||
keyExtractor={v2KeyExtractor}
|
||||
extraData={{
|
||||
projectByKey,
|
||||
serverConfigs,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
}}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListFooterComponent={
|
||||
threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
|
||||
onPress={showMoreSettled}
|
||||
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-muted">
|
||||
Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null
|
||||
}
|
||||
ListEmptyComponent={v2ListEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
{...scrollGateHandlers}
|
||||
scrollEventThrottle={16}
|
||||
contentContainerStyle={{
|
||||
paddingBottom:
|
||||
Platform.OS === "ios"
|
||||
? Math.max(insets.bottom, 24) + 96
|
||||
: Math.max(insets.bottom, 16) + 88,
|
||||
}}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { buildHomeListFilterMenu } from "./home-list-filter-menu";
|
||||
|
||||
describe("buildHomeListFilterMenu", () => {
|
||||
it("adds a project scope submenu that selects and clears the same scope as the chips", () => {
|
||||
const onProjectChange = vi.fn();
|
||||
const menu = buildHomeListFilterMenu({
|
||||
environments: [],
|
||||
projects: [
|
||||
{ key: "environment-1:project-1", label: "Codething" },
|
||||
{ key: "environment-1:project-2", label: "Website" },
|
||||
],
|
||||
selectedEnvironmentId: null,
|
||||
selectedProjectKey: "environment-1:project-1",
|
||||
projectSortOrder: "updated_at",
|
||||
threadSortOrder: "updated_at",
|
||||
onEnvironmentChange: vi.fn(),
|
||||
onProjectChange,
|
||||
onProjectSortOrderChange: vi.fn(),
|
||||
onThreadSortOrderChange: vi.fn(),
|
||||
});
|
||||
|
||||
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: [
|
||||
{ title: "All projects", state: "off" },
|
||||
{ title: "Codething", state: "on" },
|
||||
{ title: "Website", state: "off" },
|
||||
],
|
||||
});
|
||||
if (projectMenu?.type !== "submenu") throw new Error("Expected project submenu");
|
||||
|
||||
projectMenu.items[0]?.onPress();
|
||||
projectMenu.items[2]?.onPress();
|
||||
expect(onProjectChange).toHaveBeenNthCalledWith(1, null);
|
||||
expect(onProjectChange).toHaveBeenNthCalledWith(2, "environment-1:project-2");
|
||||
});
|
||||
});
|
||||
@@ -1,21 +1,18 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
import { PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS } from "./home-list-options";
|
||||
|
||||
export interface HomeListFilterMenuEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
export interface HomeListFilterMenuProject {
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
type HomeListFilterMenuAction = {
|
||||
readonly type: "action";
|
||||
readonly title: string;
|
||||
@@ -37,81 +34,91 @@ export interface HomeListFilterMenu {
|
||||
|
||||
export function buildHomeListFilterMenu(props: {
|
||||
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
|
||||
readonly projects: ReadonlyArray<HomeListFilterMenuProject>;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => 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. */
|
||||
readonly listOrganization?: boolean;
|
||||
}): HomeListFilterMenu {
|
||||
const items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu> = [];
|
||||
|
||||
if (props.onOpenSettings) {
|
||||
items.push({
|
||||
type: "action",
|
||||
title: "Settings",
|
||||
onPress: props.onOpenSettings,
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
type: "submenu",
|
||||
title: "Environment",
|
||||
items: [
|
||||
{
|
||||
type: "action",
|
||||
title: "All environments",
|
||||
subtitle: "Show threads from every environment",
|
||||
state: props.selectedEnvironmentId === null ? "on" : "off",
|
||||
onPress: () => props.onEnvironmentChange(null),
|
||||
},
|
||||
...props.environments.map((environment) => ({
|
||||
type: "action" as const,
|
||||
title: environment.label,
|
||||
state:
|
||||
props.selectedEnvironmentId === environment.environmentId
|
||||
? ("on" as const)
|
||||
: ("off" as const),
|
||||
onPress: () => props.onEnvironmentChange(environment.environmentId),
|
||||
})),
|
||||
],
|
||||
});
|
||||
|
||||
items.push(
|
||||
{
|
||||
if (props.projects.length > 0) {
|
||||
items.push({
|
||||
type: "submenu",
|
||||
title: "Environment",
|
||||
title: "Project",
|
||||
items: [
|
||||
{
|
||||
type: "action",
|
||||
title: "All environments",
|
||||
subtitle: "Show threads from every environment",
|
||||
state: props.selectedEnvironmentId === null ? "on" : "off",
|
||||
onPress: () => props.onEnvironmentChange(null),
|
||||
title: "All projects",
|
||||
subtitle: "Show threads from every project",
|
||||
state: props.selectedProjectKey === null ? "on" : "off",
|
||||
onPress: () => props.onProjectChange(null),
|
||||
},
|
||||
...props.environments.map((environment) => ({
|
||||
...props.projects.map((project) => ({
|
||||
type: "action" as const,
|
||||
title: environment.label,
|
||||
state:
|
||||
props.selectedEnvironmentId === environment.environmentId
|
||||
? ("on" as const)
|
||||
: ("off" as const),
|
||||
onPress: () => props.onEnvironmentChange(environment.environmentId),
|
||||
title: project.label,
|
||||
state: props.selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
|
||||
onPress: () => props.onProjectChange(project.key),
|
||||
})),
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort projects",
|
||||
items: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.projectSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort threads",
|
||||
items: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.threadSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onThreadSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Group projects",
|
||||
items: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
subtitle: option.subtitle,
|
||||
state: props.projectGroupingMode === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectGroupingModeChange(option.value),
|
||||
})),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (props.listOrganization !== false) {
|
||||
items.push(
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort projects",
|
||||
items: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.projectSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort threads",
|
||||
items: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.threadSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onThreadSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
title: "Thread list options",
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -14,7 +13,6 @@ const defaults: HomeListOptions = {
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
|
||||
describe("home list options", () => {
|
||||
@@ -22,10 +20,12 @@ describe("home list options", () => {
|
||||
expect(hasCustomHomeListOptions(defaults)).toBe(false);
|
||||
});
|
||||
|
||||
it("marks environment filters and grouping changes as customized", () => {
|
||||
it("marks environment filters as customized", () => {
|
||||
expect(
|
||||
hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }),
|
||||
).toBe(true);
|
||||
expect(hasCustomHomeListOptions({ ...defaults, projectGroupingMode: "separate" })).toBe(true);
|
||||
expect(
|
||||
hasCustomHomeListOptions({ ...defaults, selectedProjectKey: "environment-1:project-1" }),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -26,9 +25,18 @@ export interface HomeListOptions {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
}
|
||||
|
||||
export interface ResolvedHomeListOptions extends HomeListOptions {
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
export function resolveProjectGroupingMode(
|
||||
projectGroupingEnabled: boolean | undefined,
|
||||
): SidebarProjectGroupingMode {
|
||||
return projectGroupingEnabled === false ? "separate" : "repository";
|
||||
}
|
||||
|
||||
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: HomeProjectSortOrder;
|
||||
readonly label: string;
|
||||
@@ -45,28 +53,6 @@ export const THREAD_SORT_OPTIONS: ReadonlyArray<{
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
export const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarProjectGroupingMode;
|
||||
readonly label: string;
|
||||
readonly subtitle: string;
|
||||
}> = [
|
||||
{
|
||||
value: "repository",
|
||||
label: "Group by repository",
|
||||
subtitle: "Combine matching repositories across environments",
|
||||
},
|
||||
{
|
||||
value: "repository_path",
|
||||
label: "Group by repository path",
|
||||
subtitle: "Combine only matching paths within a repository",
|
||||
},
|
||||
{
|
||||
value: "separate",
|
||||
label: "Keep separate",
|
||||
subtitle: "Show every project path separately",
|
||||
},
|
||||
];
|
||||
|
||||
function defaultHomeListOptions(): HomeListOptions {
|
||||
return {
|
||||
selectedEnvironmentId: null,
|
||||
@@ -75,34 +61,44 @@ function defaultHomeListOptions(): HomeListOptions {
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
}
|
||||
|
||||
interface HomeListOptionsContextValue {
|
||||
readonly options: HomeListOptions;
|
||||
readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>(null);
|
||||
|
||||
/** Keeps list preferences stable while the app moves between compact and split shells. */
|
||||
export function HomeListOptionsProvider({ children }: PropsWithChildren) {
|
||||
export function HomeListOptionsProvider({
|
||||
children,
|
||||
projectGroupingMode,
|
||||
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
|
||||
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
|
||||
const value = useMemo(() => ({ options, setOptions }), [options]);
|
||||
const value = useMemo(
|
||||
() => ({ options, setOptions, projectGroupingMode }),
|
||||
[options, projectGroupingMode],
|
||||
);
|
||||
return createElement(HomeListOptionsContext, { value }, children);
|
||||
}
|
||||
|
||||
export function hasCustomHomeListOptions(options: HomeListOptions): boolean {
|
||||
export function hasCustomHomeListOptions(
|
||||
options: HomeListOptions & {
|
||||
readonly selectedProjectKey?: string | null;
|
||||
},
|
||||
): boolean {
|
||||
const defaultProjectSortOrder =
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER;
|
||||
return (
|
||||
options.selectedEnvironmentId !== null ||
|
||||
(options.selectedProjectKey !== null && options.selectedProjectKey !== undefined) ||
|
||||
options.projectSortOrder !== defaultProjectSortOrder ||
|
||||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
|
||||
options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE
|
||||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER
|
||||
);
|
||||
}
|
||||
|
||||
@@ -116,10 +112,14 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
|
||||
availableEnvironmentIds.has(options.selectedEnvironmentId)
|
||||
? options.selectedEnvironmentId
|
||||
: null;
|
||||
const resolvedOptions =
|
||||
const availableOptions =
|
||||
selectedEnvironmentId === options.selectedEnvironmentId
|
||||
? options
|
||||
: { ...options, selectedEnvironmentId };
|
||||
const resolvedOptions: ResolvedHomeListOptions = {
|
||||
...availableOptions,
|
||||
projectGroupingMode: shared?.projectGroupingMode ?? "repository",
|
||||
};
|
||||
|
||||
const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {
|
||||
setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
|
||||
@@ -130,15 +130,10 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
|
||||
const setThreadSortOrder = useCallback((value: SidebarThreadSortOrder) => {
|
||||
setOptions((current) => ({ ...current, threadSortOrder: value }));
|
||||
}, []);
|
||||
const setProjectGroupingMode = useCallback((value: SidebarProjectGroupingMode) => {
|
||||
setOptions((current) => ({ ...current, projectGroupingMode: value }));
|
||||
}, []);
|
||||
|
||||
return {
|
||||
options: resolvedOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
setProjectGroupingMode,
|
||||
} as const;
|
||||
}
|
||||
@@ -47,6 +47,8 @@ function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -5,7 +5,11 @@ import type {
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildHomeThreadGroups } from "./homeThreadList";
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -41,6 +45,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -65,6 +71,346 @@ function buildGroups(
|
||||
}
|
||||
|
||||
describe("buildHomeThreadGroups", () => {
|
||||
it("builds one v2 scope for the same repository across environments", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
];
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.title).toBe("t3code");
|
||||
expect(scopes[0]?.projects).toEqual(projects);
|
||||
expect(scopes[0]?.projectRefs).toEqual(
|
||||
projects.map((project) => ({
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
it("routes stale duplicate project refs through the canonical repository group", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const local = makeProject({
|
||||
id: ProjectId.make("project-local"),
|
||||
environmentId: localEnvironmentId,
|
||||
title: "t3code",
|
||||
workspaceRoot: "/workspaces/t3code",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const stale = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-stale"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
});
|
||||
const canonicalRemote = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-canonical-remote"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code/",
|
||||
repositoryIdentity,
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const projects = [local, stale, canonicalRemote];
|
||||
const staleThread = makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("thread-stale-project-ref"),
|
||||
projectId: stale.id,
|
||||
title: "Still visible",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
const groups = buildGroups(projects, [staleThread]);
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.projects.map((project) => project.id)).toEqual([
|
||||
local.id,
|
||||
canonicalRemote.id,
|
||||
]);
|
||||
expect(scopes[0]?.projectRefs.map((projectRef) => projectRef.projectId)).toEqual([
|
||||
local.id,
|
||||
stale.id,
|
||||
canonicalRemote.id,
|
||||
]);
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.threads.map((thread) => thread.id)).toEqual([staleThread.id]);
|
||||
expect(groups[0]?.newThreadTarget?.id).toBe(canonicalRemote.id);
|
||||
});
|
||||
|
||||
it("keeps repository identity from an older duplicate when the freshness winner lacks it", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote-with-identity"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code",
|
||||
repositoryIdentity,
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote-fresh"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code/",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.representative.id).toBe(ProjectId.make("project-local"));
|
||||
expect(scopes[0]?.projects.map((project) => project.id)).toContain(
|
||||
ProjectId.make("project-remote-fresh"),
|
||||
);
|
||||
expect(scopes[0]?.projectRefs).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("sorts v2 project scopes by their grouped thread activity", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const olderProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-older"),
|
||||
title: "Older project",
|
||||
});
|
||||
const newerProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-newer"),
|
||||
title: "Newer project",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [newerProject, olderProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "separate",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-older-project"),
|
||||
projectId: olderProject.id,
|
||||
title: "Most recently active",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-newer-project"),
|
||||
projectId: newerProject.id,
|
||||
title: "Less recently active",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
}).map((scope) => scope.representative.id),
|
||||
).toEqual([olderProject.id, newerProject.id]);
|
||||
});
|
||||
|
||||
it("sorts invalid project creation timestamps after valid ones", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const invalidProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-invalid"),
|
||||
title: "A invalid timestamp",
|
||||
createdAt: "invalid",
|
||||
});
|
||||
const validProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-valid"),
|
||||
title: "Z valid timestamp",
|
||||
createdAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [invalidProject, validProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "separate",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "created_at",
|
||||
}).map((scope) => scope.representative.id),
|
||||
).toEqual([validProject.id, invalidProject.id]);
|
||||
});
|
||||
|
||||
it("uses the freshest member when a grouped scope has no activity", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const olderMember = makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-older-member"),
|
||||
title: "t3code",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const newerMember = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-newer-member"),
|
||||
title: "t3code",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const otherProject = makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-other"),
|
||||
title: "other",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [olderMember, newerMember, otherProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
})[0]?.key,
|
||||
).toBe(scopes.find((scope) => scope.projects.length === 2)?.key);
|
||||
});
|
||||
|
||||
it("does not merge unrelated repositories that share a title", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const projects = ["one", "two"].map((name) =>
|
||||
makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make(`project-${name}`),
|
||||
title: "app",
|
||||
repositoryIdentity: {
|
||||
canonicalKey: `github.com/example/${name}`,
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: `[email protected]:example/${name}.git`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
}),
|
||||
).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({
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import {
|
||||
deriveLogicalProjectKey,
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupLabel,
|
||||
} from "@t3tools/client-runtime/state/project-grouping";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import {
|
||||
getThreadSortTimestamp,
|
||||
sortThreads,
|
||||
toSortableTimestamp,
|
||||
} from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ScopedProjectRef,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarProjectSortOrder,
|
||||
SidebarThreadSortOrder,
|
||||
@@ -22,6 +28,161 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
|
||||
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
|
||||
|
||||
export interface HomeProjectScope {
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly representative: EnvironmentProject;
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
|
||||
}
|
||||
|
||||
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
|
||||
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
|
||||
}
|
||||
|
||||
function getProjectSortTimestamp(
|
||||
project: EnvironmentProject,
|
||||
sortOrder: HomeProjectSortOrder,
|
||||
): number {
|
||||
return sortOrder === "created_at"
|
||||
? (toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY)
|
||||
: (toSortableTimestamp(project.updatedAt) ??
|
||||
toSortableTimestamp(project.createdAt) ??
|
||||
Number.NEGATIVE_INFINITY);
|
||||
}
|
||||
|
||||
export function buildHomeProjectScopes(input: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}): ReadonlyArray<HomeProjectScope> {
|
||||
const projects = input.projects.filter(
|
||||
(project) => input.environmentId === null || project.environmentId === input.environmentId,
|
||||
);
|
||||
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
|
||||
for (const project of projects) {
|
||||
const physicalKey = derivePhysicalProjectKey(project);
|
||||
const existing = projectsByPhysicalKey.get(physicalKey);
|
||||
if (existing) existing.push(project);
|
||||
else projectsByPhysicalKey.set(physicalKey, [project]);
|
||||
}
|
||||
|
||||
const winnersByPhysicalKey = new Map<
|
||||
string,
|
||||
{ readonly key: string; readonly project: EnvironmentProject }
|
||||
>();
|
||||
for (const [physicalKey, members] of projectsByPhysicalKey) {
|
||||
const project = members.reduce((winner, candidate) => {
|
||||
const freshnessDelta =
|
||||
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
|
||||
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
|
||||
? candidate
|
||||
: winner;
|
||||
});
|
||||
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
|
||||
winnersByPhysicalKey.set(physicalKey, {
|
||||
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
|
||||
project,
|
||||
});
|
||||
}
|
||||
|
||||
const groups = new Map<string, EnvironmentProject[]>();
|
||||
for (const { key, project } of winnersByPhysicalKey.values()) {
|
||||
const existing = groups.get(key);
|
||||
if (existing) existing.push(project);
|
||||
else groups.set(key, [project]);
|
||||
}
|
||||
|
||||
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
|
||||
const seenProjectRefs = new Set<string>();
|
||||
for (const project of projects) {
|
||||
const refKey = scopedProjectKey(project.environmentId, project.id);
|
||||
if (seenProjectRefs.has(refKey)) continue;
|
||||
seenProjectRefs.add(refKey);
|
||||
|
||||
const key =
|
||||
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
|
||||
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
|
||||
const refs = projectRefsByGroup.get(key);
|
||||
const projectRef = { environmentId: project.environmentId, projectId: project.id };
|
||||
if (refs) refs.push(projectRef);
|
||||
else projectRefsByGroup.set(key, [projectRef]);
|
||||
}
|
||||
|
||||
return Array.from(groups, ([key, projects]) => {
|
||||
const representative = projects[0]!;
|
||||
return {
|
||||
key,
|
||||
title: deriveProjectGroupLabel({ representative, members: projects }),
|
||||
representative,
|
||||
projects,
|
||||
projectRefs: projectRefsByGroup.get(key) ?? [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function sortHomeProjectScopes(input: {
|
||||
readonly scopes: ReadonlyArray<HomeProjectScope>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
}): ReadonlyArray<HomeProjectScope> {
|
||||
const scopeKeyByProjectRef = new Map(
|
||||
input.scopes.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.key] as const,
|
||||
),
|
||||
),
|
||||
);
|
||||
const latestActivityByScope = new Map<string, number>();
|
||||
const recordActivity = (scopeKey: string | undefined, timestamp: number) => {
|
||||
if (!scopeKey || !Number.isFinite(timestamp)) return;
|
||||
latestActivityByScope.set(
|
||||
scopeKey,
|
||||
Math.max(latestActivityByScope.get(scopeKey) ?? Number.NEGATIVE_INFINITY, timestamp),
|
||||
);
|
||||
};
|
||||
|
||||
for (const thread of input.threads) {
|
||||
if (thread.archivedAt !== null) continue;
|
||||
recordActivity(
|
||||
scopeKeyByProjectRef.get(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
getThreadSortTimestamp(thread, input.projectSortOrder),
|
||||
);
|
||||
}
|
||||
for (const pendingTask of input.pendingTasks) {
|
||||
recordActivity(
|
||||
scopeKeyByProjectRef.get(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
Date.parse(pendingTask.message.createdAt),
|
||||
);
|
||||
}
|
||||
|
||||
return Arr.sort(
|
||||
input.scopes,
|
||||
Order.mapInput(
|
||||
Order.Struct({
|
||||
timestamp: Order.flip(Order.Number),
|
||||
title: Order.String,
|
||||
key: Order.String,
|
||||
}),
|
||||
(scope: HomeProjectScope) => ({
|
||||
timestamp:
|
||||
latestActivityByScope.get(scope.key) ??
|
||||
Math.max(
|
||||
...scope.projects.map((project) =>
|
||||
getProjectSortTimestamp(project, input.projectSortOrder),
|
||||
),
|
||||
),
|
||||
title: scope.title,
|
||||
key: scope.key,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Default home view only surfaces threads active within this window, to keep the
|
||||
* screen compact while keeping recent work visible.
|
||||
@@ -103,22 +264,18 @@ export function buildHomeThreadGroups(input: {
|
||||
const groups = new Map<string, MutableHomeThreadGroup>();
|
||||
const groupKeyByProjectKey = new Map<string, string>();
|
||||
|
||||
for (const project of input.projects) {
|
||||
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const groupKey = deriveLogicalProjectKey(project, {
|
||||
groupingMode: input.projectGroupingMode,
|
||||
for (const scope of buildHomeProjectScopes(input)) {
|
||||
groups.set(scope.key, {
|
||||
key: scope.key,
|
||||
projects: [...scope.projects],
|
||||
pendingTasks: [],
|
||||
threads: [],
|
||||
});
|
||||
const physicalKey = scopedProjectKey(project.environmentId, project.id);
|
||||
groupKeyByProjectKey.set(physicalKey, groupKey);
|
||||
|
||||
const existing = groups.get(groupKey);
|
||||
if (existing) {
|
||||
existing.projects.push(project);
|
||||
} else {
|
||||
groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
|
||||
for (const projectRef of scope.projectRefs) {
|
||||
groupKeyByProjectKey.set(
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.key,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,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) ||
|
||||
@@ -215,19 +369,21 @@ export function buildHomeThreadGroups(input: {
|
||||
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
|
||||
: sortedThreads;
|
||||
|
||||
// Sorted newest-first, so the first thread whose project is a group member
|
||||
// marks the machine the user last worked on.
|
||||
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
|
||||
group.projects.some(
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
).pipe(
|
||||
// A stale project id still resolves to the canonical member with the same
|
||||
// environment/path, so quick creation follows the machine with the newest activity.
|
||||
const lastActiveProject = Arr.head(sortedThreads).pipe(
|
||||
Option.flatMap((thread) =>
|
||||
Arr.findFirst(
|
||||
input.projects,
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
),
|
||||
Option.flatMap((threadProject) =>
|
||||
Arr.findFirst(
|
||||
group.projects,
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
derivePhysicalProjectKey(project) === derivePhysicalProjectKey(threadProject),
|
||||
),
|
||||
),
|
||||
Option.getOrNull,
|
||||
|
||||
@@ -36,6 +36,8 @@ import { AppText as Text } from "../../components/AppText";
|
||||
const ACTION_ITEM_WIDTH = 58;
|
||||
const ACTION_CIRCLE_SIZE = 36;
|
||||
const ACTION_ICON_SIZE = 15;
|
||||
const COMPACT_ACTION_CIRCLE_SIZE = 28;
|
||||
const COMPACT_ACTION_ICON_SIZE = 13;
|
||||
|
||||
export const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
|
||||
export const THREAD_SWIPE_SPRING = {
|
||||
@@ -163,10 +165,20 @@ export function useSwipeableScrollGate(options?: {
|
||||
export function ThreadSwipeable(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly children: (close: () => void) => ReactNode;
|
||||
/** Uses action visuals that fit inside compact 44pt rows. The press target
|
||||
* still spans the row's full height and width. */
|
||||
readonly compactActions?: boolean;
|
||||
readonly containerStyle?: StyleProp<ViewStyle>;
|
||||
/** Disables NEW swipe activations (e.g. while the list scrolls). */
|
||||
readonly enabled?: boolean;
|
||||
readonly enableTrackpadSwipe?: boolean;
|
||||
/**
|
||||
* What a full swipe commits: "delete" (default, v1 behavior — the Delete
|
||||
* button stretches) or "primary" — the advertised primary action fires and
|
||||
* its button stretches instead. A full swipe must always match the action
|
||||
* the stretching button advertises.
|
||||
*/
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeWidth: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
|
||||
@@ -239,7 +251,11 @@ export function ThreadSwipeable(props: {
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
if (props.fullSwipeAction === "primary") {
|
||||
props.primaryAction.onPress();
|
||||
} else {
|
||||
props.onDelete();
|
||||
}
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
@@ -247,6 +263,8 @@ export function ThreadSwipeable(props: {
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
compact={props.compactActions === true}
|
||||
fullSwipeAction={props.fullSwipeAction ?? "delete"}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
@@ -273,6 +291,7 @@ export function ThreadSwipeable(props: {
|
||||
function SwipeActionButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly backgroundColor: string;
|
||||
readonly compact: boolean;
|
||||
readonly entryRange: readonly [number, number];
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
@@ -281,6 +300,8 @@ function SwipeActionButton(props: {
|
||||
readonly stretchesOnFullSwipe: boolean;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const circleSize = props.compact ? COMPACT_ACTION_CIRCLE_SIZE : ACTION_CIRCLE_SIZE;
|
||||
const iconSize = props.compact ? COMPACT_ACTION_ICON_SIZE : ACTION_ICON_SIZE;
|
||||
const actionStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
|
||||
@@ -312,7 +333,7 @@ function SwipeActionButton(props: {
|
||||
|
||||
return {
|
||||
transform: [{ translateX: -stretch }],
|
||||
width: ACTION_CIRCLE_SIZE + stretch,
|
||||
width: circleSize + stretch,
|
||||
};
|
||||
});
|
||||
const iconStyle = useAnimatedStyle(() => {
|
||||
@@ -374,13 +395,13 @@ function SwipeActionButton(props: {
|
||||
width: "100%",
|
||||
})}
|
||||
>
|
||||
<View style={{ height: ACTION_CIRCLE_SIZE, width: ACTION_CIRCLE_SIZE }}>
|
||||
<View style={{ height: circleSize, width: circleSize }}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
backgroundColor: props.backgroundColor,
|
||||
borderRadius: 999,
|
||||
height: ACTION_CIRCLE_SIZE,
|
||||
height: circleSize,
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
@@ -392,25 +413,25 @@ function SwipeActionButton(props: {
|
||||
style={[
|
||||
{
|
||||
alignItems: "center",
|
||||
height: ACTION_CIRCLE_SIZE,
|
||||
height: circleSize,
|
||||
justifyContent: "center",
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
width: ACTION_CIRCLE_SIZE,
|
||||
width: circleSize,
|
||||
},
|
||||
iconStyle,
|
||||
]}
|
||||
>
|
||||
<SymbolView
|
||||
name={props.icon}
|
||||
size={ACTION_ICON_SIZE}
|
||||
tintColor="#ffffff"
|
||||
type="monochrome"
|
||||
/>
|
||||
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
|
||||
</Animated.View>
|
||||
</View>
|
||||
<Animated.View style={[{ paddingTop: 2 }, labelStyle]}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
|
||||
labelStyle,
|
||||
]}
|
||||
>
|
||||
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
|
||||
{props.label}
|
||||
</Text>
|
||||
@@ -422,6 +443,8 @@ function SwipeActionButton(props: {
|
||||
|
||||
export function ThreadSwipeActions(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly compact: boolean;
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onFullSwipeArmedChange: (armed: boolean) => void;
|
||||
@@ -430,6 +453,7 @@ export function ThreadSwipeActions(props: {
|
||||
readonly threadTitle: string;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
|
||||
useAnimatedReaction(
|
||||
() => -props.translation.value >= props.fullSwipeThreshold,
|
||||
(armed, previous) => {
|
||||
@@ -452,17 +476,19 @@ export function ThreadSwipeActions(props: {
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={props.primaryAction.accessibilityLabel}
|
||||
backgroundColor="#007aff"
|
||||
compact={props.compact}
|
||||
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={props.primaryAction.icon}
|
||||
label={props.primaryAction.label}
|
||||
onPress={props.primaryAction.onPress}
|
||||
stretchesOnFullSwipe={false}
|
||||
stretchesOnFullSwipe={fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={`Delete ${props.threadTitle}`}
|
||||
backgroundColor="#ff2d55"
|
||||
compact={props.compact}
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon="trash"
|
||||
@@ -471,7 +497,7 @@ export function ThreadSwipeActions(props: {
|
||||
props.swipeableMethods.close();
|
||||
props.onDelete();
|
||||
}}
|
||||
stretchesOnFullSwipe
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useRef } from "react";
|
||||
@@ -6,19 +7,37 @@ import { Alert } from "react-native";
|
||||
|
||||
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete";
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
(capability defaults false on decode for older servers). */
|
||||
function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSettlement === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
archive: "archived",
|
||||
unarchive: "unarchived",
|
||||
delete: "deleted",
|
||||
settle: "settled",
|
||||
unsettle: "un-settled",
|
||||
};
|
||||
|
||||
function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause<unknown>): string {
|
||||
const error = Cause.squash(cause);
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
const verb =
|
||||
action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
|
||||
return `The thread could not be ${verb}.`;
|
||||
return `The thread could not be ${ACTION_VERBS[action]}.`;
|
||||
}
|
||||
|
||||
function selectionHaptic(): void {
|
||||
@@ -28,54 +47,115 @@ function selectionHaptic(): void {
|
||||
function actionFailureTitle(action: ThreadListAction): string {
|
||||
if (action === "archive") return "Could not archive thread";
|
||||
if (action === "unarchive") return "Could not unarchive thread";
|
||||
if (action === "settle") return "Could not settle thread";
|
||||
if (action === "unsettle") return "Could not un-settle thread";
|
||||
return "Could not delete thread";
|
||||
}
|
||||
|
||||
/** Resolves to true iff the action was dispatched and succeeded. */
|
||||
function useThreadActionExecutor(
|
||||
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
|
||||
) {
|
||||
const archiveMutation = useAtomCommand(threadEnvironment.archive, { reportFailure: false });
|
||||
const unarchiveMutation = useAtomCommand(threadEnvironment.unarchive, { reportFailure: false });
|
||||
const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
|
||||
const settleMutation = useAtomCommand(threadEnvironment.settle, { reportFailure: false });
|
||||
const unsettleMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
|
||||
const inFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const executeAction = useCallback(
|
||||
async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (inFlightThreadKeys.current.has(key)) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
inFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
const mutation =
|
||||
action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation;
|
||||
const result = await mutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (
|
||||
(action === "settle" || action === "unsettle") &&
|
||||
!environmentSupportsSettlement(thread.environmentId)
|
||||
) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This environment's server does not support settling yet. Update the server to use Settle.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Settle may only target what effectiveSettled could classify as
|
||||
// settled: not starting/running sessions, not threads waiting on
|
||||
// approvals or user input. Anything else would hide live work.
|
||||
if (action === "settle" && !canSettle(thread, { now: new Date().toISOString() })) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread still needs attention. Resolve or interrupt it first, then try again.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Archive keeps its original, narrower guard: never interrupt a
|
||||
// thread mid-turn.
|
||||
if (
|
||||
action === "archive" &&
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId != null
|
||||
) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread is working. Interrupt it first, then try again.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const result =
|
||||
action === "unsettle"
|
||||
? // reason "user" pins the thread active: auto-settle stays
|
||||
// suppressed until real activity clears the pin server-side.
|
||||
await unsettleMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, reason: "user" },
|
||||
})
|
||||
: await (
|
||||
action === "settle"
|
||||
? settleMutation
|
||||
: action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation
|
||||
)({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
// Settled threads stay in the live shell stream; only the archive
|
||||
// lifecycle still feeds the archived-snapshot surface.
|
||||
if (action === "archive" || action === "unarchive" || action === "delete") {
|
||||
refreshArchivedThreadsForEnvironment(thread.environmentId);
|
||||
}
|
||||
onCompleted?.(action, thread);
|
||||
return true;
|
||||
} finally {
|
||||
inFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
|
||||
[
|
||||
archiveMutation,
|
||||
deleteMutation,
|
||||
onCompleted,
|
||||
settleMutation,
|
||||
unarchiveMutation,
|
||||
unsettleMutation,
|
||||
],
|
||||
);
|
||||
|
||||
return executeAction;
|
||||
}
|
||||
|
||||
function useConfirmDeleteThread(
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<boolean>,
|
||||
) {
|
||||
return useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -111,6 +191,8 @@ function useConfirmDeleteThread(
|
||||
export function useThreadListActions(): {
|
||||
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
|
||||
@@ -120,10 +202,18 @@ export function useThreadListActions(): {
|
||||
},
|
||||
[executeAction],
|
||||
);
|
||||
const settleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const unsettleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return { archiveThread, confirmDeleteThread };
|
||||
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
|
||||
}
|
||||
|
||||
export function useArchivedThreadListActions(
|
||||
|
||||
@@ -2,7 +2,8 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useFocusEffect } from "@react-navigation/native";
|
||||
import {
|
||||
NavigationContext,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
} from "react";
|
||||
import { useWindowDimensions, View } from "react-native";
|
||||
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
deriveFileInspectorPaneLayout,
|
||||
@@ -34,11 +36,12 @@ import {
|
||||
} from "../../lib/layout";
|
||||
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import {
|
||||
parseActiveThreadPath,
|
||||
useHardwareKeyboardCommand,
|
||||
} from "../keyboard/hardwareKeyboardCommands";
|
||||
import { HomeListOptionsProvider } from "../home/home-list-options";
|
||||
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
|
||||
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
|
||||
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
|
||||
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
|
||||
@@ -184,6 +187,31 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly pathname: string;
|
||||
}) {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
return AsyncResult.isFailure(preferencesResult) ? (
|
||||
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
|
||||
) : null;
|
||||
}
|
||||
return (
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={resolveProjectGroupingMode(
|
||||
preferencesResult.value.projectGroupingEnabled,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AdaptiveWorkspaceLayoutContent(
|
||||
props: {
|
||||
readonly children: ReactNode;
|
||||
readonly pathname: string;
|
||||
} & {
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
},
|
||||
) {
|
||||
const projectGroupingMode = props.projectGroupingMode;
|
||||
const { width, height } = useWindowDimensions();
|
||||
const pathname = props.pathname;
|
||||
const navigation = useNavigation();
|
||||
@@ -474,7 +502,7 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
);
|
||||
|
||||
return (
|
||||
<HomeListOptionsProvider>
|
||||
<HomeListOptionsProvider projectGroupingMode={projectGroupingMode}>
|
||||
<AdaptiveWorkspaceContext.Provider value={contextValue}>
|
||||
<View testID="adaptive-workspace-layout" className="flex-1 flex-row">
|
||||
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
|
||||
|
||||
@@ -119,10 +119,14 @@ function LocalSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<GeneralSettingsSection />
|
||||
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -502,10 +506,14 @@ function ConfiguredSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<GeneralSettingsSection />
|
||||
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -514,6 +522,54 @@ function ConfiguredSettingsRouteScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
function GeneralSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.projectGroupingEnabled !== false
|
||||
: true;
|
||||
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsSwitchRow
|
||||
icon="folder"
|
||||
label="Project Grouping"
|
||||
value={projectGroupingEnabled}
|
||||
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Device-local beta toggles. Mobile has no client-settings sync, so this is
|
||||
* the counterpart of web's Settings → Beta backed by mobile preferences.
|
||||
*/
|
||||
function BetaSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const threadListV2Enabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.threadListV2Enabled === true
|
||||
: false;
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
<SettingsSection title="Beta">
|
||||
<SettingsSwitchRow
|
||||
icon="sidebar.left"
|
||||
label="Thread List v2"
|
||||
value={threadListV2Enabled}
|
||||
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-sm text-foreground-muted">
|
||||
One flat thread list in creation order. Active work renders as cards; settled threads
|
||||
collapse to compact rows. Switch back any time.
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function AppSettingsSection() {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -582,10 +582,13 @@ export function NewTaskDraftScreen(props: {
|
||||
? "Approve actions"
|
||||
: flow.runtimeMode === "auto-accept-edits"
|
||||
? "Auto-accept edits"
|
||||
: "Full access",
|
||||
: flow.runtimeMode === "auto"
|
||||
? "Auto"
|
||||
: "Full access",
|
||||
subactions: [
|
||||
{ id: "options:runtime:approval-required", title: "Approve actions" },
|
||||
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
|
||||
{ id: "options:runtime:auto", title: "Auto" },
|
||||
{ id: "options:runtime:full-access", title: "Full access" },
|
||||
].map((option) => {
|
||||
const value = option.id.replace("options:runtime:", "");
|
||||
|
||||
@@ -26,7 +26,13 @@ import {
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeInDown,
|
||||
FadeOut,
|
||||
FadeOutDown,
|
||||
LinearTransition,
|
||||
} from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
@@ -232,7 +238,12 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
const isReconnecting = props.status.kind !== "unavailable";
|
||||
|
||||
return (
|
||||
<View className="items-center pb-2">
|
||||
<Animated.View
|
||||
className="absolute inset-x-0 bottom-full items-center pb-2"
|
||||
entering={FadeInDown.duration(180)}
|
||||
exiting={FadeOutDown.duration(140)}
|
||||
pointerEvents="box-none"
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
@@ -250,7 +261,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
{props.status.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -627,10 +638,13 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
? "Approve actions"
|
||||
: currentRuntimeMode === "auto-accept-edits"
|
||||
? "Auto-accept edits"
|
||||
: "Full access",
|
||||
: currentRuntimeMode === "auto"
|
||||
? "Auto"
|
||||
: "Full access",
|
||||
subactions: [
|
||||
{ id: "options:runtime:approval-required", title: "Approve actions" },
|
||||
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
|
||||
{ id: "options:runtime:auto", title: "Auto" },
|
||||
{ id: "options:runtime:full-access", title: "Full access" },
|
||||
].map((option) => {
|
||||
const value = option.id.replace("options:runtime:", "");
|
||||
|
||||
@@ -14,21 +14,18 @@ import type {
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Platform, View, type GestureResponderEvent } from "react-native";
|
||||
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -172,54 +169,6 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
|
||||
}, [threadId, feed]);
|
||||
}
|
||||
|
||||
// Pre-measurement estimate for the working pill's slot (the real height is
|
||||
// measured via onComposerLayout since the pill lives inside the composer
|
||||
// overlay). Matches the rendered pill: pt-2 + pb-2 (16) wrapping a bordered
|
||||
// px-3/py-2 row (~36), so ~52 — keep it in sync with WorkingDurationPill.
|
||||
const WORKING_INDICATOR_HEIGHT = 52;
|
||||
|
||||
const WorkingDurationPill = memo(function WorkingDurationPill(props: {
|
||||
readonly startedAt: string;
|
||||
}) {
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, 1_000);
|
||||
return () => clearInterval(intervalId);
|
||||
}, [props.startedAt]);
|
||||
|
||||
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
className="shrink-0 px-4 pb-2 pt-2"
|
||||
entering={FadeInDown.duration(200)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
>
|
||||
<View
|
||||
className={
|
||||
Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? "self-start rounded-full border border-border bg-card px-3 py-2"
|
||||
: "self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]"
|
||||
}
|
||||
>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View className="flex-row items-center gap-1">
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
Working for {durationLabel}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
@@ -253,8 +202,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
const estimatedOverlayHeight = composerOverlapHeight;
|
||||
// The overlay's measured height includes the home-indicator inset (the
|
||||
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
|
||||
// UIKit add the safe-area bottom to the content inset AGAIN — leaving a
|
||||
@@ -411,6 +359,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
activeWorkStartedAt={props.activeWorkStartedAt}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
@@ -438,15 +387,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
list's bottom inset, so any padding above the pill/composer
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
<Animated.View
|
||||
className="w-full self-center"
|
||||
layout={LinearTransition.duration(220)}
|
||||
style={{ maxWidth: contentMaxWidth }}
|
||||
>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
@@ -473,7 +414,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
</View>
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
@@ -128,6 +129,7 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
@@ -816,6 +818,10 @@ function renderFeedEntry(
|
||||
const entry = info.item;
|
||||
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
||||
|
||||
if (entry.type === "working") {
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
@@ -993,6 +999,32 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
const WorkingTimelineRow = memo(function WorkingTimelineRow(props: { readonly startedAt: string }) {
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, 1_000);
|
||||
return () => clearInterval(intervalId);
|
||||
}, [props.startedAt]);
|
||||
|
||||
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
|
||||
|
||||
return (
|
||||
<View className="mb-4 flex-row items-center gap-2 px-1.5 py-1">
|
||||
<View className="flex-row items-center gap-1">
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400 dark:bg-neutral-500" />
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
|
||||
Working for {durationLabel}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function UserMessageContent(props: {
|
||||
readonly text: string;
|
||||
readonly markdownStyles: MarkdownStyleSet;
|
||||
@@ -1415,8 +1447,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
props.latestTurn,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
),
|
||||
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
|
||||
[
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
],
|
||||
);
|
||||
|
||||
// The empty↔filled key below remounts the list, which resets its imperative
|
||||
@@ -1761,7 +1800,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
{props.feed.length === 0 && props.contentPresentation.kind === "ready" ? (
|
||||
{props.feed.length === 0 &&
|
||||
props.activeWorkStartedAt === null &&
|
||||
props.contentPresentation.kind === "ready" ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
|
||||
@@ -5,9 +5,12 @@ import type {
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
|
||||
import { Platform, StyleSheet, TextInput, View, useColorScheme } from "react-native";
|
||||
import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -22,13 +25,14 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
useHomeListOptions,
|
||||
@@ -43,7 +47,7 @@ import {
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "../home/homeListItems";
|
||||
import { buildHomeThreadGroups } from "../home/homeThreadList";
|
||||
import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
|
||||
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
|
||||
import { useThreadListActions } from "../home/useThreadListActions";
|
||||
@@ -59,6 +63,27 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "./thread-list-items";
|
||||
import { ThreadListV2Row } from "./thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
|
||||
type ThreadListV2Item,
|
||||
} from "./threadListV2";
|
||||
|
||||
/** The sidebar list serves both lists: v1 grouped items or, when the Thread
|
||||
List v2 beta is on, queued offline tasks, flat v2 rows, and a settled
|
||||
"Show more" pager. */
|
||||
type SidebarListItem =
|
||||
| HomeListItem
|
||||
| {
|
||||
readonly type: "v2-pending-task";
|
||||
readonly key: string;
|
||||
readonly pendingTask: PendingNewTask;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
| { readonly type: "v2-thread"; readonly key: string; readonly item: ThreadListV2Item }
|
||||
| { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
|
||||
|
||||
/**
|
||||
* Shared capsule behind the sidebar header buttons — a native liquid-glass
|
||||
@@ -169,7 +194,12 @@ function ThreadNavigationSidebarPane(
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const headerIsOverContentRef = useRef(false);
|
||||
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -186,26 +216,109 @@ function ThreadNavigationSidebarPane(
|
||||
() => new Set(environments.map((environment) => environment.environmentId)),
|
||||
[environments],
|
||||
);
|
||||
const {
|
||||
options,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
} = useHomeListOptions(availableEnvironmentIds);
|
||||
const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
|
||||
useHomeListOptions(availableEnvironmentIds);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
}),
|
||||
[options.projectGroupingMode, options.selectedEnvironmentId, projects],
|
||||
);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
projectScopes.map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[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
|
||||
? null
|
||||
: (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
|
||||
[projectScopes, selectedProjectKey],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
selectedProjectKey !== null &&
|
||||
!projectFilterOptions.some((project) => project.key === selectedProjectKey)
|
||||
) {
|
||||
setSelectedProjectKey(null);
|
||||
}
|
||||
}, [projectFilterOptions, selectedProjectKey]);
|
||||
const selectedProjectRefs = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
? projects
|
||||
: projects.filter((project) =>
|
||||
selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[projects, selectedProjectRefs],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
? threads
|
||||
: threads.filter((thread) =>
|
||||
selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
),
|
||||
[selectedProjectRefs, threads],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
? pendingTasks
|
||||
: pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefs.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
),
|
||||
[pendingTasks, selectedProjectRefs],
|
||||
);
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
buildHomeThreadGroups({
|
||||
projects,
|
||||
threads,
|
||||
pendingTasks,
|
||||
projects: scopedProjects,
|
||||
threads: scopedThreads,
|
||||
pendingTasks: scopedPendingTasks,
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
projectSortOrder: options.projectSortOrder,
|
||||
threadSortOrder: options.threadSortOrder,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
}),
|
||||
[options, pendingTasks, projects, props.searchQuery, threads],
|
||||
[options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads],
|
||||
);
|
||||
const [groupDisplayStates, setGroupDisplayStates] = useState<
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
@@ -237,6 +350,180 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return map;
|
||||
}, [projects]);
|
||||
const projectByKey = useMemo(() => {
|
||||
const map = new Map<string, EnvironmentProject>();
|
||||
for (const project of projects) {
|
||||
map.set(scopedProjectKey(project.environmentId, project.id), project);
|
||||
}
|
||||
return map;
|
||||
}, [projects]);
|
||||
|
||||
// Thread List v2 (beta) support — same model as the compact Home list
|
||||
// (HomeScreen.tsx): flat creation-order card block + settled recency tail.
|
||||
// PR states stream in per-row; merged/closed PRs auto-settle their thread
|
||||
// on the next partition.
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
const handleChangeRequestState = useCallback(
|
||||
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
|
||||
setChangeRequestStateByKey((current) => {
|
||||
if ((current.get(threadKey) ?? null) === state) return current;
|
||||
const next = new Map(current);
|
||||
if (state === null) {
|
||||
next.delete(threadKey);
|
||||
} else {
|
||||
next.set(threadKey, state);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
// context changes so environment/search flips never inherit a deep page.
|
||||
const [settledVisibleCount, setSettledVisibleCount] = useState(
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
);
|
||||
const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
|
||||
const lastSettledResetKeyRef = useRef(settledResetKey);
|
||||
if (lastSettledResetKeyRef.current !== settledResetKey) {
|
||||
lastSettledResetKeyRef.current = settledResetKey;
|
||||
setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
|
||||
}
|
||||
const showMoreSettled = useCallback(
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
// now ticks per minute so the inactivity auto-settle boundary is actually
|
||||
// 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
|
||||
// by the time the beta is switched on, which would misclassify the
|
||||
// inactivity auto-settle boundary until the first tick.
|
||||
setNowMinute(new Date().toISOString().slice(0, 16));
|
||||
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
|
||||
return () => clearInterval(id);
|
||||
}, [threadListV2Enabled]);
|
||||
// Threads on servers without the settlement capability never classify as
|
||||
// settled (the user could neither un-settle nor pin them).
|
||||
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
|
||||
const settlementEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSettlement === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
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, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
|
||||
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
|
||||
// compact Home v2 list): they are not thread shells, so the v2 item
|
||||
// builder never sees them, but they must stay visible and deletable
|
||||
// while their environment is offline. Same environment scope and
|
||||
// search filter as the list.
|
||||
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
|
||||
const v2PendingTasks = pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
(options.selectedEnvironmentId === null ||
|
||||
pendingTask.message.environmentId === options.selectedEnvironmentId) &&
|
||||
(selectedProjectRefs === null ||
|
||||
selectedProjectRefs.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
)) &&
|
||||
(v2SearchQuery.length === 0 ||
|
||||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
|
||||
);
|
||||
const items: SidebarListItem[] = v2PendingTasks.map((pendingTask, index) => ({
|
||||
type: "v2-pending-task" as const,
|
||||
key: `v2-pending:${pendingTask.message.messageId}`,
|
||||
pendingTask,
|
||||
isLast: index === v2PendingTasks.length - 1,
|
||||
}));
|
||||
for (const item of threadListV2Layout.items) {
|
||||
items.push({
|
||||
type: "v2-thread" as const,
|
||||
key: scopedThreadKey(item.thread.environmentId, item.thread.id),
|
||||
item,
|
||||
});
|
||||
}
|
||||
if (threadListV2Layout.hiddenSettledCount > 0) {
|
||||
items.push({
|
||||
type: "v2-show-more",
|
||||
key: "v2-show-more",
|
||||
hiddenCount: threadListV2Layout.hiddenSettledCount,
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}, [
|
||||
listLayout.items,
|
||||
options.selectedEnvironmentId,
|
||||
pendingTasks,
|
||||
props.searchQuery,
|
||||
selectedProjectRefs,
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
|
||||
const listMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
@@ -260,36 +547,54 @@ function ThreadNavigationSidebarPane(
|
||||
})),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "project-sort",
|
||||
title: "Sort projects",
|
||||
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
id: `project-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: options.projectSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "thread-sort",
|
||||
title: "Sort threads",
|
||||
subactions: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
id: `thread-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: options.threadSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "project-grouping",
|
||||
title: "Group projects",
|
||||
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
id: `project-grouping:${option.value}`,
|
||||
title: option.label,
|
||||
subtitle: option.subtitle,
|
||||
state: options.projectGroupingMode === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
...(projectFilterOptions.length === 0
|
||||
? []
|
||||
: ([
|
||||
{
|
||||
id: "project",
|
||||
title: "Project",
|
||||
subactions: [
|
||||
{
|
||||
id: "project:all",
|
||||
title: "All projects",
|
||||
subtitle: "Show threads from every project",
|
||||
state: selectedProjectKey === null ? "on" : "off",
|
||||
},
|
||||
...projectFilterOptions.map((project) => ({
|
||||
id: `project:${project.key}`,
|
||||
title: project.label,
|
||||
state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
|
||||
})),
|
||||
],
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
// v2 lays the list out in fixed creation order — offering sort/group
|
||||
// controls it silently ignores would be a lie. Environment still
|
||||
// scopes the v2 partition, so it stays.
|
||||
...(threadListV2Enabled
|
||||
? []
|
||||
: ([
|
||||
{
|
||||
id: "project-sort",
|
||||
title: "Sort projects",
|
||||
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
id: `project-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: options.projectSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "thread-sort",
|
||||
title: "Sort threads",
|
||||
subactions: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
id: `thread-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: options.threadSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
],
|
||||
[environments, options],
|
||||
[environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
|
||||
);
|
||||
const handleListMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
@@ -305,6 +610,17 @@ function ThreadNavigationSidebarPane(
|
||||
if (environment) setSelectedEnvironmentId(environment.environmentId);
|
||||
return;
|
||||
}
|
||||
if (event === "project:all") {
|
||||
setSelectedProjectKey(null);
|
||||
return;
|
||||
}
|
||||
if (event.startsWith("project:")) {
|
||||
const projectKey = event.slice("project:".length);
|
||||
if (projectFilterOptions.some((project) => project.key === projectKey)) {
|
||||
setSelectedProjectKey(projectKey);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const projectSort = PROJECT_SORT_OPTIONS.find(
|
||||
(option) => `project-sort:${option.value}` === event,
|
||||
);
|
||||
@@ -319,14 +635,10 @@ function ThreadNavigationSidebarPane(
|
||||
setThreadSortOrder(threadSort.value);
|
||||
return;
|
||||
}
|
||||
const grouping = PROJECT_GROUPING_OPTIONS.find(
|
||||
(option) => `project-grouping:${option.value}` === event,
|
||||
);
|
||||
if (grouping) setProjectGroupingMode(grouping.value);
|
||||
},
|
||||
[
|
||||
environments,
|
||||
setProjectGroupingMode,
|
||||
projectFilterOptions,
|
||||
setProjectSortOrder,
|
||||
setSelectedEnvironmentId,
|
||||
setThreadSortOrder,
|
||||
@@ -382,7 +694,44 @@ function ThreadNavigationSidebarPane(
|
||||
onScroll: handleScroll,
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
const listExtraData = props.selectedThreadKey ?? "";
|
||||
const listExtraData = useMemo(
|
||||
() => ({
|
||||
selectedThreadKey: props.selectedThreadKey ?? "",
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
}),
|
||||
[props.selectedThreadKey, savedConnectionsById, serverConfigs],
|
||||
);
|
||||
const sidebarItemsAreEqual = useCallback(
|
||||
(previous: SidebarListItem, item: SidebarListItem): boolean => {
|
||||
if (previous.type === "v2-thread" && item.type === "v2-thread") {
|
||||
return (
|
||||
previous.key === item.key &&
|
||||
previous.item.thread === item.item.thread &&
|
||||
previous.item.variant === item.item.variant &&
|
||||
previous.item.showSettledDivider === item.item.showSettledDivider
|
||||
);
|
||||
}
|
||||
if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
|
||||
return previous.hiddenCount === item.hiddenCount;
|
||||
}
|
||||
if (previous.type === "v2-pending-task" && item.type === "v2-pending-task") {
|
||||
return previous.pendingTask === item.pendingTask && previous.isLast === item.isLast;
|
||||
}
|
||||
if (
|
||||
previous.type === "v2-thread" ||
|
||||
previous.type === "v2-show-more" ||
|
||||
previous.type === "v2-pending-task" ||
|
||||
item.type === "v2-thread" ||
|
||||
item.type === "v2-show-more" ||
|
||||
item.type === "v2-pending-task"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return homeListItemsAreEqual(previous, item);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const focusSearch = useCallback(() => {
|
||||
const focus = () => {
|
||||
if (props.nativeChrome) {
|
||||
@@ -401,8 +750,79 @@ function ThreadNavigationSidebarPane(
|
||||
}, [props.nativeChrome, props.onRequestVisibility, props.visible]);
|
||||
useHardwareKeyboardCommand("focusSearch", focusSearch);
|
||||
const renderListItem = useCallback(
|
||||
({ item }: { readonly item: HomeListItem }) => {
|
||||
({ item }: { readonly item: SidebarListItem }) => {
|
||||
switch (item.type) {
|
||||
case "v2-pending-task":
|
||||
return (
|
||||
<PendingTaskListRow
|
||||
variant="sidebar"
|
||||
pendingTask={item.pendingTask}
|
||||
environmentLabel={
|
||||
savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
|
||||
null
|
||||
}
|
||||
isLast={item.isLast}
|
||||
onSelectPendingTask={openPendingTask}
|
||||
onDeletePendingTask={confirmDeletePendingTask}
|
||||
/>
|
||||
);
|
||||
case "v2-thread": {
|
||||
const thread = item.item.thread;
|
||||
const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
|
||||
return (
|
||||
<ThreadListV2Row
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
projectTitle={projectTitleByProjectKey.get(scopeKey)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(thread.environmentId)
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
Object.keys(savedConnectionsById).length > 1
|
||||
? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
pane="sidebar"
|
||||
selected={
|
||||
scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
|
||||
}
|
||||
fullSwipeWidth={props.width - 20}
|
||||
onSelectThread={handleSelectThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onArchiveThread={archiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
simultaneousSwipeGesture={sidebarScrollGesture}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case "v2-show-more":
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Show ${Math.min(item.hiddenCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
|
||||
onPress={showMoreSettled}
|
||||
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-muted">
|
||||
Show more ({item.hiddenCount} settled hidden)
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
case "header":
|
||||
return (
|
||||
<ThreadListGroupHeader
|
||||
@@ -478,42 +898,59 @@ function ThreadNavigationSidebarPane(
|
||||
archiveThread,
|
||||
confirmDeletePendingTask,
|
||||
confirmDeleteThread,
|
||||
handleChangeRequestState,
|
||||
handleSelectThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
openPendingTask,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
props.onNewThreadInProject,
|
||||
props.selectedThreadKey,
|
||||
props.width,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
settleThread,
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
sidebarScrollGesture,
|
||||
unsettleThread,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
const filterIcon = hasCustomHomeListOptions(options)
|
||||
// v2 ignores the sort/group options, so only the environment filter can
|
||||
// light the "customized" state while the beta is on.
|
||||
const filterCustomized = threadListV2Enabled
|
||||
? options.selectedEnvironmentId !== null || selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions({ ...options, selectedProjectKey });
|
||||
const filterIcon = filterCustomized
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle";
|
||||
const filterMenu = useMemo(
|
||||
() =>
|
||||
buildHomeListFilterMenu({
|
||||
environments,
|
||||
projects: projectFilterOptions,
|
||||
selectedEnvironmentId: options.selectedEnvironmentId,
|
||||
selectedProjectKey,
|
||||
projectSortOrder: options.projectSortOrder,
|
||||
threadSortOrder: options.threadSortOrder,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
onEnvironmentChange: setSelectedEnvironmentId,
|
||||
onProjectChange: setSelectedProjectKey,
|
||||
onProjectSortOrderChange: setProjectSortOrder,
|
||||
onThreadSortOrderChange: setThreadSortOrder,
|
||||
onProjectGroupingModeChange: setProjectGroupingMode,
|
||||
listOrganization: !threadListV2Enabled,
|
||||
}),
|
||||
[
|
||||
environments,
|
||||
options,
|
||||
setProjectGroupingMode,
|
||||
projectFilterOptions,
|
||||
selectedProjectKey,
|
||||
setProjectSortOrder,
|
||||
setSelectedEnvironmentId,
|
||||
setThreadSortOrder,
|
||||
threadListV2Enabled,
|
||||
],
|
||||
);
|
||||
const nativeHeaderItems = useMemo(
|
||||
@@ -525,13 +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"
|
||||
: "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>
|
||||
);
|
||||
|
||||
@@ -539,6 +991,7 @@ function ThreadNavigationSidebarPane(
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
optionsVersion={nativeHeaderItems}
|
||||
options={{
|
||||
headerSearchBarOptions: {
|
||||
ref: searchBarRef,
|
||||
@@ -564,12 +1017,12 @@ function ThreadNavigationSidebarPane(
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<GestureDetector gesture={sidebarScrollGesture}>
|
||||
<LegendList
|
||||
data={listLayout.items}
|
||||
data={listItems}
|
||||
drawDistance={500}
|
||||
estimatedItemSize={64}
|
||||
extraData={listExtraData}
|
||||
getItemType={(item) => item.type}
|
||||
itemsAreEqual={homeListItemsAreEqual}
|
||||
itemsAreEqual={sidebarItemsAreEqual}
|
||||
keyExtractor={(item) => item.key}
|
||||
renderItem={renderListItem}
|
||||
automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
|
||||
@@ -625,12 +1078,12 @@ function ThreadNavigationSidebarPane(
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<GestureDetector gesture={sidebarScrollGesture}>
|
||||
<LegendList
|
||||
data={listLayout.items}
|
||||
data={listItems}
|
||||
drawDistance={500}
|
||||
estimatedItemSize={64}
|
||||
extraData={listExtraData}
|
||||
getItemType={(item) => item.type}
|
||||
itemsAreEqual={homeListItemsAreEqual}
|
||||
itemsAreEqual={sidebarItemsAreEqual}
|
||||
keyExtractor={(item) => item.key}
|
||||
renderItem={renderListItem}
|
||||
contentContainerStyle={[
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
|
||||
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
|
||||
|
||||
/**
|
||||
* Thread List v2 renders one flat native list: rich edge-to-edge rows for
|
||||
* active work and a receded settled tail, all with native swipe and
|
||||
* long-press actions. State reads through colored status labels and text
|
||||
* hierarchy rather than card fills.
|
||||
*/
|
||||
|
||||
const MONO_FONT = Platform.select({
|
||||
ios: "Menlo",
|
||||
android: "monospace",
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
// Status hues follow the system-wide convention set by sidebar v1 and the
|
||||
// Live Activity/widgets (amber approval, indigo input, sky working) so a
|
||||
// thread reads the same color everywhere it surfaces.
|
||||
const STATUS_LABEL_BY_STATUS: Partial<
|
||||
Record<ThreadListV2Status, { label: string; className: string }>
|
||||
> = {
|
||||
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
|
||||
input: { label: "Input", className: "text-indigo-600 dark:text-indigo-300" },
|
||||
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
|
||||
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
|
||||
};
|
||||
|
||||
function threadTimeLabel(thread: EnvironmentThreadShell): string {
|
||||
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
|
||||
}
|
||||
|
||||
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
|
||||
// its own surface (thread screen / settings) rather than crowding the row.
|
||||
const CARD_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
const SLIM_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "unsettle", title: "Un-settle", image: "arrow.uturn.backward" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
// Pre-settlement servers: no lifecycle items, archive fills the gap.
|
||||
const LEGACY_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "archive", title: "Archive", image: "archivebox" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
/** Rounded-row radius shared with the v1 sidebar rows. */
|
||||
const SIDEBAR_V2_ROW_RADIUS = 12;
|
||||
|
||||
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider(props: {
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
}) {
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
return (
|
||||
<View
|
||||
className={cn(
|
||||
"mb-1.5 mt-4 flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
)}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-tertiary">Settled</Text>
|
||||
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
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
|
||||
the web sidebar's remote-environment cloud icon, but as text since
|
||||
phones have no hover tooltips. */
|
||||
readonly environmentLabel: string | null;
|
||||
/** Hosting surface. "screen" (default) renders the compact Home idiom:
|
||||
flat edge-to-edge rows on the screen background with inset hairlines.
|
||||
"sidebar" renders the iPad split-view idiom: rounded rows blending
|
||||
into the drawer surface, selection filled with the accent color —
|
||||
matching the v1 sidebar rows. */
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
/** Highlights the thread open in the detail pane (iPad split view). The
|
||||
compact Home list never sets it — phones navigate away on select. */
|
||||
readonly selected?: boolean;
|
||||
/** Override for narrow panes (iPad sidebar); defaults to window width. */
|
||||
readonly fullSwipeWidth?: number;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** False on environments whose server predates thread.settle/unsettle:
|
||||
swipe + menu fall back to Archive instead of failing on use. */
|
||||
readonly settlementSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
merged/closed work (mirrors web's onChangeRequestState). */
|
||||
readonly onChangeRequestState?: (
|
||||
threadKey: string,
|
||||
state: "open" | "closed" | "merged" | null,
|
||||
) => void;
|
||||
readonly projectCwd?: string | null;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
typeof ThreadSwipeable
|
||||
>["simultaneousWithExternalGesture"];
|
||||
}) {
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const {
|
||||
thread,
|
||||
variant,
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onSettleThread,
|
||||
onUnsettleThread,
|
||||
onArchiveThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
const threadKey = `${thread.environmentId}:${thread.id}`;
|
||||
useEffect(() => {
|
||||
onChangeRequestState?.(threadKey, prState);
|
||||
}, [onChangeRequestState, prState, threadKey]);
|
||||
|
||||
const screenColor = useThemeColor("--color-screen");
|
||||
const drawerColor = useThemeColor("--color-drawer");
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
const sidebarPane = props.pane === "sidebar";
|
||||
const selected = props.selected === true;
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
const statusLabel = STATUS_LABEL_BY_STATUS[status];
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete, handleSettle, handleUnsettle],
|
||||
);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
// row can un-settle — explicit settles clear the override, auto-settled
|
||||
// rows get pinned active until real activity clears the pin.
|
||||
const canUnsettle = variant === "slim";
|
||||
const primaryAction = useMemo(() => {
|
||||
// Pre-settlement server: archive is the swipe action, as in v1. (Slim
|
||||
// rows cannot occur here — unsupported environments never classify as
|
||||
// settled.)
|
||||
if (!props.settlementSupported) {
|
||||
return {
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
icon: "archivebox" as const,
|
||||
label: "Archive",
|
||||
onPress: handleArchive,
|
||||
};
|
||||
}
|
||||
return canUnsettle
|
||||
? {
|
||||
accessibilityLabel: `Un-settle ${thread.title}`,
|
||||
icon: "arrow.uturn.backward" as const,
|
||||
label: "Un-settle",
|
||||
onPress: handleUnsettle,
|
||||
}
|
||||
: {
|
||||
accessibilityLabel: `Settle ${thread.title}`,
|
||||
icon: "checkmark" as const,
|
||||
label: "Settle",
|
||||
onPress: handleSettle,
|
||||
};
|
||||
}, [
|
||||
canUnsettle,
|
||||
handleArchive,
|
||||
handleSettle,
|
||||
handleUnsettle,
|
||||
props.settlementSupported,
|
||||
thread.title,
|
||||
]);
|
||||
|
||||
// The sidebar pane fills selected rows with the accent color (matching the
|
||||
// v1 sidebar), so every piece of row text needs a white-on-accent variant.
|
||||
const cardContent = (
|
||||
<>
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-sm font-t3-medium",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.projectTitle ?? props.project?.title ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs tabular-nums",
|
||||
selected ? "text-white" : (statusLabel?.className ?? "text-foreground-tertiary"),
|
||||
)}
|
||||
>
|
||||
{statusLabel?.label ?? timeLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
className={cn(
|
||||
"mt-1 text-base font-t3-medium",
|
||||
selected ? "text-user-bubble-foreground" : "text-foreground",
|
||||
)}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{thread.title}
|
||||
</Text>
|
||||
<View className="mt-1 flex-row items-center gap-2">
|
||||
{status === "failed" && thread.session?.lastError ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
selected
|
||||
? "text-user-bubble-foreground-muted"
|
||||
: "text-red-600/80 dark:text-red-400/80",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.session.lastError}
|
||||
</Text>
|
||||
) : thread.branch || props.environmentLabel ? (
|
||||
/* "branch · machine" share one truncating line. The machine sits
|
||||
last so a tight fit cuts the repetitive label, not the branch —
|
||||
and machine-only fills the row for non-git projects. */
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.branch ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{thread.branch}
|
||||
</Text>
|
||||
) : null}
|
||||
{thread.branch && props.environmentLabel ? " · " : null}
|
||||
{props.environmentLabel ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
|
||||
)}
|
||||
>
|
||||
{props.environmentLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
) : (
|
||||
<View className="flex-1" />
|
||||
)}
|
||||
{pr ? (
|
||||
<Text
|
||||
accessibilityLabel={pr.accessibilityLabel}
|
||||
className={cn("text-xs", selected ? "text-white" : pr.textClassName)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
#{pr.label}
|
||||
</Text>
|
||||
) : null}
|
||||
{props.providerDriver ? (
|
||||
<View className="opacity-60">
|
||||
<ProviderIcon provider={props.providerDriver} size={14} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
|
||||
const rowContent = (close: () => void) =>
|
||||
variant === "card" ? (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
onPress={() => {
|
||||
close();
|
||||
onSelectThread(thread);
|
||||
}}
|
||||
style={
|
||||
sidebarPane
|
||||
? ({ pressed }) => ({
|
||||
backgroundColor: selected
|
||||
? selectedBackgroundColor
|
||||
: pressed
|
||||
? pressedBackgroundColor
|
||||
: drawerColor,
|
||||
borderRadius: SIDEBAR_V2_ROW_RADIUS,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 10,
|
||||
})
|
||||
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
|
||||
}
|
||||
>
|
||||
{sidebarPane ? (
|
||||
cardContent
|
||||
) : (
|
||||
/* Flat native list rows: no tonal containers — colored status
|
||||
labels and text hierarchy carry state, an inset hairline
|
||||
separates rows. The opaque screen background stays so swipe
|
||||
actions reveal behind the row. */
|
||||
<View className="bg-screen">
|
||||
<View className="px-5 py-2.5">{cardContent}</View>
|
||||
<View className="ml-5 h-px bg-border-subtle" />
|
||||
</View>
|
||||
)}
|
||||
</Pressable>
|
||||
) : (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
className={sidebarPane ? undefined : "bg-screen"}
|
||||
onPress={() => {
|
||||
close();
|
||||
onSelectThread(thread);
|
||||
}}
|
||||
style={
|
||||
sidebarPane
|
||||
? ({ pressed }) => ({
|
||||
backgroundColor: selected
|
||||
? selectedBackgroundColor
|
||||
: pressed
|
||||
? pressedBackgroundColor
|
||||
: drawerColor,
|
||||
borderRadius: SIDEBAR_V2_ROW_RADIUS,
|
||||
})
|
||||
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
|
||||
}
|
||||
>
|
||||
{/* Settled history recedes: dimmed favicon + muted title. */}
|
||||
<View
|
||||
className={cn(
|
||||
"min-h-[44px] flex-row items-center gap-2.5 py-2",
|
||||
sidebarPane ? "px-3" : "px-5",
|
||||
)}
|
||||
>
|
||||
{props.project ? (
|
||||
<View className="opacity-40">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-base",
|
||||
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-sm tabular-nums",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.showSettledDivider ? <ThreadListV2SettledDivider pane={props.pane} /> : null}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={sidebarPane ? drawerColor : screenColor}
|
||||
compactActions={variant === "slim"}
|
||||
containerStyle={
|
||||
sidebarPane ? { borderRadius: SIDEBAR_V2_ROW_RADIUS, overflow: "hidden" } : undefined
|
||||
}
|
||||
enableTrackpadSwipe
|
||||
// Full swipe commits the advertised lifecycle action (Settle /
|
||||
// Un-settle), never the destructive delete.
|
||||
fullSwipeAction="primary"
|
||||
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
|
||||
onDelete={handleDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={primaryAction}
|
||||
resetKey={`${thread.environmentId}:${thread.id}`}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={thread.title}
|
||||
>
|
||||
{(close) => (
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
!props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
: CARD_MENU_ACTIONS
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
{rowContent(close)}
|
||||
</ControlPillMenu>
|
||||
)}
|
||||
</ThreadSwipeable>
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,322 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
resolveThreadListV2Status,
|
||||
sortThreadsForListV2,
|
||||
} from "./threadListV2";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
const NOW = "2026-06-02T00:00:00.000Z";
|
||||
|
||||
describe("resolveThreadListV2Status", () => {
|
||||
it("prioritizes approval over a running session", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
hasPendingApprovals: true,
|
||||
session: {
|
||||
threadId: ThreadId.make("t"),
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
});
|
||||
expect(resolveThreadListV2Status(thread)).toBe("approval");
|
||||
});
|
||||
|
||||
it("resolves ready for quiescent threads", () => {
|
||||
expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe(
|
||||
"ready",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForListV2", () => {
|
||||
it("orders by creation time, newest first, ignoring activity", () => {
|
||||
const sorted = sortThreadsForListV2([
|
||||
{ id: "oldest", createdAt: "2026-06-01T08:00:00.000Z" },
|
||||
{ id: "newest", createdAt: "2026-06-01T12:00:00.000Z" },
|
||||
{ id: "middle", createdAt: "2026-06-01T10:00:00.000Z" },
|
||||
]);
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
|
||||
});
|
||||
});
|
||||
|
||||
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: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled-2"),
|
||||
title: "Settled 2",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["active", "card"],
|
||||
["settled", "slim"],
|
||||
["settled-2", "slim"],
|
||||
]);
|
||||
expect(items.map((item) => item.showSettledDivider)).toEqual([false, true, false]);
|
||||
expect(items.map((item) => item.isLast)).toEqual([false, false, true]);
|
||||
});
|
||||
|
||||
it("keeps cards in creation order while settled sorts by recency", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("older-created"),
|
||||
title: "Older",
|
||||
createdAt: "2026-06-01T08:00:00.000Z",
|
||||
updatedAt: NOW, // recent activity must NOT promote it
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("newer-created"),
|
||||
title: "Newer",
|
||||
createdAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]);
|
||||
});
|
||||
|
||||
it("keeps settled threads in the tail and filters by search query", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("match"), title: "Fix login bug" }),
|
||||
makeThread({ id: ThreadId.make("miss"), title: "Greeting" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Fix login again",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "login",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["match", "card"],
|
||||
["settled", "slim"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("scopes the flat list to one project", () => {
|
||||
const otherProjectId = ProjectId.make("project-2");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("included"), title: "Included" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("excluded"),
|
||||
projectId: otherProjectId,
|
||||
title: "Excluded",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["included"]);
|
||||
});
|
||||
|
||||
it("scopes the flat list to every environment member of a logical project", () => {
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("local"), title: "Local" }),
|
||||
makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("remote"),
|
||||
title: "Remote",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [
|
||||
{ environmentId, projectId: ProjectId.make("project-1") },
|
||||
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
|
||||
],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["local", "remote"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items settled paging", () => {
|
||||
it("caps the settled tail at settledLimit and reports the hidden count", () => {
|
||||
const threads = [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
...Array.from({ length: 4 }, (_, index) =>
|
||||
makeThread({
|
||||
id: ThreadId.make(`settled-${index}`),
|
||||
title: `Settled ${index}`,
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
// A turn adopted the message (same requestedAt): without it the
|
||||
// thread reads as a queued turn start, which never settles.
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${index}`),
|
||||
state: "completed",
|
||||
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
startedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
completedAt: `2026-06-01T0${index}:10:00.000Z`,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
const layout = buildThreadListV2Items({
|
||||
threads,
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
settledLimit: 2,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.hiddenSettledCount).toBe(2);
|
||||
expect(layout.items.filter((item) => item.variant === "slim")).toHaveLength(2);
|
||||
// Most recent settled first — the hidden ones are the oldest.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual([
|
||||
"active",
|
||||
"settled-3",
|
||||
"settled-2",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
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";
|
||||
|
||||
/**
|
||||
* Thread List v2 model, ported from the web sidebar v2
|
||||
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
|
||||
*
|
||||
* Four visual states, three colors: color is reserved for "act now"
|
||||
* (approval), "in motion" (working), and "broken" (failed). Ready is the
|
||||
* unlabeled resting state.
|
||||
*/
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
|
||||
// Settled-tail paging: recent history is the common lookup; the deep tail
|
||||
// stays behind an explicit Show more. Shared by the compact Home list and
|
||||
// the iPad sidebar so both page identically.
|
||||
export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
|
||||
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
|
||||
|
||||
export function resolveThreadListV2Status(
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
|
||||
): ThreadListV2Status {
|
||||
if (thread.hasPendingApprovals) {
|
||||
return "approval";
|
||||
}
|
||||
if (thread.hasPendingUserInput) {
|
||||
return "input";
|
||||
}
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") {
|
||||
return "working";
|
||||
}
|
||||
if (thread.session?.status === "error") {
|
||||
return "failed";
|
||||
}
|
||||
return "ready";
|
||||
}
|
||||
|
||||
/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
|
||||
poison the whole ordering, so it sinks to the epoch instead. */
|
||||
function parseTimestampMs(isoDate: string): number {
|
||||
const parsed = Date.parse(isoDate);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
/** First VALID timestamp wins: a present-yet-malformed string falls through
|
||||
to the next candidate rather than sinking the row to the epoch. */
|
||||
function firstValidTimestampMs(...candidates: ReadonlyArray<string | null | undefined>): number {
|
||||
for (const candidate of candidates) {
|
||||
if (candidate == null) continue;
|
||||
const parsed = Date.parse(candidate);
|
||||
if (!Number.isNaN(parsed)) return parsed;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. Mirrors web's
|
||||
* sortThreadsForSidebarV2.
|
||||
*/
|
||||
export function sortThreadsForListV2<T extends { readonly id: string; readonly createdAt: string }>(
|
||||
threads: readonly T[],
|
||||
): T[] {
|
||||
// .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023
|
||||
// change-by-copy array methods.
|
||||
return [...threads].sort(
|
||||
(left, right) =>
|
||||
parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
|
||||
left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
export interface ThreadListV2Item {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
/** First settled row after the card block draws the SETTLED divider. */
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Partitions visible threads into the active card block (creation order) and
|
||||
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
|
||||
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
|
||||
* the default is fixed here rather than user-configurable.
|
||||
*/
|
||||
export function buildThreadListV2Items(input: {
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly projectRefs?: ReadonlyArray<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectId: ProjectId;
|
||||
}> | null;
|
||||
readonly searchQuery: string;
|
||||
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
|
||||
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
|
||||
/** Environments whose server supports thread.settle/unsettle. Threads on
|
||||
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
|
||||
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
|
||||
: null;
|
||||
|
||||
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.
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
|
||||
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
|
||||
continue;
|
||||
}
|
||||
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 })
|
||||
) {
|
||||
settled.push(thread);
|
||||
} else {
|
||||
active.push(thread);
|
||||
}
|
||||
}
|
||||
|
||||
const orderedActive = sortThreadsForListV2(active);
|
||||
const orderedSettled = [...settled].sort(
|
||||
(left, right) =>
|
||||
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
|
||||
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
|
||||
);
|
||||
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
|
||||
const visibleSettled =
|
||||
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of orderedActive) {
|
||||
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
|
||||
}
|
||||
for (const [index, thread] of visibleSettled.entries()) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
showSettledDivider: index === 0,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
const last = items.at(-1);
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
}
|
||||
@@ -38,6 +38,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -50,6 +50,8 @@ function makeThread(
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -412,6 +414,20 @@ describe("buildThreadFeed", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("appends active work as a normal timeline row", () => {
|
||||
const startedAt = "2026-04-01T00:00:01.000Z";
|
||||
const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
|
||||
|
||||
expect(presented).toEqual([
|
||||
{
|
||||
type: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: startedAt,
|
||||
},
|
||||
]);
|
||||
expect(deriveThreadFeedPresentation(presented, null, new Set())).toEqual([]);
|
||||
});
|
||||
|
||||
it("models work-log overflow as list rows", () => {
|
||||
const activity = (
|
||||
id: string,
|
||||
|
||||
@@ -98,6 +98,11 @@ type RawThreadFeedEntry =
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| {
|
||||
readonly type: "working";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -1105,9 +1110,11 @@ export function deriveThreadFeedPresentation(
|
||||
latestTurn: ThreadFeedLatestTurn | null,
|
||||
expandedTurnIds: ReadonlySet<TurnId>,
|
||||
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
|
||||
activeWorkStartedAt: string | null = null,
|
||||
): ThreadFeedEntry[] {
|
||||
const sourceFeed = feed.filter(
|
||||
(entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
|
||||
(entry) =>
|
||||
entry.type !== "turn-fold" && entry.type !== "work-toggle" && entry.type !== "working",
|
||||
);
|
||||
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
|
||||
const collapsedEntryIds = new Set<string>();
|
||||
@@ -1136,12 +1143,19 @@ export function deriveThreadFeedPresentation(
|
||||
appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
|
||||
}
|
||||
}
|
||||
if (activeWorkStartedAt !== null) {
|
||||
result.push({
|
||||
type: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: activeWorkStartedAt,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function appendPresentedFeedEntry(
|
||||
result: ThreadFeedEntry[],
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" | "working" }>,
|
||||
expandedWorkGroupIds: ReadonlySet<string>,
|
||||
): void {
|
||||
if (entry.type !== "activity-group") {
|
||||
|
||||
@@ -142,6 +142,13 @@ function stabilizeOptionFunctions(
|
||||
|
||||
export function NativeStackScreenOptions(props: {
|
||||
readonly options?: AppNativeStackNavigationOptions;
|
||||
/**
|
||||
* Causes dynamic native header factories to be reapplied when their closed-over
|
||||
* menu content changes. Factory functions are intentionally stabilized, so
|
||||
* their source alone cannot capture a menu that was initially empty while
|
||||
* asynchronous data was loading.
|
||||
*/
|
||||
readonly optionsVersion?: unknown;
|
||||
readonly listeners?: Record<string, (event: never) => void>;
|
||||
readonly name?: string;
|
||||
}) {
|
||||
@@ -163,7 +170,7 @@ export function NativeStackScreenOptions(props: {
|
||||
if (!navigation || !stableOptions) {
|
||||
return;
|
||||
}
|
||||
const signature = optionsSignature(stableOptions);
|
||||
const signature = optionsSignature([stableOptions, props.optionsVersion]);
|
||||
// Avoid re-entering navigation state when semantically equal options are
|
||||
// reapplied every layout (common when callers pass unstable object literals).
|
||||
if (lastAppliedOptionsSignatureRef.current === signature) {
|
||||
@@ -171,7 +178,7 @@ export function NativeStackScreenOptions(props: {
|
||||
}
|
||||
lastAppliedOptionsSignatureRef.current = signature;
|
||||
navigation.setOptions(stableOptions);
|
||||
}, [navigation, stableOptions]);
|
||||
}, [navigation, props.optionsVersion, stableOptions]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!navigation || !props.listeners) {
|
||||
|
||||
@@ -22,6 +22,13 @@ export interface Preferences {
|
||||
readonly codeWordBreak?: boolean;
|
||||
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
readonly collapsedProjectGroups?: readonly string[];
|
||||
readonly projectGroupingEnabled?: boolean;
|
||||
/**
|
||||
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
|
||||
* client-settings sync, so the flat v2 thread list is opted into per
|
||||
* device.
|
||||
*/
|
||||
readonly threadListV2Enabled?: boolean;
|
||||
}
|
||||
|
||||
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
|
||||
@@ -71,6 +78,8 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
codeWordBreak?: boolean;
|
||||
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
collapsedProjectGroups?: readonly string[];
|
||||
projectGroupingEnabled?: boolean;
|
||||
threadListV2Enabled?: boolean;
|
||||
} = {};
|
||||
|
||||
if (typeof parsed.liveActivitiesEnabled === "boolean") {
|
||||
@@ -97,6 +106,12 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
(key): key is string => typeof key === "string",
|
||||
);
|
||||
}
|
||||
if (typeof parsed.projectGroupingEnabled === "boolean") {
|
||||
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
|
||||
}
|
||||
if (typeof parsed.threadListV2Enabled === "boolean") {
|
||||
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
|
||||
}
|
||||
return preferences;
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,10 @@ function threadDetailToShell(
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
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");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -11,6 +11,7 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
|
||||
|
||||
@@ -20,7 +21,10 @@ const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
const testLayer = Layer.mergeAll(
|
||||
configLayer,
|
||||
WorkspacePaths.layer,
|
||||
ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer)),
|
||||
ProjectFaviconResolver.layer.pipe(
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provide(T3ProjectFileLoader.layer),
|
||||
),
|
||||
ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -202,6 +202,18 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
|
||||
);
|
||||
|
||||
it.effect("exposes service lifecycle commands without T3 Connect configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli));
|
||||
|
||||
assert.include(output, "Manage the T3 Code background service.");
|
||||
assert.include(output, "install");
|
||||
assert.include(output, "uninstall");
|
||||
assert.include(output, "update");
|
||||
assert.include(output, "status");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports fresh headless connect state without requiring local configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
@@ -305,7 +317,10 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.equal(output, "Signed out of T3 Connect locally.");
|
||||
assert.equal(
|
||||
output,
|
||||
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
|
||||
);
|
||||
assert.isFalse(NodeFS.existsSync(tokenPath));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -13,6 +13,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
import { serviceCommand } from "./cli/service.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
@@ -47,6 +48,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
|
||||
serveCommand,
|
||||
authCommand,
|
||||
projectCommand,
|
||||
serviceCommand,
|
||||
cloudEnabled ? connectCommand : connectUnavailableCommand,
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -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", {
|
||||
|
||||
@@ -16,9 +16,9 @@ import {
|
||||
formatRelayClientReady,
|
||||
headlessSessionConfig,
|
||||
isPublishAgentActivityEnabledValue,
|
||||
recoverBootServiceOffer,
|
||||
reportCloudDisconnectResults,
|
||||
} from "./connect.ts";
|
||||
import { recoverServiceOnboardingOffer } from "./service.ts";
|
||||
|
||||
it("explains how to complete headless authorization", () => {
|
||||
assert.equal(
|
||||
@@ -58,7 +58,7 @@ it.effect("detects headless operation from individual SSH config values", () =>
|
||||
|
||||
it.effect("treats cancelling optional background setup as a successful skip", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* recoverBootServiceOffer(Effect.fail(new Terminal.QuitError({})));
|
||||
const result = yield* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));
|
||||
assert.isFalse(result);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { RelayOkResponse } from "@t3tools/contracts/relay";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Config from "effect/Config";
|
||||
@@ -20,6 +19,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
} from "effect/unstable/http";
|
||||
import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
@@ -45,9 +44,13 @@ import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as ExternalLauncher from "../process/externalLauncher.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
import {
|
||||
bootServiceLayer,
|
||||
offerServiceDuringOnboarding,
|
||||
recoverServiceOnboardingOffer,
|
||||
} from "./service.ts";
|
||||
|
||||
const jsonFlag = Flag.boolean("json").pipe(
|
||||
Flag.withDescription("Emit JSON instead of human-readable output."),
|
||||
@@ -396,21 +399,6 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
if (options.clearAuthorization) {
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
yield* tokens.clear;
|
||||
|
||||
// uninstall itself no-ops when nothing is installed (and on non-Linux),
|
||||
// so no status pre-check that could mask a real removal failure.
|
||||
const bootService = yield* BootService.BootService;
|
||||
yield* bootService.uninstall.pipe(
|
||||
Effect.tap((removed) =>
|
||||
removed ? Console.log("Removed the T3 Code background service.") : Effect.void,
|
||||
),
|
||||
Effect.catchTag("BootServiceUnsupportedError", () => Effect.succeed(false)),
|
||||
Effect.catch((error) =>
|
||||
Console.warn(`Could not remove the background service: ${error.message}`).pipe(
|
||||
Effect.as(false),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
yield* reportCloudDisconnectResults({
|
||||
@@ -420,7 +408,9 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
});
|
||||
|
||||
if (options.clearAuthorization) {
|
||||
yield* Console.log("Signed out of T3 Connect locally.");
|
||||
yield* Console.log(
|
||||
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -457,11 +447,7 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
|
||||
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
|
||||
EnvironmentAuth.runtimeLayer,
|
||||
ServerEnvironment.layer,
|
||||
BootService.layer({
|
||||
baseDir: config.baseDir,
|
||||
logsDir: config.logsDir,
|
||||
cliVersion: packageJson.version,
|
||||
}).pipe(Layer.provide(ProcessRunner.layer)),
|
||||
bootServiceLayer(config),
|
||||
headlessRelayClientTracingLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
@@ -683,50 +669,6 @@ const connectLogoutCommand = Command.make("logout", {
|
||||
),
|
||||
);
|
||||
|
||||
const offerBootService = Effect.gen(function* () {
|
||||
const bootService = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* bootService.status;
|
||||
if (!supported) {
|
||||
// Don't prompt for something that can only fail; background setup is
|
||||
// Linux/systemd-only for now.
|
||||
return false;
|
||||
}
|
||||
if (installed && current) {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
? "The installed T3 Code background service is from an older setup. Update it now?"
|
||||
: "Run T3 Code in the background whenever this machine boots? " +
|
||||
"It stays reachable through T3 Connect even after you log out.",
|
||||
initial: true,
|
||||
}),
|
||||
);
|
||||
if (!wanted) {
|
||||
return false;
|
||||
}
|
||||
const plan = yield* bootService.install;
|
||||
yield* Console.log(`Background service installed. Logs: ${plan.logPath}`);
|
||||
return true;
|
||||
});
|
||||
|
||||
export const recoverBootServiceOffer = <R>(
|
||||
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
|
||||
) =>
|
||||
offer.pipe(
|
||||
Effect.catchTags({
|
||||
QuitError: () => Effect.succeed(false),
|
||||
BootServiceUnsupportedError: (error) =>
|
||||
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceCommandError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceInstallError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
}),
|
||||
);
|
||||
|
||||
export const connectCommand = Command.make("connect", {
|
||||
...projectLocationFlags,
|
||||
headless: headlessFlag,
|
||||
@@ -748,7 +690,7 @@ export const connectCommand = Command.make("connect", {
|
||||
|
||||
// Connect itself already succeeded; a boot-service failure must not
|
||||
// fail the command, just tell the user what happened and move on.
|
||||
const background = yield* recoverBootServiceOffer(offerBootService);
|
||||
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
|
||||
yield* Console.log(
|
||||
background
|
||||
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { formatServiceStatus } from "./service.ts";
|
||||
|
||||
const status = {
|
||||
supported: true,
|
||||
installed: true,
|
||||
current: true,
|
||||
unitPath: "/home/me/.config/systemd/user/t3code.service",
|
||||
logPath: "/home/me/.t3/userdata/logs/boot-service.log",
|
||||
} as const;
|
||||
|
||||
it("reports the installed service version and host paths", () => {
|
||||
assert.equal(
|
||||
formatServiceStatus(status, "0.0.29"),
|
||||
[
|
||||
"T3 Code service",
|
||||
" Status: installed · [email protected]",
|
||||
" Unit: /home/me/.config/systemd/user/t3code.service",
|
||||
" Logs: /home/me/.t3/userdata/logs/boot-service.log",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("gives a direct repair command for a stale service", () => {
|
||||
assert.include(
|
||||
formatServiceStatus({ ...status, current: false }, "0.0.29"),
|
||||
"Next: Run `npx t3@latest service update`.",
|
||||
);
|
||||
});
|
||||
|
||||
it("explains service availability without systemd", () => {
|
||||
assert.include(
|
||||
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
|
||||
"Supported on: Linux with systemd",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
import type * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
|
||||
export const bootServiceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
|
||||
BootService.layer({
|
||||
baseDir: config.baseDir,
|
||||
logsDir: config.logsDir,
|
||||
cliVersion: packageJson.version,
|
||||
}).pipe(Layer.provide(ProcessRunner.layer));
|
||||
|
||||
export type ServiceReconcileResult =
|
||||
| {
|
||||
readonly changed: false;
|
||||
readonly status: BootService.BootServiceStatus;
|
||||
}
|
||||
| {
|
||||
readonly changed: true;
|
||||
readonly previouslyInstalled: boolean;
|
||||
readonly plan: BootService.BootServicePlan;
|
||||
};
|
||||
|
||||
/** Install, update, or repair the service using the CLI version running this command. */
|
||||
export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const status = yield* service.status;
|
||||
if (status.installed && status.current) {
|
||||
return { changed: false, status } satisfies ServiceReconcileResult;
|
||||
}
|
||||
const plan = yield* service.install;
|
||||
return {
|
||||
changed: true,
|
||||
previouslyInstalled: status.installed,
|
||||
plan,
|
||||
} satisfies ServiceReconcileResult;
|
||||
});
|
||||
|
||||
export function formatServiceStatus(
|
||||
status: BootService.BootServiceStatus,
|
||||
cliVersion: string,
|
||||
): string {
|
||||
if (!status.supported) {
|
||||
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
|
||||
}
|
||||
if (!status.installed) {
|
||||
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
|
||||
}
|
||||
return [
|
||||
"T3 Code service",
|
||||
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
|
||||
` Unit: ${status.unitPath}`,
|
||||
` Logs: ${status.logPath}`,
|
||||
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
|
||||
flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
|
||||
run: Effect.Effect<A, E, BootService.BootService>,
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
|
||||
});
|
||||
|
||||
const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(
|
||||
Command.withDescription("Install T3 Code as a background service for this user."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
if (!result.changed) {
|
||||
yield* Console.log(
|
||||
`T3 Code service is already installed with t3@${packageJson.version}.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
|
||||
Command.withDescription(
|
||||
"Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
if (!result.changed) {
|
||||
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
|
||||
Command.withDescription("Stop and remove the T3 Code background service."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const removed = yield* service.uninstall;
|
||||
yield* Console.log(
|
||||
removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
|
||||
Command.withDescription("Show whether the T3 Code background service is installed."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version));
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* service.status;
|
||||
if (!supported) {
|
||||
return false;
|
||||
}
|
||||
if (installed && current) {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
? "The installed T3 Code service needs an update or repair. Update it now?"
|
||||
: "Run T3 Code in the background whenever this machine boots? " +
|
||||
"It stays reachable through T3 Connect even after you log out.",
|
||||
initial: true,
|
||||
}),
|
||||
);
|
||||
if (!wanted) {
|
||||
return false;
|
||||
}
|
||||
const result = yield* reconcileService();
|
||||
if (result.changed) {
|
||||
yield* Console.log(
|
||||
`Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
export const recoverServiceOnboardingOffer = <R>(
|
||||
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
|
||||
) =>
|
||||
offer.pipe(
|
||||
Effect.catchTags({
|
||||
QuitError: () => Effect.succeed(false),
|
||||
BootServiceUnsupportedError: (error) =>
|
||||
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceCommandError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceInstallError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
}),
|
||||
);
|
||||
|
||||
export const serviceCommand = Command.make("service").pipe(
|
||||
Command.withDescription("Manage the T3 Code background service."),
|
||||
Command.withSubcommands([
|
||||
serviceInstallCommand,
|
||||
serviceUninstallCommand,
|
||||
serviceUpdateCommand,
|
||||
serviceStatusCommand,
|
||||
]),
|
||||
);
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
|
||||
import { reconcileService } from "../cli/service.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as BootService from "./bootService.ts";
|
||||
|
||||
@@ -100,7 +101,7 @@ it("renders a systemd unit with absolute paths and append-mode logging", () => {
|
||||
unit,
|
||||
[
|
||||
"[Unit]",
|
||||
"Description=T3 Code server (T3 Connect)",
|
||||
"Description=T3 Code server",
|
||||
"StartLimitIntervalSec=300",
|
||||
"StartLimitBurst=5",
|
||||
"",
|
||||
@@ -108,6 +109,7 @@ it("renders a systemd unit with absolute paths and append-mode logging", () => {
|
||||
"Type=simple",
|
||||
"WorkingDirectory=%h",
|
||||
"Environment=T3CODE_HOME=/home/theo/.t3",
|
||||
"Environment=T3_BOOT_SERVICE_UNIT=t3code.service",
|
||||
"ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve",
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
@@ -170,6 +172,33 @@ it("flags package-manager cache entry points as ephemeral", () => {
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("BootService", (it) => {
|
||||
it.effect("reconciles the standalone service once and is then idempotent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dirs } = yield* makeTestContext();
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
const service = yield* BootService.make({
|
||||
baseDir: dirs.baseDir,
|
||||
logsDir: dirs.logsDir,
|
||||
cliVersion: "0.0.27",
|
||||
host: makeHost(dirs.stableEntry),
|
||||
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
|
||||
|
||||
const first = yield* reconcileService().pipe(
|
||||
Effect.provideService(BootService.BootService, service),
|
||||
);
|
||||
assert.isTrue(first.changed);
|
||||
if (!first.changed) return;
|
||||
assert.isFalse(first.previouslyInstalled);
|
||||
|
||||
const commandCount = commands.length;
|
||||
const second = yield* reconcileService().pipe(
|
||||
Effect.provideService(BootService.BootService, service),
|
||||
);
|
||||
assert.isFalse(second.changed);
|
||||
assert.lengthOf(commands, commandCount);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs the unit, enables the service, and enables linger", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dirs, fs, path } = yield* makeTestContext();
|
||||
@@ -311,7 +340,7 @@ it.layer(NodeServices.layer)("BootService", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports an installed-but-stale unit so connect can offer a repair", () =>
|
||||
it.effect("reports an installed-but-stale unit so the lifecycle can offer a repair", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dirs, fs, path } = yield* makeTestContext();
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
@@ -402,8 +431,8 @@ it.layer(NodeServices.layer)("BootService", (it) => {
|
||||
|
||||
const error = yield* service.install.pipe(Effect.flip);
|
||||
assert.isTrue(isCommandError(error));
|
||||
// A leftover unit would make the next connect report "already set up"
|
||||
// even though linger never happened.
|
||||
// A leftover unit would make status report "installed" even though
|
||||
// linger never happened.
|
||||
assert.isFalse(
|
||||
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
|
||||
);
|
||||
|
||||
@@ -16,21 +16,19 @@ import {
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
|
||||
|
||||
/**
|
||||
* Installs T3 Code as a per-user boot service so a connected machine stays
|
||||
* reachable through T3 Connect after the SSH session ends. Linux-only for
|
||||
* now: systemd user unit + loginctl enable-linger. The service runs a pinned
|
||||
* runtime installed under <baseDir>/runtime — never `npx t3`, whose cache is
|
||||
* ephemeral and whose registry fetch at boot would make startup depend on
|
||||
* the network.
|
||||
* Installs T3 Code as a per-user boot service. Linux-only for now: systemd
|
||||
* user unit + loginctl enable-linger. The service runs a stable or pinned
|
||||
* runtime — never an ephemeral `npx t3` cache whose eviction could break
|
||||
* startup.
|
||||
*/
|
||||
|
||||
const BOOT_SERVICE_NAME = "t3code";
|
||||
const BOOT_RUNTIME_DIR = "runtime";
|
||||
|
||||
const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
|
||||
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
|
||||
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
|
||||
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
|
||||
|
||||
const EPHEMERAL_CACHE_SEGMENTS = [
|
||||
"/_npx/", // npx
|
||||
@@ -92,7 +90,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
// relay connection, and Restart=always covers early-boot failures.
|
||||
return [
|
||||
"[Unit]",
|
||||
"Description=T3 Code server (T3 Connect)",
|
||||
"Description=T3 Code server",
|
||||
// Give up after 5 crashes in 5 minutes so a persistently broken install
|
||||
// (deleted runtime, broken workspace) stops instead of restarting every
|
||||
// 5s forever and growing the unrotated append log without bound.
|
||||
@@ -103,6 +101,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
"Type=simple",
|
||||
"WorkingDirectory=%h",
|
||||
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
|
||||
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
|
||||
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`,
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
@@ -206,14 +205,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
const unitDir = path.join(homeDir, ".config", "systemd", "user");
|
||||
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
|
||||
const logPath = path.join(input.logsDir, "boot-service.log");
|
||||
const runtimeVersionDir = path.join(
|
||||
input.baseDir,
|
||||
BOOT_RUNTIME_DIR,
|
||||
"versions",
|
||||
input.cliVersion,
|
||||
);
|
||||
const runtimeEntryPath = path.join(runtimeVersionDir, "node_modules", "t3", "dist", "bin.mjs");
|
||||
const runtimeSentinelPath = path.join(runtimeVersionDir, ".install-complete");
|
||||
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
|
||||
|
||||
const requireSystemdLinux = Effect.gen(function* () {
|
||||
if (platform !== "linux" || homeDir === "") {
|
||||
@@ -263,52 +255,41 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
if (!isEphemeralCacheEntry(host.cliEntryPath)) {
|
||||
return;
|
||||
}
|
||||
// The sentinel is written only after npm exits 0. Checking the entry
|
||||
// file alone is not enough: npm extracts files before running native
|
||||
// builds (node-pty), so a killed install leaves a plausible-looking but
|
||||
// broken tree behind.
|
||||
const alreadyPinned = yield* Effect.all([
|
||||
fs.exists(runtimeSentinelPath),
|
||||
fs.exists(runtimeEntryPath),
|
||||
]).pipe(
|
||||
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
|
||||
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
|
||||
);
|
||||
if (alreadyPinned) {
|
||||
return;
|
||||
}
|
||||
yield* fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(
|
||||
Effect.andThen(fs.makeDirectory(runtimeVersionDir, { recursive: true })),
|
||||
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
|
||||
);
|
||||
yield* runStep(
|
||||
"installing the pinned t3 runtime (this can take a few minutes)",
|
||||
"npm",
|
||||
[
|
||||
"install",
|
||||
"--prefix",
|
||||
runtimeVersionDir,
|
||||
"--no-fund",
|
||||
"--no-audit",
|
||||
`t3@${input.cliVersion}`,
|
||||
],
|
||||
// Native deps (node-pty) can compile from source on slow boxes; the
|
||||
// ProcessRunner default of 60s would kill a healthy install.
|
||||
{ timeout: PINNED_RUNTIME_INSTALL_TIMEOUT },
|
||||
).pipe(
|
||||
Effect.tapError(() =>
|
||||
fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(Effect.ignore),
|
||||
yield* ensurePinnedRuntimeInstalled({
|
||||
baseDir: input.baseDir,
|
||||
version: input.cliVersion,
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
error.step.startsWith("installing")
|
||||
? new BootServiceCommandError({
|
||||
step: error.step,
|
||||
exitCode: error.exitCode,
|
||||
stdoutLength: error.stdoutLength,
|
||||
stderrLength: error.stderrLength,
|
||||
cause: error.cause,
|
||||
})
|
||||
: new BootServiceInstallError({ cause: error }),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.flatMap((now) =>
|
||||
fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
|
||||
flag: "a",
|
||||
}),
|
||||
),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* fs
|
||||
.writeFileString(runtimeSentinelPath, `${input.cliVersion}\n`)
|
||||
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
|
||||
});
|
||||
|
||||
// Where the unit will point: derivable without touching the network, so
|
||||
// status can compare units purely; install materializes it first.
|
||||
const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
|
||||
? runtimeEntryPath
|
||||
? runtimePaths.entryPath
|
||||
: host.cliEntryPath;
|
||||
const plan: BootServicePlan = {
|
||||
nodePath: host.execPath,
|
||||
@@ -341,8 +322,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
);
|
||||
|
||||
// If any activation step fails, remove the unit again: a leftover file
|
||||
// would make the next `t3 connect` report the service as already set up
|
||||
// even though it was never enabled or lingered.
|
||||
// would make service status report it as installed even though it was
|
||||
// never enabled or lingered.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
|
||||
yield* runStep("enabling the service", "systemctl", [
|
||||
@@ -372,7 +353,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
// fails), leave nothing behind: disable removes the enable symlink, remove
|
||||
// deletes the file, daemon-reload clears the stale definition — otherwise a
|
||||
// dangling wants/ symlink logs "Failed to load unit" at every boot and the
|
||||
// next connect misreports the state.
|
||||
// next lifecycle command misreports the state.
|
||||
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
|
||||
previousUnit: Option.Option<string>,
|
||||
) {
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
ensurePinnedRuntimeInstalled,
|
||||
pinnedRuntimePaths,
|
||||
removePinnedRuntimeInstallation,
|
||||
} from "./pinnedRuntime.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
|
||||
it.effect("serializes concurrent installs of the same runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
|
||||
const installStarted = yield* Deferred.make<void>();
|
||||
const allowInstallToFinish = yield* Deferred.make<void>();
|
||||
const paths = pinnedRuntimePaths(path, baseDir, "0.0.29");
|
||||
let npmRuns = 0;
|
||||
|
||||
const runner = ProcessRunner.ProcessRunner.of({
|
||||
run: (_input) =>
|
||||
Effect.gen(function* () {
|
||||
npmRuns += 1;
|
||||
yield* Deferred.succeed(installStarted, undefined);
|
||||
yield* Deferred.await(allowInstallToFinish);
|
||||
yield* fs
|
||||
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
const install = ensurePinnedRuntimeInstalled({
|
||||
baseDir,
|
||||
version: "0.0.29",
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
});
|
||||
|
||||
const first = yield* Effect.forkChild(install, { startImmediately: true });
|
||||
yield* Deferred.await(installStarted);
|
||||
const second = yield* Effect.forkChild(install, { startImmediately: true });
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(npmRuns, 1);
|
||||
|
||||
yield* Deferred.succeed(allowInstallToFinish, undefined);
|
||||
yield* Fiber.join(first);
|
||||
yield* Fiber.join(second);
|
||||
|
||||
assert.equal(npmRuns, 1);
|
||||
assert.isTrue(yield* fs.exists(paths.sentinelPath));
|
||||
assert.isTrue(yield* fs.exists(paths.entryPath));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("waits for an active install before removing its runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
|
||||
const installStarted = yield* Deferred.make<void>();
|
||||
const allowInstallToFinish = yield* Deferred.make<void>();
|
||||
const paths = pinnedRuntimePaths(path, baseDir, "0.0.30");
|
||||
const runner = ProcessRunner.ProcessRunner.of({
|
||||
run: (_input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Deferred.succeed(installStarted, undefined);
|
||||
yield* Deferred.await(allowInstallToFinish);
|
||||
yield* fs
|
||||
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
const installFiber = yield* Effect.forkChild(
|
||||
ensurePinnedRuntimeInstalled({
|
||||
baseDir,
|
||||
version: "0.0.30",
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
}),
|
||||
{ startImmediately: true },
|
||||
);
|
||||
yield* Deferred.await(installStarted);
|
||||
const removeFiber = yield* Effect.forkChild(
|
||||
removePinnedRuntimeInstallation({
|
||||
baseDir,
|
||||
version: "0.0.30",
|
||||
fs,
|
||||
path,
|
||||
}),
|
||||
{ startImmediately: true },
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(yield* fs.exists(paths.versionDir));
|
||||
|
||||
yield* Deferred.succeed(allowInstallToFinish, undefined);
|
||||
yield* Fiber.join(installFiber);
|
||||
yield* Fiber.join(removeFiber);
|
||||
assert.isFalse(yield* fs.exists(paths.versionDir));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
|
||||
/**
|
||||
* A pinned runtime is an exact `t3@<version>` npm-installed into
|
||||
* <baseDir>/runtime/versions/<version>. The boot service points its systemd
|
||||
* unit here, and server self-update installs the target version here before
|
||||
* switching over — never `npx t3`, whose cache is ephemeral and whose
|
||||
* registry fetch at boot would make startup depend on the network.
|
||||
*/
|
||||
|
||||
const PINNED_RUNTIME_DIR = "runtime";
|
||||
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
|
||||
// Boot-service setup and remote self-update share this module but can be
|
||||
// constructed in separate layers. Serialize the complete check/install/
|
||||
// sentinel transaction across all callers in this process.
|
||||
const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
|
||||
|
||||
export interface PinnedRuntimePaths {
|
||||
readonly versionDir: string;
|
||||
readonly entryPath: string;
|
||||
readonly sentinelPath: string;
|
||||
}
|
||||
|
||||
export function pinnedRuntimePaths(
|
||||
path: Path.Path,
|
||||
baseDir: string,
|
||||
version: string,
|
||||
): PinnedRuntimePaths {
|
||||
const versionDir = path.join(baseDir, PINNED_RUNTIME_DIR, "versions", version);
|
||||
return {
|
||||
versionDir,
|
||||
entryPath: path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs"),
|
||||
sentinelPath: path.join(versionDir, ".install-complete"),
|
||||
};
|
||||
}
|
||||
|
||||
export class PinnedRuntimeInstallError extends Schema.TaggedErrorClass<PinnedRuntimeInstallError>()(
|
||||
"PinnedRuntimeInstallError",
|
||||
{
|
||||
step: Schema.String,
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
stdoutLength: Schema.optional(Schema.Number),
|
||||
stderrLength: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.exitCode === undefined
|
||||
? `Pinned runtime install failed while ${this.step}.`
|
||||
: `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs `t3@<version>` into the pinned runtime directory unless a complete
|
||||
* install is already there, and returns its paths. The sentinel is written
|
||||
* only after npm exits 0; checking the entry file alone is not enough — npm
|
||||
* extracts files before running native builds (node-pty), so a killed
|
||||
* install leaves a plausible-looking but broken tree behind.
|
||||
*/
|
||||
export const ensurePinnedRuntimeInstalled = Effect.fn("cloud.pinned_runtime.ensure_installed")(
|
||||
function* (input: {
|
||||
readonly baseDir: string;
|
||||
readonly version: string;
|
||||
readonly fs: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly runner: ProcessRunner.ProcessRunner["Service"];
|
||||
}) {
|
||||
const { fs, runner } = input;
|
||||
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
|
||||
|
||||
return yield* pinnedRuntimeInstallLock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const alreadyPinned = yield* Effect.all([
|
||||
fs.exists(paths.sentinelPath),
|
||||
fs.exists(paths.entryPath),
|
||||
]).pipe(
|
||||
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
|
||||
),
|
||||
);
|
||||
if (alreadyPinned) {
|
||||
return paths;
|
||||
}
|
||||
|
||||
yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
|
||||
Effect.andThen(fs.makeDirectory(paths.versionDir, { recursive: true })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({
|
||||
step: "preparing the pinned runtime directory",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
|
||||
yield* runner
|
||||
.run({
|
||||
command: "npm",
|
||||
args: [
|
||||
"install",
|
||||
"--prefix",
|
||||
paths.versionDir,
|
||||
"--no-fund",
|
||||
"--no-audit",
|
||||
`t3@${input.version}`,
|
||||
],
|
||||
// Native deps (node-pty) can compile from source on slow boxes; the
|
||||
// ProcessRunner default of 60s would kill a healthy install.
|
||||
timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
|
||||
Effect.filterOrFail(
|
||||
(result) => result.code === 0,
|
||||
(result) =>
|
||||
new PinnedRuntimeInstallError({
|
||||
step: installStep,
|
||||
exitCode: Number(result.code),
|
||||
stdoutLength: result.stdout.length,
|
||||
stderrLength: result.stderr.length,
|
||||
}),
|
||||
),
|
||||
Effect.tapError(() =>
|
||||
fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(Effect.ignore),
|
||||
),
|
||||
);
|
||||
|
||||
yield* fs
|
||||
.writeFileString(paths.sentinelPath, `${input.version}\n`)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
|
||||
),
|
||||
);
|
||||
|
||||
return paths;
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
/** Removes one pinned runtime while holding the same process-wide lock used
|
||||
* by install/check/sentinel work, so cleanup cannot race another caller that
|
||||
* is materializing or reusing the runtime tree. */
|
||||
export const removePinnedRuntimeInstallation = Effect.fn("cloud.pinned_runtime.remove")(
|
||||
function* (input: {
|
||||
readonly baseDir: string;
|
||||
readonly version: string;
|
||||
readonly fs: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
}) {
|
||||
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
|
||||
yield* pinnedRuntimeInstallLock.withPermit(
|
||||
input.fs
|
||||
.remove(paths.versionDir, { recursive: true, force: true })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({ step: "removing the pinned runtime", cause }),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,589 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
HostProcessArguments,
|
||||
HostProcessEnvironment,
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
BOOT_SERVICE_UNIT_ENV,
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
renderBootServiceUnit,
|
||||
} from "./bootService.ts";
|
||||
import * as SelfUpdate from "./selfUpdate.ts";
|
||||
|
||||
const NODE_PATH = "/usr/local/bin/node";
|
||||
|
||||
interface RecordedCommand {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const makeRecordingRunnerLayer = (
|
||||
commands: Array<RecordedCommand>,
|
||||
options?: {
|
||||
readonly failWhen?: ((command: string, args: ReadonlyArray<string>) => boolean) | undefined;
|
||||
readonly stdoutFor?:
|
||||
| ((command: string, args: ReadonlyArray<string>) => string | undefined)
|
||||
| undefined;
|
||||
},
|
||||
) =>
|
||||
Layer.succeed(
|
||||
ProcessRunner.ProcessRunner,
|
||||
ProcessRunner.ProcessRunner.of({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
commands.push({ command: input.command, args: input.args });
|
||||
const failed = options?.failWhen?.(input.command, input.args) === true;
|
||||
const versionFromPath =
|
||||
input.command === NODE_PATH && input.args[1] === "--version"
|
||||
? /[/\\]runtime[/\\]versions[/\\]([^/\\]+)/.exec(input.args[0] ?? "")?.[1]
|
||||
: undefined;
|
||||
return {
|
||||
stdout:
|
||||
options?.stdoutFor?.(input.command, input.args) ??
|
||||
(versionFromPath === undefined ? "" : `t3 v${versionFromPath}\n`),
|
||||
stderr: failed ? `${input.command} exploded` : "",
|
||||
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const provideHostRefs = (input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly entryPath: string;
|
||||
}) =>
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(HostProcessPlatform, input.platform),
|
||||
Layer.succeed(HostProcessEnvironment, input.env),
|
||||
Layer.succeed(HostProcessExecutablePath, NODE_PATH),
|
||||
Layer.succeed(HostProcessArguments, [NODE_PATH, input.entryPath, "serve"]),
|
||||
),
|
||||
);
|
||||
|
||||
it("recognizes published npm artifacts as swappable entry points", () => {
|
||||
assert.isTrue(SelfUpdate.isPublishedCliEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
|
||||
assert.isTrue(
|
||||
SelfUpdate.isPublishedCliEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
|
||||
);
|
||||
assert.isTrue(
|
||||
SelfUpdate.isPublishedCliEntry(
|
||||
"C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
|
||||
),
|
||||
);
|
||||
// Dev checkouts and the desktop bundle run apps/server/dist directly.
|
||||
assert.isFalse(SelfUpdate.isPublishedCliEntry("/home/theo/dev/t3/apps/server/dist/bin.mjs"));
|
||||
assert.isFalse(SelfUpdate.isPublishedCliEntry(""));
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("resolveServerSelfUpdateCapability", (it) => {
|
||||
const makeHome = Effect.fn("test.makeHome")(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
|
||||
return { fs, path, home };
|
||||
});
|
||||
|
||||
const writeUnitReferencing = Effect.fn("test.writeUnitReferencing")(function* (
|
||||
home: string,
|
||||
entryPath: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const unitDir = path.join(home, ".config", "systemd", "user");
|
||||
yield* fs.makeDirectory(unitDir, { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(unitDir, "t3code.service"),
|
||||
renderBootServiceUnit({
|
||||
nodePath: NODE_PATH,
|
||||
t3EntryPath: entryPath,
|
||||
baseDir: path.join(home, ".t3"),
|
||||
logPath: path.join(home, ".t3", "userdata", "logs", "boot-service.log"),
|
||||
unitPath: path.join(unitDir, "t3code.service"),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports boot-service for the systemd-spawned unit process", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "linux",
|
||||
env: {
|
||||
HOME: home,
|
||||
INVOCATION_ID: "abc123",
|
||||
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
|
||||
},
|
||||
entryPath,
|
||||
}),
|
||||
);
|
||||
assert.equal(method, "boot-service");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not claim a systemd process owned by another unit", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "linux",
|
||||
env: { HOME: home, INVOCATION_ID: "abc123" },
|
||||
entryPath,
|
||||
}),
|
||||
);
|
||||
assert.isNull(method);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports respawn for a manual run of the pinned artifact", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
// Same unit on disk, but no INVOCATION_ID: restarting the unit would
|
||||
// not replace this process, so it must respawn itself instead.
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(provideHostRefs({ platform: "linux", env: { HOME: home }, entryPath }));
|
||||
assert.equal(method, "respawn");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports respawn for a foreground npx artifact on darwin", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home } = yield* makeHome();
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "darwin",
|
||||
env: { HOME: home },
|
||||
entryPath: `${home}/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs`,
|
||||
}),
|
||||
);
|
||||
assert.equal(method, "respawn");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports desktop-managed for desktop-supervised backends", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
// Desktop ownership wins over every process-shape heuristic: even a
|
||||
// systemd-looking pinned artifact belongs to the app that spawned it.
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: true,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "linux",
|
||||
env: {
|
||||
HOME: home,
|
||||
INVOCATION_ID: "abc123",
|
||||
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
|
||||
},
|
||||
entryPath,
|
||||
}),
|
||||
);
|
||||
assert.equal(method, "desktop-managed");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports no method for dev checkouts and Windows", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home } = yield* makeHome();
|
||||
const devMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "darwin",
|
||||
env: { HOME: home },
|
||||
entryPath: `${home}/dev/t3/apps/server/dist/bin.mjs`,
|
||||
}),
|
||||
);
|
||||
assert.isNull(devMethod);
|
||||
const windowsMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "win32",
|
||||
env: { HOME: home },
|
||||
entryPath: "C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
|
||||
}),
|
||||
);
|
||||
assert.isNull(windowsMethod);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
interface RecordedSpawn {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const makeContext = Effect.fn("test.makeContext")(function* (options?: {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly bootService?: boolean;
|
||||
readonly desktopManaged?: boolean;
|
||||
readonly entryPath?: string;
|
||||
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
|
||||
readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
|
||||
readonly failSpawn?: boolean;
|
||||
}) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
|
||||
const baseDir = path.join(home, ".t3");
|
||||
const entryPath =
|
||||
options?.entryPath ??
|
||||
path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
const env: NodeJS.ProcessEnv =
|
||||
options?.bootService === true
|
||||
? {
|
||||
HOME: home,
|
||||
INVOCATION_ID: "abc123",
|
||||
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
|
||||
}
|
||||
: { HOME: home };
|
||||
if (options?.bootService === true) {
|
||||
const unitDir = path.join(home, ".config", "systemd", "user");
|
||||
yield* fs.makeDirectory(unitDir, { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(unitDir, "t3code.service"),
|
||||
renderBootServiceUnit({
|
||||
nodePath: NODE_PATH,
|
||||
t3EntryPath: entryPath,
|
||||
baseDir,
|
||||
logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
|
||||
unitPath: path.join(unitDir, "t3code.service"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
const spawns: Array<RecordedSpawn> = [];
|
||||
let exited = 0;
|
||||
// layerTest always reports mode "web"; desktop-managed contexts overlay
|
||||
// the mode the desktop app's bootstrap envelope would set.
|
||||
const configLayer =
|
||||
options?.desktopManaged === true
|
||||
? Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
return { ...config, mode: "desktop" as const };
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(home, baseDir)))
|
||||
: ServerConfig.layerTest(home, baseDir);
|
||||
const service = yield* SelfUpdate.make({
|
||||
host: {
|
||||
spawnDetached: (command, args) =>
|
||||
Effect.sync(() => spawns.push({ command, args })).pipe(
|
||||
Effect.andThen(
|
||||
options?.failSpawn === true
|
||||
? Effect.fail(
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command,
|
||||
argumentCount: args.length,
|
||||
cause: new Error("detached spawn failed"),
|
||||
}),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
exitProcess: () => {
|
||||
exited += 1;
|
||||
},
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeRecordingRunnerLayer(commands, {
|
||||
failWhen: options?.failWhen,
|
||||
stdoutFor: options?.stdoutFor,
|
||||
}),
|
||||
configLayer,
|
||||
),
|
||||
),
|
||||
provideHostRefs({ platform: options?.platform ?? "linux", env, entryPath }),
|
||||
);
|
||||
return {
|
||||
fs,
|
||||
path,
|
||||
home,
|
||||
baseDir,
|
||||
entryPath,
|
||||
commands,
|
||||
spawns,
|
||||
exitCount: () => exited,
|
||||
service,
|
||||
};
|
||||
});
|
||||
|
||||
it.effect("rejects dist-tags and other non-exact versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext();
|
||||
const error = yield* context.service.update({ targetVersion: "latest" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "not an exact t3 version");
|
||||
assert.lengthOf(context.commands, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses to update a desktop-managed backend and points at the app", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ desktopManaged: true, bootService: true });
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "desktop app");
|
||||
assert.lengthOf(context.commands, 0);
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails without touching anything when no update method applies", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
entryPath: "/home/theo/dev/t3/apps/server/dist/bin.mjs",
|
||||
});
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "cannot update itself");
|
||||
assert.lengthOf(context.commands, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a failed npm install and never schedules a restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ failWhen: (command) => command === "npm" });
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.equal(error.reason, "Could not install the requested t3 version.");
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("reinstalls the same version after a failed preflight", () =>
|
||||
Effect.gen(function* () {
|
||||
let preflightAttempts = 0;
|
||||
const context = yield* makeContext({
|
||||
failWhen: (command) => {
|
||||
if (command !== NODE_PATH) return false;
|
||||
preflightAttempts += 1;
|
||||
return preflightAttempts === 1;
|
||||
},
|
||||
});
|
||||
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
|
||||
const entryPath = context.path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
|
||||
yield* context.fs.makeDirectory(context.path.dirname(entryPath), { recursive: true });
|
||||
yield* context.fs.writeFileString(entryPath, "export {};\n");
|
||||
yield* context.fs.writeFileString(
|
||||
context.path.join(versionDir, ".install-complete"),
|
||||
"0.0.29\n",
|
||||
);
|
||||
|
||||
const firstError = yield* context.service
|
||||
.update({ targetVersion: "0.0.29" })
|
||||
.pipe(Effect.flip);
|
||||
assert.include(firstError.reason, "failed its version check");
|
||||
assert.isFalse(yield* context.fs.exists(versionDir));
|
||||
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
[NODE_PATH, "npm", NODE_PATH],
|
||||
);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("rejects and removes an installed runtime that reports the wrong version", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
stdoutFor: (command, args) =>
|
||||
command === NODE_PATH && args[1] === "--version" ? "t3 v0.0.28\n" : undefined,
|
||||
});
|
||||
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
|
||||
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
|
||||
assert.include(error.reason, "did not report the requested");
|
||||
assert.isFalse(yield* context.fs.exists(versionDir));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a detached replacement spawn failure and leaves updates retryable", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ failSpawn: true });
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(first.reason, "Could not start the replacement");
|
||||
|
||||
const second = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(second.reason, "Could not start the replacement");
|
||||
assert.notInclude(second.reason, "already in progress");
|
||||
assert.lengthOf(context.spawns, 2);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs, preflights, and respawns a foreground server", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext();
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
|
||||
assert.lengthOf(context.spawns, 1);
|
||||
|
||||
const concurrentError = yield* context.service
|
||||
.update({ targetVersion: "0.0.30" })
|
||||
.pipe(Effect.flip);
|
||||
assert.include(concurrentError.reason, "already in progress");
|
||||
|
||||
const pinnedEntry = context.path.join(
|
||||
context.baseDir,
|
||||
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
|
||||
);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => [entry.command, ...entry.args].join(" ")),
|
||||
[
|
||||
`npm install --prefix ${context.path.join(context.baseDir, "runtime/versions/0.0.29")} --no-fund --no-audit [email protected]`,
|
||||
`${NODE_PATH} ${pinnedEntry} --version`,
|
||||
],
|
||||
);
|
||||
|
||||
// The restart is deferred so the RPC acknowledgement flushes first.
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 1);
|
||||
const spawn = context.spawns[0];
|
||||
assert.equal(spawn?.command, "/bin/sh");
|
||||
assert.include(spawn?.args ?? [], pinnedEntry);
|
||||
// The replacement replays the original CLI arguments.
|
||||
assert.include(spawn?.args ?? [], "serve");
|
||||
assert.equal(context.exitCount(), 1);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("rewrites the systemd unit and restarts the boot service", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ bootService: true });
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "boot-service" });
|
||||
|
||||
const pinnedEntry = context.path.join(
|
||||
context.baseDir,
|
||||
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
|
||||
);
|
||||
const unit = yield* context.fs.readFileString(
|
||||
context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
|
||||
);
|
||||
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl", "systemctl"],
|
||||
);
|
||||
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
|
||||
|
||||
assert.deepEqual(context.commands[3], {
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", "t3code.service"],
|
||||
});
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
// systemd replaces the process; the server must not exit itself.
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
|
||||
Effect.gen(function* () {
|
||||
let failRestart = true;
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
failWhen: (command, args) => {
|
||||
if (command !== "systemctl" || args[1] !== "restart" || !failRestart) {
|
||||
return false;
|
||||
}
|
||||
failRestart = false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const unitPath = context.path.join(
|
||||
context.home,
|
||||
".config",
|
||||
"systemd",
|
||||
"user",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(first.reason, "Restarting the systemd boot service failed");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
assert.deepEqual(
|
||||
context.commands.slice(-2).map((entry) => entry.args),
|
||||
[
|
||||
["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
["--user", "daemon-reload"],
|
||||
],
|
||||
);
|
||||
|
||||
const retry = yield* context.service.update({ targetVersion: "0.0.30" });
|
||||
assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous systemd unit when daemon-reload fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
failWhen: (command) => command === "systemctl",
|
||||
});
|
||||
const unitPath = context.path.join(
|
||||
context.home,
|
||||
".config",
|
||||
"systemd",
|
||||
"user",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "Reloading systemd units failed");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl", "systemctl"],
|
||||
);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,430 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
// node:child_process directly: the foreground-server replacement must be a
|
||||
// detached fire-and-forget child that outlives this process, while Effect's
|
||||
// ChildProcessSpawner ties every child to a scope that kills it.
|
||||
import {
|
||||
ServerSelfUpdateError,
|
||||
type ServerSelfUpdateCapability,
|
||||
type ServerSelfUpdateInput,
|
||||
type ServerSelfUpdateResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
HostProcessArguments,
|
||||
HostProcessEnvironment,
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { writeFileStringAtomically } from "../atomicWrite.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
BOOT_SERVICE_UNIT_ENV,
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
quoteSystemdValue,
|
||||
renderBootServiceUnit,
|
||||
} from "./bootService.ts";
|
||||
import { ensurePinnedRuntimeInstalled, removePinnedRuntimeInstallation } from "./pinnedRuntime.ts";
|
||||
|
||||
/**
|
||||
* Lets a connected client replace this server with another published `t3`
|
||||
* version over RPC — the only update path that works when the user is not at
|
||||
* the machine (phone against a home server, relay-managed box). The target
|
||||
* version is npm-installed into the pinned runtime and verified before
|
||||
* anything restarts, so a failed install leaves the running server untouched.
|
||||
*/
|
||||
|
||||
const PREFLIGHT_TIMEOUT = Duration.seconds(30);
|
||||
/** Grace between acknowledging the RPC and killing the process, so the
|
||||
response (and its relay hop) flushes before the socket drops. */
|
||||
const RESTART_DELAY = Duration.seconds(2);
|
||||
|
||||
/** Exact npm versions only — never dist-tags — so the acknowledgement names
|
||||
the version that was actually installed. Also keeps the value safe to
|
||||
pass to npm and embed in filesystem paths. */
|
||||
const EXACT_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
|
||||
export interface ServerSelfUpdateHost {
|
||||
readonly execPath: string;
|
||||
readonly cliEntryPath: string;
|
||||
/** Original CLI arguments after the entry path, replayed on respawn. */
|
||||
readonly cliArgs: ReadonlyArray<string>;
|
||||
/** Resolves once the foreground replacement process has actually spawned. */
|
||||
readonly spawnDetached: (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) => Effect.Effect<void, ProcessRunner.ProcessSpawnError>;
|
||||
readonly exitProcess: () => void;
|
||||
}
|
||||
|
||||
function normalizeEntryPath(entryPath: string): string {
|
||||
return entryPath.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Only a published npm artifact can be swapped for another version: dev
|
||||
* checkouts (apps/server/dist) and the desktop app's bundled backend have no
|
||||
* npm identity, and the desktop manages its own updates.
|
||||
*/
|
||||
export function isPublishedCliEntry(entryPath: string): boolean {
|
||||
return normalizeEntryPath(entryPath).includes("/node_modules/t3/dist/");
|
||||
}
|
||||
|
||||
/**
|
||||
* The update path this process can offer, or null when only a manual
|
||||
* relaunch works. "desktop-managed" — the T3 Code desktop app spawned this
|
||||
* backend and owns its version; only updating the app updates it.
|
||||
* "boot-service" — this is the systemd-supervised process from
|
||||
* bootService.ts: rewrite the unit and let systemd swap it. "respawn" — a
|
||||
* foreground POSIX process running a published artifact: replace it with a
|
||||
* detached child. Windows foreground runs are unsupported for now (no
|
||||
* equivalent of the detach-and-exec handoff below).
|
||||
*/
|
||||
export const resolveServerSelfUpdateCapability = Effect.fn(
|
||||
"cloud.server_self_update.resolve_capability",
|
||||
)(function* (input: {
|
||||
/** True when the desktop app supervises this backend (mode "desktop"). */
|
||||
readonly desktopManaged: boolean;
|
||||
}) {
|
||||
if (input.desktopManaged) {
|
||||
return "desktop-managed" as const;
|
||||
}
|
||||
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const env = yield* HostProcessEnvironment;
|
||||
const hostArguments = yield* HostProcessArguments;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const entryPath = hostArguments[1] ?? "";
|
||||
if (entryPath === "") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const homeDir = env.HOME ?? "";
|
||||
if (platform === "linux" && homeDir !== "") {
|
||||
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
|
||||
const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(
|
||||
Effect.map((unit) => unit.includes(quoteSystemdValue(entryPath))),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
// INVOCATION_ID only proves that some systemd unit launched us. The
|
||||
// explicit marker written into t3code.service identifies this unit as the
|
||||
// supervisor that will replace the current process when restarted.
|
||||
if (
|
||||
unitReferencesEntry &&
|
||||
(env.INVOCATION_ID ?? "") !== "" &&
|
||||
env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_UNIT_FILE
|
||||
) {
|
||||
return "boot-service" as const;
|
||||
}
|
||||
|
||||
// A process owned by another (or a legacy unmarked) systemd unit must not
|
||||
// use the foreground respawn path: Restart=always could otherwise launch
|
||||
// the old unit beside the detached replacement.
|
||||
if ((env.INVOCATION_ID ?? "") !== "") {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if ((platform === "linux" || platform === "darwin") && isPublishedCliEntry(entryPath)) {
|
||||
return "respawn" as const;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
export class ServerSelfUpdate extends Context.Service<
|
||||
ServerSelfUpdate,
|
||||
{
|
||||
readonly update: (
|
||||
input: ServerSelfUpdateInput,
|
||||
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
|
||||
}
|
||||
>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
|
||||
|
||||
export const make = Effect.fn("cloud.server_self_update.make")(function* (options?: {
|
||||
readonly host?: Partial<ServerSelfUpdateHost>;
|
||||
}) {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const env = yield* HostProcessEnvironment;
|
||||
const hostExecPath = yield* HostProcessExecutablePath;
|
||||
const hostArguments = yield* HostProcessArguments;
|
||||
const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({
|
||||
desktopManaged: serverConfig.mode === "desktop",
|
||||
});
|
||||
|
||||
const host: ServerSelfUpdateHost = {
|
||||
execPath: options?.host?.execPath ?? hostExecPath,
|
||||
cliEntryPath: options?.host?.cliEntryPath ?? hostArguments[1] ?? "",
|
||||
cliArgs: options?.host?.cliArgs ?? hostArguments.slice(2),
|
||||
spawnDetached:
|
||||
options?.host?.spawnDetached ??
|
||||
((command, args) =>
|
||||
Effect.callback<void, ProcessRunner.ProcessSpawnError>((resume) => {
|
||||
const spawnError = (cause: unknown) =>
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command,
|
||||
argumentCount: args.length,
|
||||
cause,
|
||||
});
|
||||
let child: NodeChildProcess.ChildProcess;
|
||||
try {
|
||||
child = NodeChildProcess.spawn(command, [...args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
} catch (cause) {
|
||||
resume(Effect.fail(spawnError(cause)));
|
||||
return;
|
||||
}
|
||||
|
||||
const onSpawnError = (cause: Error) => resume(Effect.fail(spawnError(cause)));
|
||||
child.once("error", onSpawnError);
|
||||
child.once("spawn", () => {
|
||||
child.removeListener("error", onSpawnError);
|
||||
// Keep asynchronous child errors from becoming uncaught after the
|
||||
// successful spawn handoff has already been acknowledged.
|
||||
child.on("error", () => undefined);
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
});
|
||||
})),
|
||||
exitProcess: options?.host?.exitProcess ?? (() => process.exit(0)),
|
||||
};
|
||||
|
||||
const inFlight = yield* Ref.make(false);
|
||||
|
||||
const failWith = (reason: string, cause?: unknown) =>
|
||||
cause === undefined
|
||||
? new ServerSelfUpdateError({ reason })
|
||||
: new ServerSelfUpdateError({ reason, cause });
|
||||
|
||||
/** Deferred so the RPC acknowledgement flushes before the process dies.
|
||||
Detached from the request scope: the triggering connection is exactly
|
||||
what the restart tears down. */
|
||||
const scheduleRestart = (restart: Effect.Effect<void>) =>
|
||||
Effect.sleep(RESTART_DELAY).pipe(
|
||||
Effect.andThen(restart),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
const writeUnitAtomically = (filePath: string, contents: string) =>
|
||||
writeFileStringAtomically({ filePath, contents }).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
|
||||
"cloud.server_self_update.update",
|
||||
)(function* (input) {
|
||||
if (capability === "desktop-managed") {
|
||||
return yield* failWith(
|
||||
"This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
|
||||
);
|
||||
}
|
||||
if (capability === null) {
|
||||
return yield* failWith(
|
||||
"This server cannot update itself; relaunch it manually with the new version.",
|
||||
);
|
||||
}
|
||||
const activeMethod = capability;
|
||||
const targetVersion = input.targetVersion.trim();
|
||||
if (!EXACT_VERSION_PATTERN.test(targetVersion)) {
|
||||
return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
|
||||
}
|
||||
|
||||
const alreadyRunning = yield* Ref.getAndSet(inFlight, true);
|
||||
if (alreadyRunning) {
|
||||
return yield* failWith("A server update is already in progress.");
|
||||
}
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const runtimePaths = yield* ensurePinnedRuntimeInstalled({
|
||||
baseDir: serverConfig.baseDir,
|
||||
version: targetVersion,
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
}).pipe(
|
||||
Effect.mapError((error) => failWith("Could not install the requested t3 version.", error)),
|
||||
);
|
||||
|
||||
// A broken artifact (failed native build, incompatible node) must be
|
||||
// caught while the current server is still alive to report it.
|
||||
const preflight = yield* runner
|
||||
.run({
|
||||
command: host.execPath,
|
||||
args: [runtimePaths.entryPath, "--version"],
|
||||
timeout: PREFLIGHT_TIMEOUT,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith(`Could not verify the installed t3@${targetVersion}.`, cause),
|
||||
),
|
||||
);
|
||||
// Effect CLI's unstable formatVersion currently emits `${name} v${version}`.
|
||||
// Extract the version token so surrounding presentation changes do not break updates.
|
||||
const reportedVersion = /\bv(\S+)\s*$/.exec(preflight.stdout)?.[1];
|
||||
if (preflight.code !== 0 || reportedVersion !== targetVersion) {
|
||||
// A completed npm install can still be unusable under this Node or on
|
||||
// this machine. Remove its sentinel and tree so a retry of the same
|
||||
// version performs a clean install instead of reusing a known-bad one.
|
||||
yield* removePinnedRuntimeInstallation({
|
||||
baseDir: serverConfig.baseDir,
|
||||
version: targetVersion,
|
||||
fs,
|
||||
path,
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
failWith(`Could not remove the failed t3@${targetVersion} installation.`, error),
|
||||
),
|
||||
);
|
||||
return yield* failWith(
|
||||
preflight.code !== 0
|
||||
? `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`
|
||||
: `The installed runtime did not report the requested t3@${targetVersion} version.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (activeMethod === "boot-service") {
|
||||
const homeDir = env.HOME ?? "";
|
||||
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
|
||||
const previousUnit = yield* fs
|
||||
.readFileString(unitPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => failWith("Could not read the current systemd unit.", cause)),
|
||||
);
|
||||
// Same shape bootService.install writes, so host lifecycle commands
|
||||
// still recognize the unit as current.
|
||||
const unit = renderBootServiceUnit({
|
||||
nodePath: host.execPath,
|
||||
t3EntryPath: runtimePaths.entryPath,
|
||||
baseDir: serverConfig.baseDir,
|
||||
logPath: path.join(serverConfig.logsDir, "boot-service.log"),
|
||||
unitPath,
|
||||
});
|
||||
yield* writeUnitAtomically(unitPath, unit).pipe(
|
||||
Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)),
|
||||
);
|
||||
|
||||
const reloadSystemd = Effect.fn("cloud.server_self_update.reload_systemd")(function* () {
|
||||
const reload = yield* runner
|
||||
.run({ command: "systemctl", args: ["--user", "daemon-reload"] })
|
||||
.pipe(Effect.mapError((cause) => failWith("Could not reload systemd units.", cause)));
|
||||
if (reload.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Reloading systemd units failed (exit code ${String(reload.code)}).`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
yield* reloadSystemd().pipe(
|
||||
Effect.catch((reloadError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.mapError((rollbackCause) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
reloadError,
|
||||
rollbackCause,
|
||||
}),
|
||||
),
|
||||
// Systemd should still have the old unit in memory after the
|
||||
// failed reload, but retry after restoring in case it applied a
|
||||
// partial update before returning an error.
|
||||
Effect.andThen(reloadSystemd().pipe(Effect.ignore)),
|
||||
Effect.andThen(Effect.fail(reloadError)),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
|
||||
targetVersion,
|
||||
});
|
||||
// A successful systemd restart stops this process, so the RPC is
|
||||
// interrupted and the reconnecting client observes the new version.
|
||||
// A rejected restart returns while the old process is still alive;
|
||||
// restore the previous unit and report that failure through the RPC.
|
||||
yield* Effect.gen(function* () {
|
||||
const restart = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not restart the systemd boot service.", cause),
|
||||
),
|
||||
);
|
||||
if (restart.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch((restartError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.andThen(reloadSystemd()),
|
||||
Effect.mapError((rollbackError) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
restartError,
|
||||
rollbackError,
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Effect.fail(restartError)),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Spawn the shim before acknowledging the RPC so ENOENT/EACCES and
|
||||
// other launch failures leave this server alive and return a useful
|
||||
// error. The shim itself waits until after the acknowledgement and
|
||||
// deferred exit before binding the replacement server.
|
||||
yield* host
|
||||
.spawnDetached("/bin/sh", [
|
||||
"-c",
|
||||
'sleep 3; exec "$@"',
|
||||
"t3-self-update",
|
||||
host.execPath,
|
||||
runtimePaths.entryPath,
|
||||
...host.cliArgs,
|
||||
])
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not start the replacement t3 process.", cause),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });
|
||||
yield* scheduleRestart(
|
||||
Effect.try({
|
||||
try: () => host.exitProcess(),
|
||||
catch: (cause) => failWith("Could not exit the replaced t3 process.", cause),
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError("Server self-update could not exit the replaced process.").pipe(
|
||||
Effect.annotateLogs({ targetVersion, error: error.reason }),
|
||||
Effect.ensuring(Ref.set(inFlight, false)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return { targetVersion, method: activeMethod };
|
||||
}).pipe(Effect.onError(() => Ref.set(inFlight, false)));
|
||||
});
|
||||
|
||||
return ServerSelfUpdate.of({ update });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
|
||||
Layer.provide(ProcessRunner.layer),
|
||||
);
|
||||
@@ -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");
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
@@ -124,6 +125,9 @@ export const make = Effect.gen(function* () {
|
||||
const environmentId = EnvironmentId.make(environmentIdRaw);
|
||||
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
||||
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
|
||||
const serverSelfUpdate = yield* resolveServerSelfUpdateCapability({
|
||||
desktopManaged: serverConfig.mode === "desktop",
|
||||
});
|
||||
|
||||
const descriptor: ExecutionEnvironmentDescriptor = {
|
||||
environmentId,
|
||||
@@ -136,6 +140,9 @@ export const make = Effect.gen(function* () {
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -50,6 +51,8 @@ interface FakeGhScenario {
|
||||
};
|
||||
repositoryCloneUrls?: Record<string, { url: string; sshUrl: string }>;
|
||||
failWith?: GitHubCli.GitHubCliError;
|
||||
/** Let this many gh calls succeed before failWith kicks in (default 0 = fail immediately). */
|
||||
failAfterCalls?: number;
|
||||
}
|
||||
|
||||
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
@@ -382,7 +385,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
const args = [...input.args];
|
||||
ghCalls.push(args.join(" "));
|
||||
|
||||
if (scenario.failWith) {
|
||||
if (scenario.failWith && ghCalls.length > (scenario.failAfterCalls ?? 0)) {
|
||||
return Effect.fail(scenario.failWith);
|
||||
}
|
||||
|
||||
@@ -1336,6 +1339,230 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status keeps the last known PR when a later lookup fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 214,
|
||||
title: "Sticky PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/214",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-sticky",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(214);
|
||||
|
||||
// An explicit invalidation (user refresh, git action) bypasses the PR
|
||||
// cache and forces a live lookup — which now fails. The badge must keep
|
||||
// the last known PR instead of blanking out.
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr?.number).toBe(214);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"status does not reuse a stale PR after the branch is retargeted to a different upstream",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-retarget"]);
|
||||
|
||||
const originRemote = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originRemote]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-retarget"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 214,
|
||||
title: "Sticky PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/214",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-retarget",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(214);
|
||||
|
||||
// Retarget the branch to a different remote/upstream (e.g. the PR was
|
||||
// reopened against a fork). The previously cached PR belonged to the
|
||||
// old upstream and must not be shown against the new one.
|
||||
const forkRemote = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "fork", forkRemote]);
|
||||
yield* runGit(repoDir, ["push", "fork", "feature/pr-retarget"]);
|
||||
yield* runGit(repoDir, [
|
||||
"branch",
|
||||
"--set-upstream-to=fork/feature/pr-retarget",
|
||||
"feature/pr-retarget",
|
||||
]);
|
||||
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status keeps the last known PR when the branch gains its first upstream", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky-first-push"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
|
||||
const existingPr = {
|
||||
number: 215,
|
||||
title: "Sticky first-push PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/215",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-sticky-first-push",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(215);
|
||||
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky-first-push"]);
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr?.number).toBe(215);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status drops the last known PR when the tracked remote is repointed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-repointed"]);
|
||||
const originalRemoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originalRemoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-repointed"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 216,
|
||||
title: "Old remote PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/216",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-repointed",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(216);
|
||||
|
||||
const replacementRemoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "replacement", replacementRemoteDir]);
|
||||
yield* runGit(repoDir, ["push", "replacement", "feature/pr-repointed"]);
|
||||
yield* runGit(repoDir, ["remote", "set-url", "origin", replacementRemoteDir]);
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status keeps the last known PR when the current remote URL can't be resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-config-hiccup"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-config-hiccup"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 217,
|
||||
title: "Config hiccup PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/217",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-config-hiccup",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(217);
|
||||
|
||||
// `remote.origin.url` reads go through readConfigValueNullable, which
|
||||
// maps ANY failed read (a real "no remote configured" state or a
|
||||
// transient git-config hiccup) to null the same way. Unsetting the
|
||||
// key here reproduces that ambiguity without touching branch
|
||||
// tracking (refs/remotes/origin/* and branch.<b>.remote are
|
||||
// untouched) — the remote identity has not actually changed, so the
|
||||
// sticky PR must survive even though the current lookup can no
|
||||
// longer resolve a remote URL to compare against.
|
||||
yield* runGit(repoDir, ["config", "--unset", "remote.origin.url"]);
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr?.number).toBe(217);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates a commit when working tree is dirty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -2187,6 +2414,123 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
12_000,
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"does not reuse a cross-repo PR when GitHub omits head identity metadata",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
|
||||
const forkDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequenceByHeadSelector: {
|
||||
"octocat:statemachine": [
|
||||
`[{"number":41,"title":"Ambiguous fork PR","url":"https://github.com/pingdotgg/codething-mvp/pull/41","baseRefName":"main","headRefName":"statemachine","state":"OPEN"}]`,
|
||||
`[{"number":142,"title":"Add stacked git actions","url":"https://github.com/pingdotgg/codething-mvp/pull/142","baseRefName":"main","headRefName":"statemachine","state":"OPEN","isCrossRepository":true,"headRepository":{"nameWithOwner":"octocat/codething-mvp"},"headRepositoryOwner":{"login":"octocat"}}]`,
|
||||
],
|
||||
"fork-seed:statemachine": ["[]"],
|
||||
statemachine: ["[]"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(142);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(true);
|
||||
}),
|
||||
20_000,
|
||||
);
|
||||
|
||||
it.effect("rejects same-repo PR metadata when matching a cross-repo head context", () =>
|
||||
Effect.sync(() => {
|
||||
const headContext = {
|
||||
headBranch: "statemachine",
|
||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
||||
headRepositoryOwnerLogin: "pingdotgg",
|
||||
isCrossRepository: true,
|
||||
};
|
||||
|
||||
expect(
|
||||
GitManager.matchesBranchHeadContext(
|
||||
{
|
||||
number: 41,
|
||||
title: "Same-repo PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/41",
|
||||
baseRefName: "main",
|
||||
headRefName: "statemachine",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: false,
|
||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
||||
headRepositoryOwnerLogin: "pingdotgg",
|
||||
},
|
||||
headContext,
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
GitManager.matchesBranchHeadContext(
|
||||
{
|
||||
number: 142,
|
||||
title: "Fork PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
|
||||
baseRefName: "main",
|
||||
headRefName: "statemachine",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
||||
headRepositoryOwnerLogin: "pingdotgg",
|
||||
},
|
||||
headContext,
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts fork PR metadata when origin is the fork checkout remote", () =>
|
||||
Effect.sync(() => {
|
||||
const headContext = {
|
||||
headBranch: "t3code/git-audit-stability",
|
||||
headRepositoryNameWithOwner: "justsomelegs/t3code",
|
||||
headRepositoryOwnerLogin: "justsomelegs",
|
||||
isCrossRepository: false,
|
||||
};
|
||||
|
||||
expect(
|
||||
GitManager.matchesBranchHeadContext(
|
||||
{
|
||||
number: 2284,
|
||||
title: "Improve branch mismatch warnings",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/2284",
|
||||
baseRefName: "main",
|
||||
headRefName: "t3code/git-audit-stability",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "justsomelegs/t3code",
|
||||
headRepositoryOwnerLogin: "justsomelegs",
|
||||
},
|
||||
headContext,
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates PR when one does not already exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
import {
|
||||
detectSourceControlProviderFromGitRemoteUrl,
|
||||
mergeGitStatusParts,
|
||||
normalizeGitRemoteUrl,
|
||||
resolveAutoFeatureBranchName,
|
||||
sanitizeBranchFragment,
|
||||
sanitizeFeatureBranchName,
|
||||
@@ -95,6 +96,9 @@ const SHORT_SHA_LENGTH = 7;
|
||||
const TOAST_DESCRIPTION_MAX = 72;
|
||||
const STATUS_RESULT_CACHE_TTL = Duration.seconds(1);
|
||||
const STATUS_RESULT_CACHE_CAPACITY = 2_048;
|
||||
const PR_LOOKUP_CACHE_TTL = Duration.minutes(2);
|
||||
const PR_LOOKUP_FAILURE_TTL = Duration.seconds(20);
|
||||
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
|
||||
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
|
||||
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
|
||||
type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;
|
||||
@@ -142,6 +146,7 @@ interface BranchHeadContext {
|
||||
headSelectors: ReadonlyArray<string>;
|
||||
preferredHeadSelector: string;
|
||||
remoteName: string | null;
|
||||
headRemoteUrlKey: string | null;
|
||||
headRepositoryNameWithOwner: string | null;
|
||||
headRepositoryOwnerLogin: string | null;
|
||||
isCrossRepository: boolean;
|
||||
@@ -247,7 +252,38 @@ function resolvePullRequestHeadRepositoryNameWithOwner(
|
||||
return `${ownerLogin}/${repositoryName}`;
|
||||
}
|
||||
|
||||
function matchesBranchHeadContext(
|
||||
interface PullRequestHeadIdentity {
|
||||
readonly repositoryNameWithOwner: string | null;
|
||||
readonly ownerLogin: string | null;
|
||||
}
|
||||
|
||||
function resolveExpectedHeadIdentity(
|
||||
headContext: Pick<BranchHeadContext, "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin">,
|
||||
): PullRequestHeadIdentity {
|
||||
const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
|
||||
headContext.headRepositoryNameWithOwner,
|
||||
);
|
||||
return {
|
||||
repositoryNameWithOwner,
|
||||
ownerLogin:
|
||||
normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
|
||||
parseRepositoryOwnerLogin(repositoryNameWithOwner),
|
||||
};
|
||||
}
|
||||
|
||||
function resolvePullRequestHeadIdentity(pr: PullRequestInfo): PullRequestHeadIdentity {
|
||||
const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
|
||||
resolvePullRequestHeadRepositoryNameWithOwner(pr),
|
||||
);
|
||||
return {
|
||||
repositoryNameWithOwner,
|
||||
ownerLogin:
|
||||
normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
|
||||
parseRepositoryOwnerLogin(repositoryNameWithOwner),
|
||||
};
|
||||
}
|
||||
|
||||
export function matchesBranchHeadContext(
|
||||
pr: PullRequestInfo,
|
||||
headContext: Pick<
|
||||
BranchHeadContext,
|
||||
@@ -258,44 +294,51 @@ function matchesBranchHeadContext(
|
||||
return false;
|
||||
}
|
||||
|
||||
const expectedHeadRepository = normalizeOptionalRepositoryNameWithOwner(
|
||||
headContext.headRepositoryNameWithOwner,
|
||||
);
|
||||
const expectedHeadOwner =
|
||||
normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
|
||||
parseRepositoryOwnerLogin(expectedHeadRepository);
|
||||
const prHeadRepository = normalizeOptionalRepositoryNameWithOwner(
|
||||
resolvePullRequestHeadRepositoryNameWithOwner(pr),
|
||||
);
|
||||
const prHeadOwner =
|
||||
normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
|
||||
parseRepositoryOwnerLogin(prHeadRepository);
|
||||
const expectedHead = resolveExpectedHeadIdentity(headContext);
|
||||
const pullRequestHead = resolvePullRequestHeadIdentity(pr);
|
||||
|
||||
if (expectedHead.repositoryNameWithOwner) {
|
||||
if (pullRequestHead.repositoryNameWithOwner) {
|
||||
if (expectedHead.repositoryNameWithOwner !== pullRequestHead.repositoryNameWithOwner) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
|
||||
if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
|
||||
if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (headContext.isCrossRepository) {
|
||||
if (pr.isCrossRepository === false) {
|
||||
return false;
|
||||
}
|
||||
if ((expectedHeadRepository || expectedHeadOwner) && !prHeadRepository && !prHeadOwner) {
|
||||
return false;
|
||||
}
|
||||
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
|
||||
return false;
|
||||
}
|
||||
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
|
||||
if (
|
||||
(expectedHead.repositoryNameWithOwner || expectedHead.ownerLogin) &&
|
||||
!pullRequestHead.repositoryNameWithOwner &&
|
||||
!pullRequestHead.ownerLogin
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pr.isCrossRepository === true) {
|
||||
return false;
|
||||
}
|
||||
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
|
||||
return false;
|
||||
}
|
||||
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
|
||||
return false;
|
||||
if (
|
||||
(!expectedHead.repositoryNameWithOwner && !expectedHead.ownerLogin) ||
|
||||
(!pullRequestHead.repositoryNameWithOwner && !pullRequestHead.ownerLogin)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -768,6 +811,154 @@ export const make = Effect.gen(function* () {
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
|
||||
);
|
||||
// PR lookups hit the hosting provider's API (gh/glab/...), so they refresh
|
||||
// on their own, slower cadence: ahead/behind counts stay fresh on every
|
||||
// status poll while the PR association is re-fetched at most once per
|
||||
// PR_LOOKUP_CACHE_TTL per branch. Git actions and user-driven refreshes bump
|
||||
// the epoch (invalidateStatus) to bypass the cache immediately.
|
||||
const prLookupEpochByCwd = new Map<string, number>();
|
||||
const prLookupEpoch = (cwd: string) => prLookupEpochByCwd.get(cwd) ?? 0;
|
||||
const bumpPrLookupEpoch = (cwd: string) =>
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.map((cacheKey) => {
|
||||
prLookupEpochByCwd.set(cacheKey, prLookupEpoch(cacheKey) + 1);
|
||||
}),
|
||||
);
|
||||
// Cache keys are NUL-joined [cwd, branch, upstreamRef, epoch] — none of the
|
||||
// segments can contain a NUL byte, and refs are never empty, so "" decodes
|
||||
// back to a null upstreamRef.
|
||||
const prLookupCacheKey = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
|
||||
[cwd, details.branch, details.upstreamRef ?? "", String(prLookupEpoch(cwd))].join("\u0000");
|
||||
const prLookupCache = yield* Cache.makeWith(
|
||||
(key: string) => {
|
||||
const [cwd = "", branch = "", upstreamRef = ""] = key.split("\u0000");
|
||||
const details = {
|
||||
branch,
|
||||
upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,
|
||||
};
|
||||
return resolveBranchHeadContext(cwd, details).pipe(
|
||||
Effect.flatMap((headContext) =>
|
||||
findLatestPrForHeadContext(cwd, headContext).pipe(
|
||||
Effect.map((latest) => ({ latest, headContext })),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
{
|
||||
capacity: PR_LOOKUP_CACHE_CAPACITY,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? PR_LOOKUP_CACHE_TTL : PR_LOOKUP_FAILURE_TTL),
|
||||
},
|
||||
);
|
||||
// A transient lookup failure (rate limit, network blip) must not clear an
|
||||
// already-known PR badge, so the last successful answer per branch sticks
|
||||
// around as the fallback. Keep the resolved head context with it so a
|
||||
// branch retargeted to another remote/fork cannot inherit the old badge.
|
||||
interface LastKnownPr {
|
||||
readonly pr: ReturnType<typeof toStatusPr> | null;
|
||||
readonly upstreamRef: string | null;
|
||||
readonly headBranch: string;
|
||||
readonly remoteName: string | null;
|
||||
readonly headRemoteUrlKey: string | null;
|
||||
}
|
||||
const lastKnownPrByBranchKey = new Map<string, LastKnownPr>();
|
||||
const rememberLastKnownPr = (branchKey: string, entry: LastKnownPr) => {
|
||||
if (
|
||||
!lastKnownPrByBranchKey.has(branchKey) &&
|
||||
lastKnownPrByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY
|
||||
) {
|
||||
const oldestKey = lastKnownPrByBranchKey.keys().next().value;
|
||||
if (oldestKey !== undefined) {
|
||||
lastKnownPrByBranchKey.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
lastKnownPrByBranchKey.set(branchKey, entry);
|
||||
};
|
||||
const resolveLastKnownPr = (
|
||||
branchKey: string,
|
||||
current: Pick<LastKnownPr, "upstreamRef" | "headBranch" | "remoteName" | "headRemoteUrlKey">,
|
||||
): ReturnType<typeof toStatusPr> | null => {
|
||||
const lastKnown = lastKnownPrByBranchKey.get(branchKey);
|
||||
if (!lastKnown) return null;
|
||||
if (lastKnown.headBranch !== current.headBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The normalized URL catches both remote-alias changes and an existing
|
||||
// alias being repointed. Both sides must be resolved before treating a
|
||||
// mismatch as real: `readConfigValueNullable` swallows any git-config
|
||||
// read failure into `null`, so a transient failure to resolve the
|
||||
// *current* remote URL must read as "unknown", not as "no remote" — the
|
||||
// latter would otherwise drop an already-known PR badge on every hiccup.
|
||||
if (lastKnown.headRemoteUrlKey !== null && current.headRemoteUrlKey !== null) {
|
||||
return lastKnown.headRemoteUrlKey === current.headRemoteUrlKey ? lastKnown.pr : null;
|
||||
}
|
||||
|
||||
// If the remote URL can't be compared, fall back to the remote identity
|
||||
// encoded by tracked branches — same "both sides known" requirement, for
|
||||
// the same reason. A null-to-non-null transition (upstream/remoteName)
|
||||
// is allowed because that is the expected first-push case.
|
||||
if (
|
||||
lastKnown.upstreamRef !== null &&
|
||||
current.upstreamRef !== null &&
|
||||
lastKnown.remoteName !== null &&
|
||||
current.remoteName !== null
|
||||
) {
|
||||
return lastKnown.remoteName === current.remoteName ? lastKnown.pr : null;
|
||||
}
|
||||
return lastKnown.pr;
|
||||
};
|
||||
const lookupStatusPr = Effect.fn("lookupStatusPr")(function* (
|
||||
cwd: string,
|
||||
details: { branch: string; upstreamRef: string | null; isDefaultBranch: boolean },
|
||||
) {
|
||||
// Keyed by (cwd, branch) only: the upstream ref changing (e.g. a first
|
||||
// `push -u`) must not orphan the fallback value for the same branch.
|
||||
const branchKey = `${cwd}\u0000${details.branch}`;
|
||||
return yield* Cache.get(prLookupCache, prLookupCacheKey(cwd, details)).pipe(
|
||||
Effect.map(({ latest, headContext }) => {
|
||||
if (!latest) return { pr: null, headContext };
|
||||
// On the default branch, only surface open PRs.
|
||||
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
|
||||
if (details.isDefaultBranch && latest.state !== "open") {
|
||||
return { pr: null, headContext };
|
||||
}
|
||||
return { pr: toStatusPr(latest), headContext };
|
||||
}),
|
||||
Effect.tap(({ pr, headContext }) =>
|
||||
Effect.sync(() =>
|
||||
rememberLastKnownPr(branchKey, {
|
||||
pr,
|
||||
upstreamRef: details.upstreamRef,
|
||||
headBranch: headContext.headBranch,
|
||||
remoteName: headContext.remoteName,
|
||||
headRemoteUrlKey: headContext.headRemoteUrlKey,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map(({ pr }) => pr),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("PR lookup failed; keeping last known PR state.").pipe(
|
||||
Effect.annotateLogs({
|
||||
operation: "lookupStatusPr",
|
||||
branch: details.branch,
|
||||
errorTag:
|
||||
typeof error === "object" && error !== null && "_tag" in error
|
||||
? String(error._tag)
|
||||
: typeof error,
|
||||
}),
|
||||
Effect.andThen(resolveBranchHeadContext(cwd, details)),
|
||||
Effect.map((headContext) =>
|
||||
resolveLastKnownPr(branchKey, {
|
||||
upstreamRef: details.upstreamRef,
|
||||
headBranch: headContext.headBranch,
|
||||
remoteName: headContext.remoteName,
|
||||
headRemoteUrlKey: headContext.headRemoteUrlKey,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (
|
||||
cwd: string,
|
||||
options?: GitVcsDriver.GitRemoteStatusOptions,
|
||||
@@ -781,19 +972,11 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(cwd, {
|
||||
? yield* lookupStatusPr(cwd, {
|
||||
branch: details.branch,
|
||||
upstreamRef: details.upstreamRef,
|
||||
}).pipe(
|
||||
Effect.map((latest) => {
|
||||
if (!latest) return null;
|
||||
// On the default branch, only surface open PRs.
|
||||
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
|
||||
if (details.isDefaultBranch && latest.state !== "open") return null;
|
||||
return toStatusPr(latest);
|
||||
}),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
isDefaultBranch: details.isDefaultBranch,
|
||||
})
|
||||
: null;
|
||||
|
||||
return {
|
||||
@@ -837,6 +1020,7 @@ export const make = Effect.gen(function* () {
|
||||
) {
|
||||
if (!remoteName) {
|
||||
return {
|
||||
remoteUrlKey: null,
|
||||
repositoryNameWithOwner: null,
|
||||
ownerLogin: null,
|
||||
};
|
||||
@@ -845,6 +1029,7 @@ export const make = Effect.gen(function* () {
|
||||
const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
|
||||
const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
|
||||
return {
|
||||
remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
|
||||
repositoryNameWithOwner,
|
||||
ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
|
||||
};
|
||||
@@ -915,6 +1100,9 @@ export const make = Effect.gen(function* () {
|
||||
preferredHeadSelector:
|
||||
ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
|
||||
remoteName,
|
||||
headRemoteUrlKey:
|
||||
remoteRepository.remoteUrlKey ??
|
||||
(remoteName === null ? originRepository.remoteUrlKey : null),
|
||||
headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
|
||||
headRepositoryOwnerLogin: remoteRepository.ownerLogin,
|
||||
isCrossRepository,
|
||||
@@ -960,11 +1148,10 @@ export const make = Effect.gen(function* () {
|
||||
return null;
|
||||
});
|
||||
|
||||
const findLatestPr = Effect.fn("findLatestPr")(function* (
|
||||
const findLatestPrForHeadContext = Effect.fn("findLatestPrForHeadContext")(function* (
|
||||
cwd: string,
|
||||
details: { branch: string; upstreamRef: string | null },
|
||||
headContext: BranchHeadContext,
|
||||
) {
|
||||
const headContext = yield* resolveBranchHeadContext(cwd, details);
|
||||
const parsedByNumber = new Map<number, PullRequestInfo>();
|
||||
|
||||
for (const headSelector of headContext.headSelectors) {
|
||||
@@ -991,7 +1178,6 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
return parsed[0] ?? null;
|
||||
});
|
||||
|
||||
const buildCompletionToast = Effect.fn("buildCompletionToast")(function* (
|
||||
cwd: string,
|
||||
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
|
||||
@@ -1442,6 +1628,10 @@ export const make = Effect.gen(function* () {
|
||||
function* (cwd) {
|
||||
yield* invalidateLocalStatusResultCache(cwd);
|
||||
yield* invalidateRemoteStatusResultCache(cwd);
|
||||
// Full invalidation is the explicit-freshness path (git actions, user
|
||||
// refresh); it also bypasses the slow PR-lookup cache. The periodic
|
||||
// status poll only invalidates local/remote and keeps the PR cache warm.
|
||||
yield* bumpPrLookupEpoch(cwd);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
+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,
|
||||
|
||||
@@ -146,6 +146,8 @@ describe("OrchestrationEngine", () => {
|
||||
createdAt: "2026-03-03T00:00:02.000Z",
|
||||
updatedAt: "2026-03-03T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -171,6 +171,70 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
for (const row of stateRows) {
|
||||
assert.equal(row.lastAppliedSequence, 3);
|
||||
}
|
||||
|
||||
// Settled lifecycle through the DB pipeline: thread.settled writes the
|
||||
// override + timestamp, thread.unsettled(user) flips to the active pin.
|
||||
yield* eventStore.append({
|
||||
type: "thread.settled",
|
||||
eventId: EventId.make("evt-settle-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
occurredAt: "2026-01-01T00:00:01.000Z",
|
||||
commandId: CommandId.make("cmd-settle-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-settle-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
settledAt: "2026-01-01T00:00:01.000Z",
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
},
|
||||
});
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const settledRows = yield* sql<{
|
||||
readonly settledOverride: string | null;
|
||||
readonly settledAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-1'
|
||||
`;
|
||||
assert.deepEqual(settledRows, [
|
||||
{ settledOverride: "settled", settledAt: "2026-01-01T00:00:01.000Z" },
|
||||
]);
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.unsettled",
|
||||
eventId: EventId.make("evt-unsettle-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
occurredAt: "2026-01-01T00:00:02.000Z",
|
||||
commandId: CommandId.make("cmd-unsettle-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-unsettle-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
updatedAt: "2026-01-01T00:00:02.000Z",
|
||||
},
|
||||
});
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const unsettledRows = yield* sql<{
|
||||
readonly settledOverride: string | null;
|
||||
readonly settledAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-1'
|
||||
`;
|
||||
assert.deepEqual(unsettledRows, [{ settledOverride: "active", settledAt: null }]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2400,6 +2464,74 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(makeProjectionPipelinePrefixedTestLayer("t3-pending-turn-terminal-test-"))(
|
||||
"OrchestrationProjectionPipeline pending turn cleanup",
|
||||
(it) => {
|
||||
it.effect("clears pending turn starts when startup reaches a terminal session state", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
for (const [index, status] of (["error", "interrupted", "stopped"] as const).entries()) {
|
||||
const threadId = ThreadId.make(`thread-terminal-${status}`);
|
||||
const requestedAt = `2026-02-26T14:00:0${index}.000Z`;
|
||||
yield* eventStore.append({
|
||||
type: "thread.turn-start-requested",
|
||||
eventId: EventId.make(`evt-terminal-pending-${status}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: requestedAt,
|
||||
commandId: CommandId.make(`cmd-terminal-pending-${status}`),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make(`cmd-terminal-pending-${status}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make(`message-terminal-${status}`),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: requestedAt,
|
||||
},
|
||||
});
|
||||
yield* eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make(`evt-terminal-session-${status}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: requestedAt,
|
||||
commandId: CommandId.make(`cmd-terminal-session-${status}`),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make(`cmd-terminal-session-${status}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status,
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: status === "error" ? "startup failed" : null,
|
||||
updatedAt: requestedAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const pendingRows = yield* sql<{ readonly threadId: string }>`
|
||||
SELECT thread_id AS "threadId"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NULL
|
||||
AND state = 'pending'
|
||||
`;
|
||||
assert.deepEqual(pendingRows, []);
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("restores pending turn-start metadata across projection pipeline restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dbPath } = yield* ServerConfig;
|
||||
|
||||
@@ -18,7 +18,6 @@ import { OrchestrationEventStore } from "../../persistence/Services/Orchestratio
|
||||
import { ProjectionPendingApprovalRepository } from "../../persistence/Services/ProjectionPendingApprovals.ts";
|
||||
import { ProjectionProjectRepository } from "../../persistence/Services/ProjectionProjects.ts";
|
||||
import { ProjectionStateRepository } from "../../persistence/Services/ProjectionState.ts";
|
||||
import { ProjectionUsageRepository } from "../../persistence/Services/ProjectionUsage.ts";
|
||||
import { ProjectionThreadActivityRepository } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import { type ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import {
|
||||
@@ -38,7 +37,6 @@ import { ProjectionThreadRepository } from "../../persistence/Services/Projectio
|
||||
import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts";
|
||||
import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts";
|
||||
import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts";
|
||||
import { ProjectionUsageRepositoryLive } from "../../persistence/Layers/ProjectionUsage.ts";
|
||||
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
|
||||
@@ -67,7 +65,6 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
threadTurns: "projection.thread-turns",
|
||||
checkpoints: "projection.checkpoints",
|
||||
pendingApprovals: "projection.pending-approvals",
|
||||
usage: "projection.usage",
|
||||
} as const;
|
||||
|
||||
type ProjectorName =
|
||||
@@ -483,7 +480,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||
const projectionUsageRepository = yield* ProjectionUsageRepository;
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -611,6 +607,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -649,6 +649,70 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.settled": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
settledOverride: "settled",
|
||||
settledAt: event.payload.settledAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unsettled": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
settledOverride: event.payload.reason === "user" ? "active" : null,
|
||||
settledAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
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,
|
||||
@@ -1011,51 +1075,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
});
|
||||
});
|
||||
|
||||
const applyUsageProjection: ProjectorDefinition["apply"] = Effect.fn("applyUsageProjection")(
|
||||
function* (event, _attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.usage-recorded":
|
||||
yield* Effect.forEach(
|
||||
event.payload.facts,
|
||||
(fact) =>
|
||||
projectionUsageRepository.upsertFact({
|
||||
factId: fact.factId,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
projectId: event.payload.projectId,
|
||||
provider: fact.provider,
|
||||
providerInstanceId: fact.providerInstanceId ?? null,
|
||||
providerSessionId: fact.providerSessionId,
|
||||
model: fact.model,
|
||||
modelRaw: fact.modelRaw,
|
||||
reasoningEffort: fact.reasoningEffort ?? null,
|
||||
kind: fact.kind,
|
||||
inputTokens: fact.tokens.inputTokens,
|
||||
cachedInputTokens: fact.tokens.cachedInputTokens,
|
||||
cacheCreationTokens: fact.tokens.cacheCreationTokens,
|
||||
outputTokens: fact.tokens.outputTokens,
|
||||
reasoningOutputTokens: fact.tokens.reasoningOutputTokens,
|
||||
costMicroUsd: fact.costMicroUsd ?? null,
|
||||
stale: fact.stale ?? false,
|
||||
observedAt: fact.observedAt,
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
return;
|
||||
|
||||
case "thread.deleted":
|
||||
yield* projectionUsageRepository.redactThread({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
return;
|
||||
|
||||
// No thread.reverted case: usage facts are immutable billing history and survive reverts.
|
||||
default:
|
||||
return;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadTurnsProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
@@ -1074,6 +1093,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
case "thread.session-set": {
|
||||
const turnId = event.payload.session.activeTurnId;
|
||||
if (turnId === null || event.payload.session.status !== "running") {
|
||||
if (
|
||||
event.payload.session.status === "error" ||
|
||||
event.payload.session.status === "stopped" ||
|
||||
event.payload.session.status === "interrupted"
|
||||
) {
|
||||
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
}
|
||||
// Leaving the "running" session status is the turn-end signal:
|
||||
// settle still-running turns so their duration reflects the whole
|
||||
// turn rather than the last assistant message.
|
||||
@@ -1529,10 +1557,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
apply: applyThreadSessionsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.usage,
|
||||
apply: applyUsageProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
|
||||
apply: applyThreadTurnsProjection,
|
||||
@@ -1649,7 +1673,6 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
|
||||
Layer.provideMerge(ProjectionUsageRepositoryLive),
|
||||
Layer.provideMerge(ProjectionTurnRepositoryLive),
|
||||
Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
|
||||
Layer.provideMerge(ProjectionStateRepositoryLive),
|
||||
|
||||
@@ -1,557 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type UsageFact,
|
||||
UsageFactId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
|
||||
import { ProjectionUsageRepository } from "../../persistence/Services/ProjectionUsage.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
|
||||
const BaseTestLayer = OrchestrationProjectionPipelineLive.pipe(
|
||||
Layer.provideMerge(OrchestrationEventStoreLive),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), { prefix: "t3-projection-pipeline-usage-test-" }),
|
||||
),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const threadId = ThreadId.make("thread-usage");
|
||||
const turnId = TurnId.make("turn-usage");
|
||||
const projectId = ProjectId.make("project-usage");
|
||||
const observedAt = IsoDateTime.make("2026-04-01T12:00:00.000Z");
|
||||
|
||||
function makeFact(factId: string, overrides: Partial<UsageFact> = {}): UsageFact {
|
||||
return {
|
||||
factId: UsageFactId.make(factId),
|
||||
kind: "final",
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
providerInstanceId: ProviderInstanceId.make("claude-primary"),
|
||||
providerSessionId: "session-claude-1",
|
||||
model: "claude-fable-5",
|
||||
modelRaw: "claude-fable-5[1m]",
|
||||
reasoningEffort: "high",
|
||||
tokens: {
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 1_000,
|
||||
cacheCreationTokens: 200,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 0,
|
||||
},
|
||||
costMicroUsd: 1_250_000,
|
||||
observedAt,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(BaseTestLayer)("usage projection", (it) => {
|
||||
it.effect("projects every usage fact with exact persisted values", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.usage-recorded",
|
||||
eventId: EventId.make("evt-usage-single"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: observedAt,
|
||||
commandId: CommandId.make("cmd-usage-single"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-usage-single"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId,
|
||||
projectId,
|
||||
facts: [
|
||||
makeFact("fact-final"),
|
||||
makeFact("fact-interval", {
|
||||
kind: "interval",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: undefined,
|
||||
providerSessionId: "session-codex-1",
|
||||
model: "gpt-5.6",
|
||||
modelRaw: "gpt-5.6",
|
||||
reasoningEffort: undefined,
|
||||
tokens: {
|
||||
inputTokens: 300,
|
||||
cachedInputTokens: 75,
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: 125,
|
||||
reasoningOutputTokens: 40,
|
||||
},
|
||||
costMicroUsd: undefined,
|
||||
observedAt: IsoDateTime.make("2026-04-01T12:00:01.000Z"),
|
||||
}),
|
||||
],
|
||||
recordedAt: IsoDateTime.make("2026-04-01T12:00:02.000Z"),
|
||||
},
|
||||
});
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly factId: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId: string | null;
|
||||
readonly projectId: string | null;
|
||||
readonly provider: string;
|
||||
readonly providerInstanceId: string | null;
|
||||
readonly providerSessionId: string;
|
||||
readonly model: string;
|
||||
readonly modelRaw: string;
|
||||
readonly reasoningEffort: string | null;
|
||||
readonly kind: string;
|
||||
readonly inputTokens: number;
|
||||
readonly cachedInputTokens: number;
|
||||
readonly cacheCreationTokens: number;
|
||||
readonly outputTokens: number;
|
||||
readonly reasoningOutputTokens: number;
|
||||
readonly costMicroUsd: number | null;
|
||||
readonly stale: number;
|
||||
readonly observedAt: string;
|
||||
}>`
|
||||
SELECT
|
||||
fact_id AS "factId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
project_id AS "projectId",
|
||||
provider,
|
||||
provider_instance_id AS "providerInstanceId",
|
||||
provider_session_id AS "providerSessionId",
|
||||
model,
|
||||
model_raw AS "modelRaw",
|
||||
reasoning_effort AS "reasoningEffort",
|
||||
kind,
|
||||
input_tokens AS "inputTokens",
|
||||
cached_input_tokens AS "cachedInputTokens",
|
||||
cache_creation_tokens AS "cacheCreationTokens",
|
||||
output_tokens AS "outputTokens",
|
||||
reasoning_output_tokens AS "reasoningOutputTokens",
|
||||
cost_micro_usd AS "costMicroUsd",
|
||||
stale,
|
||||
observed_at AS "observedAt"
|
||||
FROM projection_usage_facts
|
||||
ORDER BY fact_id ASC
|
||||
`;
|
||||
|
||||
assert.deepEqual(rows, [
|
||||
{
|
||||
factId: "fact-final",
|
||||
threadId: "thread-usage",
|
||||
turnId: "turn-usage",
|
||||
projectId: "project-usage",
|
||||
provider: "claudeAgent",
|
||||
providerInstanceId: "claude-primary",
|
||||
providerSessionId: "session-claude-1",
|
||||
model: "claude-fable-5",
|
||||
modelRaw: "claude-fable-5[1m]",
|
||||
reasoningEffort: "high",
|
||||
kind: "final",
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 1_000,
|
||||
cacheCreationTokens: 200,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 0,
|
||||
costMicroUsd: 1_250_000,
|
||||
stale: 0,
|
||||
observedAt: "2026-04-01T12:00:00.000Z",
|
||||
},
|
||||
{
|
||||
factId: "fact-interval",
|
||||
threadId: "thread-usage",
|
||||
turnId: "turn-usage",
|
||||
projectId: "project-usage",
|
||||
provider: "codex",
|
||||
providerInstanceId: null,
|
||||
providerSessionId: "session-codex-1",
|
||||
model: "gpt-5.6",
|
||||
modelRaw: "gpt-5.6",
|
||||
reasoningEffort: null,
|
||||
kind: "interval",
|
||||
inputTokens: 300,
|
||||
cachedInputTokens: 75,
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: 125,
|
||||
reasoningOutputTokens: 40,
|
||||
costMicroUsd: null,
|
||||
stale: 0,
|
||||
observedAt: "2026-04-01T12:00:01.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("upserts repeated facts by fact id", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
const facts = [makeFact("fact-replay-1"), makeFact("fact-replay-2", { kind: "interval" })];
|
||||
|
||||
for (const suffix of ["one", "two"] as const) {
|
||||
yield* appendAndProject({
|
||||
type: "thread.usage-recorded",
|
||||
eventId: EventId.make(`evt-usage-replay-${suffix}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: observedAt,
|
||||
commandId: CommandId.make(`cmd-usage-replay-${suffix}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make(`cmd-usage-replay-${suffix}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId,
|
||||
projectId,
|
||||
facts,
|
||||
recordedAt: observedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const rows = yield* sql<{ readonly factId: string }>`
|
||||
SELECT fact_id AS "factId"
|
||||
FROM projection_usage_facts
|
||||
WHERE fact_id IN ('fact-replay-1', 'fact-replay-2')
|
||||
ORDER BY fact_id ASC
|
||||
`;
|
||||
assert.deepEqual(rows, [{ factId: "fact-replay-1" }, { factId: "fact-replay-2" }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains usage facts after a thread revert", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.usage-recorded",
|
||||
eventId: EventId.make("evt-usage-before-revert"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: observedAt,
|
||||
commandId: CommandId.make("cmd-usage-before-revert"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-usage-before-revert"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId,
|
||||
projectId,
|
||||
facts: [makeFact("fact-retained")],
|
||||
recordedAt: observedAt,
|
||||
},
|
||||
});
|
||||
|
||||
const before = yield* sql<{
|
||||
readonly factId: string;
|
||||
readonly threadId: string;
|
||||
readonly projectId: string | null;
|
||||
readonly outputTokens: number;
|
||||
readonly costMicroUsd: number | null;
|
||||
}>`
|
||||
SELECT
|
||||
fact_id AS "factId",
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
output_tokens AS "outputTokens",
|
||||
cost_micro_usd AS "costMicroUsd"
|
||||
FROM projection_usage_facts
|
||||
WHERE fact_id = 'fact-retained'
|
||||
`;
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.reverted",
|
||||
eventId: EventId.make("evt-usage-reverted"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: IsoDateTime.make("2026-04-01T12:01:00.000Z"),
|
||||
commandId: CommandId.make("cmd-usage-reverted"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-usage-reverted"),
|
||||
metadata: {},
|
||||
payload: { threadId, turnCount: 0 },
|
||||
});
|
||||
|
||||
const after = yield* sql<{
|
||||
readonly factId: string;
|
||||
readonly threadId: string;
|
||||
readonly projectId: string | null;
|
||||
readonly outputTokens: number;
|
||||
readonly costMicroUsd: number | null;
|
||||
}>`
|
||||
SELECT
|
||||
fact_id AS "factId",
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
output_tokens AS "outputTokens",
|
||||
cost_micro_usd AS "costMicroUsd"
|
||||
FROM projection_usage_facts
|
||||
WHERE fact_id = 'fact-retained'
|
||||
`;
|
||||
|
||||
assert.deepEqual(after, before);
|
||||
assert.deepEqual(after, [
|
||||
{
|
||||
factId: "fact-retained",
|
||||
threadId: "thread-usage",
|
||||
projectId: "project-usage",
|
||||
outputTokens: 50,
|
||||
costMicroUsd: 1_250_000,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("redacts thread and project attribution after thread deletion", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.usage-recorded",
|
||||
eventId: EventId.make("evt-usage-before-delete"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: observedAt,
|
||||
commandId: CommandId.make("cmd-usage-before-delete"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-usage-before-delete"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId,
|
||||
projectId,
|
||||
facts: [makeFact("fact-redacted-1"), makeFact("fact-redacted-2")],
|
||||
recordedAt: observedAt,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.deleted",
|
||||
eventId: EventId.make("evt-usage-deleted"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: IsoDateTime.make("2026-04-01T12:01:00.000Z"),
|
||||
commandId: CommandId.make("cmd-usage-deleted"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-usage-deleted"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
deletedAt: IsoDateTime.make("2026-04-01T12:01:00.000Z"),
|
||||
},
|
||||
});
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly factId: string;
|
||||
readonly threadId: string;
|
||||
readonly projectId: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
fact_id AS "factId",
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId"
|
||||
FROM projection_usage_facts
|
||||
WHERE fact_id IN ('fact-redacted-1', 'fact-redacted-2')
|
||||
ORDER BY fact_id ASC
|
||||
`;
|
||||
assert.deepEqual(rows, [
|
||||
{ factId: "fact-redacted-1", threadId: "deleted", projectId: null },
|
||||
{ factId: "fact-redacted-2", threadId: "deleted", projectId: null },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("persists the stale flag", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.usage-recorded",
|
||||
eventId: EventId.make("evt-usage-stale"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: observedAt,
|
||||
commandId: CommandId.make("cmd-usage-stale"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-usage-stale"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId,
|
||||
projectId: null,
|
||||
facts: [makeFact("fact-stale", { stale: true })],
|
||||
recordedAt: observedAt,
|
||||
},
|
||||
});
|
||||
|
||||
const rows = yield* sql<{ readonly factId: string; readonly stale: number }>`
|
||||
SELECT fact_id AS "factId", stale
|
||||
FROM projection_usage_facts
|
||||
WHERE fact_id = 'fact-stale'
|
||||
`;
|
||||
assert.deepEqual(rows, [{ factId: "fact-stale", stale: 1 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("sums final and interval facts by session and model", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const usageRepository = yield* ProjectionUsageRepository;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.usage-recorded",
|
||||
eventId: EventId.make("evt-usage-sums"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: observedAt,
|
||||
commandId: CommandId.make("cmd-usage-sums"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-usage-sums"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId,
|
||||
projectId,
|
||||
facts: [
|
||||
makeFact("fact-sum-fable-final", {
|
||||
providerSessionId: "session-target",
|
||||
tokens: {
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 10,
|
||||
cacheCreationTokens: 5,
|
||||
outputTokens: 20,
|
||||
reasoningOutputTokens: 2,
|
||||
},
|
||||
costMicroUsd: 1_000,
|
||||
}),
|
||||
makeFact("fact-sum-fable-interval", {
|
||||
kind: "interval",
|
||||
providerSessionId: "session-target",
|
||||
tokens: {
|
||||
inputTokens: 50,
|
||||
cachedInputTokens: 5,
|
||||
cacheCreationTokens: 3,
|
||||
outputTokens: 10,
|
||||
reasoningOutputTokens: 1,
|
||||
},
|
||||
costMicroUsd: 500,
|
||||
}),
|
||||
makeFact("fact-sum-opus", {
|
||||
providerSessionId: "session-target",
|
||||
model: "claude-opus-4-8",
|
||||
modelRaw: "claude-opus-4-8",
|
||||
tokens: {
|
||||
inputTokens: 200,
|
||||
cachedInputTokens: 20,
|
||||
cacheCreationTokens: 8,
|
||||
outputTokens: 40,
|
||||
reasoningOutputTokens: 4,
|
||||
},
|
||||
costMicroUsd: 2_000,
|
||||
}),
|
||||
makeFact("fact-sum-turn-total", {
|
||||
kind: "turn-total",
|
||||
providerSessionId: "session-target",
|
||||
tokens: {
|
||||
inputTokens: 9_999,
|
||||
cachedInputTokens: 9_999,
|
||||
cacheCreationTokens: 9_999,
|
||||
outputTokens: 9_999,
|
||||
reasoningOutputTokens: 9_999,
|
||||
},
|
||||
costMicroUsd: 9_999,
|
||||
}),
|
||||
makeFact("fact-sum-other-session", {
|
||||
providerSessionId: "session-other",
|
||||
tokens: {
|
||||
inputTokens: 8_888,
|
||||
cachedInputTokens: 8_888,
|
||||
cacheCreationTokens: 8_888,
|
||||
outputTokens: 8_888,
|
||||
reasoningOutputTokens: 8_888,
|
||||
},
|
||||
costMicroUsd: 8_888,
|
||||
}),
|
||||
],
|
||||
recordedAt: observedAt,
|
||||
},
|
||||
});
|
||||
|
||||
const sums = yield* usageRepository.sumBySessionModel({
|
||||
providerSessionId: "session-target",
|
||||
});
|
||||
assert.deepEqual(
|
||||
[...sums].toSorted((left, right) => left.model.localeCompare(right.model)),
|
||||
[
|
||||
{
|
||||
model: "claude-fable-5",
|
||||
inputTokens: 150,
|
||||
cachedInputTokens: 15,
|
||||
cacheCreationTokens: 8,
|
||||
outputTokens: 30,
|
||||
reasoningOutputTokens: 3,
|
||||
costMicroUsd: 1_500,
|
||||
},
|
||||
{
|
||||
model: "claude-opus-4-8",
|
||||
inputTokens: 200,
|
||||
cachedInputTokens: 20,
|
||||
cacheCreationTokens: 8,
|
||||
outputTokens: 40,
|
||||
reasoningOutputTokens: 4,
|
||||
costMicroUsd: 2_000,
|
||||
},
|
||||
],
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -308,6 +308,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -418,6 +422,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
@@ -562,6 +570,115 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps settled threads in the shell snapshot with non-null settlement fields", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-settled-test',
|
||||
'Settled Test',
|
||||
'/tmp/settled-test',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-06T00:00:00.000Z',
|
||||
'2026-04-06T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-settled',
|
||||
'project-settled-test',
|
||||
'Settled Thread',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-06T00:00:02.000Z',
|
||||
'2026-04-06T00:00:05.000Z',
|
||||
NULL,
|
||||
'settled',
|
||||
'2026-04-06T00:00:04.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
|
||||
VALUES
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 4, '2026-04-06T00:00:07.000Z')
|
||||
`;
|
||||
|
||||
// Settled ≠ archived: the thread must appear in the LIVE shell
|
||||
// snapshot, carrying its settlement fields through the row aliases.
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.deepEqual(
|
||||
shellSnapshot.threads.map((thread) => thread.id),
|
||||
[ThreadId.make("thread-settled")],
|
||||
);
|
||||
assert.equal(shellSnapshot.threads[0]?.settledOverride, "settled");
|
||||
assert.equal(shellSnapshot.threads[0]?.settledAt, "2026-04-06T00:00:04.000Z");
|
||||
|
||||
// And the full command read model carries them too.
|
||||
const readModel = yield* snapshotQuery.getCommandReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(candidate) => candidate.id === ThreadId.make("thread-settled"),
|
||||
);
|
||||
assert.equal(thread?.settledOverride, "settled");
|
||||
assert.equal(thread?.settledAt, "2026-04-06T00:00:04.000Z");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"reads targeted project, thread, and count queries without hydrating the full snapshot",
|
||||
() =>
|
||||
|
||||
@@ -334,6 +334,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -362,6 +366,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -392,6 +400,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -754,6 +766,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -1186,6 +1202,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
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) ?? [],
|
||||
@@ -1384,6 +1404,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1513,6 +1537,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
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,
|
||||
@@ -1647,6 +1675,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
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,
|
||||
@@ -1887,6 +1919,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
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,
|
||||
@@ -1981,6 +2017,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
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 = {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
@@ -145,6 +146,9 @@ describe("ProviderCommandReactor", () => {
|
||||
readonly threadModelSelection?: ModelSelection;
|
||||
readonly sessionModelSwitch?: "unsupported" | "in-session";
|
||||
readonly requiresNewThreadForModelChange?: boolean;
|
||||
readonly startSessionEffect?: (
|
||||
session: ProviderSession,
|
||||
) => Effect.Effect<ProviderSession, ProviderAdapterRequestError>;
|
||||
}) {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const baseDir =
|
||||
@@ -159,6 +163,7 @@ describe("ProviderCommandReactor", () => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
const startSessionEffect = input?.startSessionEffect;
|
||||
const startSession = vi.fn((_: unknown, input: unknown) => {
|
||||
const sessionIndex = nextSessionIndex++;
|
||||
const resumeCursor =
|
||||
@@ -212,8 +217,13 @@ describe("ProviderCommandReactor", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
runtimeSessions.push(session);
|
||||
return Effect.succeed(session);
|
||||
return (startSessionEffect?.(session) ?? Effect.succeed(session)).pipe(
|
||||
Effect.tap((startedSession) =>
|
||||
Effect.sync(() => {
|
||||
runtimeSessions.push(startedSession);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
const sendTurn = vi.fn((_: unknown) =>
|
||||
Effect.succeed({
|
||||
@@ -463,9 +473,120 @@ describe("ProviderCommandReactor", () => {
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.status).toBe("starting");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
effectIt.effect("projects starting before a slow provider session finishes", () =>
|
||||
Effect.gen(function* () {
|
||||
const releaseStart = yield* Deferred.make<void>();
|
||||
const harness = yield* Effect.promise(() =>
|
||||
createHarness({
|
||||
startSessionEffect: (session) => Deferred.await(releaseStart).pipe(Effect.as(session)),
|
||||
}),
|
||||
);
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-slow-provider"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-slow-provider"),
|
||||
role: "user",
|
||||
text: "start slowly",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => waitFor(() => harness.startSession.mock.calls.length === 1));
|
||||
const duringStartup = yield* Effect.promise(() => harness.readModel());
|
||||
expect(
|
||||
duringStartup.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session
|
||||
?.status,
|
||||
).toBe("starting");
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
yield* Deferred.succeed(releaseStart, undefined);
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("settles a failed provider startup and allows a clean retry", () =>
|
||||
Effect.gen(function* () {
|
||||
let failStartup = true;
|
||||
const harness = yield* Effect.promise(() =>
|
||||
createHarness({
|
||||
startSessionEffect: (session) =>
|
||||
failStartup
|
||||
? Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "codex",
|
||||
method: "thread.start",
|
||||
detail: "deterministic startup failure",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(session),
|
||||
}),
|
||||
);
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-provider-failure"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-failure"),
|
||||
role: "user",
|
||||
text: "fail once",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() =>
|
||||
waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session
|
||||
?.status === "error"
|
||||
);
|
||||
}),
|
||||
);
|
||||
let readModel = yield* Effect.promise(() => harness.readModel());
|
||||
let thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.lastError).toContain("deterministic startup failure");
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
failStartup = false;
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-provider-retry"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-retry"),
|
||||
role: "user",
|
||||
text: "retry",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
readModel = yield* Effect.promise(() => harness.readModel());
|
||||
thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.status).toBe("starting");
|
||||
expect(thread?.session?.lastError).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it("generates a thread title on the first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -288,15 +288,20 @@ const make = Effect.gen(function* () {
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
const session = thread?.session;
|
||||
if (!session) {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const session = thread.session;
|
||||
yield* setThreadSession({
|
||||
threadId: input.threadId,
|
||||
session: {
|
||||
...session,
|
||||
status: session.status === "stopped" ? "stopped" : "ready",
|
||||
...(session ?? {
|
||||
threadId: input.threadId,
|
||||
providerName: null,
|
||||
providerInstanceId: thread.modelSelection.instanceId,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
}),
|
||||
status: session?.status === "stopped" ? "stopped" : "error",
|
||||
activeTurnId: null,
|
||||
lastError: input.detail,
|
||||
updatedAt: input.createdAt,
|
||||
@@ -354,6 +359,7 @@ const make = Effect.gen(function* () {
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly pendingTurnStart?: boolean;
|
||||
},
|
||||
) {
|
||||
const thread = yield* resolveThread(threadId);
|
||||
@@ -428,6 +434,22 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderDriverKind = desiredDriverKind;
|
||||
if (options?.pendingTurnStart === true && thread.session?.status !== "running") {
|
||||
yield* setThreadSession({
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "starting",
|
||||
providerName: activeSession?.provider ?? preferredProvider,
|
||||
providerInstanceId: activeSession?.providerInstanceId ?? desiredInstanceId,
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
}
|
||||
if (thread.session !== null) {
|
||||
yield* rejectStartedThreadModelChangeIfRequired({
|
||||
threadId,
|
||||
@@ -498,7 +520,10 @@ const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
||||
status:
|
||||
options?.pendingTurnStart === true && session.status === "ready"
|
||||
? "starting"
|
||||
: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
||||
providerName: session.provider,
|
||||
providerInstanceId: session.providerInstanceId,
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
@@ -597,11 +622,10 @@ const make = Effect.gen(function* () {
|
||||
new Error(`Thread '${input.threadId}' was not found in read model.`),
|
||||
);
|
||||
}
|
||||
yield* ensureSessionForThread(
|
||||
input.threadId,
|
||||
input.createdAt,
|
||||
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
|
||||
);
|
||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
pendingTurnStart: true,
|
||||
});
|
||||
if (input.modelSelection !== undefined) {
|
||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
@@ -493,6 +494,185 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(thread.session?.lastError).toBeNull();
|
||||
});
|
||||
|
||||
effectIt.effect(
|
||||
"keeps a reconnecting pending turn starting while ready clears stale active state",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() => createHarness());
|
||||
const threadId = asThreadId("thread-1");
|
||||
const staleTurnId = asTurnId("turn-stale-before-reconnect");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-pending-reconnect"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-pending-reconnect"),
|
||||
role: "user",
|
||||
text: "resume after reconnect",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-starting-pending-reconnect"),
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "starting",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: staleTurnId,
|
||||
lastError: null,
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "session.state.changed",
|
||||
eventId: asEventId("evt-session-ready-pending-reconnect"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
payload: { state: "ready" },
|
||||
});
|
||||
|
||||
let thread = yield* Effect.promise(() =>
|
||||
waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.session?.status === "starting" && entry.session.activeTurnId === null,
|
||||
),
|
||||
);
|
||||
expect(thread.session?.status).toBe("starting");
|
||||
expect(thread.session?.activeTurnId).toBeNull();
|
||||
|
||||
harness.emit({
|
||||
type: "session.started",
|
||||
eventId: asEventId("evt-session-started-pending-reconnect"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
});
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
thread = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
)!;
|
||||
expect(thread.session?.status).toBe("starting");
|
||||
expect(thread.session?.activeTurnId).toBeNull();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-pending-reconnect"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
turnId: asTurnId("turn-after-reconnect"),
|
||||
createdAt: "2026-01-01T00:00:04.000Z",
|
||||
});
|
||||
thread = yield* Effect.promise(() =>
|
||||
waitForThread(
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "running" &&
|
||||
entry.session.activeTurnId === asTurnId("turn-after-reconnect"),
|
||||
),
|
||||
);
|
||||
expect(thread.session?.status).toBe("running");
|
||||
|
||||
harness.emit({
|
||||
type: "session.started",
|
||||
eventId: asEventId("evt-session-started-duplicate-midturn"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:05.000Z",
|
||||
});
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
thread = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
)!;
|
||||
expect(thread.session?.status).toBe("running");
|
||||
expect(thread.session?.activeTurnId).toBe(asTurnId("turn-after-reconnect"));
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps an aborted pending start stopped across duplicate exit events", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() => createHarness());
|
||||
const threadId = asThreadId("thread-1");
|
||||
const stoppedAt = "2026-01-01T00:00:02.000Z";
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-before-stop"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-before-stop"),
|
||||
role: "user",
|
||||
text: "stop this startup",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-starting-before-stop"),
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "starting",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-stop-pending-start"),
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "stopped",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: stoppedAt,
|
||||
},
|
||||
createdAt: stoppedAt,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "session.exited",
|
||||
eventId: asEventId("evt-session-exited-after-stop"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
});
|
||||
harness.emit({
|
||||
type: "session.exited",
|
||||
eventId: asEventId("evt-duplicate-session-exited-after-stop"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:04.000Z",
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
const thread = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
);
|
||||
expect(thread?.session?.status).toBe("stopped");
|
||||
expect(thread?.session?.activeTurnId).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it("does not clear active turn when session/thread started arrives mid-turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -3,9 +3,6 @@ import {
|
||||
type AssistantDeliveryMode,
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationThreadShell,
|
||||
type UsageFact,
|
||||
UsageFactId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProposedPlanId,
|
||||
@@ -33,17 +30,6 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionUsageRepository } from "../../persistence/Services/ProjectionUsage.ts";
|
||||
import { ProjectionUsageRepositoryLive } from "../../persistence/Layers/ProjectionUsage.ts";
|
||||
import {
|
||||
ZERO_USAGE_COUNTERS,
|
||||
type UsageCumulativeCounters,
|
||||
canonicalModelId,
|
||||
claudeCumulativeByModel,
|
||||
codexCumulativeFromSnapshot,
|
||||
isZeroUsage,
|
||||
usageDelta,
|
||||
} from "../usageAccounting.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
@@ -711,7 +697,6 @@ const make = Effect.gen(function* () {
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
|
||||
);
|
||||
const projectionUsageRepository = yield* ProjectionUsageRepository;
|
||||
|
||||
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
|
||||
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
||||
@@ -1305,194 +1290,6 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Usage accounting: converts provider-cumulative counters into interval
|
||||
// usage facts dispatched as thread.usage.record commands. Baselines are
|
||||
// keyed by provider-native session id + model; on first sight of a session
|
||||
// they are reseeded from projection_usage_facts sums so a server restart
|
||||
// between samples never double counts.
|
||||
// ---------------------------------------------------------------------
|
||||
const usageBaselines = new Map<string, UsageCumulativeCounters>();
|
||||
const seededUsageSessions = new Set<string>();
|
||||
const usageBaselineKey = (providerSessionId: string, model: string) =>
|
||||
`${providerSessionId}|${model}`;
|
||||
|
||||
const seedUsageBaselines = Effect.fn("seedUsageBaselines")(function* (providerSessionId: string) {
|
||||
if (seededUsageSessions.has(providerSessionId)) {
|
||||
return;
|
||||
}
|
||||
seededUsageSessions.add(providerSessionId);
|
||||
const sums = yield* projectionUsageRepository.sumBySessionModel({ providerSessionId });
|
||||
for (const sum of sums) {
|
||||
const key = usageBaselineKey(providerSessionId, sum.model);
|
||||
if (!usageBaselines.has(key)) {
|
||||
usageBaselines.set(key, {
|
||||
inputTokens: sum.inputTokens,
|
||||
cachedInputTokens: sum.cachedInputTokens,
|
||||
cacheCreationTokens: sum.cacheCreationTokens,
|
||||
outputTokens: sum.outputTokens,
|
||||
reasoningOutputTokens: sum.reasoningOutputTokens,
|
||||
costMicroUsd: sum.costMicroUsd,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const reasoningEffortFromThread = (thread: OrchestrationThreadShell): string | undefined => {
|
||||
const options = thread.modelSelection.options;
|
||||
if (!options) return undefined;
|
||||
for (const option of options) {
|
||||
if (option.id === "reasoningEffort" && typeof option.value === "string") {
|
||||
return option.value;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const dispatchUsageFacts = (input: {
|
||||
readonly event: ProviderRuntimeEvent;
|
||||
readonly threadId: ThreadId;
|
||||
readonly projectId: OrchestrationThreadShell["projectId"] | null;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly facts: ReadonlyArray<UsageFact>;
|
||||
}) =>
|
||||
providerCommandId(input.event, "usage-record").pipe(
|
||||
Effect.flatMap((commandId) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.usage.record",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
projectId: input.projectId,
|
||||
facts: input.facts,
|
||||
createdAt: input.event.createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const recordUsageForRuntimeEvent = (
|
||||
event: ProviderRuntimeEvent,
|
||||
thread: OrchestrationThreadShell,
|
||||
options: { readonly staleCompletion: boolean },
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
// Codex path: cumulative totals ride every token-usage notification and
|
||||
// are attributed by the provider-native thread id. Snapshots without
|
||||
// native identity or cumulative fields are context-window telemetry
|
||||
// only and carry no accounting weight.
|
||||
if (event.type === "thread.token-usage.updated") {
|
||||
const cumulative = codexCumulativeFromSnapshot(event.payload.usage);
|
||||
const providerSessionId = event.providerRefs?.providerSessionId;
|
||||
if (!cumulative || !providerSessionId || isZeroUsage(cumulative)) {
|
||||
return;
|
||||
}
|
||||
const model = canonicalModelId(thread.modelSelection.model);
|
||||
yield* seedUsageBaselines(providerSessionId);
|
||||
const key = usageBaselineKey(providerSessionId, model);
|
||||
const baseline = usageBaselines.get(key) ?? ZERO_USAGE_COUNTERS;
|
||||
const { delta, nextBaseline } = usageDelta(baseline, cumulative);
|
||||
usageBaselines.set(key, nextBaseline);
|
||||
if (isZeroUsage(delta)) {
|
||||
return;
|
||||
}
|
||||
const effort = reasoningEffortFromThread(thread);
|
||||
const fact: UsageFact = {
|
||||
factId: UsageFactId.make(`usage:${event.eventId}:${model}`),
|
||||
kind: "interval",
|
||||
provider: event.provider,
|
||||
...(event.providerInstanceId !== undefined
|
||||
? { providerInstanceId: event.providerInstanceId }
|
||||
: {}),
|
||||
providerSessionId,
|
||||
model,
|
||||
modelRaw: thread.modelSelection.model,
|
||||
...(effort !== undefined ? { reasoningEffort: effort } : {}),
|
||||
tokens: {
|
||||
inputTokens: delta.inputTokens,
|
||||
cachedInputTokens: delta.cachedInputTokens,
|
||||
cacheCreationTokens: delta.cacheCreationTokens,
|
||||
outputTokens: delta.outputTokens,
|
||||
reasoningOutputTokens: delta.reasoningOutputTokens,
|
||||
},
|
||||
observedAt: event.createdAt,
|
||||
};
|
||||
yield* dispatchUsageFacts({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
projectId: thread.projectId,
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
facts: [fact],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Claude path: turn.completed carries the SDK's session-cumulative
|
||||
// per-model usage map (exact cost included). Settle each model's delta
|
||||
// as a final fact; stale completions are recorded but flagged.
|
||||
if (event.type === "turn.completed") {
|
||||
const byModel = claudeCumulativeByModel(event.payload.modelUsage);
|
||||
if (!byModel || byModel.size === 0) {
|
||||
return;
|
||||
}
|
||||
const providerSessionId = event.providerRefs?.providerSessionId ?? thread.id;
|
||||
yield* seedUsageBaselines(providerSessionId);
|
||||
const facts: Array<UsageFact> = [];
|
||||
for (const [rawModel, cumulative] of byModel) {
|
||||
const model = canonicalModelId(rawModel);
|
||||
const key = usageBaselineKey(providerSessionId, model);
|
||||
const baseline = usageBaselines.get(key) ?? ZERO_USAGE_COUNTERS;
|
||||
const { delta, nextBaseline } = usageDelta(baseline, cumulative);
|
||||
usageBaselines.set(key, nextBaseline);
|
||||
if (isZeroUsage(delta)) {
|
||||
continue;
|
||||
}
|
||||
facts.push({
|
||||
factId: UsageFactId.make(`usage:${event.eventId}:${model}`),
|
||||
kind: "final",
|
||||
provider: event.provider,
|
||||
...(event.providerInstanceId !== undefined
|
||||
? { providerInstanceId: event.providerInstanceId }
|
||||
: {}),
|
||||
providerSessionId,
|
||||
model,
|
||||
modelRaw: rawModel,
|
||||
tokens: {
|
||||
inputTokens: delta.inputTokens,
|
||||
cachedInputTokens: delta.cachedInputTokens,
|
||||
cacheCreationTokens: delta.cacheCreationTokens,
|
||||
outputTokens: delta.outputTokens,
|
||||
reasoningOutputTokens: delta.reasoningOutputTokens,
|
||||
},
|
||||
...(delta.costMicroUsd > 0 ? { costMicroUsd: delta.costMicroUsd } : {}),
|
||||
...(options.staleCompletion ? { stale: true } : {}),
|
||||
observedAt: event.createdAt,
|
||||
});
|
||||
}
|
||||
if (facts.length === 0) {
|
||||
return;
|
||||
}
|
||||
yield* dispatchUsageFacts({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
projectId: thread.projectId,
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
facts,
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("usage accounting failed for runtime event", {
|
||||
eventId: event.eventId,
|
||||
eventType: event.type,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const thread = yield* resolveThreadShell(event.threadId);
|
||||
@@ -1511,6 +1308,11 @@ const make = Effect.gen(function* () {
|
||||
const now = event.createdAt;
|
||||
const eventTurnId = toTurnId(event.turnId);
|
||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: thread.id,
|
||||
});
|
||||
const hasPendingTurnStart =
|
||||
Option.isSome(pendingTurnStart) && thread.session?.status === "starting";
|
||||
|
||||
const conflictsWithActiveTurn =
|
||||
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
|
||||
@@ -1525,11 +1327,7 @@ const make = Effect.gen(function* () {
|
||||
const conflictingTurnStartIsPendingTurnStart =
|
||||
event.type === "turn.started" && conflictsWithActiveTurn
|
||||
? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&
|
||||
Option.isSome(
|
||||
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: thread.id,
|
||||
}),
|
||||
)
|
||||
Option.isSome(pendingTurnStart)
|
||||
: false;
|
||||
|
||||
const shouldApplyThreadLifecycle = (() => {
|
||||
@@ -1563,13 +1361,6 @@ const make = Effect.gen(function* () {
|
||||
? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
|
||||
: null;
|
||||
|
||||
// Usage accounting runs for every usage-bearing event, including
|
||||
// lifecycle-rejected completions (recorded with stale: true) — tokens
|
||||
// were consumed regardless of what the turn state machine thinks.
|
||||
yield* recordUsageForRuntimeEvent(event, thread, {
|
||||
staleCompletion: event.type === "turn.completed" && !shouldApplyThreadLifecycle,
|
||||
});
|
||||
|
||||
if (
|
||||
event.type === "session.started" ||
|
||||
event.type === "session.state.changed" ||
|
||||
@@ -1580,8 +1371,10 @@ const make = Effect.gen(function* () {
|
||||
) {
|
||||
const status = (() => {
|
||||
switch (event.type) {
|
||||
case "session.state.changed":
|
||||
return orchestrationSessionStatusFromRuntimeState(event.payload.state);
|
||||
case "session.state.changed": {
|
||||
const runtimeStatus = orchestrationSessionStatusFromRuntimeState(event.payload.state);
|
||||
return hasPendingTurnStart && runtimeStatus === "ready" ? "starting" : runtimeStatus;
|
||||
}
|
||||
case "turn.started":
|
||||
return "running";
|
||||
case "session.exited":
|
||||
@@ -1593,8 +1386,8 @@ const make = Effect.gen(function* () {
|
||||
case "session.started":
|
||||
case "thread.started":
|
||||
// Provider thread/session start notifications can arrive during an
|
||||
// active turn; preserve turn-running state in that case.
|
||||
return activeTurnId !== null ? "running" : "ready";
|
||||
// active or pending turn; preserve that lifecycle state.
|
||||
return activeTurnId !== null ? "running" : hasPendingTurnStart ? "starting" : "ready";
|
||||
}
|
||||
})();
|
||||
const nextActiveTurnId =
|
||||
@@ -1602,7 +1395,10 @@ const make = Effect.gen(function* () {
|
||||
? (eventTurnId ?? null)
|
||||
: event.type === "turn.completed" || event.type === "session.exited"
|
||||
? null
|
||||
: event.type === "session.state.changed" && !sessionStatusAllowsActiveTurn(status)
|
||||
: event.type === "session.state.changed" &&
|
||||
!sessionStatusAllowsActiveTurn(
|
||||
orchestrationSessionStatusFromRuntimeState(event.payload.state),
|
||||
)
|
||||
? null
|
||||
: activeTurnId;
|
||||
const lastError =
|
||||
@@ -2032,4 +1828,4 @@ const make = Effect.gen(function* () {
|
||||
export const ProviderRuntimeIngestionLive = Layer.effect(
|
||||
ProviderRuntimeIngestionService,
|
||||
make,
|
||||
).pipe(Layer.provide(ProjectionTurnRepositoryLive), Layer.provide(ProjectionUsageRepositoryLive));
|
||||
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
|
||||
@@ -4,11 +4,15 @@ import {
|
||||
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
||||
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
||||
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
|
||||
ThreadSettledPayload as ContractsThreadSettledPayloadSchema,
|
||||
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
||||
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
|
||||
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
|
||||
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -29,11 +33,15 @@ export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
||||
|
||||
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
||||
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
|
||||
export const ThreadSettledPayload = ContractsThreadSettledPayloadSchema;
|
||||
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
||||
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
|
||||
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
|
||||
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;
|
||||
|
||||
@@ -68,6 +68,8 @@ const readModel: OrchestrationReadModel = {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
@@ -91,6 +93,8 @@ const readModel: OrchestrationReadModel = {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
|
||||
@@ -0,0 +1,521 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationSession,
|
||||
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";
|
||||
const SETTLED_AT = "2025-12-30T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(
|
||||
settledOverride: OrchestrationThread["settledOverride"],
|
||||
archivedAt: string | null = null,
|
||||
session: OrchestrationSession | null = null,
|
||||
activities: OrchestrationThread["activities"] = [],
|
||||
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,
|
||||
settledOverride,
|
||||
settledAt: settledOverride === "settled" ? SETTLED_AT : null,
|
||||
deletedAt: null,
|
||||
messages,
|
||||
proposedPlans: [],
|
||||
activities,
|
||||
checkpoints: [],
|
||||
session,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSession(status: OrchestrationSession["status"]): OrchestrationSession {
|
||||
return {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status,
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("settled thread decider", (it) => {
|
||||
it.effect("settles active threads and re-emits idempotently for settled ones", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.settled");
|
||||
if (events[0]?.type === "thread.settled") {
|
||||
expect(events[0].payload.settledAt).toBe(events[0].payload.updatedAt);
|
||||
}
|
||||
|
||||
// Already settled: the engine rejects zero-event commands, so idempotency
|
||||
// is by re-emission — preserving the original settledAt.
|
||||
const reEmit = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const reEmitEvents = Array.isArray(reEmit) ? reEmit : [reEmit];
|
||||
expect(reEmitEvents).toHaveLength(1);
|
||||
expect(reEmitEvents[0]?.type).toBe("thread.settled");
|
||||
if (reEmitEvents[0]?.type === "thread.settled") {
|
||||
expect(reEmitEvents[0].payload.settledAt).toBe(SETTLED_AT);
|
||||
// updatedAt must NOT rewind to the historical settledAt: sorting and
|
||||
// relative-time labels key on it.
|
||||
expect(reEmitEvents[0].payload.updatedAt).not.toBe(SETTLED_AT);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects settling a thread with a live session", () =>
|
||||
Effect.gen(function* () {
|
||||
for (const status of ["starting", "running"] as const) {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make(`cmd-settle-live-${status}`),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, makeSession(status)),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}
|
||||
// Stopped/error sessions are settleable — only live work is protected.
|
||||
const settled = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-stopped"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, makeSession("stopped")),
|
||||
});
|
||||
const settledEvents = Array.isArray(settled) ? settled : [settled];
|
||||
expect(settledEvents[0]?.type).toBe("thread.settled");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects settling a thread with an open approval or user-input request", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestActivity = (kind: string, requestId: string, at: string) =>
|
||||
({
|
||||
id: EventId.make(`activity-${requestId}-${kind}`),
|
||||
tone: "approval" as const,
|
||||
kind,
|
||||
summary: kind,
|
||||
payload: { requestId },
|
||||
turnId: null,
|
||||
createdAt: at,
|
||||
}) as OrchestrationThread["activities"][number];
|
||||
|
||||
// Open approval request: settle rejected.
|
||||
const openError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-pending"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
requestActivity("approval.requested", "req-1", NOW),
|
||||
]),
|
||||
}).pipe(Effect.flip);
|
||||
expect(openError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
|
||||
// Same request later resolved: settleable again.
|
||||
const settled = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-resolved"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
requestActivity("approval.requested", "req-1", NOW),
|
||||
requestActivity("approval.resolved", "req-1", NOW),
|
||||
]),
|
||||
});
|
||||
const settledEvents = Array.isArray(settled) ? settled : [settled];
|
||||
expect(settledEvents[0]?.type).toBe("thread.settled");
|
||||
|
||||
// Open user-input request: also rejected.
|
||||
const inputError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-pending-input"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
requestActivity("user-input.requested", "req-2", NOW),
|
||||
]),
|
||||
}).pipe(Effect.flip);
|
||||
expect(inputError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears an open request when its respond failure marks it stale", () =>
|
||||
Effect.gen(function* () {
|
||||
const activity = (
|
||||
kind: string,
|
||||
requestId: string,
|
||||
payload: Record<string, unknown>,
|
||||
): OrchestrationThread["activities"][number] =>
|
||||
({
|
||||
id: EventId.make(`activity-${requestId}-${kind}`),
|
||||
tone: "approval" as const,
|
||||
kind,
|
||||
summary: kind,
|
||||
payload: { requestId, ...payload },
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
}) as OrchestrationThread["activities"][number];
|
||||
|
||||
// Stale-failure detail clears the request — mirrors the projection's
|
||||
// pending accounting, which is what the client's canSettle sees.
|
||||
const settled = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-stale-failed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
activity("approval.requested", "req-1", {}),
|
||||
activity("provider.approval.respond.failed", "req-1", {
|
||||
detail: "Unknown pending approval request req-1",
|
||||
}),
|
||||
activity("user-input.requested", "req-2", {}),
|
||||
activity("provider.user-input.respond.failed", "req-2", {
|
||||
detail: "stale pending user-input request req-2",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
const settledEvents = Array.isArray(settled) ? settled : [settled];
|
||||
expect(settledEvents[0]?.type).toBe("thread.settled");
|
||||
|
||||
// A non-stale respond failure (transient provider error) keeps the
|
||||
// request open: the user can retry, so it is still blocked-on-you.
|
||||
const stillOpen = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-transient-failed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
activity("approval.requested", "req-3", {}),
|
||||
activity("provider.approval.respond.failed", "req-3", {
|
||||
detail: "provider connection reset",
|
||||
}),
|
||||
]),
|
||||
}).pipe(Effect.flip);
|
||||
expect(stillOpen._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("bounds the queued-turn grace window against client clock skew", () =>
|
||||
Effect.gen(function* () {
|
||||
const userMessage = (createdAt: string): OrchestrationThread["messages"][number] => ({
|
||||
id: MessageId.make("message-queued"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
});
|
||||
|
||||
// The decider's clock is the Effect test clock, pinned to the epoch:
|
||||
// timestamps here are relative to 1970-01-01T00:00:00.000Z.
|
||||
|
||||
// Within the grace window: genuinely queued, settle rejected.
|
||||
const queuedError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-queued"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [], [userMessage("1969-12-31T23:59:30.000Z")]),
|
||||
}).pipe(Effect.flip);
|
||||
expect(queuedError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
|
||||
// Message timestamp far in the FUTURE (client clock ahead of server):
|
||||
// a negative age must not read as queued forever — past the grace
|
||||
// bound in either direction the thread is settleable.
|
||||
const skewed = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-skewed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [], [userMessage("1970-01-01T01:00:00.000Z")]),
|
||||
});
|
||||
const skewedEvents = Array.isArray(skewed) ? skewed : [skewed];
|
||||
expect(skewedEvents[0]?.type).toBe("thread.settled");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects settling and unsettling archived threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const settleError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, NOW),
|
||||
}).pipe(Effect.flip);
|
||||
expect(settleError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
|
||||
const unsettleError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsettle",
|
||||
commandId: CommandId.make("cmd-unsettle-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel("settled", NOW),
|
||||
}).pipe(Effect.flip);
|
||||
expect(unsettleError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps unsettle reasons to overrides and re-emits idempotently", () =>
|
||||
Effect.gen(function* () {
|
||||
const userEvent = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsettle",
|
||||
commandId: CommandId.make("cmd-unsettle-user"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const userEvents = Array.isArray(userEvent) ? userEvent : [userEvent];
|
||||
expect(userEvents).toHaveLength(1);
|
||||
expect(userEvents[0]?.type).toBe("thread.unsettled");
|
||||
if (userEvents[0]?.type === "thread.unsettled") {
|
||||
expect(userEvents[0].payload.reason).toBe("user");
|
||||
}
|
||||
|
||||
// Re-dispatching against the already-reached state re-emits rather than
|
||||
// producing zero events (the engine rejects empty commands).
|
||||
const userAgain = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsettle",
|
||||
commandId: CommandId.make("cmd-unsettle-user-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const userAgainEvents = Array.isArray(userAgain) ? userAgain : [userAgain];
|
||||
expect(userAgainEvents).toHaveLength(1);
|
||||
expect(userAgainEvents[0]?.type).toBe("thread.unsettled");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prepends activity unsets for turn starts and live session updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const turnResult = 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("settled"),
|
||||
});
|
||||
const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
|
||||
expect(turnEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
|
||||
const sessionResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: makeSession("running"),
|
||||
createdAt: NOW,
|
||||
},
|
||||
// A keep-active pin is also an override: real activity clears it
|
||||
// back to neutral so auto-settle can apply again later.
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const sessionEvents = Array.isArray(sessionResult) ? sessionResult : [sessionResult];
|
||||
expect(sessionEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.session-set",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears a keep-active pin on real activity", () =>
|
||||
Effect.gen(function* () {
|
||||
const turnResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-active-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-active"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
|
||||
// The pin exists to suppress AUTO-settle, not to survive real work:
|
||||
// activity resets it to neutral, restoring the default lifecycle.
|
||||
expect(turnEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
|
||||
const activityResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-active-approval"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.make("activity-active"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: null,
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
},
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const activityEvents = Array.isArray(activityResult) ? activityResult : [activityResult];
|
||||
expect(activityEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.activity-appended",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not unsettle for session stop/error status writes", () =>
|
||||
Effect.gen(function* () {
|
||||
for (const status of ["stopped", "error", "ready", "idle"] as const) {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make(`cmd-session-${status}`),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: makeSession(status),
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
expect(events.map((event) => event.type)).toEqual(["thread.session-set"]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unsettles for approval and user-input activities but not others", () =>
|
||||
Effect.gen(function* () {
|
||||
const approvalResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-activity-approval"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.make("activity-1"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: null,
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
},
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const approvalEvents = Array.isArray(approvalResult) ? approvalResult : [approvalResult];
|
||||
expect(approvalEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.activity-appended",
|
||||
]);
|
||||
|
||||
const routineResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-activity-routine"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.make("activity-2"),
|
||||
tone: "info",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool completed",
|
||||
payload: null,
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
},
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const routineEvents = Array.isArray(routineResult) ? routineResult : [routineResult];
|
||||
expect(routineEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -24,6 +24,124 @@ import { projectEvent } from "./projector.ts";
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
// Session adoption takes seconds; a user message still unadopted after this
|
||||
// window is a failed/stale start, not pending work. Mirrors the client's
|
||||
// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.
|
||||
const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
|
||||
|
||||
/**
|
||||
* Blocked-on-you work derived from the thread's retained activities: an
|
||||
* approval or user-input request with no later resolution for the same
|
||||
* requestId. The server-side twin of the shell's hasPendingApprovals /
|
||||
* hasPendingUserInput flags, which the decider read model does not carry.
|
||||
* The clearing rules MUST match ProjectionPipeline's pending accounting —
|
||||
* resolved activities always clear, respond.failed clears only when the
|
||||
* failure detail marks the request stale/unknown — or settle would be
|
||||
* rejected on threads whose shell flags read as clear.
|
||||
*/
|
||||
function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): boolean {
|
||||
const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
if (detail === null) return false;
|
||||
return (
|
||||
detail.includes("stale pending approval request") ||
|
||||
detail.includes("unknown pending approval request") ||
|
||||
detail.includes("unknown pending permission request") ||
|
||||
detail.includes("stale pending user-input request") ||
|
||||
detail.includes("unknown pending user-input request") ||
|
||||
detail.includes("unknown pending user input request") ||
|
||||
detail.includes("unknown pending codex user input request")
|
||||
);
|
||||
}
|
||||
|
||||
// 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 {
|
||||
const openRequestIds = new Set<string>();
|
||||
for (const activity of thread.activities) {
|
||||
const payload =
|
||||
typeof activity.payload === "object" && activity.payload !== null
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const requestId = typeof payload?.requestId === "string" ? payload.requestId : null;
|
||||
if (requestId === null) continue;
|
||||
if (activity.kind === "approval.requested" || activity.kind === "user-input.requested") {
|
||||
openRequestIds.add(requestId);
|
||||
} else if (activity.kind === "approval.resolved" || activity.kind === "user-input.resolved") {
|
||||
openRequestIds.delete(requestId);
|
||||
} else if (
|
||||
(activity.kind === "provider.approval.respond.failed" ||
|
||||
activity.kind === "provider.user-input.respond.failed") &&
|
||||
isStaleRequestFailureDetail(payload)
|
||||
) {
|
||||
openRequestIds.delete(requestId);
|
||||
}
|
||||
}
|
||||
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"];
|
||||
@@ -327,6 +445,191 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.settle": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Server-side twin of the client's canSettle session check: a stale
|
||||
// or raced client must not settle a thread whose session is coming
|
||||
// alive or working.
|
||||
if (thread.session?.status === "starting" || thread.session?.status === "running") {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has an active session and cannot be settled`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Pending approval / user-input requests are blocked-on-you work: a
|
||||
// raced or stale client must not park them behind a settled override
|
||||
// that would surface only after the request resolves.
|
||||
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 settled`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
// Settling inside the adoption window would hide just-requested work.
|
||||
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 settled`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Settling an already-settled thread re-emits with the original
|
||||
// settledAt: the engine rejects zero-event commands, and bulk-settle /
|
||||
// double-click must stay silent no-ops rather than surface errors.
|
||||
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.settled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
settledAt: alreadySettled ? thread.settledAt : occurredAt,
|
||||
// A re-emission is a projected no-op: keep the existing updatedAt
|
||||
// so duplicate settles neither rewind nor churn ordering. A fresh
|
||||
// settle stamps the command time.
|
||||
updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unsettle": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Idempotent by re-emission (see thread.settle): reducing the event a
|
||||
// second time lands on the same override state. A re-emission keeps
|
||||
// the existing updatedAt so duplicates do not churn ordering.
|
||||
const alreadyPinnedActive = thread.settledOverride === "active";
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: command.reason,
|
||||
updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -479,7 +782,45 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
// 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.
|
||||
// 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,
|
||||
},
|
||||
});
|
||||
}
|
||||
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": {
|
||||
@@ -600,12 +941,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.session.set": {
|
||||
yield* requireThread({
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -619,6 +960,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
session: command.session,
|
||||
},
|
||||
};
|
||||
// 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. 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).
|
||||
if (thread.settledOverride === null || !isSessionActivity) {
|
||||
return sessionSetEvent;
|
||||
}
|
||||
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, sessionSetEvent];
|
||||
}
|
||||
|
||||
case "thread.message.assistant.delta": {
|
||||
@@ -745,7 +1115,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.activity.append": {
|
||||
yield* requireThread({
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
@@ -758,7 +1128,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
? ((command.activity.payload as { requestId: string })
|
||||
.requestId as OrchestrationEvent["metadata"]["requestId"])
|
||||
: undefined;
|
||||
return {
|
||||
const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -772,30 +1142,30 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
activity: command.activity,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.usage.record": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
// An approval or user-input request is blocked-on-you work — it must
|
||||
// never stay hidden inside a settled slim row.
|
||||
const wakesSettledThread =
|
||||
command.activity.kind === "approval.requested" ||
|
||||
command.activity.kind === "user-input.requested";
|
||||
// Real activity resets ANY override (settled wakes, active unpins).
|
||||
if (thread.settledOverride === null || !wakesSettledThread) {
|
||||
return activityAppendedEvent;
|
||||
}
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.usage-recorded",
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
turnId: command.turnId,
|
||||
projectId: command.projectId,
|
||||
facts: command.facts,
|
||||
recordedAt: command.createdAt,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, activityAppendedEvent];
|
||||
}
|
||||
|
||||
default: {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
function makeEvent(input: {
|
||||
readonly sequence: number;
|
||||
readonly type: OrchestrationEvent["type"];
|
||||
readonly payload: unknown;
|
||||
}): OrchestrationEvent {
|
||||
return {
|
||||
sequence: input.sequence,
|
||||
eventId: EventId.make(`event-${input.sequence}`),
|
||||
type: input.type,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
occurredAt: "2026-01-01T00:00:00.000Z",
|
||||
commandId: CommandId.make(`command-${input.sequence}`),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
payload: input.payload as never,
|
||||
} as OrchestrationEvent;
|
||||
}
|
||||
|
||||
it.effect("projects settled lifecycle events", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const created = yield* projectEvent(
|
||||
createEmptyReadModel(now),
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const settled = yield* projectEvent(
|
||||
created,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.settled",
|
||||
payload: { threadId: ThreadId.make("thread-1"), settledAt: now, updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(settled.threads[0]?.settledOverride).toBe("settled");
|
||||
expect(settled.threads[0]?.settledAt).toBe(now);
|
||||
|
||||
const userUnsettled = yield* projectEvent(
|
||||
settled,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.unsettled",
|
||||
payload: { threadId: ThreadId.make("thread-1"), reason: "user", updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(userUnsettled.threads[0]?.settledOverride).toBe("active");
|
||||
expect(userUnsettled.threads[0]?.settledAt).toBeNull();
|
||||
|
||||
const activityUnsettled = yield* projectEvent(
|
||||
userUnsettled,
|
||||
makeEvent({
|
||||
sequence: 4,
|
||||
type: "thread.unsettled",
|
||||
payload: { threadId: ThreadId.make("thread-1"), reason: "activity", updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(activityUnsettled.threads[0]?.settledOverride).toBeNull();
|
||||
expect(activityUnsettled.threads[0]?.settledAt).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -89,6 +89,10 @@ describe("orchestration projector", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -22,7 +22,11 @@ import {
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadSnoozedPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadUnsnoozedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -286,6 +290,10 @@ export function projectEvent(
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -337,6 +345,54 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.settled":
|
||||
return decodeForEvent(ThreadSettledPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
settledOverride: "settled",
|
||||
settledAt: payload.settledAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unsettled":
|
||||
return decodeForEvent(ThreadUnsettledPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
settledOverride: payload.reason === "user" ? "active" : null,
|
||||
settledAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
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) => ({
|
||||
|
||||
@@ -2,7 +2,6 @@ import * as Layer from "effect/Layer";
|
||||
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { ProjectionUsageRepositoryLive } from "../persistence/Layers/ProjectionUsage.ts";
|
||||
import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";
|
||||
@@ -20,8 +19,6 @@ export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
OrchestrationEventInfrastructureLayerLive,
|
||||
OrchestrationProjectionPipelineLayerLive,
|
||||
// Exposed for the usage.getSummary RPC handler in ws.ts.
|
||||
ProjectionUsageRepositoryLive,
|
||||
);
|
||||
|
||||
export const OrchestrationLayerLive = Layer.mergeAll(
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
canonicalModelId,
|
||||
claudeCumulativeByModel,
|
||||
codexCumulativeFromSnapshot,
|
||||
isZeroUsage,
|
||||
usageDelta,
|
||||
ZERO_USAGE_COUNTERS,
|
||||
} from "./usageAccounting.ts";
|
||||
|
||||
describe("usageAccounting", () => {
|
||||
describe("usageDelta", () => {
|
||||
it("computes interval counters from cumulative counters", () => {
|
||||
const result = usageDelta(
|
||||
{
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 20,
|
||||
cacheCreationTokens: 10,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 5,
|
||||
costMicroUsd: 1_000_000,
|
||||
},
|
||||
{
|
||||
inputTokens: 175,
|
||||
cachedInputTokens: 35,
|
||||
cacheCreationTokens: 18,
|
||||
outputTokens: 90,
|
||||
reasoningOutputTokens: 12,
|
||||
costMicroUsd: 1_750_000,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
delta: {
|
||||
inputTokens: 75,
|
||||
cachedInputTokens: 15,
|
||||
cacheCreationTokens: 8,
|
||||
outputTokens: 40,
|
||||
reasoningOutputTokens: 7,
|
||||
costMicroUsd: 750_000,
|
||||
},
|
||||
nextBaseline: {
|
||||
inputTokens: 175,
|
||||
cachedInputTokens: 35,
|
||||
cacheCreationTokens: 18,
|
||||
outputTokens: 90,
|
||||
reasoningOutputTokens: 12,
|
||||
costMicroUsd: 1_750_000,
|
||||
},
|
||||
reset: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a zero delta when baseline equals cumulative", () => {
|
||||
const cumulative = {
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 20,
|
||||
cacheCreationTokens: 10,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 5,
|
||||
costMicroUsd: 1_000_000,
|
||||
};
|
||||
|
||||
expect(usageDelta(cumulative, cumulative)).toEqual({
|
||||
delta: ZERO_USAGE_COUNTERS,
|
||||
nextBaseline: cumulative,
|
||||
reset: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("treats a counter regression as a provider session reset", () => {
|
||||
const cumulative = {
|
||||
inputTokens: 125,
|
||||
cachedInputTokens: 25,
|
||||
cacheCreationTokens: 12,
|
||||
outputTokens: 10,
|
||||
reasoningOutputTokens: 6,
|
||||
costMicroUsd: 1_250_000,
|
||||
};
|
||||
|
||||
expect(
|
||||
usageDelta(
|
||||
{
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 20,
|
||||
cacheCreationTokens: 10,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 5,
|
||||
costMicroUsd: 1_000_000,
|
||||
},
|
||||
cumulative,
|
||||
),
|
||||
).toEqual({
|
||||
delta: cumulative,
|
||||
nextBaseline: cumulative,
|
||||
reset: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("claudeCumulativeByModel", () => {
|
||||
it("decodes per-model cumulative usage and converts USD to micro-USD", () => {
|
||||
const result = claudeCumulativeByModel({
|
||||
"claude-fable-5[1m]": {
|
||||
inputTokens: 100,
|
||||
outputTokens: 50,
|
||||
cacheReadInputTokens: 1_000,
|
||||
cacheCreationInputTokens: 200,
|
||||
costUSD: 1.25,
|
||||
},
|
||||
"claude-opus-4-8": {
|
||||
inputTokens: 80,
|
||||
outputTokens: 30,
|
||||
cacheReadInputTokens: 400,
|
||||
cacheCreationInputTokens: 25,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual(
|
||||
new Map([
|
||||
[
|
||||
"claude-fable-5[1m]",
|
||||
{
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 1_000,
|
||||
cacheCreationTokens: 200,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 0,
|
||||
costMicroUsd: 1_250_000,
|
||||
},
|
||||
],
|
||||
[
|
||||
"claude-opus-4-8",
|
||||
{
|
||||
inputTokens: 80,
|
||||
cachedInputTokens: 400,
|
||||
cacheCreationTokens: 25,
|
||||
outputTokens: 30,
|
||||
reasoningOutputTokens: 0,
|
||||
costMicroUsd: 0,
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns undefined for malformed input", () => {
|
||||
expect(claudeCumulativeByModel({ model: "not usage" })).toBeUndefined();
|
||||
expect(claudeCumulativeByModel(null)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("codexCumulativeFromSnapshot", () => {
|
||||
it("stores only the uncached share in inputTokens", () => {
|
||||
expect(
|
||||
codexCumulativeFromSnapshot({
|
||||
totalInputTokens: 1_000,
|
||||
totalCachedInputTokens: 250,
|
||||
totalOutputTokens: 400,
|
||||
totalReasoningOutputTokens: 125,
|
||||
}),
|
||||
).toEqual({
|
||||
inputTokens: 750,
|
||||
cachedInputTokens: 250,
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: 400,
|
||||
reasoningOutputTokens: 125,
|
||||
costMicroUsd: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns undefined when no cumulative total fields are present", () => {
|
||||
expect(codexCumulativeFromSnapshot({})).toBeUndefined();
|
||||
expect(
|
||||
codexCumulativeFromSnapshot({
|
||||
totalCachedInputTokens: 100,
|
||||
totalReasoningOutputTokens: 20,
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it("canonicalizes provider capacity suffixes", () => {
|
||||
expect(canonicalModelId("claude-fable-5[1m]")).toBe("claude-fable-5");
|
||||
expect(canonicalModelId("claude-opus-4-8")).toBe("claude-opus-4-8");
|
||||
});
|
||||
|
||||
it("detects zero usage", () => {
|
||||
expect(isZeroUsage(ZERO_USAGE_COUNTERS)).toBe(true);
|
||||
expect(isZeroUsage({ ...ZERO_USAGE_COUNTERS, outputTokens: 1 })).toBe(false);
|
||||
expect(isZeroUsage({ ...ZERO_USAGE_COUNTERS, costMicroUsd: 1 })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,136 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ClaudeModelUsageMap, type UsageTokenCounters } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Pure delta accounting for usage facts.
|
||||
*
|
||||
* Providers report session-cumulative counters (Codex `tokenUsage.total`,
|
||||
* Claude `modelUsage`). A usage fact must carry interval counters, so every
|
||||
* emission subtracts a baseline: the sum of everything already recorded for
|
||||
* that provider-native session and model. Baselines survive restarts by
|
||||
* reseeding from `projection_usage_facts` sums.
|
||||
*/
|
||||
|
||||
export interface UsageCumulativeCounters extends UsageTokenCounters {
|
||||
readonly costMicroUsd: number;
|
||||
}
|
||||
|
||||
export const ZERO_USAGE_COUNTERS: UsageCumulativeCounters = {
|
||||
inputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: 0,
|
||||
reasoningOutputTokens: 0,
|
||||
costMicroUsd: 0,
|
||||
};
|
||||
|
||||
export interface UsageDeltaResult {
|
||||
readonly delta: UsageCumulativeCounters;
|
||||
/** The cumulative counters that become the next baseline. */
|
||||
readonly nextBaseline: UsageCumulativeCounters;
|
||||
/** True when any counter went backwards (provider session reset); the
|
||||
* absolute cumulative value is used as the delta in that case. */
|
||||
readonly reset: boolean;
|
||||
}
|
||||
|
||||
function nonNegative(value: number): number {
|
||||
return value > 0 ? Math.round(value) : 0;
|
||||
}
|
||||
|
||||
export function usageDelta(
|
||||
baseline: UsageCumulativeCounters,
|
||||
cumulative: UsageCumulativeCounters,
|
||||
): UsageDeltaResult {
|
||||
const reset =
|
||||
cumulative.inputTokens < baseline.inputTokens ||
|
||||
cumulative.cachedInputTokens < baseline.cachedInputTokens ||
|
||||
cumulative.outputTokens < baseline.outputTokens;
|
||||
|
||||
if (reset) {
|
||||
return { delta: cumulative, nextBaseline: cumulative, reset: true };
|
||||
}
|
||||
|
||||
return {
|
||||
delta: {
|
||||
inputTokens: nonNegative(cumulative.inputTokens - baseline.inputTokens),
|
||||
cachedInputTokens: nonNegative(cumulative.cachedInputTokens - baseline.cachedInputTokens),
|
||||
cacheCreationTokens: nonNegative(
|
||||
cumulative.cacheCreationTokens - baseline.cacheCreationTokens,
|
||||
),
|
||||
outputTokens: nonNegative(cumulative.outputTokens - baseline.outputTokens),
|
||||
reasoningOutputTokens: nonNegative(
|
||||
cumulative.reasoningOutputTokens - baseline.reasoningOutputTokens,
|
||||
),
|
||||
costMicroUsd: nonNegative(cumulative.costMicroUsd - baseline.costMicroUsd),
|
||||
},
|
||||
nextBaseline: cumulative,
|
||||
reset: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function isZeroUsage(counters: UsageCumulativeCounters): boolean {
|
||||
return (
|
||||
counters.inputTokens === 0 &&
|
||||
counters.cachedInputTokens === 0 &&
|
||||
counters.cacheCreationTokens === 0 &&
|
||||
counters.outputTokens === 0 &&
|
||||
counters.reasoningOutputTokens === 0 &&
|
||||
counters.costMicroUsd === 0
|
||||
);
|
||||
}
|
||||
|
||||
/** Strip provider capacity suffixes (`claude-fable-5[1m]` → `claude-fable-5`)
|
||||
* while keeping the raw id available for display and pricing overrides. */
|
||||
export function canonicalModelId(rawModel: string): string {
|
||||
return rawModel.replace(/\[[^\]]+\]$/, "");
|
||||
}
|
||||
|
||||
const decodeClaudeModelUsage = Schema.decodeUnknownOption(ClaudeModelUsageMap);
|
||||
|
||||
/** Claude's `modelUsage` map is cumulative per SDK session. Returns cumulative
|
||||
* counters per raw model id, or undefined when the payload doesn't parse. */
|
||||
export function claudeCumulativeByModel(
|
||||
modelUsage: unknown,
|
||||
): ReadonlyMap<string, UsageCumulativeCounters> | undefined {
|
||||
const decoded = decodeClaudeModelUsage(modelUsage);
|
||||
if (decoded._tag === "None") {
|
||||
return undefined;
|
||||
}
|
||||
const result = new Map<string, UsageCumulativeCounters>();
|
||||
for (const [rawModel, entry] of Object.entries(decoded.value)) {
|
||||
result.set(rawModel, {
|
||||
inputTokens: nonNegative(entry.inputTokens),
|
||||
cachedInputTokens: nonNegative(entry.cacheReadInputTokens),
|
||||
cacheCreationTokens: nonNegative(entry.cacheCreationInputTokens),
|
||||
outputTokens: nonNegative(entry.outputTokens),
|
||||
reasoningOutputTokens: 0,
|
||||
costMicroUsd: entry.costUSD !== undefined ? nonNegative(entry.costUSD * 1_000_000) : 0,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Codex cumulative totals from a ThreadTokenUsageSnapshot's `total*` fields.
|
||||
* Codex reports input inclusive of cached reads; the uncached share is the
|
||||
* difference. Returns undefined when the snapshot has no cumulative fields
|
||||
* (Claude context-window snapshots land here and are settled at turn end). */
|
||||
export function codexCumulativeFromSnapshot(usage: {
|
||||
readonly totalInputTokens?: number | undefined;
|
||||
readonly totalCachedInputTokens?: number | undefined;
|
||||
readonly totalOutputTokens?: number | undefined;
|
||||
readonly totalReasoningOutputTokens?: number | undefined;
|
||||
}): UsageCumulativeCounters | undefined {
|
||||
if (usage.totalInputTokens === undefined && usage.totalOutputTokens === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const totalInput = usage.totalInputTokens ?? 0;
|
||||
const cached = usage.totalCachedInputTokens ?? 0;
|
||||
return {
|
||||
inputTokens: nonNegative(totalInput - cached),
|
||||
cachedInputTokens: nonNegative(cached),
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: nonNegative(usage.totalOutputTokens ?? 0),
|
||||
reasoningOutputTokens: nonNegative(usage.totalReasoningOutputTokens ?? 0),
|
||||
costMicroUsd: 0,
|
||||
};
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
import type { UsageAggregate, UsageSummaryResponse } from "@t3tools/contracts";
|
||||
import { USAGE_PRICING_VERSION, estimateCostMicroUsd } from "@t3tools/shared/usagePricing";
|
||||
|
||||
import type { ProjectionUsageFact } from "../persistence/Services/ProjectionUsage.ts";
|
||||
|
||||
/**
|
||||
* Pure aggregation of usage facts into the dashboard-shaped summary. Calendar
|
||||
* bucketing happens in the requested IANA timezone via Intl (DST folds into
|
||||
* the local calendar naturally). `turn-total` facts are reconciliation-only
|
||||
* and excluded from all sums; stale facts count (tokens were consumed).
|
||||
*/
|
||||
|
||||
interface MutableAggregate {
|
||||
inputTokens: number;
|
||||
cachedInputTokens: number;
|
||||
cacheCreationTokens: number;
|
||||
outputTokens: number;
|
||||
reasoningOutputTokens: number;
|
||||
totalTokens: number;
|
||||
turns: number;
|
||||
exactCostMicroUsd: number;
|
||||
estimatedCostMicroUsd: number;
|
||||
}
|
||||
|
||||
function newAggregate(): MutableAggregate {
|
||||
return {
|
||||
inputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: 0,
|
||||
reasoningOutputTokens: 0,
|
||||
totalTokens: 0,
|
||||
turns: 0,
|
||||
exactCostMicroUsd: 0,
|
||||
estimatedCostMicroUsd: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function addFact(
|
||||
aggregate: MutableAggregate,
|
||||
fact: ProjectionUsageFact,
|
||||
estimatedMicroUsd: number | undefined,
|
||||
): void {
|
||||
aggregate.inputTokens += fact.inputTokens;
|
||||
aggregate.cachedInputTokens += fact.cachedInputTokens;
|
||||
aggregate.cacheCreationTokens += fact.cacheCreationTokens;
|
||||
aggregate.outputTokens += fact.outputTokens;
|
||||
aggregate.reasoningOutputTokens += fact.reasoningOutputTokens;
|
||||
aggregate.totalTokens +=
|
||||
fact.inputTokens + fact.cachedInputTokens + fact.cacheCreationTokens + fact.outputTokens;
|
||||
if (fact.costMicroUsd !== null) {
|
||||
aggregate.exactCostMicroUsd += fact.costMicroUsd;
|
||||
} else if (estimatedMicroUsd !== undefined) {
|
||||
aggregate.estimatedCostMicroUsd += estimatedMicroUsd;
|
||||
}
|
||||
}
|
||||
|
||||
function toAggregate(mutable: MutableAggregate): UsageAggregate {
|
||||
return { ...mutable };
|
||||
}
|
||||
|
||||
function makeCalendarFormatter(timeZone: string): Intl.DateTimeFormat {
|
||||
return new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
hour12: false,
|
||||
weekday: "short",
|
||||
});
|
||||
}
|
||||
|
||||
const WEEKDAY_INDEX: Record<string, number> = {
|
||||
Sun: 0,
|
||||
Mon: 1,
|
||||
Tue: 2,
|
||||
Wed: 3,
|
||||
Thu: 4,
|
||||
Fri: 5,
|
||||
Sat: 6,
|
||||
};
|
||||
|
||||
interface CalendarParts {
|
||||
readonly day: string;
|
||||
readonly hour: number;
|
||||
readonly dayOfWeek: number;
|
||||
}
|
||||
|
||||
function calendarParts(formatter: Intl.DateTimeFormat, iso: string): CalendarParts {
|
||||
const parts = formatter.formatToParts(Date.parse(iso));
|
||||
let year = "",
|
||||
month = "",
|
||||
day = "",
|
||||
hour = 0,
|
||||
dayOfWeek = 0;
|
||||
for (const part of parts) {
|
||||
switch (part.type) {
|
||||
case "year":
|
||||
year = part.value;
|
||||
break;
|
||||
case "month":
|
||||
month = part.value;
|
||||
break;
|
||||
case "day":
|
||||
day = part.value;
|
||||
break;
|
||||
case "hour":
|
||||
hour = Number(part.value) % 24;
|
||||
break;
|
||||
case "weekday":
|
||||
dayOfWeek = WEEKDAY_INDEX[part.value] ?? 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { day: `${year}-${month}-${day}`, hour, dayOfWeek };
|
||||
}
|
||||
|
||||
export type UsageProjectTitleLookup = (projectId: string) => string | null;
|
||||
|
||||
export function summarizeUsageFacts(input: {
|
||||
readonly facts: ReadonlyArray<ProjectionUsageFact>;
|
||||
readonly timeZone: string;
|
||||
readonly earliestFactAt: string | null;
|
||||
readonly projectTitle: UsageProjectTitleLookup;
|
||||
}): UsageSummaryResponse {
|
||||
const formatter = makeCalendarFormatter(input.timeZone);
|
||||
|
||||
const totals = newAggregate();
|
||||
const byModel = new Map<
|
||||
string,
|
||||
MutableAggregate & { provider: ProjectionUsageFact["provider"]; hasEstimate: boolean }
|
||||
>();
|
||||
const daily = new Map<
|
||||
string,
|
||||
MutableAggregate & {
|
||||
day: string;
|
||||
provider: ProjectionUsageFact["provider"];
|
||||
model: string;
|
||||
}
|
||||
>();
|
||||
const hourOfWeek = new Map<
|
||||
string,
|
||||
{ dayOfWeek: number; hour: number; turns: number; totalTokens: number }
|
||||
>();
|
||||
const byProject = new Map<
|
||||
string,
|
||||
MutableAggregate & { projectId: ProjectionUsageFact["projectId"] }
|
||||
>();
|
||||
const unpricedModels = new Set<string>();
|
||||
const turnKeys = new Set<string>();
|
||||
const turnKeysByScope = new Map<string, Set<string>>();
|
||||
|
||||
const scopedTurnCount = (scope: string, turnKey: string): number => {
|
||||
let keys = turnKeysByScope.get(scope);
|
||||
if (!keys) {
|
||||
keys = new Set();
|
||||
turnKeysByScope.set(scope, keys);
|
||||
}
|
||||
const before = keys.size;
|
||||
keys.add(turnKey);
|
||||
return keys.size - before;
|
||||
};
|
||||
|
||||
for (const fact of input.facts) {
|
||||
if (fact.kind === "turn-total") {
|
||||
continue;
|
||||
}
|
||||
const estimated =
|
||||
fact.costMicroUsd === null
|
||||
? estimateCostMicroUsd(fact.model, fact.observedAt, {
|
||||
inputTokens: fact.inputTokens,
|
||||
cachedInputTokens: fact.cachedInputTokens,
|
||||
cacheCreationTokens: fact.cacheCreationTokens,
|
||||
outputTokens: fact.outputTokens,
|
||||
})
|
||||
: undefined;
|
||||
if (fact.costMicroUsd === null && estimated === undefined) {
|
||||
unpricedModels.add(fact.model);
|
||||
}
|
||||
|
||||
const cal = calendarParts(formatter, fact.observedAt);
|
||||
const turnKey = `${fact.threadId}|${fact.turnId ?? fact.factId}`;
|
||||
const factTokens =
|
||||
fact.inputTokens + fact.cachedInputTokens + fact.cacheCreationTokens + fact.outputTokens;
|
||||
|
||||
addFact(totals, fact, estimated);
|
||||
if (!turnKeys.has(turnKey)) {
|
||||
turnKeys.add(turnKey);
|
||||
totals.turns += 1;
|
||||
}
|
||||
|
||||
const modelKey = `${fact.provider}|${fact.model}`;
|
||||
let model = byModel.get(modelKey);
|
||||
if (!model) {
|
||||
model = { ...newAggregate(), provider: fact.provider, hasEstimate: false };
|
||||
byModel.set(modelKey, model);
|
||||
}
|
||||
addFact(model, fact, estimated);
|
||||
if (estimated !== undefined) model.hasEstimate = true;
|
||||
model.turns += scopedTurnCount(`model:${modelKey}`, turnKey);
|
||||
|
||||
const dayKey = `${cal.day}|${fact.provider}|${fact.model}`;
|
||||
let dayBucket = daily.get(dayKey);
|
||||
if (!dayBucket) {
|
||||
dayBucket = { ...newAggregate(), day: cal.day, provider: fact.provider, model: fact.model };
|
||||
daily.set(dayKey, dayBucket);
|
||||
}
|
||||
addFact(dayBucket, fact, estimated);
|
||||
dayBucket.turns += scopedTurnCount(`day:${dayKey}`, turnKey);
|
||||
|
||||
const howKey = `${cal.dayOfWeek}|${cal.hour}`;
|
||||
let how = hourOfWeek.get(howKey);
|
||||
if (!how) {
|
||||
how = { dayOfWeek: cal.dayOfWeek, hour: cal.hour, turns: 0, totalTokens: 0 };
|
||||
hourOfWeek.set(howKey, how);
|
||||
}
|
||||
how.totalTokens += factTokens;
|
||||
how.turns += scopedTurnCount(`how:${howKey}`, turnKey);
|
||||
|
||||
const projectKey = fact.projectId ?? "__none__";
|
||||
let project = byProject.get(projectKey);
|
||||
if (!project) {
|
||||
project = { ...newAggregate(), projectId: fact.projectId };
|
||||
byProject.set(projectKey, project);
|
||||
}
|
||||
addFact(project, fact, estimated);
|
||||
project.turns += scopedTurnCount(`project:${projectKey}`, turnKey);
|
||||
}
|
||||
|
||||
const modelBuckets = [...byModel.entries()]
|
||||
.map(([key, aggregate]) => ({
|
||||
...toAggregate(aggregate),
|
||||
provider: aggregate.provider,
|
||||
model: key.slice(key.indexOf("|") + 1),
|
||||
costSource:
|
||||
aggregate.exactCostMicroUsd > 0
|
||||
? ("exact" as const)
|
||||
: aggregate.hasEstimate
|
||||
? ("estimated" as const)
|
||||
: ("none" as const),
|
||||
}))
|
||||
.sort((a, b) => b.totalTokens - a.totalTokens);
|
||||
|
||||
const dailyBuckets = [...daily.values()]
|
||||
.map((bucket) => ({
|
||||
...toAggregate(bucket),
|
||||
day: bucket.day,
|
||||
provider: bucket.provider,
|
||||
model: bucket.model,
|
||||
}))
|
||||
.sort((a, b) => (a.day === b.day ? b.totalTokens - a.totalTokens : a.day.localeCompare(b.day)));
|
||||
|
||||
const hourBuckets = [...hourOfWeek.values()].sort(
|
||||
(a, b) => a.dayOfWeek - b.dayOfWeek || a.hour - b.hour,
|
||||
);
|
||||
|
||||
const projectBuckets = [...byProject.values()]
|
||||
.map((bucket) => ({
|
||||
...toAggregate(bucket),
|
||||
projectId: bucket.projectId,
|
||||
projectTitle: bucket.projectId ? input.projectTitle(bucket.projectId) : null,
|
||||
}))
|
||||
.sort((a, b) => b.totalTokens - a.totalTokens);
|
||||
|
||||
return {
|
||||
totals: toAggregate(totals),
|
||||
byModel: modelBuckets,
|
||||
daily: dailyBuckets,
|
||||
hourOfWeek: hourBuckets,
|
||||
byProject: projectBuckets,
|
||||
unpricedModels: [...unpricedModels].sort(),
|
||||
pricingVersion: USAGE_PRICING_VERSION,
|
||||
earliestFactAt: input.earliestFactAt,
|
||||
} as UsageSummaryResponse;
|
||||
}
|
||||
@@ -91,6 +91,10 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -128,4 +132,67 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("round-trips non-null settlement values through the thread row", () =>
|
||||
Effect.gen(function* () {
|
||||
const threads = yield* ProjectionThreadRepository;
|
||||
|
||||
yield* threads.upsert({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Settled thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurnId: null,
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-25T00:00:00.000Z",
|
||||
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,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const persisted = yield* threads.getById({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
});
|
||||
const row = Option.getOrNull(persisted);
|
||||
if (!row) {
|
||||
return yield* Effect.die("Expected settled projection_threads row to exist.");
|
||||
}
|
||||
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 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"),
|
||||
});
|
||||
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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
Loaded 100 of 347 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user