Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5df247241 | ||
|
|
abc19a4c41 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
description: Launch, retain, and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, cross-turn dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, iteratively test UI behavior with a human, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
---
|
||||
|
||||
# Test T3 App
|
||||
@@ -13,35 +13,13 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
|
||||
2. Choose a base directory that belongs only to the current worktree or test:
|
||||
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
|
||||
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
|
||||
3. Start the full web stack with `bun run dev`. Use `bun run dev:share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.
|
||||
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
|
||||
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
|
||||
|
||||
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
|
||||
|
||||
The worktree-local default deliberately outranks an ambient `T3CODE_HOME`; do not pass the shared home through to a worktree dev server.
|
||||
|
||||
Ports are derived from the worktree path but can shift when occupied. Always read the actual values from the `[dev-runner]` line.
|
||||
|
||||
Shared browser dev is single-origin: Vite proxies the backend paths, so never set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
|
||||
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
|
||||
|
||||
### Verify a shared environment before human handoff
|
||||
|
||||
When another person will use the printed pairing URL, first open the shared origin without the pairing path or fragment in the controlled browser and confirm the T3 Code app loads. This browser navigation is required even when curl succeeds because browsers block some otherwise reachable ports before making a network request.
|
||||
|
||||
Do not open the other person's complete pairing URL during this reachability check; doing so consumes its one-time token. If the agent also needs an authenticated browser, create and consume a separate pairing token, then leave a fresh token for the other person.
|
||||
|
||||
## Preserve the environment while iterating
|
||||
|
||||
Treat the overall testing or implementation loop—not an assistant turn or one verification pass—as the environment lifecycle boundary.
|
||||
|
||||
- Keep the dev process, base directory, selected ports, authenticated browser tab, registered projects, and seeded fixtures alive while the user may inspect the result or request follow-up changes.
|
||||
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
|
||||
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
|
||||
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
|
||||
@@ -54,45 +32,40 @@ Treat pairing URLs as secrets. Do not copy them into final responses, screenshot
|
||||
|
||||
## Recover a consumed or expired pairing token
|
||||
|
||||
Ask the running server for a fresh pairing URL:
|
||||
Create another token against the same database and web URL as the running dev server:
|
||||
|
||||
```bash
|
||||
bun run dev:pair
|
||||
bun run dev:pair -- --base-dir <base-dir>
|
||||
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
|
||||
```
|
||||
|
||||
It finds the live server state under either the `dev` or `userdata` state directory and reuses the recorded web origin, including a tailnet URL. Pass `--base-dir` only when the server was started with `--home-dir`. Use the printed URL once.
|
||||
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.
|
||||
|
||||
An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before changing the database.
|
||||
|
||||
- Use `node apps/server/scripts/t3-sqlite-state.ts query` for schema discovery and read-only checks.
|
||||
- To populate realistic list and thread data, stop the server and run `bun run dev:seed`, then restart it. This copies recent projections from the shared home while refusing to write to it. It also refuses to run while a server is still using the target directory, so stop the server first rather than expecting the seed to wait.
|
||||
- Stop the dev server before using `node apps/server/scripts/t3-sqlite-state.ts exec`, then restart it with the same base directory.
|
||||
- Seed projection tables only for disposable UI fixtures. Use application commands and APIs when testing business behavior or projection correctness.
|
||||
- Use the auth CLI, not direct `auth_*` table edits, for pairing and sessions.
|
||||
|
||||
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
|
||||
|
||||
## Tear down only when the testing loop is finished
|
||||
## Finish the test
|
||||
|
||||
Tear down when the user explicitly asks, confirms the iteration is finished, or the overall task is genuinely complete with no pending human review. Do not infer completion from the end of an assistant turn.
|
||||
|
||||
When teardown is appropriate:
|
||||
|
||||
1. Stop the dev process with its terminal interrupt.
|
||||
2. Preserve the isolated base directory when it contains useful reproduction evidence or state for a likely follow-up.
|
||||
3. Otherwise remove only a path created for this test after resolving and verifying the exact target.
|
||||
|
||||
If completion is uncertain, keep the environment alive and mention that it is retained for further iteration. A fresh isolated base directory remains the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
|
||||
## Troubleshoot predictably
|
||||
|
||||
- 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, run `bun run dev:pair`. Add `-- --base-dir <base-dir>` only when the server was started with `--home-dir`.
|
||||
- If the replacement token is rejected, verify that `dev:pair` and the server resolve the same base directory.
|
||||
- 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 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`.
|
||||
@@ -1,4 +1,4 @@
|
||||
interface:
|
||||
display_name: "T3 App Testing"
|
||||
short_description: "Launch and retain isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 environment and iteratively test it in the browser while preserving state."
|
||||
short_description: "Launch and seed isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
|
||||
@@ -49,8 +49,6 @@ The web UI primarily reads these projection tables:
|
||||
- `projection_pending_approvals`
|
||||
- `projection_thread_proposed_plans`
|
||||
|
||||
`projection_state` holds one cursor row per projector and is not read by the UI, but a fixture that omits it still breaks: `computeSnapshotSequence` returns 0 unless every projector has a row, which makes every shell snapshot advertise sequence 0. Write all of them (`PROJECTOR_NAMES` in `scripts/lib/projection-tables.ts`), at a sequence no higher than the event log actually reaches.
|
||||
|
||||
Inspect `PRAGMA table_info(<table>)` and the current migrations under `apps/server/src/persistence/Migrations/` before constructing inserts. Keep identifiers unique, timestamps as ISO strings, JSON columns valid, and related project/thread/turn IDs consistent.
|
||||
|
||||
For a substantial current example, inspect `seedDatabase` in `scripts/mobile-showcase-environment.ts`. Adapt its column set to the target database instead of assuming copied SQL remains current.
|
||||
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -88,7 +88,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
ALCHEMY_TELEMETRY_DISABLED: "1"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ jobs:
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
T3_SHOWCASE_ANDROID_ABI: x86_64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -81,7 +81,7 @@ jobs:
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -189,7 +189,7 @@ jobs:
|
||||
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -266,7 +266,7 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
@@ -678,7 +678,7 @@ jobs:
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -799,7 +799,7 @@ jobs:
|
||||
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -909,7 +909,7 @@ jobs:
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
@@ -982,7 +982,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
|
||||
@@ -13,16 +13,6 @@
|
||||
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
|
||||
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
|
||||
|
||||
## Dev Servers
|
||||
|
||||
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
|
||||
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
|
||||
- Use `vp run dev:pair` to issue a fresh URL for the running server without reconstructing its port or origin.
|
||||
- Use `vp run dev:seed` while the server is stopped to populate an isolated database with recent projects and threads from the shared home. It refuses to run against a directory a live server is using.
|
||||
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
|
||||
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
|
||||
|
||||
## Package Roles
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
|
||||
@@ -472,10 +472,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -497,18 +493,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
@@ -518,38 +504,20 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProjectGroup,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
@@ -845,31 +813,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. 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;
|
||||
// fact when a query is active. Pending tasks render in the header, so the
|
||||
// list showing them isn't empty in the user's eyes.
|
||||
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."
|
||||
/>
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
|
||||
@@ -399,10 +399,6 @@ function ThreadNavigationSidebarPane(
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -424,18 +420,8 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
@@ -443,38 +429,20 @@ function ThreadNavigationSidebarPane(
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Enabled,
|
||||
threads,
|
||||
selectedProjectScope,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const listItems = useMemo<readonly SidebarListItem[]>(() => {
|
||||
if (!threadListV2Enabled) return listLayout.items;
|
||||
// Queued offline tasks render above the thread rows (mirrors the
|
||||
@@ -962,28 +930,15 @@ 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
|
||||
? 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"}
|
||||
? "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
|
||||
@@ -77,85 +77,6 @@ describe("sortThreadsForListV2", () => {
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("hides snoozed threads and counts them — visibility parity with web", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("woken"),
|
||||
title: "Woken",
|
||||
// Wake time already passed: back in the active list.
|
||||
snoozedUntil: "2026-06-01T18:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
// Same createdAt → static sort tiebreaks by id; the point is the woken
|
||||
// thread is BACK in the card block and the snoozed one is gone.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("classifies snooze with the second-precise clock and reports the next wake", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("just-woke"),
|
||||
title: "Just woke",
|
||||
// Woke 30s ago: hidden under the minute-floored clock, visible
|
||||
// under the precise one.
|
||||
snoozedUntil: "2026-06-02T00:00:30.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("still-snoozed"),
|
||||
title: "Still snoozed",
|
||||
snoozedUntil: "2026-06-02T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
// Minute-floored partition clock vs precise snooze clock.
|
||||
now: "2026-06-02T00:01:00.000Z",
|
||||
snoozeNow: "2026-06-02T00:01:07.500Z",
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["just-woke"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
|
||||
});
|
||||
|
||||
it("keeps snoozed threads visible on environments without the snooze capability", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
snoozeEnvironmentIds: new Set(),
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
|
||||
expect(layout.snoozedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("partitions settled threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
@@ -84,13 +84,6 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,22 +106,13 @@ export function buildThreadListV2Items(input: {
|
||||
other environments never classify as settled — the user could neither
|
||||
un-settle nor pin them. Absent = no gating (tests). */
|
||||
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
/** Environments whose server supports thread.snooze/unsnooze. Same
|
||||
contract as settlementEnvironmentIds. */
|
||||
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
readonly now?: string;
|
||||
/** Second-precise clock for snooze classification. Callers pass a
|
||||
minute-quantized `now` for memoization; snooze wake times are
|
||||
second-precise, so classifying with the floored minute would hold a
|
||||
woken thread hidden for up to a minute. Defaults to `now`. */
|
||||
readonly snoozeNow?: string;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const projectKeys = input.projectRefs
|
||||
@@ -137,8 +121,6 @@ export function buildThreadListV2Items(input: {
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
let snoozedCount = 0;
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
@@ -148,23 +130,8 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: a snoozed thread leaves the list until it
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozedCount += 1;
|
||||
if (
|
||||
thread.snoozedUntil != null &&
|
||||
(nextSnoozeWakeAt === null ||
|
||||
parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
|
||||
) {
|
||||
nextSnoozeWakeAt = thread.snoozedUntil;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
@@ -201,10 +168,5 @@ export function buildThreadListV2Items(input: {
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
|
||||
}
|
||||
@@ -60,8 +60,6 @@ function threadDetailToShell(
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
snoozedUntil: thread.snoozedUntil ?? null,
|
||||
snoozedAt: thread.snoozedAt ?? null,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: latestUserMessageAt(thread),
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -8,13 +8,9 @@ import * as ServerConfig from "../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as PairingGrantStore from "./PairingGrantStore.ts";
|
||||
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
|
||||
import { resolveSessionCookieName } from "./utils.ts";
|
||||
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
/** Pinned so dev-mode cookie tests can assert the port-scoped name. */
|
||||
const TEST_SERVER_PORT = 13_773;
|
||||
|
||||
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
|
||||
Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
@@ -23,12 +19,6 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
// Last, so the port cannot be overridden out from under
|
||||
// makeCookieRequest — which builds the cookie name from this constant.
|
||||
// An override that changed it would leave the server reading
|
||||
// t3_session_<other> while every request still sent t3_session_13773,
|
||||
// and the tests would fail for a reason unrelated to what they assert.
|
||||
port: TEST_SERVER_PORT,
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
|
||||
@@ -45,9 +35,7 @@ const makeCookieRequest = (
|
||||
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
// Derived, not hardcoded: the name is port-scoped so concurrent servers
|
||||
// on one hostname don't share a cookie.
|
||||
[resolveSessionCookieName({ port: TEST_SERVER_PORT, devUrl: undefined })]: sessionToken,
|
||||
t3_session: sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<
|
||||
|
||||
@@ -438,7 +438,6 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput,
|
||||
@@ -747,13 +746,11 @@ export const make = Effect.gen(function* () {
|
||||
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) =>
|
||||
createPairingLink({
|
||||
scopes: input.scopes,
|
||||
subject: input.subject,
|
||||
...(input.label ? { label: input.label } : {}),
|
||||
...(input.purpose ? { purpose: input.purpose } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
@@ -777,7 +774,6 @@ export const make = Effect.gen(function* () {
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
...(input?.purpose ? { purpose: input.purpose } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
@@ -876,7 +872,6 @@ export const make = Effect.gen(function* () {
|
||||
issuePairingCredentialForSubject({
|
||||
scopes: AuthAdministrativeScopes,
|
||||
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
|
||||
purpose: "startup",
|
||||
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
|
||||
|
||||
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
|
||||
|
||||
@@ -34,7 +34,7 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session");
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
@@ -75,24 +75,6 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
port: 13773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("scopes session cookies by port only in development", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
port: 13773,
|
||||
devUrl: new URL("http://127.0.0.1:5733"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -38,7 +38,10 @@ export const make = Effect.gen(function* () {
|
||||
policy,
|
||||
bootstrapMethods,
|
||||
sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],
|
||||
sessionCookieName: resolveSessionCookieName({ port: config.port, devUrl: config.devUrl }),
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
}),
|
||||
};
|
||||
|
||||
return EnvironmentAuthPolicy.of({
|
||||
|
||||
@@ -202,11 +202,6 @@ export class PairingGrantStore extends Context.Service<
|
||||
readonly subject?: string;
|
||||
readonly label?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
/**
|
||||
* "startup" marks the credential the server mints for itself at boot,
|
||||
* which gets the long dev TTL when a dev URL is configured.
|
||||
*/
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthPairingLink>,
|
||||
@@ -248,15 +243,6 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
||||
// window can still recover by re-bootstrapping rather than locking
|
||||
// the user out of the backend.
|
||||
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
|
||||
// A dev server's startup token is read off a log by whoever (or whatever) is
|
||||
// driving the session, often minutes later — after a `node --watch` restart, a
|
||||
// detour into another task, or a hand-off to the person actually doing the
|
||||
// testing. Five minutes turns that into a restart-the-server loop for no
|
||||
// security benefit: the token only unlocks a local dev backend, and its holder
|
||||
// could read the log anyway. Same reasoning (and duration) as the desktop
|
||||
// bootstrap grant above. Only applies when a dev URL is configured; user-issued
|
||||
// pairing links and real servers keep the 5-minute default.
|
||||
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
|
||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
const PAIRING_TOKEN_LENGTH = 12;
|
||||
const PAIRING_TOKEN_REJECTION_LIMIT =
|
||||
@@ -385,10 +371,7 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const credential = yield* generatePairingToken;
|
||||
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
|
||||
const ttl =
|
||||
input?.ttl ??
|
||||
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
|
||||
@@ -468,8 +468,8 @@ export const make = Effect.gen(function* () {
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
devUrl: serverConfig.devUrl,
|
||||
});
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
|
||||
@@ -10,17 +10,15 @@ import * as Result from "effect/Result";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
/**
|
||||
* Cookies are scoped by host but *not* by port, so concurrent dev servers on a
|
||||
* hostname need separate names. Hosted deployments keep the stable production
|
||||
* name: their public port can change between releases, and scoping it would log
|
||||
* every user out.
|
||||
*/
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
readonly devUrl: URL | undefined;
|
||||
}): string {
|
||||
return input.devUrl === undefined ? SESSION_COOKIE_NAME : `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
|
||||
@@ -84,7 +84,6 @@ const makeCliTestServerConfig = (baseDir: string) =>
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
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("prefers a legacy dev state without a dev URL", () =>
|
||||
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,
|
||||
});
|
||||
yield* writeRuntimeState({
|
||||
baseDir: config.baseDir,
|
||||
stateDir: "dev",
|
||||
pid: process.pid,
|
||||
port: 16_602,
|
||||
});
|
||||
|
||||
const live = Option.getOrThrow(yield* findLiveServerRuntimeState(config));
|
||||
assert.equal(live.stateDir, path.join(config.baseDir, "dev"));
|
||||
assert.equal(live.state.port, 16_602);
|
||||
}).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)),
|
||||
);
|
||||
});
|
||||
+10
-154
@@ -3,14 +3,11 @@ 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";
|
||||
@@ -22,11 +19,6 @@ import {
|
||||
formatSessionList,
|
||||
} from "../cliAuthFormat.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import {
|
||||
isPersistedServerRuntimeStateLive,
|
||||
type PersistedServerRuntimeState,
|
||||
readPersistedServerRuntimeState,
|
||||
} from "../serverRuntimeState.ts";
|
||||
import {
|
||||
authLocationFlags,
|
||||
type CliAuthLocationFlags,
|
||||
@@ -34,24 +26,6 @@ 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>,
|
||||
@@ -62,10 +36,18 @@ 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(environmentAuthLayer(config, options?.quietLogs ?? false)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(EnvironmentAuth.runtimeLayer).pipe(
|
||||
Layer.provide(ServerConfig.layer(config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const ttlFlag = Flag.string("ttl").pipe(
|
||||
@@ -131,127 +113,6 @@ 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. Older runtime-state files predate
|
||||
// that field, but an implicit dev server still lives in `<base>/dev`, which is
|
||||
// enough to prefer it over a production-style `<base>/userdata` server.
|
||||
const devStateDir = path.join(config.baseDir, "dev");
|
||||
return Option.fromNullishOr(
|
||||
live.find((candidate) => candidate.state.devUrl !== undefined) ??
|
||||
live.find((candidate) => candidate.stateDir === devStateDir) ??
|
||||
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);
|
||||
// Quieted here rather than only around the issuing layer below: probing
|
||||
// reads both state directories, and a corrupt file in the one *not* in
|
||||
// use logs a Warn to stdout — ahead of the payload, breaking `--json`
|
||||
// for any consumer piping it. The warning is about a file the command
|
||||
// then ignores, so under --json it is noise either way.
|
||||
const live = yield* findLiveServerRuntimeState(config).pipe(
|
||||
Effect.provide(
|
||||
Layer.succeed(References.MinimumLogLevel, flags.json ? "Error" : config.logLevel),
|
||||
),
|
||||
);
|
||||
|
||||
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,
|
||||
@@ -295,12 +156,7 @@ const pairingRevokeCommand = Command.make("revoke", {
|
||||
|
||||
const pairingCommand = Command.make("pairing").pipe(
|
||||
Command.withDescription("Manage one-time client pairing tokens."),
|
||||
Command.withSubcommands([
|
||||
pairingCreateCommand,
|
||||
pairingUrlCommand,
|
||||
pairingListCommand,
|
||||
pairingRevokeCommand,
|
||||
]),
|
||||
Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
|
||||
);
|
||||
|
||||
const sessionIssueCommand = Command.make("issue", {
|
||||
|
||||
@@ -48,7 +48,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
devAllowedOrigins: [],
|
||||
} as const;
|
||||
|
||||
const openBootstrapFd = Effect.fn(function* (payload: DesktopBackendBootstrapValue) {
|
||||
@@ -96,8 +95,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
T3CODE_HOST: "0.0.0.0",
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
T3CODE_DEV_ALLOWED_ORIGINS:
|
||||
"https://host.example.ts.net, https://phone.example.ts.net ",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
@@ -120,7 +117,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
host: "0.0.0.0",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
devAllowedOrigins: ["https://host.example.ts.net", "https://phone.example.ts.net"],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -106,15 +106,6 @@ const EnvServerConfig = Config.all({
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devAllowedOrigins: Config.string("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
|
||||
Config.withDefault(""),
|
||||
Config.map((value) =>
|
||||
value
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0),
|
||||
),
|
||||
),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
@@ -372,7 +363,6 @@ export const resolveServerConfig = (
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
devAllowedOrigins: env.devAllowedOrigins,
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
|
||||
@@ -47,13 +47,6 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,7 +72,6 @@ export class ServerConfig extends Context.Service<
|
||||
readonly baseDir: string;
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly devAllowedOrigins: ReadonlyArray<string>;
|
||||
readonly noBrowser: boolean;
|
||||
readonly startupPresentation: StartupPresentation;
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
@@ -106,9 +98,10 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
options: DeriveServerPathsOptions = {},
|
||||
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
|
||||
const { join } = yield* Path.Path;
|
||||
const stateDir =
|
||||
options.stateDir ??
|
||||
join(baseDir, devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata");
|
||||
const 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");
|
||||
@@ -194,7 +187,6 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
});
|
||||
|
||||
@@ -43,7 +43,6 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
|
||||
@@ -141,7 +141,6 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
+1
-14
@@ -4,7 +4,6 @@ import {
|
||||
AuthOrchestrationReadScope,
|
||||
EnvironmentHttpApi,
|
||||
} from "@t3tools/contracts";
|
||||
import { isDevProxiedPath } from "@t3tools/shared/devProxy";
|
||||
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -49,17 +48,9 @@ export const browserApiCorsLayer = Layer.unwrap(
|
||||
const devOrigin = config.devUrl?.origin;
|
||||
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
|
||||
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
|
||||
//
|
||||
// T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
|
||||
// origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
|
||||
// through Vite and is same-origin (no preflight at all), so this is a
|
||||
// safety net for the desktop renderer and any direct-to-backend caller.
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin
|
||||
? {
|
||||
allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
|
||||
credentials: true,
|
||||
}
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
: {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
@@ -225,10 +216,6 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
|
||||
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
|
||||
status: 302,
|
||||
|
||||
@@ -609,8 +609,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -681,38 +679,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.snoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: event.payload.snoozedUntil,
|
||||
snoozedAt: event.payload.snoozedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unsnoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -310,8 +310,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -424,8 +422,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
|
||||
@@ -336,8 +336,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -368,8 +366,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -402,8 +398,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -768,8 +762,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -1204,8 +1196,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1406,8 +1396,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1539,8 +1527,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1677,8 +1663,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1921,8 +1905,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
@@ -2019,8 +2001,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
|
||||
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -40,8 +38,6 @@ export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSet
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
|
||||
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -1,286 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
// The decider's clock is the Effect test clock, pinned to the epoch, so
|
||||
// "future" wake times are relative to 1970-01-01T00:00:00.000Z.
|
||||
const FUTURE_WAKE = "1970-01-02T09:00:00.000Z";
|
||||
const PAST_WAKE = "1969-12-31T09:00:00.000Z";
|
||||
const SNOOZED_AT = "1969-12-30T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(input: {
|
||||
readonly snoozedUntil?: string | null;
|
||||
readonly snoozedAt?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
readonly activities?: OrchestrationThread["activities"];
|
||||
readonly messages?: OrchestrationThread["messages"];
|
||||
}): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: input.archivedAt ?? null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: input.snoozedUntil ?? null,
|
||||
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
|
||||
deletedAt: null,
|
||||
messages: input.messages ?? [],
|
||||
proposedPlans: [],
|
||||
activities: input.activities ?? [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("snoozed thread decider", (it) => {
|
||||
it.effect("snoozes a thread to a future wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.snoozed");
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe(FUTURE_WAKE);
|
||||
expect(events[0].payload.snoozedAt).toBe(events[0].payload.updatedAt);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a wake time that is not in the future", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-past"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: PAST_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects an unparseable wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
// IsoDateTime is structurally a string, so garbage can reach the
|
||||
// decider; a NaN wake time must never persist as snooze state.
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-garbage"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "not-a-date",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing blocked-on-you work", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestActivity = {
|
||||
id: EventId.make("activity-req-1"),
|
||||
tone: "approval" as const,
|
||||
kind: "approval.requested",
|
||||
summary: "approval.requested",
|
||||
payload: { requestId: "req-1" },
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
} as OrchestrationThread["activities"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-blocked"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ activities: [requestActivity] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-emits idempotently for a duplicate snooze to the same wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const reEmit = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(reEmit) ? reEmit : [reEmit];
|
||||
expect(events).toHaveLength(1);
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
// Original snoozedAt preserved; updatedAt must not churn.
|
||||
expect(events[0].payload.snoozedAt).toBe(SNOOZED_AT);
|
||||
expect(events[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-snoozing to a DIFFERENT wake time stamps fresh", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-extend"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "1970-01-03T09:00:00.000Z",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe("1970-01-03T09:00:00.000Z");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unsnoozes with reason user and re-emits idempotently when awake", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events[0]?.type).toBe("thread.unsnoozed");
|
||||
if (events[0]?.type === "thread.unsnoozed") {
|
||||
expect(events[0].payload.reason).toBe("user");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
|
||||
const awake = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze-awake"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const awakeEvents = Array.isArray(awake) ? awake : [awake];
|
||||
expect(awakeEvents[0]?.type).toBe("thread.unsnoozed");
|
||||
if (awakeEvents[0]?.type === "thread.unsnoozed") {
|
||||
// No state change — keep the existing updatedAt.
|
||||
expect(awakeEvents[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing a thread with a queued turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
// The decider clock is the Effect test clock pinned to the epoch: a
|
||||
// user message 30s before it with no adopting turn is queued work.
|
||||
const queuedMessage = {
|
||||
id: MessageId.make("message-queued"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "1969-12-31T23:59:30.000Z",
|
||||
updatedAt: "1969-12-31T23:59:30.000Z",
|
||||
} as OrchestrationThread["messages"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-queued"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ messages: [queuedMessage] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing an archived thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ archivedAt: NOW }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("a user message spends the snooze return ticket (activity wake)", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-1"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
|
||||
expect(unsnoozed).toBeDefined();
|
||||
if (unsnoozed?.type === "thread.unsnoozed") {
|
||||
expect(unsnoozed.payload.reason).toBe("activity");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -53,13 +53,6 @@ function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): b
|
||||
);
|
||||
}
|
||||
|
||||
// Scans the read model's activities, which the projector caps at the most
|
||||
// recent 500. That bound is safe here: an OPEN approval/user-input request
|
||||
// blocks its turn, so the thread cannot accumulate hundreds of later
|
||||
// activities while one is outstanding — a request that has scrolled out of
|
||||
// the window is one whose turn kept running, i.e. it was resolved or went
|
||||
// stale. (The projection pipeline's pendingApprovalCount reads the same
|
||||
// capped stream and stays consistent with this view.)
|
||||
function hasOpenBlockingRequest(thread: {
|
||||
readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
|
||||
}): boolean {
|
||||
@@ -86,62 +79,6 @@ function hasOpenBlockingRequest(thread: {
|
||||
return openRequestIds.size > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A queued turn start — a user message no turn has picked up yet — is work
|
||||
* in flight even though session is still null (turn.start emits
|
||||
* message-sent + turn-start-requested; the session arrives later). Detection
|
||||
* mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
* strictly newer than every latestTurn timestamp (adoption stamps the new
|
||||
* turn's requestedAt with the message time, clearing this), and only within
|
||||
* the adoption grace window — historical threads whose last user message
|
||||
* postdates their turn timestamps (older-server data, mid-turn messages)
|
||||
* must not be blocked forever. A failed session start (status "error")
|
||||
* clears the block immediately.
|
||||
*
|
||||
* The age check is bounded on BOTH sides: message timestamps are
|
||||
* client-supplied, so a client clock ahead of the server yields a negative
|
||||
* age. Without the lower bound that negative age satisfies `<= grace` for
|
||||
* as long as the skew lasts, extending the block far past the intended two
|
||||
* minutes.
|
||||
*/
|
||||
function threadHasQueuedTurnStart(
|
||||
thread: {
|
||||
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
|
||||
readonly latestTurn: {
|
||||
readonly requestedAt: string;
|
||||
readonly startedAt: string | null;
|
||||
readonly completedAt: string | null;
|
||||
} | null;
|
||||
readonly session: { readonly status: string } | null;
|
||||
},
|
||||
occurredAt: string,
|
||||
): boolean {
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
return (
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS
|
||||
);
|
||||
}
|
||||
|
||||
function withEventBase(
|
||||
input: Pick<OrchestrationCommand, "commandId"> & {
|
||||
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
|
||||
@@ -474,8 +411,46 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
);
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
// Settling inside the adoption window would hide just-requested work.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
// A queued turn start — a user message no turn has picked up yet — is
|
||||
// work in flight even though session is still null (turn.start emits
|
||||
// message-sent + turn-start-requested; the session arrives later).
|
||||
// Settling in that window would hide just-requested work. Detection
|
||||
// mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
// strictly newer than every latestTurn timestamp (adoption stamps the
|
||||
// new turn's requestedAt with the message time, clearing this), and
|
||||
// only within the adoption grace window — historical threads whose
|
||||
// last user message postdates their turn timestamps (older-server
|
||||
// data, mid-turn messages) must stay settleable. A failed session
|
||||
// start (status "error") clears the block immediately.
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
// The age check is bounded on BOTH sides: message timestamps are
|
||||
// client-supplied, so a client clock ahead of the server yields a
|
||||
// negative age. Without the lower bound that negative age satisfies
|
||||
// `<= grace` for as long as the skew lasts, extending the settle
|
||||
// block far past the intended two minutes.
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
const hasQueuedTurnStart =
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS;
|
||||
if (hasQueuedTurnStart) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
@@ -533,103 +508,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.snooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
// A wake time in the past would create a thread that is snoozed and
|
||||
// woken at once — the row would never leave the inbox but still carry
|
||||
// snooze state. Reject instead of silently normalizing. The negated
|
||||
// comparison also catches unparseable wake times (IsoDateTime is
|
||||
// structurally just a string): NaN fails every comparison, and an
|
||||
// unparseable snoozedUntil must never persist.
|
||||
if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Blocked-on-you work must not be snoozed away: a pending approval or
|
||||
// user-input request is the agent waiting on the user, and hiding it
|
||||
// defeats the request. (A running session IS snoozable — snooze only
|
||||
// affects visibility, never the agent.)
|
||||
if (hasOpenBlockingRequest(thread)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// A queued turn start — a user message no turn has adopted yet — is
|
||||
// invisible pending work: no session, no pending flags. Snoozing in
|
||||
// that window would hide a just-requested turn exactly the way settle
|
||||
// would.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Re-snoozing an already-snoozed thread to the SAME wake time is a
|
||||
// duplicate (double-click, raced clients): re-emit with the original
|
||||
// timestamps so the projection is a no-op. A different wake time is a
|
||||
// real change and stamps fresh.
|
||||
const existingSnoozedAt =
|
||||
thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
|
||||
? thread.snoozedAt
|
||||
: null;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.snoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
snoozedUntil: command.snoozedUntil,
|
||||
snoozedAt: existingSnoozedAt ?? occurredAt,
|
||||
updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unsnooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Idempotent by re-emission (see thread.settle): waking a thread that
|
||||
// is not snoozed lands on the same null state without churning
|
||||
// updatedAt.
|
||||
const alreadyAwake = thread.snoozedUntil == null;
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: command.reason,
|
||||
updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
@@ -785,42 +663,24 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
// Real activity resets ANY override: it wakes an explicitly settled
|
||||
// thread, and it clears a keep-active pin back to neutral so the
|
||||
// thread can auto-settle again after this burst of work goes stale.
|
||||
// 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.settledOverride === null) {
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
if (targetThread.snoozedUntil != null) {
|
||||
lifecycleResetEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
|
||||
case "thread.turn.interrupt": {
|
||||
@@ -962,12 +822,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
// Only a session coming alive is activity worth waking a settled thread
|
||||
// for — status writes like ready/stopped/error arrive after the fact and
|
||||
// must not fight a user's explicit settle. 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.
|
||||
// must not fight a user's explicit settle.
|
||||
const isSessionActivity =
|
||||
command.session.status === "starting" || command.session.status === "running";
|
||||
// Real activity resets ANY override (settled wakes, active unpins).
|
||||
|
||||
@@ -91,8 +91,6 @@ describe("orchestration projector", () => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -23,10 +23,8 @@ import {
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadSnoozedPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadUnsnoozedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -292,8 +290,6 @@ export function projectEvent(
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -369,30 +365,6 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.snoozed":
|
||||
return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: payload.snoozedUntil,
|
||||
snoozedAt: payload.snoozedAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unsnoozed":
|
||||
return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
@@ -93,8 +93,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -155,8 +153,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-03-25T00:00:00.000Z",
|
||||
snoozedUntil: "2026-03-26T09:00:00.000Z",
|
||||
snoozedAt: "2026-03-25T00:00:00.000Z",
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -173,17 +169,12 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
}
|
||||
assert.strictEqual(row.settledOverride, "settled");
|
||||
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
|
||||
|
||||
// Un-settle to the keep-active pin and wake the snooze; confirm the
|
||||
// flips persist.
|
||||
// Un-settle to the keep-active pin and confirm the flip persists.
|
||||
yield* threads.upsert({
|
||||
...row,
|
||||
settledOverride: "active",
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
});
|
||||
const repersisted = yield* threads.getById({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
@@ -191,8 +182,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
const updated = Option.getOrNull(repersisted);
|
||||
assert.strictEqual(updated?.settledOverride, "active");
|
||||
assert.strictEqual(updated?.settledAt, null);
|
||||
assert.strictEqual(updated?.snoozedUntil, null);
|
||||
assert.strictEqual(updated?.snoozedAt, null);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -45,8 +45,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
snoozed_until,
|
||||
snoozed_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
@@ -68,8 +66,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.archivedAt},
|
||||
${row.settledOverride},
|
||||
${row.settledAt},
|
||||
${row.snoozedUntil},
|
||||
${row.snoozedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -91,8 +87,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at = excluded.archived_at,
|
||||
settled_override = excluded.settled_override,
|
||||
settled_at = excluded.settled_at,
|
||||
snoozed_until = excluded.snoozed_until,
|
||||
snoozed_at = excluded.snoozed_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
@@ -121,8 +115,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -153,8 +145,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
|
||||
@@ -46,7 +46,6 @@ import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.
|
||||
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
|
||||
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
|
||||
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
|
||||
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -92,7 +91,6 @@ export const migrationEntries = [
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (!columns.some((column) => column.name === "snoozed_until")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_until TEXT
|
||||
`;
|
||||
}
|
||||
|
||||
if (!columns.some((column) => column.name === "snoozed_at")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_at TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -38,8 +38,6 @@ export const ProjectionThread = Schema.Struct({
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
|
||||
settledAt: Schema.NullOr(IsoDateTime),
|
||||
snoozedUntil: Schema.NullOr(IsoDateTime),
|
||||
snoozedAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
|
||||
@@ -530,29 +530,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("preserves xhigh effort for Claude Opus 5", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
"claude-opus-5",
|
||||
[{ id: "effort", value: "xhigh" }],
|
||||
),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, "xhigh");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -51,7 +51,6 @@ const CLAUDE_PRESENTATION = {
|
||||
displayName: "Claude",
|
||||
showInteractionModeToggle: true,
|
||||
} as const;
|
||||
const MINIMUM_CLAUDE_OPUS_5_VERSION = "2.1.219";
|
||||
const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
|
||||
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
|
||||
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
|
||||
@@ -88,42 +87,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-5",
|
||||
name: "Claude Opus 5",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultracode", label: "Ultracode" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
// Claude Code selects the 1M variant explicitly (`claude-opus-5[1m]`).
|
||||
options: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-8",
|
||||
name: "Claude Opus 4.8",
|
||||
@@ -309,10 +272,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
},
|
||||
];
|
||||
|
||||
function supportsClaudeOpus5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;
|
||||
}
|
||||
|
||||
function supportsClaudeFable5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
|
||||
}
|
||||
@@ -329,9 +288,6 @@ function getBuiltInClaudeModelsForVersion(
|
||||
version: string | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
return BUILT_IN_MODELS.filter((model) => {
|
||||
if (model.slug === "claude-opus-5") {
|
||||
return supportsClaudeOpus5(version);
|
||||
}
|
||||
if (model.slug === "claude-fable-5") {
|
||||
return supportsClaudeFable5(version);
|
||||
}
|
||||
@@ -345,11 +301,6 @@ function getBuiltInClaudeModelsForVersion(
|
||||
});
|
||||
}
|
||||
|
||||
function formatClaudeOpus5UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Opus 5. Upgrade to v${MINIMUM_CLAUDE_OPUS_5_VERSION} or newer to access it.`;
|
||||
}
|
||||
|
||||
function formatClaudeFable5UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;
|
||||
@@ -409,7 +360,6 @@ export function normalizeClaudeCliEffort(
|
||||
if (
|
||||
effort === "xhigh" &&
|
||||
model !== "claude-fable-5" &&
|
||||
model !== "claude-opus-5" &&
|
||||
model !== "claude-opus-4-8" &&
|
||||
model !== "claude-sonnet-5"
|
||||
) {
|
||||
@@ -887,15 +837,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const versionUpgradeMessage = supportsClaudeOpus5(parsedVersion)
|
||||
const versionUpgradeMessage = supportsClaudeFable5(parsedVersion)
|
||||
? undefined
|
||||
: supportsClaudeFable5(parsedVersion)
|
||||
? formatClaudeOpus5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
|
||||
const capabilities = resolveCapabilities
|
||||
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
|
||||
|
||||
@@ -1842,62 +1842,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes Claude Opus 5 on supported Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
const opus5 = status.models.find((model) => model.slug === "claude-opus-5");
|
||||
assert.strictEqual(opus5?.name, "Claude Opus 5");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.219\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides Claude Opus 5 on older Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.models.some((model) => model.slug === "claude-opus-5"),
|
||||
false,
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Code v2.1.218 is too old for Claude Opus 5. Upgrade to v2.1.219 or newer to access it.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.218\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes Claude Fable 5 on supported Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
|
||||
@@ -380,7 +380,6 @@ const buildAppUnderTest = (options?: {
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: defaultDesktopBootstrapToken,
|
||||
@@ -1329,7 +1328,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
"bearer-access-token",
|
||||
"dpop-access-token",
|
||||
]);
|
||||
assert.equal(body.auth.sessionCookieName, "t3_session");
|
||||
assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -3247,34 +3246,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("allows configured development origins through ServerConfig", () =>
|
||||
Effect.gen(function* () {
|
||||
const tailnetOrigin = "https://host.example.ts.net";
|
||||
yield* buildAppUnderTest({
|
||||
config: {
|
||||
devUrl: new URL(crossOriginClientOrigin),
|
||||
devAllowedOrigins: [tailnetOrigin],
|
||||
},
|
||||
});
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const response = yield* fetchEffect(sessionUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: tailnetOrigin,
|
||||
"access-control-request-method": "GET",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assertBrowserApiCorsPreflightHeaders(response.headers, {
|
||||
origin: tailnetOrigin,
|
||||
credentials: true,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
|
||||
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -43,59 +43,6 @@ describe("serverRuntimeState", () => {
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
// A server killed with SIGKILL never runs its release finalizer, so the file
|
||||
// survives it. Trusting a leftover file points callers at a dead port.
|
||||
describe("isPersistedServerRuntimeStateLive", () => {
|
||||
const stateForPid = (pid: number): ServerRuntimeState.PersistedServerRuntimeState => ({
|
||||
version: 1,
|
||||
pid,
|
||||
port: 4_971,
|
||||
origin: "http://127.0.0.1:4971",
|
||||
startedAt: "2026-06-20T00:00:00.000Z",
|
||||
});
|
||||
|
||||
it.effect("recognizes the current process as live", () =>
|
||||
Effect.gen(function* () {
|
||||
assert.isTrue(
|
||||
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(process.pid)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a pid that no longer exists as dead", () =>
|
||||
Effect.gen(function* () {
|
||||
// Above the default pid_max, so it cannot be a live process.
|
||||
assert.isFalse(
|
||||
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(0x7ffffffe)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
// `process.kill` reads non-positive pids as signal-group targets rather
|
||||
// than process lookups — 0 is the caller's own group, -1 every permitted
|
||||
// process — so neither throws, and a probe that only catches would call
|
||||
// both "live" no matter what wrote the file.
|
||||
for (const pid of [0, -1]) {
|
||||
it.effect(`reports pid ${String(pid)} as dead rather than signalling a group`, () =>
|
||||
Effect.gen(function* () {
|
||||
assert.isFalse(
|
||||
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(pid)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Out of range for a pid: process.kill throws a TypeError with no errno,
|
||||
// which the EPERM check must not assume the shape of.
|
||||
it.effect("reports an out-of-range pid as dead", () =>
|
||||
Effect.gen(function* () {
|
||||
assert.isFalse(
|
||||
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(2 ** 40)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("treats a missing runtime state file as absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -10,20 +10,10 @@ import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";
|
||||
|
||||
export const PersistedServerRuntimeState = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
/**
|
||||
* Positive: `process.kill` reads 0 and negatives as signal-group targets, so
|
||||
* a liveness probe on one reports "live" for a process that never existed.
|
||||
*/
|
||||
pid: Schema.Int.check(Schema.isGreaterThan(0)),
|
||||
pid: Schema.Int,
|
||||
host: Schema.optional(Schema.String),
|
||||
port: Schema.Int,
|
||||
origin: Schema.String,
|
||||
/**
|
||||
* The web origin users actually open in dev — the Vite server, or the shared
|
||||
* tailnet URL when the dev runner published one. Recorded so tooling can mint
|
||||
* a pairing URL for a running server without being told where it lives.
|
||||
*/
|
||||
devUrl: Schema.optional(Schema.String),
|
||||
startedAt: Schema.String,
|
||||
});
|
||||
export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
|
||||
@@ -55,7 +45,7 @@ const runtimeOriginForConfig = (
|
||||
};
|
||||
|
||||
export const makePersistedServerRuntimeState = (input: {
|
||||
readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
|
||||
readonly config: Pick<ServerConfig.ServerConfig["Service"], "host">;
|
||||
readonly port: number;
|
||||
}): Effect.Effect<PersistedServerRuntimeState> =>
|
||||
Effect.map(DateTime.now, (now) => ({
|
||||
@@ -64,7 +54,6 @@ export const makePersistedServerRuntimeState = (input: {
|
||||
...(input.config.host ? { host: input.config.host } : {}),
|
||||
port: input.port,
|
||||
origin: runtimeOriginForConfig(input.config, input.port),
|
||||
...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
|
||||
startedAt: DateTime.formatIso(now),
|
||||
}));
|
||||
|
||||
@@ -111,46 +100,6 @@ export const clearPersistedServerRuntimeState = (path: string) =>
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* `process.kill` rejects an out-of-range pid with a TypeError rather than an
|
||||
* errno, so the catch below cannot assume either shape.
|
||||
*/
|
||||
const isErrnoException = (cause: unknown): cause is NodeJS.ErrnoException =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause;
|
||||
|
||||
/**
|
||||
* Whether the process that wrote a runtime-state file is still alive.
|
||||
*
|
||||
* The file is removed by a release finalizer, so a server killed with SIGKILL —
|
||||
* or one that crashed — leaves it behind. Treating a leftover file as "the
|
||||
* server is up" points callers at a port nothing is listening on. Signal 0
|
||||
* performs the permission and existence checks without delivering a signal.
|
||||
*
|
||||
* PIDs are reused eventually, so a false positive is possible in principle;
|
||||
* that is acceptable for local dev tooling, where the alternative is an
|
||||
* HTTP probe that has to guess how long to wait for a starting server.
|
||||
*/
|
||||
export const isPersistedServerRuntimeStateLive = (
|
||||
state: PersistedServerRuntimeState,
|
||||
): Effect.Effect<boolean> =>
|
||||
Effect.sync(() => {
|
||||
// `process.kill` reads non-positive pids as signal-group targets rather
|
||||
// than process lookups: 0 signals the caller's own group and -1 every
|
||||
// permitted process, so neither throws and both would report "live"
|
||||
// unconditionally. A server never records one; a corrupt or truncated file
|
||||
// can, and that file would then be believed forever.
|
||||
if (!Number.isSafeInteger(state.pid) || state.pid <= 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
process.kill(state.pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
// EPERM means the process exists but belongs to another user.
|
||||
return isErrnoException(cause) && cause.code === "EPERM";
|
||||
}
|
||||
});
|
||||
|
||||
export const readPersistedServerRuntimeState = (path: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
@@ -140,7 +140,6 @@ import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import {
|
||||
AlarmClockIcon,
|
||||
CheckCircle2Icon,
|
||||
ChevronDownIcon,
|
||||
GitBranchIcon,
|
||||
@@ -3845,24 +3844,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
hasDedicatedWorktree: (activeThread?.worktreePath ?? null) !== null,
|
||||
});
|
||||
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
|
||||
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
|
||||
const nowMinute = useNowMinute();
|
||||
const activeThreadSnoozed =
|
||||
activeThreadShell !== null &&
|
||||
supportsSnooze &&
|
||||
effectiveSnoozed(activeThreadShell, { now: new Date().toISOString() });
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
void snoozeWakeTick;
|
||||
if (!activeThreadSnoozed) return;
|
||||
const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
|
||||
if (!Number.isFinite(wakeAtMs)) return;
|
||||
const id = window.setTimeout(
|
||||
() => bumpSnoozeWakeTick((tick) => tick + 1),
|
||||
Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
|
||||
);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
|
||||
const activeThreadSettled = useMemo(() => {
|
||||
if (activeThreadShell === null || !supportsSettlement) return false;
|
||||
return effectiveSettled(activeThreadShell, {
|
||||
@@ -3908,34 +3890,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
|
||||
}
|
||||
}, [activeThreadRef, unsettleThreadMutation]);
|
||||
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
|
||||
const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
|
||||
const handleUnsnoozeActiveThread = useCallback(async () => {
|
||||
if (!activeThreadRef) return;
|
||||
const threadKey = scopedThreadKey(activeThreadRef);
|
||||
setUnsnoozingThreadKey(threadKey);
|
||||
try {
|
||||
const result = await unsnoozeThreadMutation({
|
||||
environmentId: activeThreadRef.environmentId,
|
||||
input: { threadId: activeThreadRef.threadId, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to wake thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
|
||||
}
|
||||
}, [activeThreadRef, unsnoozeThreadMutation]);
|
||||
const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
|
||||
const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
|
||||
// Once revealed for a given mismatch, the banner stays mounted until the
|
||||
@@ -4045,48 +3999,29 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
]);
|
||||
// The stack renders items[0] front-most and tucks the rest behind hover, so
|
||||
// ordering is priority: system banners, then the branch-mismatch notice,
|
||||
// and the informational parked-thread banner last — it must never cover another.
|
||||
const parkedThreadBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
|
||||
if (!activeThreadSnoozed && !activeThreadSettled) {
|
||||
// and the informational settled banner last — it must never cover another.
|
||||
const settledComposerBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
|
||||
if (!activeThreadSettled) {
|
||||
return null;
|
||||
}
|
||||
const isSnoozed = activeThreadSnoozed;
|
||||
return {
|
||||
id: `thread-${isSnoozed ? "snoozed" : "settled"}:${activeThread?.id ?? "unknown"}`,
|
||||
id: `thread-settled:${activeThread?.id ?? "unknown"}`,
|
||||
variant: "info",
|
||||
icon: isSnoozed ? <AlarmClockIcon /> : <CheckCircle2Icon />,
|
||||
title: `This thread is ${isSnoozed ? "snoozed" : "settled"}`,
|
||||
description: isSnoozed
|
||||
? "Sending a message wakes it and moves it back to Active in the sidebar."
|
||||
: "Sending a message moves it back to Active in the sidebar.",
|
||||
icon: <CheckCircle2Icon />,
|
||||
title: "This thread is settled",
|
||||
description: "Sending a message moves it back to Active in the sidebar.",
|
||||
actions: (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isSnoozed ? isUnsnoozing : isUnsettling}
|
||||
onClick={() =>
|
||||
void (isSnoozed ? handleUnsnoozeActiveThread() : handleUnsettleActiveThread())
|
||||
}
|
||||
disabled={isUnsettling}
|
||||
onClick={() => void handleUnsettleActiveThread()}
|
||||
>
|
||||
{isSnoozed
|
||||
? isUnsnoozing
|
||||
? "Waking..."
|
||||
: "Wake now"
|
||||
: isUnsettling
|
||||
? "Un-settling..."
|
||||
: "Un-settle"}
|
||||
{isUnsettling ? "Un-settling..." : "Un-settle"}
|
||||
</Button>
|
||||
),
|
||||
};
|
||||
}, [
|
||||
activeThread?.id,
|
||||
activeThreadSettled,
|
||||
activeThreadSnoozed,
|
||||
handleUnsnoozeActiveThread,
|
||||
handleUnsettleActiveThread,
|
||||
isUnsnoozing,
|
||||
isUnsettling,
|
||||
]);
|
||||
}, [activeThread?.id, activeThreadSettled, handleUnsettleActiveThread, isUnsettling]);
|
||||
const handleRestoreThreadBranch = useCallback(() => {
|
||||
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
|
||||
setBranchRestoreConfirmOpen(true);
|
||||
@@ -4095,9 +4030,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
void handleSwitchCheckoutToThread();
|
||||
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
|
||||
const settledItems = settledComposerBannerItem === null ? [] : [settledComposerBannerItem];
|
||||
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
|
||||
return [...systemComposerBannerItems, ...parkedThreadItems];
|
||||
return [...systemComposerBannerItems, ...settledItems];
|
||||
}
|
||||
return [
|
||||
...systemComposerBannerItems,
|
||||
@@ -4140,14 +4075,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setBranchMismatchDismissTick((tick) => tick + 1);
|
||||
},
|
||||
},
|
||||
...parkedThreadItems,
|
||||
...settledItems,
|
||||
];
|
||||
}, [
|
||||
activeBranchMismatchKey,
|
||||
handleRestoreThreadBranch,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
parkedThreadBannerItem,
|
||||
settledComposerBannerItem,
|
||||
showBranchMismatchBanner,
|
||||
systemComposerBannerItems,
|
||||
]);
|
||||
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsDownUpIcon,
|
||||
ChevronsUpDownIcon,
|
||||
Columns2Icon,
|
||||
PilcrowIcon,
|
||||
Rows3Icon,
|
||||
@@ -34,7 +32,6 @@ import {
|
||||
resolveDiffThemeName,
|
||||
resolveFileDiffPath,
|
||||
} from "../lib/diffRendering";
|
||||
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
@@ -42,7 +39,6 @@ import { useClientSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
|
||||
import { Button } from "./ui/button";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
import { Switch } from "./ui/switch";
|
||||
import {
|
||||
@@ -450,8 +446,6 @@ export default function DiffPanel({
|
||||
}),
|
||||
[collapsedDiffFileKeys, renderableFiles],
|
||||
);
|
||||
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
|
||||
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath) return;
|
||||
@@ -502,18 +496,6 @@ export default function DiffPanel({
|
||||
[collapseScopeKey],
|
||||
);
|
||||
|
||||
const toggleDiffFileCollapse = useCallback(() => {
|
||||
setCollapsedDiffFiles((current) => {
|
||||
const currentKeys =
|
||||
current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
|
||||
|
||||
return {
|
||||
scopeKey: collapseScopeKey,
|
||||
fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
|
||||
};
|
||||
});
|
||||
}, [collapseScopeKey, diffFileKeys]);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!routeThreadRef) return;
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
|
||||
@@ -713,30 +695,6 @@ export default function DiffPanel({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
|
||||
{codeViewFiles.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
|
||||
onClick={toggleDiffFileCollapse}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDiffFilesCollapsed ? (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<ToggleGroup
|
||||
className="shrink-0"
|
||||
variant="outline"
|
||||
@@ -866,7 +824,7 @@ export default function DiffPanel({
|
||||
<AnnotatableCodeView
|
||||
viewerRef={codeViewRef}
|
||||
key={collapseScopeKey ?? reviewSectionId}
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto [&>div>div:last-child]:top-0! [&>div>div:last-child]:bottom-auto!"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto"
|
||||
files={codeViewFiles}
|
||||
sectionId={reviewSectionId}
|
||||
sectionTitle={reviewSectionTitle}
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveSnoozePresets, snoozeWakeDescription, snoozeWakeLabel } from "./Sidebar.snooze";
|
||||
|
||||
// Local-time constructor so preset math is timezone-stable in tests.
|
||||
function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
|
||||
return new Date(year, month - 1, day, hour, minute, 0, 0);
|
||||
}
|
||||
|
||||
describe("resolveSnoozePresets", () => {
|
||||
it("offers hour, evening, tomorrow, next week in the morning", () => {
|
||||
// Wednesday 2026-04-08 10:00 local.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
expect(presets.map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"evening",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
const evening = presets.find((preset) => preset.id === "evening");
|
||||
expect(new Date(evening!.snoozedUntil).getHours()).toBe(18);
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
const tomorrowDate = new Date(tomorrow!.snoozedUntil);
|
||||
expect(tomorrowDate.getDate()).toBe(9);
|
||||
expect(tomorrowDate.getHours()).toBe(9);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
const nextWeekDate = new Date(nextWeek!.snoozedUntil);
|
||||
expect(nextWeekDate.getDay()).toBe(1);
|
||||
expect(nextWeekDate.getDate()).toBe(13);
|
||||
});
|
||||
|
||||
it("whenLabel complements the label instead of repeating it", () => {
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
for (const preset of presets) {
|
||||
// Day words live in the label column; the time column is time-only
|
||||
// (plus a weekday for next week, which names a different day).
|
||||
expect(preset.whenLabel.toLowerCase()).not.toContain("tomorrow");
|
||||
}
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
expect(tomorrow!.whenLabel).toMatch(/9/);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
expect(nextWeek!.whenLabel).toMatch(/Mon/);
|
||||
});
|
||||
|
||||
it("drops the evening preset once evening is near or past", () => {
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 17, 30)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 21)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
});
|
||||
|
||||
it("puts next week a full week out when today is Monday", () => {
|
||||
// Monday 2026-04-06.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 6, 10));
|
||||
const nextWeek = new Date(presets.find((preset) => preset.id === "next-week")!.snoozedUntil);
|
||||
expect(nextWeek.getDay()).toBe(1);
|
||||
expect(nextWeek.getDate()).toBe(13);
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeLabel", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("formats minutes, hours, and days, rounding up", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 30 * 60_000).toISOString(), now)).toBe("30m");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 90 * 60_000).toISOString(), now)).toBe("2h");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 26 * 3_600_000).toISOString(), now)).toBe("2d");
|
||||
});
|
||||
|
||||
it("reports now for past and malformed wake times", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() - 1000).toISOString(), now)).toBe("now");
|
||||
expect(snoozeWakeLabel("not-a-date", now)).toBe("now");
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeDescription", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("uses bare time today, 'tomorrow' next day, weekday within the week", () => {
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now)).not.toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 9, 9).toISOString(), now)).toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 13, 9).toISOString(), now)).toMatch(/Mon/);
|
||||
});
|
||||
});
|
||||
@@ -1,127 +0,0 @@
|
||||
/**
|
||||
* Snooze preset resolution for the sidebar snooze menu. Pure functions so
|
||||
* the preset math (evening/tomorrow/next-week boundaries) is unit-testable
|
||||
* without a DOM.
|
||||
*
|
||||
* Presets deliberately skew short: agent-thread rhythms are hours (a CI
|
||||
* run, a teammate review, the next work session), not days.
|
||||
*/
|
||||
import { parseTimestampDate } from "../timestampFormat";
|
||||
|
||||
type SnoozePresetId = "hour" | "evening" | "tomorrow" | "next-week";
|
||||
|
||||
export interface SnoozePreset {
|
||||
readonly id: SnoozePresetId;
|
||||
readonly label: string;
|
||||
/** Menu-row time column. Complements the label instead of repeating it:
|
||||
"Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
|
||||
readonly whenLabel: string;
|
||||
/** ISO wake time. */
|
||||
readonly snoozedUntil: string;
|
||||
}
|
||||
|
||||
function timeOfDayLabel(date: Date): string {
|
||||
return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
}
|
||||
|
||||
const EVENING_HOUR = 18;
|
||||
const MORNING_HOUR = 9;
|
||||
const HOUR_MS = 60 * 60 * 1_000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
|
||||
function atHour(base: Date, hour: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setHours(hour, 0, 0, 0);
|
||||
return next;
|
||||
}
|
||||
|
||||
// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
|
||||
// land on the wrong local day across DST transitions (a spring-forward day
|
||||
// is 23 hours, so 23:30 + 24h skips the whole next day).
|
||||
function addDays(base: Date, days: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setDate(next.getDate() + days);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Presets for "snooze until", computed against local time. "This evening"
|
||||
* only appears while it is still meaningfully before evening; after that
|
||||
* the list starts at "Tomorrow".
|
||||
*/
|
||||
export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
|
||||
const inAnHour = new Date(now.getTime() + HOUR_MS);
|
||||
const presets: SnoozePreset[] = [
|
||||
{
|
||||
id: "hour",
|
||||
label: "In 1 hour",
|
||||
whenLabel: timeOfDayLabel(inAnHour),
|
||||
snoozedUntil: inAnHour.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
const evening = atHour(now, EVENING_HOUR);
|
||||
// Suppress the evening preset once it is within an hour (or past): it
|
||||
// would duplicate "In 1 hour" or point at the past.
|
||||
if (evening.getTime() - now.getTime() > HOUR_MS) {
|
||||
presets.push({
|
||||
id: "evening",
|
||||
label: "This evening",
|
||||
whenLabel: timeOfDayLabel(evening),
|
||||
snoozedUntil: evening.toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
const tomorrow = atHour(addDays(now, 1), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "tomorrow",
|
||||
label: "Tomorrow",
|
||||
whenLabel: timeOfDayLabel(tomorrow),
|
||||
snoozedUntil: tomorrow.toISOString(),
|
||||
});
|
||||
|
||||
// Next Monday 9:00 (a week out when today is Monday).
|
||||
const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
|
||||
const nextWeek = atHour(addDays(now, daysUntilMonday), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "next-week",
|
||||
label: "Next week",
|
||||
whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${timeOfDayLabel(nextWeek)}`,
|
||||
snoozedUntil: nextWeek.toISOString(),
|
||||
});
|
||||
|
||||
return presets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
|
||||
* round up so a snooze never reads "0m" while still hidden.
|
||||
*/
|
||||
export function snoozeWakeLabel(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "now";
|
||||
const remainingMs = wake.getTime() - now.getTime();
|
||||
if (remainingMs <= 0) return "now";
|
||||
if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
|
||||
if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
|
||||
return `${Math.ceil(remainingMs / DAY_MS)}d`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human wake time for menus and toasts: "tomorrow 9:00", "Mon 9:00",
|
||||
* "17:30" (today).
|
||||
*/
|
||||
export function snoozeWakeDescription(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "";
|
||||
const time = wake.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
const startOfToday = new Date(now);
|
||||
startOfToday.setHours(0, 0, 0, 0);
|
||||
const dayDelta = Math.floor((wake.getTime() - startOfToday.getTime()) / DAY_MS);
|
||||
if (dayDelta === 0) return time;
|
||||
if (dayDelta === 1) return `tomorrow ${time}`;
|
||||
const weekday = wake.toLocaleDateString(undefined, { weekday: "short" });
|
||||
if (dayDelta < 7) return `${weekday} ${time}`;
|
||||
const date = wake.toLocaleDateString(undefined, { month: "short", day: "numeric" });
|
||||
return `${date}, ${time}`;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,7 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
settledPrHoverColorClass,
|
||||
} from "./ThreadStatusIndicators";
|
||||
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
@@ -74,23 +70,4 @@ describe("prStatusIndicator", () => {
|
||||
tooltipTitle: "PR branch",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses red for closed pull requests", () => {
|
||||
const closedPr = status().pr;
|
||||
if (!closedPr) throw new Error("Expected pull request fixture");
|
||||
|
||||
expect(prStatusIndicator({ ...closedPr, state: "closed" }, undefined)?.colorClass).toContain(
|
||||
"text-red-600",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("settledPrHoverColorClass", () => {
|
||||
it.each([
|
||||
["open", "text-emerald-600"],
|
||||
["merged", "text-violet-600"],
|
||||
["closed", "text-red-600"],
|
||||
] as const)("restores the %s pull request color on row hover", (state, colorClass) => {
|
||||
expect(settledPrHoverColorClass(state)).toContain(`group-hover/v2-row:${colorClass}`);
|
||||
});
|
||||
});
|
||||
@@ -35,17 +35,6 @@ export interface TerminalStatusIndicator {
|
||||
|
||||
export type ThreadPr = VcsStatusResult["pr"];
|
||||
|
||||
export function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"]): string {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return "group-hover/v2-row:text-emerald-600 dark:group-hover/v2-row:text-emerald-300/90";
|
||||
case "merged":
|
||||
return "group-hover/v2-row:text-violet-600 dark:group-hover/v2-row:text-violet-300/90";
|
||||
case "closed":
|
||||
return "group-hover/v2-row:text-red-600 dark:group-hover/v2-row:text-red-300/90";
|
||||
}
|
||||
}
|
||||
|
||||
export function prStatusIndicator(
|
||||
pr: ThreadPr,
|
||||
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
|
||||
@@ -76,7 +65,7 @@ export function prStatusIndicator(
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: `${presentation.shortName} closed`,
|
||||
colorClass: "text-red-600 dark:text-red-300/90",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip,
|
||||
tooltipLead,
|
||||
tooltipTitle: pr.title,
|
||||
|
||||
@@ -434,7 +434,6 @@ describe("MessagesTimeline", () => {
|
||||
|
||||
expect(markup).not.toContain("Show full message");
|
||||
expect(markup).toContain('data-user-message-collapsible="false"');
|
||||
expect(markup).toContain("rounded-2xl bg-accent p-3");
|
||||
});
|
||||
|
||||
it("renders inline terminal labels with the composer chip UI", () => {
|
||||
|
||||
@@ -890,7 +890,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
|
||||
return (
|
||||
<div className="group flex flex-col items-end gap-1">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-accent p-3">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-secondary p-3">
|
||||
{regularImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
|
||||
@@ -51,7 +51,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
contentClassName="flex w-full items-center gap-3"
|
||||
className={cn(
|
||||
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
|
||||
"hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-highlighted:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0 [&[data-highlighted][data-selected]]:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))]",
|
||||
"data-highlighted:bg-muted/56 data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0",
|
||||
props.disabledReason &&
|
||||
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
|
||||
)}
|
||||
|
||||
@@ -521,7 +521,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
<div
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-xl text-popover-foreground"
|
||||
data-model-picker-content="true"
|
||||
>
|
||||
{/* Sidebar */}
|
||||
@@ -568,23 +568,18 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
handleModelSelect(slug, instanceId);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
|
||||
showSidebar && "border-l",
|
||||
)}
|
||||
>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<div className="-translate-y-px rounded-lg bg-accent px-2 py-1">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
inputClassName="rounded-none bg-transparent text-sm placeholder:text-muted-foreground/80"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/80" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
|
||||
@@ -97,10 +97,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
|
||||
data-model-picker-sidebar="true"
|
||||
>
|
||||
<div className="w-12 shrink-0 overflow-hidden bg-muted/60" data-model-picker-sidebar="true">
|
||||
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<div
|
||||
ref={sidebarContentRef}
|
||||
@@ -118,14 +115,14 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
) : null}
|
||||
{/* Favorites section */}
|
||||
{showFavorites ? (
|
||||
<div className="mb-1 border-b pb-1">
|
||||
<div className="mb-1 pb-1">
|
||||
<div className="relative w-full">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
)}
|
||||
onClick={() => handleSelect("favorites")}
|
||||
type="button"
|
||||
@@ -172,7 +169,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
<button
|
||||
data-model-picker-provider={entry.instanceId}
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
|
||||
)}
|
||||
data-provider-accent-color={entry.accentColor}
|
||||
|
||||
@@ -187,8 +187,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup
|
||||
align="start"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [-webkit-backdrop-filter:none]! [--viewport-inline-padding:0] [backdrop-filter:none]!"
|
||||
viewportClassName="rounded-lg !overflow-hidden p-0"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0]"
|
||||
viewportClassName="!overflow-hidden p-0"
|
||||
>
|
||||
<ModelPickerContent
|
||||
activeInstanceId={activeInstanceId}
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
import { buildTraitsTriggerDisplay } from "./TraitsPicker";
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
options: ReadonlyArray<{ id: string; label: string }>,
|
||||
currentValue: string,
|
||||
): Extract<ProviderOptionDescriptor, { type: "select" }> {
|
||||
return { id, label: id, type: "select", options: [...options], currentValue };
|
||||
}
|
||||
|
||||
function fastModeDescriptor(
|
||||
currentValue: boolean,
|
||||
): Extract<ProviderOptionDescriptor, { type: "boolean" }> {
|
||||
return { id: "fastMode", label: "Fast Mode", type: "boolean", currentValue };
|
||||
}
|
||||
|
||||
const EFFORT = selectDescriptor(
|
||||
"effort",
|
||||
[
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "max", label: "Max" },
|
||||
],
|
||||
"high",
|
||||
);
|
||||
const CONTEXT_WINDOW = selectDescriptor(
|
||||
"contextWindow",
|
||||
[
|
||||
{ id: "200k", label: "200k" },
|
||||
{ id: "1m", label: "1M" },
|
||||
],
|
||||
"1m",
|
||||
);
|
||||
|
||||
function display(descriptors: ReadonlyArray<ProviderOptionDescriptor>, fastModeEnabled: boolean) {
|
||||
return buildTraitsTriggerDisplay({
|
||||
descriptors,
|
||||
primarySelectDescriptorId: "effort",
|
||||
ultrathinkPromptControlled: false,
|
||||
fastModeEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
describe("buildTraitsTriggerDisplay", () => {
|
||||
it("omits fast mode from the label entirely when it is off", () => {
|
||||
expect(display([EFFORT, fastModeDescriptor(false), CONTEXT_WINDOW], false)).toEqual({
|
||||
label: "High · 1M",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the bolt instead of a text label when fast mode is on", () => {
|
||||
expect(display([EFFORT, fastModeDescriptor(true), CONTEXT_WINDOW], true)).toEqual({
|
||||
label: "High · 1M",
|
||||
showFastModeIcon: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps non-fastMode booleans as text labels", () => {
|
||||
const thinking: Extract<ProviderOptionDescriptor, { type: "boolean" }> = {
|
||||
id: "thinking",
|
||||
label: "Thinking",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
};
|
||||
expect(display([EFFORT, thinking], false)).toEqual({
|
||||
label: "High · Thinking On",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to a text label when fast mode is the only trait", () => {
|
||||
expect(display([fastModeDescriptor(true)], true)).toEqual({
|
||||
label: "Fast",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
expect(display([fastModeDescriptor(false)], false)).toEqual({
|
||||
label: "Normal",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("stays blank when descriptors resolve to no label and there is no fast mode", () => {
|
||||
// A select with neither a currentValue nor an isDefault option yields no
|
||||
// label. Without a fastMode descriptor present that must stay blank rather
|
||||
// than falling through to a bogus "Normal".
|
||||
const unresolved: Extract<ProviderOptionDescriptor, { type: "select" }> = {
|
||||
id: "effort",
|
||||
label: "effort",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "high", label: "High" },
|
||||
],
|
||||
};
|
||||
expect(display([unresolved], false)).toEqual({ label: "", showFastModeIcon: false });
|
||||
});
|
||||
|
||||
it("still renders the prompt-controlled ultrathink label alongside the bolt", () => {
|
||||
expect(
|
||||
buildTraitsTriggerDisplay({
|
||||
descriptors: [EFFORT, fastModeDescriptor(true)],
|
||||
primarySelectDescriptorId: "effort",
|
||||
ultrathinkPromptControlled: true,
|
||||
fastModeEnabled: true,
|
||||
}),
|
||||
).toEqual({ label: "Ultrathink", showFastModeIcon: true });
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon, ZapIcon } from "lucide-react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -379,46 +379,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Build the traits trigger's text label plus whether the fast-mode bolt should
|
||||
* render. Fast mode is a lightning bolt when on and nothing at all when off —
|
||||
* "Normal" is the near-universal case and isn't worth the horizontal space. The
|
||||
* one exception is when fast mode is the only trait, where a bare bolt (or bare
|
||||
* chevron) would leave the trigger unreadable.
|
||||
*/
|
||||
export function buildTraitsTriggerDisplay(input: {
|
||||
descriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
primarySelectDescriptorId: string | null;
|
||||
ultrathinkPromptControlled: boolean;
|
||||
fastModeEnabled: boolean;
|
||||
}): { label: string; showFastModeIcon: boolean } {
|
||||
let hasFastMode = false;
|
||||
const labels: Array<string> = [];
|
||||
for (const descriptor of input.descriptors) {
|
||||
if (descriptor.id === "fastMode" && descriptor.type === "boolean") {
|
||||
hasFastMode = true;
|
||||
continue;
|
||||
}
|
||||
const label =
|
||||
input.ultrathinkPromptControlled && descriptor.id === input.primarySelectDescriptorId
|
||||
? "Ultrathink"
|
||||
: descriptor.type === "boolean"
|
||||
? `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
|
||||
: getProviderOptionCurrentLabel(descriptor);
|
||||
if (typeof label === "string" && label.length > 0) {
|
||||
labels.push(label);
|
||||
}
|
||||
}
|
||||
|
||||
// Only fall back to text when fast mode is genuinely the sole trait. Keying
|
||||
// off an empty label list alone would also catch descriptors that resolved to
|
||||
// no label at all, printing a bogus "Normal" for a model without fast mode.
|
||||
if (labels.length === 0 && hasFastMode) {
|
||||
return { label: input.fastModeEnabled ? "Fast" : "Normal", showFastModeIcon: false };
|
||||
}
|
||||
return { label: labels.join(" · "), showFastModeIcon: input.fastModeEnabled };
|
||||
}
|
||||
|
||||
export const TraitsPicker = memo(function TraitsPicker({
|
||||
provider,
|
||||
instanceId,
|
||||
@@ -433,7 +393,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
...persistence
|
||||
}: TraitsMenuContentProps & TraitsPersistence) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled, fastModeEnabled } =
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
|
||||
getTraitsSectionVisibility({
|
||||
provider,
|
||||
models,
|
||||
@@ -455,18 +415,23 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
return null;
|
||||
}
|
||||
|
||||
const { label: triggerLabel, showFastModeIcon } = buildTraitsTriggerDisplay({
|
||||
descriptors,
|
||||
primarySelectDescriptorId: primarySelectDescriptor?.id ?? null,
|
||||
ultrathinkPromptControlled,
|
||||
fastModeEnabled,
|
||||
});
|
||||
const fastModeIcon = showFastModeIcon ? (
|
||||
<>
|
||||
<ZapIcon aria-hidden="true" className="size-3 shrink-0 text-foreground/80 opacity-100" />
|
||||
<span className="sr-only">Fast mode on</span>
|
||||
</>
|
||||
) : null;
|
||||
const triggerLabels: Array<string> = [];
|
||||
for (const descriptor of descriptors) {
|
||||
const label =
|
||||
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
|
||||
? "Ultrathink"
|
||||
: descriptor.type === "boolean"
|
||||
? descriptor.id === "fastMode"
|
||||
? descriptor.currentValue === true
|
||||
? "Fast"
|
||||
: "Normal"
|
||||
: `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
|
||||
: getProviderOptionCurrentLabel(descriptor);
|
||||
if (typeof label === "string" && label.length > 0) {
|
||||
triggerLabels.push(label);
|
||||
}
|
||||
}
|
||||
const triggerLabel = triggerLabels.join(" · ");
|
||||
|
||||
const isCodexStyle = provider === "codex";
|
||||
|
||||
@@ -492,14 +457,12 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
}
|
||||
>
|
||||
{isCodexStyle ? (
|
||||
<span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
|
||||
{fastModeIcon}
|
||||
<span className="min-w-0 truncate">{triggerLabel}</span>
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{fastModeIcon}
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</>
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -22,7 +22,6 @@ import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsStat
|
||||
import { readLocalApi } from "../localApi";
|
||||
import {
|
||||
readEnvironmentSupportsSettlement,
|
||||
readEnvironmentSupportsSnooze,
|
||||
readEnvironmentThreadRefs,
|
||||
readProject,
|
||||
readThreadShell,
|
||||
@@ -70,30 +69,6 @@ export class ThreadSettleBlockedError extends Schema.TaggedErrorClass<ThreadSett
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadSnoozeUnsupportedError extends Schema.TaggedErrorClass<ThreadSnoozeUnsupportedError>()(
|
||||
"ThreadSnoozeUnsupportedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "This environment's server does not support snoozing yet. Update the server to use Snooze.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadSnoozeBlockedError extends Schema.TaggedErrorClass<ThreadSnoozeBlockedError>()(
|
||||
"ThreadSnoozeBlockedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "This thread is waiting on you. Respond to the pending request before snoozing it.";
|
||||
}
|
||||
}
|
||||
|
||||
export function useThreadActions() {
|
||||
const closeTerminal = useAtomCommand(terminalEnvironment.close);
|
||||
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
|
||||
@@ -111,12 +86,6 @@ export function useThreadActions() {
|
||||
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const snoozeThreadMutation = useAtomCommand(threadEnvironment.snooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
|
||||
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
|
||||
reportFailure: false,
|
||||
@@ -472,61 +441,6 @@ export function useThreadActions() {
|
||||
[unsettleThreadMutation],
|
||||
);
|
||||
|
||||
const snoozeThread = useCallback(
|
||||
async (target: ScopedThreadRef, snoozedUntil: string) => {
|
||||
// Version skew: never send the command to a server that predates it.
|
||||
if (!readEnvironmentSupportsSnooze(target.environmentId)) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSnoozeUnsupportedError({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
const resolved = resolveThreadTarget(target);
|
||||
// Blocked-on-you work and queued turns can't be snoozed away —
|
||||
// client-side twin of the server invariants so the UI rejects before
|
||||
// a round trip.
|
||||
if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSnoozeBlockedError({
|
||||
environmentId: resolved.threadRef.environmentId,
|
||||
threadId: resolved.threadRef.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
return snoozeThreadMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.threadId, snoozedUntil },
|
||||
});
|
||||
},
|
||||
[resolveThreadTarget, snoozeThreadMutation],
|
||||
);
|
||||
|
||||
const unsnoozeThread = useCallback(
|
||||
async (target: ScopedThreadRef) => {
|
||||
if (!readEnvironmentSupportsSnooze(target.environmentId)) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSnoozeUnsupportedError({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
return unsnoozeThreadMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.threadId, reason: "user" },
|
||||
});
|
||||
},
|
||||
[unsnoozeThreadMutation],
|
||||
);
|
||||
|
||||
const confirmAndDeleteThread = useCallback(
|
||||
async (target: ScopedThreadRef) => {
|
||||
const localApi = readLocalApi();
|
||||
@@ -563,18 +477,14 @@ export function useThreadActions() {
|
||||
confirmAndDeleteThread,
|
||||
settleThread,
|
||||
unsettleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
}),
|
||||
[
|
||||
archiveThread,
|
||||
confirmAndDeleteThread,
|
||||
deleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
],
|
||||
);
|
||||
}
|
||||
+2
-18
@@ -574,6 +574,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
--alert-glass-tint: var(--warning);
|
||||
}
|
||||
|
||||
.dropdown-glass,
|
||||
.dialog-glass {
|
||||
background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
@@ -587,19 +588,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
.dropdown-glass {
|
||||
/*
|
||||
* Elevated glass needs a denser tint than broad ambient surfaces. Nesting
|
||||
* the user-controlled mix inside an 18% popover tint preserves the full
|
||||
* opacity setting range (40% -> 51%, 80% -> 84%, 100% -> 100%) while
|
||||
* keeping high-contrast page content from blooming through menus.
|
||||
*/
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--popover) 18%,
|
||||
color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)
|
||||
);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur));
|
||||
backdrop-filter: blur(var(--glass-blur));
|
||||
border: 1px solid color-mix(in srgb, var(--foreground) 10%, transparent);
|
||||
box-shadow: 0 16px 40px -18px rgb(0 0 0 / 55%);
|
||||
}
|
||||
@@ -614,11 +602,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
.dark .model-picker-surface.model-picker-surface {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--popover) 18%,
|
||||
color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)
|
||||
);
|
||||
background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);
|
||||
}
|
||||
|
||||
.dark .dialog-glass {
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "./diffCollapse";
|
||||
|
||||
const FILE_KEYS = ["src/app.ts", "src/index.ts"];
|
||||
const FIRST_FILE_KEY = FILE_KEYS[0]!;
|
||||
|
||||
describe("diff collapse controls", () => {
|
||||
it("reports whether every rendered file is collapsed", () => {
|
||||
expect(areAllDiffFilesCollapsed(FILE_KEYS, new Set(FILE_KEYS))).toBe(true);
|
||||
expect(areAllDiffFilesCollapsed(FILE_KEYS, new Set([FIRST_FILE_KEY]))).toBe(false);
|
||||
expect(areAllDiffFilesCollapsed([], new Set())).toBe(false);
|
||||
});
|
||||
|
||||
it("collapses all files when any rendered file is expanded", () => {
|
||||
expect(toggleAllDiffFiles(FILE_KEYS, new Set([FIRST_FILE_KEY]))).toEqual(new Set(FILE_KEYS));
|
||||
});
|
||||
|
||||
it("expands all files when every rendered file is collapsed", () => {
|
||||
expect(toggleAllDiffFiles(FILE_KEYS, new Set(FILE_KEYS))).toEqual(new Set());
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
export function areAllDiffFilesCollapsed(
|
||||
fileKeys: ReadonlyArray<string>,
|
||||
collapsedFileKeys: ReadonlySet<string>,
|
||||
): boolean {
|
||||
return fileKeys.length > 0 && fileKeys.every((fileKey) => collapsedFileKeys.has(fileKey));
|
||||
}
|
||||
|
||||
export function toggleAllDiffFiles(
|
||||
fileKeys: ReadonlyArray<string>,
|
||||
collapsedFileKeys: ReadonlySet<string>,
|
||||
): ReadonlySet<string> {
|
||||
return areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? new Set() : new Set(fileKeys);
|
||||
}
|
||||
@@ -207,15 +207,6 @@ export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId):
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the environment's server understands thread.snooze/unsnooze.
|
||||
Same version-skew contract as settlement. */
|
||||
export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSnooze === true
|
||||
);
|
||||
}
|
||||
|
||||
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
|
||||
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ function getTimestampFormatter(
|
||||
return formatter;
|
||||
}
|
||||
|
||||
export function parseTimestampDate(isoDate: string): Date | null {
|
||||
function parseTimestampDate(isoDate: string): Date | null {
|
||||
const date = new Date(isoDate);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
+25
-74
@@ -7,27 +7,14 @@ import "vite-plus/test/config";
|
||||
import { defineConfig } from "vite-plus";
|
||||
import pkg from "./package.json" with { type: "json" };
|
||||
|
||||
import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
|
||||
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config";
|
||||
|
||||
const repoEnv = loadRepoEnv();
|
||||
Object.assign(process.env, repoEnv);
|
||||
|
||||
// Single-origin dev is signalled positively, because it cannot be inferred
|
||||
// from the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys
|
||||
// but `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so
|
||||
// a developer with either URL in their `.env` gets it back here. Baking it then
|
||||
// pins the client to localhost and breaks every non-localhost origin — the
|
||||
// exact failure single-origin mode exists to prevent, and an invisible one
|
||||
// since the page still loads.
|
||||
const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
|
||||
|
||||
const port = Number(process.env.PORT ?? 5733);
|
||||
const explicitHost = process.env.HOST?.trim();
|
||||
const host = explicitHost || "localhost";
|
||||
const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
|
||||
const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
|
||||
const host = process.env.HOST?.trim() || "localhost";
|
||||
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
|
||||
const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
|
||||
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
|
||||
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
|
||||
@@ -78,20 +65,7 @@ const unitTestProject = {
|
||||
},
|
||||
} satisfies TestProjectInlineConfiguration;
|
||||
|
||||
function resolveDevProxyTarget(
|
||||
backendPort: string | undefined,
|
||||
wsUrl: string | undefined,
|
||||
): string | undefined {
|
||||
// Browser dev is single-origin: the backend port is proxied through this
|
||||
// server so the app works from any origin (localhost, tailnet, LAN, phone).
|
||||
// T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
|
||||
const port = Number(backendPort?.trim());
|
||||
if (Number.isInteger(port) && port > 0) {
|
||||
return `http://localhost:${port}/`;
|
||||
}
|
||||
|
||||
// dev:desktop still points the renderer straight at the backend, so fall
|
||||
// back to deriving the target from the explicit websocket URL.
|
||||
function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
|
||||
if (!wsUrl) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -112,17 +86,7 @@ function resolveDevProxyTarget(
|
||||
}
|
||||
}
|
||||
|
||||
const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
|
||||
|
||||
// Vite rejects requests whose Host header isn't localhost, which blocks sharing
|
||||
// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
|
||||
// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
|
||||
// Anything else (ngrok, a LAN IP alias) goes through the env var.
|
||||
const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0);
|
||||
const allowedHosts = [".ts.net", ...configuredAllowedHosts];
|
||||
const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
|
||||
|
||||
export default defineConfig(() => {
|
||||
return {
|
||||
@@ -155,10 +119,6 @@ export default defineConfig(() => {
|
||||
define: {
|
||||
// In dev mode, tell the web app where the WebSocket server lives
|
||||
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
|
||||
// Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
|
||||
// under single-origin dev this must stay empty even when a `.env`
|
||||
// supplies it, so the client falls back to window.location.origin.
|
||||
"import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
|
||||
"import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
|
||||
"import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
|
||||
"import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
|
||||
@@ -185,41 +145,32 @@ export default defineConfig(() => {
|
||||
host,
|
||||
port,
|
||||
strictPort: true,
|
||||
allowedHosts,
|
||||
...(devProxyTarget
|
||||
? {
|
||||
// One entry per shared prefix; the server's dev catch-all 404s the
|
||||
// same list, so the two sides cannot drift. `/ws` is the app's own
|
||||
// socket — Vite's HMR socket is matched separately and exactly
|
||||
// (path "/" plus a vite-hmr subprotocol), so the two upgrade
|
||||
// handlers don't collide.
|
||||
proxy: Object.fromEntries(
|
||||
DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
|
||||
prefix,
|
||||
{
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
...(prefix === "/ws" ? { ws: true } : {}),
|
||||
},
|
||||
]),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
// Electron's BrowserWindow needs the HMR socket pinned to an explicit
|
||||
// host to connect reliably; dev:desktop is the only mode that sets HOST.
|
||||
// Everywhere else, leaving this unset lets the client derive it from the
|
||||
// page origin, which is what makes HMR work over Tailscale/LAN instead of
|
||||
// failing an attempt against the wrong machine's localhost first.
|
||||
// (Vite 8 logs connection state via console.debug — enable "Verbose".)
|
||||
...(explicitHost
|
||||
? {
|
||||
hmr: {
|
||||
protocol: "ws",
|
||||
host: explicitHost,
|
||||
clientPort: port,
|
||||
proxy: {
|
||||
"/.well-known": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/api": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/attachments": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
hmr: {
|
||||
// Explicit config so Vite's HMR WebSocket connects reliably
|
||||
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
|
||||
// connection logs — enable "Verbose" in DevTools to see them.
|
||||
protocol: "ws",
|
||||
host,
|
||||
clientPort: port,
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: "dist",
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
# Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in watch mode.
|
||||
- `bun run dev:share` — Also publishes the web port over HTTPS on this machine's tailnet. The startup pairing URL is built against the shared origin, and the mapping is removed on exit.
|
||||
- `bun run dev:pair` — Prints a fresh pairing URL for the running dev server, using its recorded state directory, port, and web origin. Add `--base-dir <path>` only when the server was started with `--home-dir`.
|
||||
- `bun run dev:seed` — Copies recent projects and threads from the shared home into the isolated dev database. Stop the server before running it, then restart. Tune the copy with `--threads` and `--activities`; it refuses to write to the shared home.
|
||||
- `vp run dev` — Starts contracts, server, and web in watch mode.
|
||||
- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.
|
||||
- `vp run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands run from a linked **git worktree** default to that worktree's gitignored `.t3`, even when `T3CODE_HOME` is set, storing state in `<worktree>/.t3/userdata`. Pass `--home-dir <path>` to choose another isolated directory explicitly. Submodules are not worktrees and keep the normal precedence.
|
||||
- From the **main checkout**, dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
|
||||
- Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
|
||||
- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
|
||||
- Pass dev-runner flags directly after the root task name, for example:
|
||||
`vp run dev --home-dir /tmp/t3code-dev`
|
||||
@@ -27,7 +23,6 @@
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/prod/black-macos-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3code://app/index.html` (not a `127.0.0.1` document URL).
|
||||
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `vp run dist:desktop:dmg -- --keep-stage`
|
||||
@@ -41,18 +36,6 @@
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
## Browser development
|
||||
|
||||
`dev` and `dev:web` leave `VITE_HTTP_URL` and `VITE_WS_URL` unset so the browser resolves the backend from `window.location.origin`. Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the server, allowing the same bundle to work from localhost or a tailnet hostname.
|
||||
|
||||
Worktrees derive a preferred port offset from their path. The runner shifts both ports together when either is occupied or the web port is blocked by browsers, so treat the `[dev-runner]` output as authoritative.
|
||||
|
||||
An isolated dev database starts empty. `bun run dev:seed` copies projection data only, clears the target event log, and resets every projector cursor to zero so later events are not skipped or replayed over unrelated projections. Because no live agent accompanies the copy, it also settles anything that would otherwise wait on one: sessions are stopped, running turns are interrupted, streaming messages are finished, pending interaction counts are cleared, and orphaned provider bindings are removed. Files backing copied image attachments are copied alongside the rows. The copy tolerates source/target migration drift and remains local because it includes real message bodies and host paths.
|
||||
|
||||
`dev:seed` refuses to run while a server is using the target directory: it replaces the projections and event log that server is holding open, and it has no way to tell the running process its read model was swapped underneath it. Stop the server, seed, then start it again.
|
||||
|
||||
Both source and target follow whichever state directory actually holds a database, so a main-checkout `bun run dev` — whose state lives in `~/.t3/dev` — is seedable without naming the directory. When a base directory holds both, the more recently written one wins, since that is the database the last server to run had open. The resolved path is printed in the summary.
|
||||
|
||||
## Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
@@ -5,9 +5,6 @@
|
||||
"scripts": {
|
||||
"prepare": "effect-tsgo patch && vp config --no-agent",
|
||||
"dev": "node scripts/dev-runner.ts dev",
|
||||
"dev:share": "node scripts/dev-runner.ts dev --share",
|
||||
"dev:pair": "node apps/server/src/bin.ts auth pairing url",
|
||||
"dev:seed": "node scripts/dev-seed.ts",
|
||||
"dev:server": "node scripts/dev-runner.ts dev:server",
|
||||
"dev:web": "node scripts/dev-runner.ts dev:web",
|
||||
"dev:marketing": "vp run --filter @t3tools/marketing dev",
|
||||
|
||||
@@ -37,8 +37,6 @@ export type ArchiveThreadInput = CommandInput<"thread.archive">;
|
||||
export type UnarchiveThreadInput = CommandInput<"thread.unarchive">;
|
||||
export type SettleThreadInput = CommandInput<"thread.settle">;
|
||||
export type UnsettleThreadInput = CommandInput<"thread.unsettle">;
|
||||
export type SnoozeThreadInput = CommandInput<"thread.snooze">;
|
||||
export type UnsnoozeThreadInput = CommandInput<"thread.unsnooze">;
|
||||
export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;
|
||||
export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;
|
||||
export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;
|
||||
@@ -177,26 +175,6 @@ export const unsettleThread: (input: UnsettleThreadInput) => CommandEffect = Eff
|
||||
});
|
||||
});
|
||||
|
||||
export const snoozeThread: (input: SnoozeThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.snoozeThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.snooze",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const unsnoozeThread: (input: UnsnoozeThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.unsnoozeThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.unsnooze",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.updateThreadMetadata",
|
||||
)(function* (input) {
|
||||
|
||||
@@ -13,12 +13,10 @@ import {
|
||||
type SetThreadInteractionModeInput,
|
||||
type SetThreadRuntimeModeInput,
|
||||
type SettleThreadInput,
|
||||
type SnoozeThreadInput,
|
||||
type StartThreadTurnInput,
|
||||
type StopThreadSessionInput,
|
||||
type UnarchiveThreadInput,
|
||||
type UnsettleThreadInput,
|
||||
type UnsnoozeThreadInput,
|
||||
type UpdateThreadMetadataInput,
|
||||
archiveThread,
|
||||
createThread,
|
||||
@@ -30,12 +28,10 @@ import {
|
||||
setThreadInteractionMode,
|
||||
setThreadRuntimeMode,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
startThreadTurn,
|
||||
stopThreadSession,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
updateThreadMetadata,
|
||||
} from "../operations/commands.ts";
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
@@ -51,12 +47,10 @@ export type {
|
||||
SetThreadInteractionModeInput,
|
||||
SetThreadRuntimeModeInput,
|
||||
SettleThreadInput,
|
||||
SnoozeThreadInput,
|
||||
StartThreadTurnInput,
|
||||
StopThreadSessionInput,
|
||||
UnarchiveThreadInput,
|
||||
UnsettleThreadInput,
|
||||
UnsnoozeThreadInput,
|
||||
UpdateThreadMetadataInput,
|
||||
} from "../operations/commands.ts";
|
||||
|
||||
@@ -106,18 +100,6 @@ export function createThreadEnvironmentAtoms<R, E>(
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
snooze: createEnvironmentCommand(runtime, {
|
||||
label: "environment-data:commands:thread:snooze",
|
||||
execute: (input: SnoozeThreadInput) => snoozeThread(input),
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
unsnooze: createEnvironmentCommand(runtime, {
|
||||
label: "environment-data:commands:thread:unsnooze",
|
||||
execute: (input: UnsnoozeThreadInput) => unsnoozeThread(input),
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
updateMetadata: createEnvironmentCommand(runtime, {
|
||||
label: "environment-data:commands:thread:update-metadata",
|
||||
execute: (input: UpdateThreadMetadataInput) => updateThreadMetadata(input),
|
||||
|
||||
@@ -59,8 +59,6 @@ export function mergeEnvironmentThread(
|
||||
archivedAt: shell.archivedAt,
|
||||
settledOverride: shell.settledOverride,
|
||||
settledAt: shell.settledAt,
|
||||
snoozedUntil: shell.snoozedUntil,
|
||||
snoozedAt: shell.snoozedAt,
|
||||
session: shell.session,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -74,8 +74,6 @@ export function applyThreadDetailEvent(
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
@@ -126,28 +124,6 @@ export function applyThreadDetailEvent(
|
||||
},
|
||||
};
|
||||
|
||||
case "thread.snoozed":
|
||||
return {
|
||||
kind: "updated",
|
||||
thread: {
|
||||
...thread,
|
||||
snoozedUntil: event.payload.snoozedUntil,
|
||||
snoozedAt: event.payload.snoozedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
},
|
||||
};
|
||||
|
||||
case "thread.unsnoozed":
|
||||
return {
|
||||
kind: "updated",
|
||||
thread: {
|
||||
...thread,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
},
|
||||
};
|
||||
|
||||
// ── Thread metadata ─────────────────────────────────────────────
|
||||
case "thread.meta-updated":
|
||||
return {
|
||||
|
||||
@@ -90,130 +90,6 @@ export function canSettle(
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The snooze lifecycle fields plus everything needed to detect a raised
|
||||
* hand. Snooze is an overlay on the active state: a snoozed thread stays
|
||||
* "active" in the data model and is only suppressed from the inbox until
|
||||
* its wake time passes or the thread demands attention.
|
||||
*/
|
||||
export type ThreadSnoozeShell = Pick<
|
||||
OrchestrationThreadShell,
|
||||
| "snoozedUntil"
|
||||
| "snoozedAt"
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingUserInput"
|
||||
| "session"
|
||||
| "latestTurn"
|
||||
>;
|
||||
|
||||
/**
|
||||
* A snoozed thread "raises its hand" when something happens that outranks
|
||||
* the user's snooze: the agent is blocked on them (approval / user input),
|
||||
* the session failed, or a run completed after the snooze was set — the
|
||||
* v1 taste of event-based snooze ("something happened" wakes early).
|
||||
* Raising a hand never clears the server-side snooze fields; it only stops
|
||||
* the thread from CLASSIFYING as snoozed, exactly like blocked work and
|
||||
* effectiveSettled.
|
||||
*/
|
||||
export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
|
||||
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
|
||||
// Only a FRESH failure raises the hand: a thread snoozed while already
|
||||
// failed stays snoozed — that snooze was the user saying "I saw it, not
|
||||
// now". session.updatedAt stamps the status edge, so an error newer than
|
||||
// the snooze is new information.
|
||||
if (
|
||||
shell.session?.status === "error" &&
|
||||
(shell.snoozedAt == null || Date.parse(shell.session.updatedAt) > Date.parse(shell.snoozedAt))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
shell.snoozedAt != null &&
|
||||
shell.latestTurn?.state === "completed" &&
|
||||
shell.latestTurn.completedAt != null &&
|
||||
Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A thread may be snoozed unless the agent is blocked on the user: hiding a
|
||||
* pending approval or user-input request defeats the request, and a queued
|
||||
* turn start (a message no turn has adopted yet) is invisible pending work
|
||||
* the same way it is for settle. A running session IS snoozable — snooze
|
||||
* only affects visibility, never the agent. Client-side twin of the server
|
||||
* invariants so the UI can reject before a round trip.
|
||||
*/
|
||||
export function canSnooze(
|
||||
shell: Pick<
|
||||
OrchestrationThreadShell,
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
|
||||
>,
|
||||
options: { readonly now: string },
|
||||
): boolean {
|
||||
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
|
||||
if (hasQueuedTurnStart(shell, options)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snoozed resolution: hidden from the inbox while the wake time is in the
|
||||
* future and the thread has not raised its hand. Timer wakes are derived —
|
||||
* no server event fires when snoozedUntil passes; the stale fields simply
|
||||
* stop classifying as snoozed (and feed the woke indicator until the user
|
||||
* visits or re-engages).
|
||||
*/
|
||||
export function effectiveSnoozed(
|
||||
shell: ThreadSnoozeShell,
|
||||
options: { readonly now: string },
|
||||
): boolean {
|
||||
if (shell.snoozedUntil == null) return false;
|
||||
const wakeAtMs = Date.parse(shell.snoozedUntil);
|
||||
// Malformed data never hides a thread.
|
||||
if (Number.isNaN(wakeAtMs)) return false;
|
||||
if (wakeAtMs <= Date.parse(options.now)) return false;
|
||||
return !threadRaisedHandWhileSnoozed(shell);
|
||||
}
|
||||
|
||||
/**
|
||||
* When a previously-snoozed thread woke, or null if it never snoozed / is
|
||||
* still snoozed. Used for the "Woke" indicator: the thread reappears in its
|
||||
* original sort position (the inbox sort is deliberately static), so the
|
||||
* wake signal has to carry the weight. Compare against the client's
|
||||
* lastVisitedAt — visiting clears the indicator like it clears unread.
|
||||
*
|
||||
* Timer wakes report the wake time itself; raised-hand wakes report the
|
||||
* triggering timestamp so a visit BEFORE the early wake doesn't suppress
|
||||
* the indicator.
|
||||
*/
|
||||
export function threadWokeAt(
|
||||
shell: ThreadSnoozeShell,
|
||||
options: { readonly now: string },
|
||||
): string | null {
|
||||
if (shell.snoozedUntil == null) return null;
|
||||
const wakeAtMs = Date.parse(shell.snoozedUntil);
|
||||
if (Number.isNaN(wakeAtMs)) return null;
|
||||
// An early hand-raise wake stays authoritative even after the scheduled
|
||||
// wake time passes: reporting snoozedUntil then would resurface a Woke
|
||||
// indicator the user already cleared by visiting (snoozedUntil is newer
|
||||
// than that visit's lastVisitedAt).
|
||||
if (threadRaisedHandWhileSnoozed(shell)) {
|
||||
if (
|
||||
shell.snoozedAt != null &&
|
||||
shell.latestTurn?.state === "completed" &&
|
||||
shell.latestTurn.completedAt != null &&
|
||||
Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
|
||||
) {
|
||||
return shell.latestTurn.completedAt;
|
||||
}
|
||||
return shell.session?.updatedAt ?? shell.snoozedAt ?? null;
|
||||
}
|
||||
// No raised hand: woke iff the timer elapsed (still-snoozed → null).
|
||||
return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A merged/closed change request settles its thread only once the thread has
|
||||
* been idle this long. Without the idle guard the merge signal is permanent:
|
||||
|
||||
@@ -1,237 +0,0 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
canSnooze,
|
||||
effectiveSnoozed,
|
||||
threadRaisedHandWhileSnoozed,
|
||||
threadWokeAt,
|
||||
type ThreadSnoozeShell,
|
||||
} from "./threadSettled.ts";
|
||||
|
||||
const NOW = "2026-04-10T12:00:00.000Z";
|
||||
const SNOOZED_AT = "2026-04-10T09:00:00.000Z";
|
||||
const FUTURE_WAKE = "2026-04-11T09:00:00.000Z";
|
||||
const PAST_WAKE = "2026-04-10T10:00:00.000Z";
|
||||
|
||||
function makeShell(input: {
|
||||
readonly snoozedUntil?: string | null;
|
||||
readonly snoozedAt?: string | null;
|
||||
readonly sessionStatus?: "starting" | "running" | "ready" | "error";
|
||||
readonly pending?: "approval" | "user-input";
|
||||
readonly turnCompletedAt?: string | null;
|
||||
}): ThreadSnoozeShell {
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
return {
|
||||
snoozedUntil: input.snoozedUntil ?? null,
|
||||
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
|
||||
hasPendingApprovals: input.pending === "approval",
|
||||
hasPendingUserInput: input.pending === "user-input",
|
||||
session:
|
||||
input.sessionStatus === undefined
|
||||
? null
|
||||
: {
|
||||
threadId,
|
||||
status: input.sessionStatus,
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: input.sessionStatus === "error" ? "boom" : null,
|
||||
updatedAt: "2026-04-10T11:00:00.000Z",
|
||||
},
|
||||
latestTurn:
|
||||
input.turnCompletedAt === undefined
|
||||
? null
|
||||
: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: SNOOZED_AT,
|
||||
startedAt: null,
|
||||
completedAt: input.turnCompletedAt,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("effectiveSnoozed", () => {
|
||||
it("hides a thread whose wake time is in the future", () => {
|
||||
expect(effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE }), { now: NOW })).toBe(true);
|
||||
});
|
||||
|
||||
it("stops classifying as snoozed once the wake time passes (timer wake, no event)", () => {
|
||||
expect(effectiveSnoozed(makeShell({ snoozedUntil: PAST_WAKE }), { now: NOW })).toBe(false);
|
||||
});
|
||||
|
||||
it("never snoozes a thread with no snooze state", () => {
|
||||
expect(effectiveSnoozed(makeShell({}), { now: NOW })).toBe(false);
|
||||
});
|
||||
|
||||
it("never hides on malformed wake data", () => {
|
||||
expect(effectiveSnoozed(makeShell({ snoozedUntil: "not-a-date" }), { now: NOW })).toBe(false);
|
||||
});
|
||||
|
||||
it("wakes early when the agent is blocked on the user", () => {
|
||||
expect(
|
||||
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "approval" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("wakes early on a failure that happened after the snooze", () => {
|
||||
// makeShell stamps session.updatedAt at 11:00, after SNOOZED_AT (9:00).
|
||||
expect(
|
||||
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("stays snoozed when the failure predates the snooze — the user saw it", () => {
|
||||
expect(
|
||||
effectiveSnoozed(
|
||||
makeShell({
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
sessionStatus: "error",
|
||||
// Snoozed AFTER the error's status edge.
|
||||
snoozedAt: "2026-04-10T11:30:00.000Z",
|
||||
}),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("stays snoozed while the session keeps working — snooze never pauses the agent", () => {
|
||||
expect(
|
||||
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "running" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("wakes early when a run completes after the snooze was set", () => {
|
||||
expect(
|
||||
effectiveSnoozed(
|
||||
makeShell({ snoozedUntil: FUTURE_WAKE, turnCompletedAt: "2026-04-10T10:30:00.000Z" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores runs that completed before the snooze — the user saw that result", () => {
|
||||
expect(
|
||||
effectiveSnoozed(
|
||||
makeShell({ snoozedUntil: FUTURE_WAKE, turnCompletedAt: "2026-04-10T08:00:00.000Z" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("threadRaisedHandWhileSnoozed", () => {
|
||||
it("is false for a quiet snoozed thread", () => {
|
||||
expect(threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE }))).toBe(false);
|
||||
});
|
||||
|
||||
it("is true for approvals, input, and failures", () => {
|
||||
expect(
|
||||
threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "approval" })),
|
||||
).toBe(true);
|
||||
expect(
|
||||
threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input" })),
|
||||
).toBe(true);
|
||||
expect(
|
||||
threadRaisedHandWhileSnoozed(
|
||||
makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canSnooze", () => {
|
||||
it("allows snoozing quiet and working threads alike", () => {
|
||||
expect(canSnooze({ ...makeShell({}), latestUserMessageAt: null }, { now: NOW })).toBe(true);
|
||||
expect(
|
||||
canSnooze(
|
||||
{ ...makeShell({ sessionStatus: "running" }), latestUserMessageAt: null },
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses blocked-on-you work", () => {
|
||||
expect(
|
||||
canSnooze({ ...makeShell({ pending: "approval" }), latestUserMessageAt: null }, { now: NOW }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
canSnooze(
|
||||
{ ...makeShell({ pending: "user-input" }), latestUserMessageAt: null },
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses a queued turn start — same invisible-pending-work rule as settle", () => {
|
||||
// Fresh user message, no turn has adopted it, within the grace window.
|
||||
expect(
|
||||
canSnooze(
|
||||
{ ...makeShell({}), latestUserMessageAt: "2026-04-10T11:59:30.000Z" },
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(false);
|
||||
// Outside the grace window the message is stale data, not queued work.
|
||||
expect(
|
||||
canSnooze(
|
||||
{ ...makeShell({}), latestUserMessageAt: "2026-04-10T11:00:00.000Z" },
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("threadWokeAt", () => {
|
||||
it("is null for never-snoozed and still-snoozed threads", () => {
|
||||
expect(threadWokeAt(makeShell({}), { now: NOW })).toBe(null);
|
||||
expect(threadWokeAt(makeShell({ snoozedUntil: FUTURE_WAKE }), { now: NOW })).toBe(null);
|
||||
});
|
||||
|
||||
it("reports the wake time for a timer wake", () => {
|
||||
expect(threadWokeAt(makeShell({ snoozedUntil: PAST_WAKE }), { now: NOW })).toBe(PAST_WAKE);
|
||||
});
|
||||
|
||||
it("reports the completion time for an early run-completed wake", () => {
|
||||
expect(
|
||||
threadWokeAt(
|
||||
makeShell({ snoozedUntil: FUTURE_WAKE, turnCompletedAt: "2026-04-10T10:30:00.000Z" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe("2026-04-10T10:30:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to session activity for blocked/failed early wakes", () => {
|
||||
expect(
|
||||
threadWokeAt(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe("2026-04-10T11:00:00.000Z");
|
||||
});
|
||||
|
||||
it("keeps the early wake authoritative after the scheduled time passes", () => {
|
||||
// Woke early at 10:30 via run-completed; the scheduled wake (PAST_WAKE
|
||||
// 10:00 relative to a later now) has ALSO passed. Reporting the
|
||||
// scheduled time would resurface a Woke pill the user already cleared
|
||||
// by visiting between the early wake and now.
|
||||
expect(
|
||||
threadWokeAt(
|
||||
makeShell({ snoozedUntil: PAST_WAKE, turnCompletedAt: "2026-04-10T09:30:00.000Z" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe("2026-04-10T09:30:00.000Z");
|
||||
});
|
||||
});
|
||||
@@ -44,9 +44,6 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
|
||||
pre-settlement servers, so clients treat missing as unsupported and
|
||||
never send the commands under version skew. */
|
||||
threadSettlement: Schema.optionalKey(Schema.Boolean),
|
||||
/** Server understands thread.snooze / thread.unsnooze commands. Same
|
||||
version-skew contract as threadSettlement. */
|
||||
threadSnooze: Schema.optionalKey(Schema.Boolean),
|
||||
/** The update path clients should offer for this server. Absent on
|
||||
servers that must be relaunched manually (dev checkouts, Windows
|
||||
foreground runs, pre-update servers). */
|
||||
|
||||
@@ -176,10 +176,7 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<
|
||||
"gpt-5.3-spark": "gpt-5.3-codex-spark",
|
||||
},
|
||||
[CLAUDE_DRIVER_KIND]: {
|
||||
opus: "claude-opus-5",
|
||||
"opus-5": "claude-opus-5",
|
||||
"claude-opus-5.0": "claude-opus-5",
|
||||
"claude-opus-5-0": "claude-opus-5",
|
||||
opus: "claude-opus-4-8",
|
||||
"opus-4.8": "claude-opus-4-8",
|
||||
"claude-opus-4.8": "claude-opus-4-8",
|
||||
"opus-4.7": "claude-opus-4-7",
|
||||
|
||||
@@ -361,12 +361,6 @@ export const OrchestrationThread = Schema.Struct({
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
|
||||
// Snooze is an overlay on the active lifecycle, not a fourth destination:
|
||||
// a snoozed thread stays "active" in the model and is only suppressed from
|
||||
// the inbox until snoozedUntil passes (or the thread raises its hand).
|
||||
// Optional so payloads from pre-snooze servers still decode.
|
||||
snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
|
||||
snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
|
||||
deletedAt: Schema.NullOr(IsoDateTime),
|
||||
messages: Schema.Array(OrchestrationMessage),
|
||||
proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(
|
||||
@@ -417,8 +411,6 @@ export const OrchestrationThreadShell = Schema.Struct({
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
|
||||
snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
|
||||
snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
|
||||
session: Schema.NullOr(OrchestrationSession),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
hasPendingApprovals: Schema.Boolean,
|
||||
@@ -591,27 +583,6 @@ const ThreadUnsettleCommand = Schema.Struct({
|
||||
reason: Schema.Literal("user"),
|
||||
});
|
||||
|
||||
const ThreadSnoozeCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.snooze"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
// The wake time. Event-based wake conditions (PR merged, review posted)
|
||||
// will arrive as an optional condition field alongside this; time-based
|
||||
// snooze is just the first kind of condition.
|
||||
snoozedUntil: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadUnsnoozeCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.unsnooze"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
// Commands only carry "user": activity wakes are decided server-side (the
|
||||
// decider emits thread.unsnoozed(reason: "activity") directly), and timer
|
||||
// wakes need no event at all — clients derive visibility from snoozedUntil,
|
||||
// so a passed wake time simply stops classifying as snoozed.
|
||||
reason: Schema.Literal("user"),
|
||||
});
|
||||
|
||||
const ThreadMetaUpdateCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.meta.update"),
|
||||
commandId: CommandId,
|
||||
@@ -756,8 +727,6 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
|
||||
ThreadUnarchiveCommand,
|
||||
ThreadSettleCommand,
|
||||
ThreadUnsettleCommand,
|
||||
ThreadSnoozeCommand,
|
||||
ThreadUnsnoozeCommand,
|
||||
ThreadMetaUpdateCommand,
|
||||
ThreadRuntimeModeSetCommand,
|
||||
ThreadInteractionModeSetCommand,
|
||||
@@ -781,8 +750,6 @@ export const ClientOrchestrationCommand = Schema.Union([
|
||||
ThreadUnarchiveCommand,
|
||||
ThreadSettleCommand,
|
||||
ThreadUnsettleCommand,
|
||||
ThreadSnoozeCommand,
|
||||
ThreadUnsnoozeCommand,
|
||||
ThreadMetaUpdateCommand,
|
||||
ThreadRuntimeModeSetCommand,
|
||||
ThreadInteractionModeSetCommand,
|
||||
@@ -887,8 +854,6 @@ export const OrchestrationEventType = Schema.Literals([
|
||||
"thread.unarchived",
|
||||
"thread.settled",
|
||||
"thread.unsettled",
|
||||
"thread.snoozed",
|
||||
"thread.unsnoozed",
|
||||
"thread.meta-updated",
|
||||
"thread.runtime-mode-set",
|
||||
"thread.interaction-mode-set",
|
||||
@@ -980,23 +945,6 @@ export const ThreadUnsettledPayload = Schema.Struct({
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadSnoozedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
snoozedUntil: IsoDateTime,
|
||||
snoozedAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadUnsnoozedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
// user: explicit "wake now". activity: real work arrived (user message /
|
||||
// session coming alive) and the decider cleared the snooze — mirrors
|
||||
// thread.unsettled's activity resets. Timer wakes emit no event: clients
|
||||
// derive them from snoozedUntil passing.
|
||||
reason: Schema.Literals(["user", "activity"]),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadMetaUpdatedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -1174,16 +1122,6 @@ export const OrchestrationEvent = Schema.Union([
|
||||
type: Schema.Literal("thread.unsettled"),
|
||||
payload: ThreadUnsettledPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.snoozed"),
|
||||
payload: ThreadSnoozedPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.unsnoozed"),
|
||||
payload: ThreadUnsnoozedPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.meta-updated"),
|
||||
|
||||
@@ -194,14 +194,6 @@
|
||||
"./httpReadiness": {
|
||||
"types": "./src/httpReadiness.ts",
|
||||
"import": "./src/httpReadiness.ts"
|
||||
},
|
||||
"./devHome": {
|
||||
"types": "./src/devHome.ts",
|
||||
"import": "./src/devHome.ts"
|
||||
},
|
||||
"./devProxy": {
|
||||
"types": "./src/devProxy.ts",
|
||||
"import": "./src/devProxy.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - builds real worktree layouts on disk.
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { resolveGitWorktreePath, resolveWorktreeT3Home } from "./devHome.ts";
|
||||
|
||||
const makeRepo = (
|
||||
kind:
|
||||
| "worktree"
|
||||
| "checkout"
|
||||
| "bare"
|
||||
| "submodule"
|
||||
| "unreadable-git-file"
|
||||
| "bare-repo-worktree"
|
||||
| "custom-common-dir-worktree",
|
||||
) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devhome-"));
|
||||
if (kind === "worktree") {
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /elsewhere/.git/worktrees/x\n");
|
||||
} else if (kind === "bare-repo-worktree") {
|
||||
// `git worktree add` from a bare repo: the common dir is `<name>.git`.
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /srv/myrepo.git/worktrees/x\n");
|
||||
} else if (kind === "custom-common-dir-worktree") {
|
||||
// $GIT_COMMON_DIR need not be named `.git` at all.
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /srv/store/worktrees/x\n");
|
||||
} else if (kind === "submodule") {
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: ../.git/modules/sub\n");
|
||||
} else if (kind === "unreadable-git-file") {
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "not a gitdir pointer\n");
|
||||
} else if (kind === "checkout") {
|
||||
NodeFS.mkdirSync(NodePath.join(root, ".git"));
|
||||
}
|
||||
const nested = NodePath.join(root, "apps", "web", "src");
|
||||
NodeFS.mkdirSync(nested, { recursive: true });
|
||||
return { root, nested };
|
||||
}),
|
||||
({ root }) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),
|
||||
);
|
||||
|
||||
describe("resolveGitWorktreePath", () => {
|
||||
it.effect("finds a worktree root from a nested directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("worktree");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a main checkout as not a linked worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("checkout");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a directory outside a repository", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("bare");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a submodule as not a linked worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("submodule");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a .git file without a usable gitdir pointer", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("unreadable-git-file");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("finds a worktree of a bare repository", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("bare-repo-worktree");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("finds a worktree whose common dir is not named .git", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("custom-common-dir-worktree");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveWorktreeT3Home", () => {
|
||||
it.effect("answers with .t3 before the dev runner creates it", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("worktree");
|
||||
const home = yield* resolveWorktreeT3Home(nested);
|
||||
assert.equal(home, NodePath.join(NodePath.resolve(root), ".t3"));
|
||||
assert.isFalse(NodeFS.existsSync(home ?? ""));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,103 +0,0 @@
|
||||
/**
|
||||
* Where development state lives, and how to keep it away from the shared
|
||||
* `~/.t3` that a user's installed T3 Code runs against.
|
||||
*
|
||||
* A linked git worktree gets its own (gitignored) `.t3`: feature work in a
|
||||
* throwaway branch must not share a database with the real app, and an ambient
|
||||
* `T3CODE_HOME` counts as an explicit base dir — flipping the state directory
|
||||
* from `<base>/dev` to `<base>/userdata`, the live production database.
|
||||
*/
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
/**
|
||||
* A `.git` file points at the real git directory. A linked worktree's lives at
|
||||
* `<common-dir>/worktrees/<name>`; a submodule's at
|
||||
* `<super-git-dir>/modules/<name>`. Both are files, so the pointer — not the
|
||||
* file-vs-directory distinction alone — is what identifies a worktree.
|
||||
*
|
||||
* The common dir is not necessarily named `.git`: a worktree of a bare repo
|
||||
* points at `<repo>.git/worktrees/<name>`, and `$GIT_COMMON_DIR` can be
|
||||
* anything. So match on the `worktrees/<name>` tail, which git always uses,
|
||||
* rather than on the name of the directory containing it.
|
||||
*/
|
||||
const pointsAtLinkedWorktree = (gitFileContents: string, path: Path.Path): boolean => {
|
||||
const gitdir = gitFileContents
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.find((line) => line.startsWith("gitdir:"))
|
||||
?.slice("gitdir:".length)
|
||||
.trim();
|
||||
if (gitdir === undefined || gitdir.length === 0) {
|
||||
return false;
|
||||
}
|
||||
// Compare as path segments so a directory merely named `…worktrees…` cannot
|
||||
// match as a substring. Trailing separators normalize away first.
|
||||
const segments = path
|
||||
.normalize(gitdir.replaceAll("\\", "/"))
|
||||
.split(/[/\\]/)
|
||||
.filter((segment) => segment.length > 0);
|
||||
// `<common-dir>/worktrees/<name>`: `worktrees` is the penultimate segment,
|
||||
// and something must precede it. This excludes `<git-dir>/modules/<name>`.
|
||||
return segments.length >= 3 && segments.at(-2) === "worktrees";
|
||||
};
|
||||
|
||||
/**
|
||||
* The path of the linked git worktree containing `cwd`, or undefined when
|
||||
* `cwd` is not inside one. Git marks a linked worktree by making `.git` a file
|
||||
* whose `gitdir:` points into the repository's `.git/worktrees`.
|
||||
*
|
||||
* Walks up to the repository root, so running from a subdirectory resolves the
|
||||
* same worktree as running from the top.
|
||||
*/
|
||||
export const resolveGitWorktreePath = (
|
||||
cwd: string,
|
||||
): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
let directory = path.resolve(cwd);
|
||||
for (;;) {
|
||||
const gitPath = path.join(directory, ".git");
|
||||
const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);
|
||||
if (Option.isSome(info)) {
|
||||
// A directory means the main checkout. Stop either way: nesting one
|
||||
// repository inside another does not make the outer one this root.
|
||||
if (info.value.type !== "File") {
|
||||
return undefined;
|
||||
}
|
||||
// A submodule also has a `.git` file, but it is not a worktree of this
|
||||
// repository and gets no worktree-local home.
|
||||
const contents = yield* fileSystem
|
||||
.readFileString(gitPath)
|
||||
.pipe(Effect.orElseSucceed(() => ""));
|
||||
return pointsAtLinkedWorktree(contents, path) ? directory : undefined;
|
||||
}
|
||||
const parent = path.dirname(directory);
|
||||
if (parent === directory) {
|
||||
return undefined;
|
||||
}
|
||||
directory = parent;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The worktree-local data directory for `cwd`, or undefined outside a linked
|
||||
* worktree. Deliberately does not require the directory to exist yet: falling
|
||||
* back because it is missing would send callers at the shared home.
|
||||
*/
|
||||
export const resolveWorktreeT3Home = (
|
||||
cwd: string,
|
||||
): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
|
||||
Effect.gen(function* () {
|
||||
const worktreePath = yield* resolveGitWorktreePath(cwd);
|
||||
if (worktreePath === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const path = yield* Path.Path;
|
||||
return path.join(worktreePath, ".t3");
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
/**
|
||||
* Backend paths the web dev server proxies in single-origin browser dev.
|
||||
*
|
||||
* Two consumers must agree on this list: the Vite proxy map
|
||||
* (apps/web/vite.config.ts) that forwards these to the backend, and the
|
||||
* server's dev catch-all (apps/server/src/http.ts) that 404s them instead of
|
||||
* redirecting back to Vite. Drift is silent and nasty in both directions — a
|
||||
* prefix only Vite knows gets answered with index.html; a prefix only the
|
||||
* server knows redirect-loops through the proxy.
|
||||
*/
|
||||
export const DEV_PROXIED_PATH_PREFIXES = ["/api", "/oauth", "/.well-known", "/ws"] as const;
|
||||
|
||||
export function isDevProxiedPath(pathname: string): boolean {
|
||||
return DEV_PROXIED_PATH_PREFIXES.some(
|
||||
(prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`),
|
||||
);
|
||||
}
|
||||
@@ -30,13 +30,6 @@ export const HostProcessEnvironment = Context.Reference<NodeJS.ProcessEnv>(
|
||||
},
|
||||
);
|
||||
|
||||
export const HostProcessWorkingDirectory = Context.Reference<string>(
|
||||
"@t3tools/shared/hostProcess/HostProcessWorkingDirectory",
|
||||
{
|
||||
defaultValue: () => process.cwd(),
|
||||
},
|
||||
);
|
||||
|
||||
export const HostProcessExecutablePath = Context.Reference<string>(
|
||||
"@t3tools/shared/hostProcess/HostProcessExecutablePath",
|
||||
{
|
||||
|
||||
@@ -151,7 +151,7 @@ describe("model slug normalization", () => {
|
||||
it("preserves exact custom slugs instead of expanding provider aliases", () => {
|
||||
const claude = ProviderDriverKind.make("claudeAgent");
|
||||
|
||||
expect(normalizeModelSlug("opus", claude)).toBe("claude-opus-5");
|
||||
expect(normalizeModelSlug("opus", claude)).toBe("claude-opus-4-8");
|
||||
expect(normalizeCustomModelSlug(" opus ")).toBe("opus");
|
||||
});
|
||||
});
|
||||
@@ -25,44 +25,6 @@ import {
|
||||
} from "./tailscale.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
/**
|
||||
* Asserts nothing reachable from `error` contains `secret`. Recurses through
|
||||
* nested objects, arrays, and `cause` chains rather than checking only
|
||||
* top-level strings: a leak one level down (say, a wrapped cause carrying raw
|
||||
* stderr) is just as visible in a log, and a shallow check would pass it.
|
||||
*
|
||||
* Walks values instead of serializing so it holds for fields added later, and
|
||||
* tracks visited objects so a cyclic cause chain terminates.
|
||||
*/
|
||||
function assertCarriesNoSecret(error: object, secret: string): void {
|
||||
const seen = new WeakSet<object>();
|
||||
|
||||
const walk = (value: unknown, path: string): void => {
|
||||
if (typeof value === "string") {
|
||||
assert.notInclude(value, secret, `${path} leaked stderr`);
|
||||
return;
|
||||
}
|
||||
if (typeof value !== "object" || value === null || seen.has(value)) {
|
||||
return;
|
||||
}
|
||||
seen.add(value);
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((entry, index) => walk(entry, `${path}[${String(index)}]`));
|
||||
return;
|
||||
}
|
||||
// `message` and `cause` are getters on Error subclasses, so they are not
|
||||
// own enumerable properties and Object.entries alone would skip them.
|
||||
walk((value as { message?: unknown }).message, `${path}.message`);
|
||||
walk((value as { cause?: unknown }).cause, `${path}.cause`);
|
||||
for (const [key, nested] of Object.entries(value)) {
|
||||
walk(nested, `${path}.${key}`);
|
||||
}
|
||||
};
|
||||
|
||||
walk(error, "error");
|
||||
}
|
||||
const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`;
|
||||
const tailscaleStatusWithSingleIpJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.90.1.2"]}}`;
|
||||
|
||||
@@ -232,26 +194,6 @@ describe("tailscale", () => {
|
||||
assert.notProperty(error, "stderr");
|
||||
assert.notInclude(error.message, "tskey-auth-secret-token-value");
|
||||
assert.equal(error.message, "tailscale status exited with code 7.");
|
||||
assert.equal(error.stderrDiagnostic, "not-logged-in");
|
||||
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("classifies unrecognized stderr without quoting it", () => {
|
||||
const layer = mockSpawnerLayer(() => ({
|
||||
code: 3,
|
||||
stderr: "something novel went wrong for node fluffy-badger tskey-auth-secret-token-value",
|
||||
}));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
|
||||
|
||||
assert.instanceOf(error, TailscaleCommandExitError);
|
||||
// Unmatched stderr degrades to "unknown" rather than passing text
|
||||
// through — that fallback is what keeps novel output from leaking.
|
||||
assert.equal(error.stderrDiagnostic, "unknown");
|
||||
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
|
||||
assertCarriesNoSecret(error, "fluffy-badger");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -311,10 +253,6 @@ describe("tailscale", () => {
|
||||
assert.notProperty(error, "command");
|
||||
assert.notProperty(error, "stderr");
|
||||
assert.notInclude(error.message, "tskey-auth-secret-token-value");
|
||||
// The diagnostic classifies the failure without quoting stderr, so the
|
||||
// key cannot reach a log through it either.
|
||||
assert.equal(error.stderrDiagnostic, "permission-denied");
|
||||
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -23,37 +23,6 @@ const TailscaleCommandContext = {
|
||||
argumentCount: Schema.Number,
|
||||
};
|
||||
|
||||
/**
|
||||
* Failure kinds we can name without quoting the CLI. Anything unrecognized
|
||||
* becomes "unknown" rather than falling back to raw text — stderr can contain
|
||||
* auth keys (`tskey-…`) and node names, and these labels are logged.
|
||||
*/
|
||||
export const TailscaleStderrDiagnostic = Schema.Literals([
|
||||
"no-existing-handler",
|
||||
"not-logged-in",
|
||||
"permission-denied",
|
||||
"unknown",
|
||||
]);
|
||||
export type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;
|
||||
|
||||
// Matched against stderr, most specific first. Patterns are deliberately short
|
||||
// and anchored on tailscale's own wording.
|
||||
const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
|
||||
readonly [RegExp, Exclude<TailscaleStderrDiagnostic, "unknown">]
|
||||
> = [
|
||||
[/handler does not exist/i, "no-existing-handler"],
|
||||
[/not logged in|logged out|needs? login/i, "not-logged-in"],
|
||||
[/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
|
||||
];
|
||||
|
||||
/** Classifies stderr into a safe label, dropping the text itself. */
|
||||
export const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {
|
||||
if (stderr.trim().length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? "unknown";
|
||||
};
|
||||
|
||||
export class TailscaleCommandSpawnError extends Schema.TaggedErrorClass<TailscaleCommandSpawnError>()(
|
||||
"TailscaleCommandSpawnError",
|
||||
{
|
||||
@@ -85,12 +54,6 @@ export class TailscaleCommandExitError extends Schema.TaggedErrorClass<Tailscale
|
||||
exitCode: Schema.Number,
|
||||
stdoutLength: Schema.optional(Schema.Number),
|
||||
stderrLength: Schema.Number,
|
||||
// A classified diagnostic, never raw CLI output. `tailscale` prints auth
|
||||
// keys and node identifiers into stderr, and this field is surfaced in
|
||||
// dev-runner logs — so it carries only a known-safe label from the closed
|
||||
// set below. Callers that need to recognize a specific failure (e.g.
|
||||
// `serve off` on a port with no mapping) match on the label.
|
||||
stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
@@ -249,9 +212,6 @@ export const readTailscaleStatus = Effect.gen(function* () {
|
||||
exitCode,
|
||||
stdoutLength: stdout.length,
|
||||
stderrLength: stderr.length,
|
||||
...(stderrDiagnosticOf(stderr) !== undefined
|
||||
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
return yield* parseTailscaleStatus(stdout);
|
||||
@@ -315,9 +275,6 @@ const runTailscaleCommand = (
|
||||
...commandContext,
|
||||
exitCode,
|
||||
stderrLength: stderr.length,
|
||||
...(stderrDiagnosticOf(stderr) !== undefined
|
||||
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
|
||||
Generated
+83
-59
@@ -35,19 +35,19 @@ catalogs:
|
||||
version: 0.2.2
|
||||
|
||||
overrides:
|
||||
'@clerk/backend': 3.13.0
|
||||
'@clerk/clerk-js': 6.25.7
|
||||
'@clerk/backend': 3.11.2
|
||||
'@clerk/clerk-js': 6.25.1
|
||||
'@clerk/clerk-js>@base-org/account': '-'
|
||||
'@clerk/clerk-js>@coinbase/wallet-sdk': '-'
|
||||
'@clerk/clerk-js>@solana/wallet-adapter-base': '-'
|
||||
'@clerk/clerk-js>@solana/wallet-adapter-react': '-'
|
||||
'@clerk/clerk-js>@solana/wallet-standard': '-'
|
||||
'@clerk/clerk-js>@wallet-standard/core': '-'
|
||||
'@clerk/electron': 0.0.18
|
||||
'@clerk/electron': 0.0.11
|
||||
'@clerk/electron-passkeys': 0.0.3
|
||||
'@clerk/expo': 4.0.2
|
||||
'@clerk/react': 6.12.7
|
||||
'@clerk/shared': 4.25.7
|
||||
'@clerk/expo': 3.7.2
|
||||
'@clerk/react': 6.12.1
|
||||
'@clerk/shared': 4.25.1
|
||||
'@effect/atom-react': 4.0.0-beta.78
|
||||
'@effect/platform-bun': 4.0.0-beta.78
|
||||
'@effect/platform-node': 4.0.0-beta.78
|
||||
@@ -109,8 +109,8 @@ importers:
|
||||
apps/desktop:
|
||||
dependencies:
|
||||
'@clerk/electron':
|
||||
specifier: 0.0.18
|
||||
version: 0.0.18(@clerk/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])
|
||||
specifier: 0.0.11
|
||||
version: 0.0.11(@clerk/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])
|
||||
'@clerk/electron-passkeys':
|
||||
specifier: 0.0.3
|
||||
version: 0.0.3
|
||||
@@ -195,8 +195,8 @@ importers:
|
||||
specifier: ^0.7.1
|
||||
version: 0.7.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
|
||||
'@clerk/expo':
|
||||
specifier: 4.0.2
|
||||
version: 4.0.2([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])
|
||||
specifier: 3.7.2
|
||||
version: 3.7.2([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])
|
||||
'@effect/atom-react':
|
||||
specifier: 4.0.0-beta.78
|
||||
version: 4.0.0-beta.78([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))([email protected])([email protected])
|
||||
@@ -512,11 +512,11 @@ importers:
|
||||
specifier: ^1.4.1
|
||||
version: 1.5.0(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||
'@clerk/electron':
|
||||
specifier: 0.0.18
|
||||
version: 0.0.18(@clerk/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])
|
||||
specifier: 0.0.11
|
||||
version: 0.0.11(@clerk/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])
|
||||
'@clerk/react':
|
||||
specifier: 6.12.7
|
||||
version: 6.12.7([email protected]([email protected]))([email protected])
|
||||
specifier: 6.12.1
|
||||
version: 6.12.1([email protected]([email protected]))([email protected])
|
||||
'@dnd-kit/core':
|
||||
specifier: ^6.3.1
|
||||
version: 6.3.1([email protected]([email protected]))([email protected])
|
||||
@@ -666,8 +666,8 @@ importers:
|
||||
infra/relay:
|
||||
dependencies:
|
||||
'@clerk/backend':
|
||||
specifier: 3.13.0
|
||||
version: 3.13.0([email protected]([email protected]))([email protected])
|
||||
specifier: 3.11.2
|
||||
version: 3.11.2([email protected]([email protected]))([email protected])
|
||||
'@effect/sql-pg':
|
||||
specifier: 4.0.0-beta.78
|
||||
version: 4.0.0-beta.78([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))
|
||||
@@ -905,9 +905,6 @@ importers:
|
||||
'@t3tools/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../packages/shared
|
||||
'@t3tools/tailscale':
|
||||
specifier: workspace:*
|
||||
version: link:../packages/tailscale
|
||||
effect:
|
||||
specifier: 4.0.0-beta.78
|
||||
version: 4.0.0-beta.78(patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5)
|
||||
@@ -1693,12 +1690,12 @@ packages:
|
||||
resolution: {integrity: sha512-EYlRokl8szrP9Z25qT5aepMdBjzBvHF9ZEhzIiUBc9guz/T31EqRgvD0QSgZcpE93xiwrr+OkB4nz0BZyF6fSA==}
|
||||
engines: {node: '>= 20.12.0'}
|
||||
|
||||
'@clerk/[email protected]3.0':
|
||||
resolution: {integrity: sha512-kYOgeR48iXYypudpYITE0L2yxi4TeFXU+ISAOULlVgOcurw8qnm1/JEuK6Mr2IFUbRS9hcHk1HVO0Ceo0XmL8Q==}
|
||||
'@clerk/[email protected]1.2':
|
||||
resolution: {integrity: sha512-HaHAnKzThRpdRi+QJkMo3+Cx/3hJUt+UdbQ62Ikzwwt0zIhUE0+qgG+zgUHjAdYhSbfiUzEWYsLdnBsfQ7yv7g==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
|
||||
'@clerk/[email protected].7':
|
||||
resolution: {integrity: sha512-GOnbEUzPKAdsdCodZsHhku2YloBBuwLGx5UP0VeezUj73wKLwlSYMlVPuntsJoY7c8+lVrMCY9LQWYVZ7VMLBw==}
|
||||
'@clerk/[email protected].1':
|
||||
resolution: {integrity: sha512-7SXj7ACQSiqg72768cMHDGfNsdmpadKPvViV0b6ozqNbRjYrGkDM74fEf8i0Mg/0nGk5zpYI5fNKgQavpg/iMg==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
|
||||
'@clerk/[email protected]':
|
||||
@@ -1725,8 +1722,8 @@ packages:
|
||||
resolution: {integrity: sha512-OHhIe88qDL+FxyBalXdXNHAS5eEramr6Rerp+6iNkfkjqT8rx4hHNmfpmjg5/T1/am8QfknbOBZkqoXZlCrjPg==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
|
||||
'@clerk/[email protected]8':
|
||||
resolution: {integrity: sha512-0lWiITlTxCviglPfPSu+uhERnQyXroiWrSMRpZcEO3FgBt3bnrpfgZUrXW8iaLoUYJrFP2byF7bHJPRwEPVXEw==}
|
||||
'@clerk/[email protected]1':
|
||||
resolution: {integrity: sha512-QQzSYKwjrd447/kLiObkLQj+J6AyFr5MmPsg7k4TYXR2C4AAlpwkTnCV1ziRHa8V+Miq2MzQhcL6/2DdS7y9eA==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
peerDependencies:
|
||||
'@clerk/electron-passkeys': 0.0.3
|
||||
@@ -1742,13 +1739,12 @@ packages:
|
||||
react-dom:
|
||||
optional: true
|
||||
|
||||
'@clerk/expo@4.0.2':
|
||||
resolution: {integrity: sha512-afBdV2bLRM55p5L7FoAGV/wCamLxXusjIBPmNo+TwAYabU0oUokMsm+0++xWDA0nxzMt/O08Oj+xAGEtE+Qvxg==}
|
||||
'@clerk/expo@3.7.2':
|
||||
resolution: {integrity: sha512-wMTnieTEsTgJ3mJLZaiH+0uLaOp93lUsZLtmS0BQyK32xK49Y28ArFt7QkmnUB39EKT4MZve1XDctxZtCFmvVA==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
peerDependencies:
|
||||
'@clerk/expo-google-signin': '>=0.1.0'
|
||||
'@clerk/expo-passkeys': '>=0.0.6'
|
||||
expo: '>=54 <58'
|
||||
expo: '>=53 <58'
|
||||
expo-apple-authentication: '>=7.0.0'
|
||||
expo-auth-session: '>=5'
|
||||
expo-constants: '>=12'
|
||||
@@ -1760,8 +1756,6 @@ packages:
|
||||
react-dom: ^18.0.0 || ^19.0.0
|
||||
react-native: '>=0.75'
|
||||
peerDependenciesMeta:
|
||||
'@clerk/expo-google-signin':
|
||||
optional: true
|
||||
'@clerk/expo-passkeys':
|
||||
optional: true
|
||||
expo-apple-authentication:
|
||||
@@ -1781,15 +1775,15 @@ packages:
|
||||
react-dom:
|
||||
optional: true
|
||||
|
||||
'@clerk/[email protected].7':
|
||||
resolution: {integrity: sha512-K8CK0tS7My/3RT5sAIJTjYgnH0xU+K4Jdnhi76xQdAY4agD/M07BbrBMWXEE0xUEDst2PqPfX660V1LRLOsxOQ==}
|
||||
'@clerk/[email protected].1':
|
||||
resolution: {integrity: sha512-FFIv0SUQh9R8lBOCpHfAC5ki+FjU0WlvBrujJUPQgBTJX7uaRUlbzKswB/ZfRlauGKnE9c80H5dnir08cEtLgw==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
peerDependencies:
|
||||
react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
|
||||
react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
|
||||
|
||||
'@clerk/[email protected].7':
|
||||
resolution: {integrity: sha512-FfBbDeFkxwDuz/2YcVs4DhyZ0VxnqNtdbO0Tn/lkLAiDvFFspWw+PDYqo7LQiBymEQaOQkb094dX21WWnZbmlA==}
|
||||
'@clerk/[email protected].1':
|
||||
resolution: {integrity: sha512-+FHoFEJ8zGenUymf03gARKEAYOLxOKm6B437tgukxP7oM5ORfI+ZND62W25S8ddVsDLlNTS0VEHlhDm3F+NF0A==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
peerDependencies:
|
||||
react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
|
||||
@@ -5683,6 +5677,9 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-ZMANVnAixE6AWWnPzlW2KpUrxhm9woycYvPOo67jWHyFowASTEd9s+QN1EIMsSDtwhIxN4sWE1jotpuDUIgyIw==}
|
||||
engines: {node: '>=6.14.2'}
|
||||
@@ -7226,6 +7223,9 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-8Sb3veuYCyrZL+VBt9LJfZjLUPWVvqn8tG28VqYNFCo43KHcKuq+b4EiXGeuaLAQWL2YmyDgMp2aSpH9JHsEQg==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
|
||||
engines: {node: '>= 4'}
|
||||
@@ -8956,8 +8956,8 @@ packages:
|
||||
react: '*'
|
||||
react-native: '*'
|
||||
|
||||
react-native-url-polyfill@4.0.0:
|
||||
resolution: {integrity: sha512-eqYM3wBAA0eL1sPYbBAoNfbES3+NkgcxUdelQ7QzmoVtqKB5qGG0U13MPTRUroAWK+y2EoJFS3MZUK0fwTf0pA==}
|
||||
react-native-url-polyfill@2.0.0:
|
||||
resolution: {integrity: sha512-My330Do7/DvKnEvwQc0WdcBnFPploYKp9CYlefDXzIdEaA+PAhDYllkvGeEroEzvc4Kzzj2O4yVdz8v6fjRvhA==}
|
||||
peerDependencies:
|
||||
react-native: '*'
|
||||
|
||||
@@ -10187,6 +10187,10 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-VlZwKPCkYKxQgeSbH5EyngOmRp7Ww7I9rQLERETtf5ofd9pGeswWiOtogpEO850jziPRarreGxn5QIiTqpb2wA==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==}
|
||||
|
||||
@@ -10196,6 +10200,10 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-XPEm0XFQWNVG292lII1PrRRJl3sItrs7CettZ4ncYxuDVpLyy+NwlGyut2hXI0JswcJUxeCH+CyOJK0ZzAXD6A==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-HoKuzZrUlgpz35YO27XgD28uh/WJH4B0+3ttFqRo//lmq+9T/mIOJ6kqmINI9HpUpz1imRC/nR/lxKpJiv0uig==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-n1brCuqClxfFfq/Rb0ICg9giSZqCS+pLtccdag6C2HyufBrh3fBOiy9nb6ggRMvWOVH5GrdJskj5iGTZNxd7SA==}
|
||||
engines: {node: '>=4'}
|
||||
@@ -11404,18 +11412,18 @@ snapshots:
|
||||
fast-wrap-ansi: 0.2.2
|
||||
sisteransi: 1.0.5
|
||||
|
||||
'@clerk/[email protected]3.0([email protected]([email protected]))([email protected])':
|
||||
'@clerk/[email protected]1.2([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@clerk/shared': 4.25.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/shared': 4.25.1([email protected]([email protected]))([email protected])
|
||||
standardwebhooks: 1.0.0
|
||||
tslib: 2.8.1
|
||||
transitivePeerDependencies:
|
||||
- react
|
||||
- react-dom
|
||||
|
||||
'@clerk/[email protected].7([email protected]([email protected]))([email protected])':
|
||||
'@clerk/[email protected].1([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@clerk/shared': 4.25.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/shared': 4.25.1([email protected]([email protected]))([email protected])
|
||||
'@stripe/stripe-js': 5.6.0
|
||||
'@swc/helpers': 0.5.21
|
||||
'@tanstack/query-core': 5.100.14
|
||||
@@ -11430,9 +11438,9 @@ snapshots:
|
||||
- react
|
||||
- react-dom
|
||||
|
||||
'@clerk/[email protected].7([email protected]([email protected]))([email protected])':
|
||||
'@clerk/[email protected].1([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@clerk/shared': 4.25.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/shared': 4.25.1([email protected]([email protected]))([email protected])
|
||||
'@stripe/stripe-js': 5.6.0
|
||||
'@swc/helpers': 0.5.21
|
||||
'@tanstack/query-core': 5.100.14
|
||||
@@ -11466,11 +11474,11 @@ snapshots:
|
||||
'@clerk/electron-passkeys-win32-arm64-msvc': 0.0.3
|
||||
'@clerk/electron-passkeys-win32-x64-msvc': 0.0.3
|
||||
|
||||
'@clerk/[email protected]8(@clerk/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])':
|
||||
'@clerk/[email protected]1(@clerk/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@clerk/clerk-js': 6.25.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/react': 6.12.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/shared': 4.25.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/clerk-js': 6.25.1([email protected]([email protected]))([email protected])
|
||||
'@clerk/react': 6.12.1([email protected]([email protected]))([email protected])
|
||||
'@clerk/shared': 4.25.1([email protected]([email protected]))([email protected])
|
||||
electron: 41.5.0
|
||||
react: 19.2.6
|
||||
tslib: 2.8.1
|
||||
@@ -11479,17 +11487,17 @@ snapshots:
|
||||
electron-store: 8.2.0
|
||||
react-dom: 19.2.6([email protected])
|
||||
|
||||
'@clerk/expo@4.0.2([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])':
|
||||
'@clerk/expo@3.7.2([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])':
|
||||
dependencies:
|
||||
'@clerk/clerk-js': 6.25.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/react': 6.12.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/shared': 4.25.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/clerk-js': 6.25.1([email protected]([email protected]))([email protected])
|
||||
'@clerk/react': 6.12.1([email protected]([email protected]))([email protected])
|
||||
'@clerk/shared': 4.25.1([email protected]([email protected]))([email protected])
|
||||
'@expo/config-plugins': 56.0.9([email protected])
|
||||
base-64: 1.0.0
|
||||
expo: 56.0.12(8895228379997a2a064f9644cda56ed0)
|
||||
react: 19.2.3
|
||||
react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])
|
||||
react-native-url-polyfill: 4.0.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))
|
||||
react-native-url-polyfill: 2.0.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))
|
||||
tslib: 2.8.1
|
||||
optionalDependencies:
|
||||
expo-auth-session: 56.0.14([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
|
||||
@@ -11502,21 +11510,21 @@ snapshots:
|
||||
- supports-color
|
||||
- typescript
|
||||
|
||||
'@clerk/[email protected].7([email protected]([email protected]))([email protected])':
|
||||
'@clerk/[email protected].1([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@clerk/shared': 4.25.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/shared': 4.25.1([email protected]([email protected]))([email protected])
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3([email protected])
|
||||
tslib: 2.8.1
|
||||
|
||||
'@clerk/[email protected].7([email protected]([email protected]))([email protected])':
|
||||
'@clerk/[email protected].1([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@clerk/shared': 4.25.7([email protected]([email protected]))([email protected])
|
||||
'@clerk/shared': 4.25.1([email protected]([email protected]))([email protected])
|
||||
react: 19.2.6
|
||||
react-dom: 19.2.6([email protected])
|
||||
tslib: 2.8.1
|
||||
|
||||
'@clerk/[email protected].7([email protected]([email protected]))([email protected])':
|
||||
'@clerk/[email protected].1([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@tanstack/query-core': 5.100.14
|
||||
dequal: 2.0.3
|
||||
@@ -11526,7 +11534,7 @@ snapshots:
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3([email protected])
|
||||
|
||||
'@clerk/[email protected].7([email protected]([email protected]))([email protected])':
|
||||
'@clerk/[email protected].1([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@tanstack/query-core': 5.100.14
|
||||
dequal: 2.0.3
|
||||
@@ -15851,6 +15859,11 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
base64-js: 1.5.1
|
||||
ieee754: 1.2.1
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
node-gyp-build: 4.8.4
|
||||
@@ -17793,6 +17806,8 @@ snapshots:
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
@@ -19777,9 +19792,10 @@ snapshots:
|
||||
react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])
|
||||
warn-once: 0.1.1
|
||||
|
||||
react-native-url-polyfill@4.0.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])):
|
||||
react-native-url-polyfill@2.0.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])):
|
||||
dependencies:
|
||||
react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])
|
||||
whatwg-url-without-unicode: 8.0.0-3
|
||||
|
||||
[email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):
|
||||
dependencies:
|
||||
@@ -21346,12 +21362,20 @@ snapshots:
|
||||
asn1js: 3.0.10
|
||||
tslib: 2.8.1
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
buffer: 5.7.1
|
||||
punycode: 2.3.1
|
||||
webidl-conversions: 5.0.0
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
|
||||
+12
-12
@@ -23,13 +23,13 @@ allowBuilds:
|
||||
workerd: false
|
||||
|
||||
catalog:
|
||||
"@clerk/backend": 3.13.0
|
||||
"@clerk/clerk-js": 6.25.7
|
||||
"@clerk/electron": 0.0.18
|
||||
"@clerk/backend": 3.11.2
|
||||
"@clerk/clerk-js": 6.25.1
|
||||
"@clerk/electron": 0.0.11
|
||||
"@clerk/electron-passkeys": 0.0.3
|
||||
"@clerk/expo": 4.0.2
|
||||
"@clerk/react": 6.12.7
|
||||
"@clerk/shared": 4.25.7
|
||||
"@clerk/expo": 3.7.2
|
||||
"@clerk/react": 6.12.1
|
||||
"@clerk/shared": 4.25.1
|
||||
"@effect/atom-react": 4.0.0-beta.78
|
||||
"@effect/openapi-generator": 4.0.0-beta.78
|
||||
"@effect/platform-bun": 4.0.0-beta.78
|
||||
@@ -52,12 +52,12 @@ catalog:
|
||||
yaml: ^2.9.0
|
||||
|
||||
minimumReleaseAgeExclude:
|
||||
- "@clerk/[email protected]3.0"
|
||||
- "@clerk/[email protected].7"
|
||||
- "@clerk/[email protected]8"
|
||||
- "@clerk/expo@4.0.2"
|
||||
- "@clerk/[email protected].7"
|
||||
- "@clerk/[email protected].7"
|
||||
- "@clerk/[email protected]1.2"
|
||||
- "@clerk/[email protected].1"
|
||||
- "@clerk/[email protected]1"
|
||||
- "@clerk/expo@3.7.2"
|
||||
- "@clerk/[email protected].1"
|
||||
- "@clerk/[email protected].1"
|
||||
|
||||
overrides:
|
||||
"@clerk/backend": "catalog:"
|
||||
|
||||
+2
-553
@@ -1,14 +1,6 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - builds real worktree layouts on disk.
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import {
|
||||
HostProcessEnvironment,
|
||||
HostProcessPlatform,
|
||||
HostProcessWorkingDirectory,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -22,10 +14,8 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
checkPortAvailabilityOnHosts,
|
||||
createDevRunnerEnv,
|
||||
devPortProbeHosts,
|
||||
findFirstAvailableOffset,
|
||||
getDevRunnerModeArgs,
|
||||
isBrowserAllowedPort,
|
||||
resolveModePortOffsets,
|
||||
resolveOffset,
|
||||
runDevRunnerWithInput,
|
||||
@@ -68,7 +58,6 @@ const devServerInput = {
|
||||
port: 13_773,
|
||||
devUrl: undefined,
|
||||
dryRun: false,
|
||||
share: false,
|
||||
runArgs: ["--inspect", "secret-token-value"],
|
||||
} as const;
|
||||
|
||||
@@ -347,175 +336,8 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_PORT, "13773");
|
||||
assert.equal(env.PORT, "5733");
|
||||
}),
|
||||
);
|
||||
|
||||
// Browser dev is single-origin: Vite proxies the backend, and the client
|
||||
// resolves it from window.location.origin. Baking a localhost URL here is
|
||||
// what breaks sharing a dev server to another device.
|
||||
for (const mode of ["dev", "dev:web"] as const) {
|
||||
it.effect(`leaves the client backend URLs unset in ${mode} mode`, () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode,
|
||||
baseEnv: {
|
||||
VITE_HTTP_URL: "http://localhost:1234",
|
||||
VITE_WS_URL: "ws://localhost:1234",
|
||||
},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.VITE_HTTP_URL, undefined);
|
||||
assert.equal(env.VITE_WS_URL, undefined);
|
||||
assert.equal(env.T3CODE_PORT, "13773");
|
||||
// Deleting the keys is not sufficient — vite.config.ts merges
|
||||
// `.env`/`.env.local` underneath this env and would revive them, so
|
||||
// the intent has to be stated positively.
|
||||
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, "1");
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Desktop pins the renderer at loopback deliberately; an ambient marker
|
||||
// must not make Vite discard those URLs.
|
||||
it.effect("clears the single-origin marker in dev:desktop mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:desktop",
|
||||
baseEnv: { T3CODE_SINGLE_ORIGIN_DEV: "1" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, undefined);
|
||||
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:13773");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears the single-origin marker in dev:server mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:server",
|
||||
baseEnv: { T3CODE_SINGLE_ORIGIN_DEV: "1" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, undefined);
|
||||
assert.equal(env.VITE_HTTP_URL, "http://localhost:13773");
|
||||
}),
|
||||
);
|
||||
|
||||
// HOST is Vite's bind address and gates the HMR pin in vite.config.ts. An
|
||||
// inherited one would survive into browser dev and point HMR at the wrong
|
||||
// interface — invisible over a shared origin, since the page still loads.
|
||||
for (const mode of ["dev", "dev:web"] as const) {
|
||||
it.effect(`drops an inherited HOST in ${mode} mode`, () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode,
|
||||
baseEnv: { HOST: "0.0.0.0" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.HOST, undefined);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// --host configures the *backend* (T3CODE_HOST). It must not become Vite's
|
||||
// bind address by way of an inherited HOST that happens to agree with it.
|
||||
it.effect("drops an inherited HOST even when --host is given", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
baseEnv: { HOST: "0.0.0.0" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: "0.0.0.0",
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.HOST, undefined);
|
||||
assert.equal(env.T3CODE_HOST, "0.0.0.0");
|
||||
}),
|
||||
);
|
||||
|
||||
// Desktop sets HOST itself, so the clearing must not reach it.
|
||||
it.effect("still pins HOST for dev:desktop", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:desktop",
|
||||
baseEnv: { HOST: "0.0.0.0" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.HOST, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps explicit backend URLs for the desktop renderer", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:desktop",
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:13773");
|
||||
assert.equal(env.VITE_WS_URL, "ws://127.0.0.1:13773");
|
||||
assert.equal(env.VITE_WS_URL, "ws://localhost:13773");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -548,41 +370,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips browser-blocked web ports before probing availability", () =>
|
||||
Effect.gen(function* () {
|
||||
const probed: Array<{ port: number; role: string | undefined }> = [];
|
||||
const offset = yield* findFirstAvailableOffset({
|
||||
// 5733 + 833 = 6566, which browsers block as sane-port.
|
||||
startOffset: 833,
|
||||
requireServerPort: true,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability: (port, role) => {
|
||||
probed.push({ port, role });
|
||||
return Effect.succeed(true);
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(offset, 834);
|
||||
assert.deepStrictEqual(probed, [
|
||||
{ port: 14_607, role: "server" },
|
||||
{ port: 6567, role: "web" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not reject a server-only offset because its unused web port is blocked", () =>
|
||||
Effect.gen(function* () {
|
||||
const offset = yield* findFirstAvailableOffset({
|
||||
startOffset: 833,
|
||||
requireServerPort: true,
|
||||
requireWebPort: false,
|
||||
checkPortAvailability: () => Effect.succeed(true),
|
||||
});
|
||||
|
||||
assert.equal(offset, 833);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows offsets where the non-required server port exceeds max", () =>
|
||||
Effect.gen(function* () {
|
||||
const offset = yield* findFirstAvailableOffset({
|
||||
@@ -619,19 +406,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("isBrowserAllowedPort", () => {
|
||||
it.each([6000, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697])(
|
||||
"rejects Fetch-blocked web port %s from the worktree offset range",
|
||||
(port) => {
|
||||
assert.equal(isBrowserAllowedPort(port), false);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([5733, 5900, 6567, 6670, 8733])("allows browser-safe web port %s", (port) => {
|
||||
assert.equal(isBrowserAllowedPort(port), true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkPortAvailabilityOnHosts", () => {
|
||||
it.effect("checks overlapping hosts sequentially to avoid self-interference", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -662,59 +436,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("devPortProbeHosts", () => {
|
||||
it.effect("probes loopback only when no bind host is configured", () =>
|
||||
Effect.sync(() => {
|
||||
assert.deepStrictEqual(devPortProbeHosts(undefined), ["127.0.0.1", "::1"]);
|
||||
assert.deepStrictEqual(devPortProbeHosts(" "), ["127.0.0.1", "::1"]);
|
||||
}),
|
||||
);
|
||||
|
||||
// A port free on loopback can be taken on the interface the server will
|
||||
// actually bind, so --host/T3CODE_HOST has to be probed as well.
|
||||
it.effect("adds a non-loopback bind host to the probe list", () =>
|
||||
Effect.sync(() => {
|
||||
assert.deepStrictEqual(devPortProbeHosts("0.0.0.0"), ["127.0.0.1", "::1", "0.0.0.0"]);
|
||||
assert.deepStrictEqual(devPortProbeHosts("192.168.1.10"), [
|
||||
"127.0.0.1",
|
||||
"::1",
|
||||
"192.168.1.10",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not probe loopback twice when it is the configured host", () =>
|
||||
Effect.sync(() => {
|
||||
assert.deepStrictEqual(devPortProbeHosts("127.0.0.1"), ["127.0.0.1", "::1"]);
|
||||
}),
|
||||
);
|
||||
|
||||
// Only the backend honours --host/T3CODE_HOST. Vite reads HOST (set for
|
||||
// desktop only), so judging the web port against the backend's interface
|
||||
// would reject ports for a server that never binds there.
|
||||
it.effect("passes the port role so only the server port sees the bind host", () =>
|
||||
Effect.gen(function* () {
|
||||
const probed: Array<{ port: number; role: string | undefined }> = [];
|
||||
|
||||
yield* resolveModePortOffsets({
|
||||
mode: "dev",
|
||||
startOffset: 0,
|
||||
hasExplicitServerPort: false,
|
||||
hasExplicitDevUrl: false,
|
||||
checkPortAvailability: (port, role) => {
|
||||
probed.push({ port, role });
|
||||
return Effect.succeed(true);
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(probed, [
|
||||
{ port: 13_773, role: "server" },
|
||||
{ port: 5733, role: "web" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveModePortOffsets", () => {
|
||||
it.effect("uses a shared fallback offset for dev mode", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -848,170 +569,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
});
|
||||
});
|
||||
|
||||
// `tailscale serve` config outlives the process, so a dry run that shared
|
||||
// would replace and then tear down whatever mapping the port already had.
|
||||
// Base-dir precedence (--home-dir > worktree .t3 > ambient T3CODE_HOME)
|
||||
// lives in runDevRunnerWithInput; the env builder must not consult the
|
||||
// ambient variable on its own, or it would silently outrank the worktree
|
||||
// default and land dev state on the user's real database.
|
||||
it.effect("ignores an ambient T3CODE_HOME when no home is resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
baseEnv: { T3CODE_HOME: "/home/user/.t3" },
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
browser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_HOME, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
// Sharing dev:desktop would publish a URL whose renderer dials the
|
||||
// visitor's own loopback, and would clobber the VITE_DEV_SERVER_URL that
|
||||
// Electron loads from. It must decline, not half-work.
|
||||
it.effect("declines to share for dev:desktop and still starts the stack", () => {
|
||||
let spawnCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => {
|
||||
spawnCount += 1;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
mode: "dev:desktop",
|
||||
port: undefined,
|
||||
share: true,
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
);
|
||||
|
||||
assert.equal(spawnCount, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// Single-origin browser dev proxies the backend at localhost, so a backend
|
||||
// bound only to a specific interface breaks every proxied request in a way
|
||||
// that looks like a broken server. Reject the combination up front.
|
||||
it.effect("rejects a specific non-loopback --host for browser dev modes", () => {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.succeed(mockProcess(0))),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
mode: "dev",
|
||||
port: undefined,
|
||||
host: "192.168.1.10",
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
if (error._tag !== "DevRunnerHostNotProxiableError") {
|
||||
assert.fail(`Unexpected error: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.mode, "dev");
|
||||
assert.equal(error.host, "192.168.1.10");
|
||||
assert.include(error.message, "0.0.0.0");
|
||||
assert.include(error.message, "--share");
|
||||
});
|
||||
});
|
||||
|
||||
// Wildcards keep loopback answering, so the proxy target stays valid and
|
||||
// the combination must keep working — it is the documented way to serve a
|
||||
// LAN interface and the browser proxy at once.
|
||||
it.effect("still spawns the stack for a wildcard --host in dev mode", () => {
|
||||
let spawnCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => {
|
||||
spawnCount += 1;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
mode: "dev",
|
||||
port: undefined,
|
||||
host: "0.0.0.0",
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
);
|
||||
|
||||
assert.equal(spawnCount, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// dev:server does not proxy — the client talks to the backend directly —
|
||||
// so a specific interface bind stays legitimate there.
|
||||
it.effect("keeps a specific --host working for dev:server", () => {
|
||||
let spawnCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => {
|
||||
spawnCount += 1;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
host: "192.168.1.10",
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
);
|
||||
|
||||
assert.equal(spawnCount, 1);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("spawns nothing when --dry-run is combined with --share", () => {
|
||||
let spawnCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => {
|
||||
spawnCount += 1;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runDevRunnerWithInput({
|
||||
...devServerInput,
|
||||
mode: "dev",
|
||||
port: undefined,
|
||||
dryRun: true,
|
||||
share: true,
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
);
|
||||
|
||||
assert.equal(spawnCount, 0);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("reports non-zero exits without manufacturing a cause", () => {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
@@ -1072,113 +629,5 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
assert.notInclude(error.message, "secret-token-value");
|
||||
});
|
||||
});
|
||||
|
||||
describe("t3 home precedence", () => {
|
||||
const makeWorktree = Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devrunner-"));
|
||||
NodeFS.writeFileSync(
|
||||
NodePath.join(root, ".git"),
|
||||
"gitdir: /elsewhere/.git/worktrees/x\n",
|
||||
);
|
||||
return root;
|
||||
}),
|
||||
(root) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),
|
||||
);
|
||||
|
||||
const spawnedHome = (input: {
|
||||
readonly t3Home: string | undefined;
|
||||
readonly cwd: string;
|
||||
readonly ambientHome: string | undefined;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
let captured: Record<string, string | undefined> | undefined;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
captured = (
|
||||
command as {
|
||||
readonly options?: { readonly env?: Record<string, string | undefined> };
|
||||
}
|
||||
).options?.env;
|
||||
return Effect.succeed(mockProcess(0));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* runDevRunnerWithInput({ ...devServerInput, t3Home: input.t3Home }).pipe(
|
||||
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.provideService(HostProcessWorkingDirectory, input.cwd),
|
||||
Effect.provideService(
|
||||
HostProcessEnvironment,
|
||||
input.ambientHome === undefined ? {} : { T3CODE_HOME: input.ambientHome },
|
||||
),
|
||||
);
|
||||
|
||||
return captured?.T3CODE_HOME;
|
||||
});
|
||||
|
||||
it.effect("prefers an explicit --home-dir over the worktree default", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* makeWorktree;
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: "/tmp/explicit-home",
|
||||
cwd: root,
|
||||
ambientHome: "/home/user/.t3",
|
||||
});
|
||||
assert.equal(home, path.resolve("/tmp/explicit-home"));
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("treats a blank --home-dir as unset rather than as a selection", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* makeWorktree;
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: " ",
|
||||
cwd: root,
|
||||
ambientHome: "/home/user/.t3",
|
||||
});
|
||||
assert.equal(home, path.join(path.resolve(root), ".t3"));
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("prefers the worktree .t3 over an ambient T3CODE_HOME", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* makeWorktree;
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: undefined,
|
||||
cwd: root,
|
||||
ambientHome: "/home/user/.t3",
|
||||
});
|
||||
assert.equal(home, path.join(path.resolve(root), ".t3"));
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("falls back to an ambient T3CODE_HOME outside a worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: undefined,
|
||||
cwd: NodeOS.tmpdir(),
|
||||
ambientHome: "/home/user/.t3",
|
||||
});
|
||||
assert.equal(home, path.resolve("/home/user/.t3"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("leaves the home implicit with no worktree and no ambient value", () =>
|
||||
Effect.gen(function* () {
|
||||
const home = yield* spawnedHome({
|
||||
t3Home: undefined,
|
||||
cwd: NodeOS.tmpdir(),
|
||||
ambientHome: undefined,
|
||||
});
|
||||
assert.equal(home, undefined);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
+28
-284
@@ -1,13 +1,11 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { resolveGitWorktreePath, resolveWorktreeT3Home } from "@t3tools/shared/devHome";
|
||||
import { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
|
||||
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -20,7 +18,6 @@ import * as Schema from "effect/Schema";
|
||||
import { Argument, Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess } from "effect/unstable/process";
|
||||
|
||||
import { acquireDevShare, cleanupOwnedDevShare, type DevShareError } from "./lib/dev-share.ts";
|
||||
import { loadRepoEnv } from "./lib/public-config.ts";
|
||||
|
||||
Object.assign(process.env, loadRepoEnv());
|
||||
@@ -30,43 +27,7 @@ const BASE_WEB_PORT = 5733;
|
||||
const MAX_HASH_OFFSET = 3000;
|
||||
const MAX_PORT = 65535;
|
||||
const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
|
||||
// HTTP(S) requests to these ports are blocked by the Fetch standard before a
|
||||
// browser reaches the network. Keep the complete list here so explicit or
|
||||
// future wider offsets cannot produce a URL that curl accepts but browsers
|
||||
// reject. https://fetch.spec.whatwg.org/#port-blocking
|
||||
const FETCH_BAD_PORTS = new Set([
|
||||
0, 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102,
|
||||
103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
|
||||
512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
|
||||
995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
|
||||
6669, 6679, 6697, 10080,
|
||||
]);
|
||||
// Dev servers bind loopback, so loopback is the only interface whose
|
||||
// availability decides whether we can use a port. Probing wildcards too made
|
||||
// the runner walk away from a perfectly free port whenever something else held
|
||||
// the same number on another interface — `tailscale serve` does exactly that,
|
||||
// which silently moved the ports out from under a URL that had just been shared.
|
||||
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
|
||||
|
||||
/**
|
||||
* Bind hosts on which a backend still answers `http://localhost:<port>`, which
|
||||
* is where single-origin browser dev proxies to. Loopback and the wildcards
|
||||
* qualify; a specific interface (e.g. a LAN IP) does not — the OS binds only
|
||||
* that address and the proxy target goes dark.
|
||||
*/
|
||||
export function isProxiableBindHost(host: string): boolean {
|
||||
const normalized = host.trim();
|
||||
return (
|
||||
normalized === "" ||
|
||||
normalized === "localhost" ||
|
||||
normalized === "127.0.0.1" ||
|
||||
normalized === "::1" ||
|
||||
normalized === "[::1]" ||
|
||||
normalized === "0.0.0.0" ||
|
||||
normalized === "::" ||
|
||||
normalized === "[::]"
|
||||
);
|
||||
}
|
||||
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::1", "::"] as const;
|
||||
|
||||
export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
path.join(NodeOS.homedir(), ".t3"),
|
||||
@@ -87,15 +48,7 @@ const MODE_ARGS = {
|
||||
} as const satisfies Record<string, ReadonlyArray<string>>;
|
||||
|
||||
type DevMode = keyof typeof MODE_ARGS;
|
||||
/**
|
||||
* `role` matters because only the backend honours `--host`/`T3CODE_HOST`; the
|
||||
* web port is always loopback. Passed explicitly rather than inferred from the
|
||||
* port number, which stops distinguishing them under a large port offset.
|
||||
*/
|
||||
type PortAvailabilityCheck<R = never> = (
|
||||
port: number,
|
||||
role?: "server" | "web",
|
||||
) => Effect.Effect<boolean, never, R>;
|
||||
type PortAvailabilityCheck<R = never> = (port: number) => Effect.Effect<boolean, never, R>;
|
||||
|
||||
const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
|
||||
|
||||
@@ -103,10 +56,6 @@ export function getDevRunnerModeArgs(mode: DevMode): ReadonlyArray<string> {
|
||||
return MODE_ARGS[mode];
|
||||
}
|
||||
|
||||
export function isBrowserAllowedPort(port: number): boolean {
|
||||
return !FETCH_BAD_PORTS.has(port);
|
||||
}
|
||||
|
||||
export class DevRunnerConfigurationError extends Schema.TaggedErrorClass<DevRunnerConfigurationError>()(
|
||||
"DevRunnerConfigurationError",
|
||||
{
|
||||
@@ -179,21 +128,8 @@ export class DevRunnerProcessExitError extends Schema.TaggedErrorClass<DevRunner
|
||||
}
|
||||
}
|
||||
|
||||
export class DevRunnerHostNotProxiableError extends Schema.TaggedErrorClass<DevRunnerHostNotProxiableError>()(
|
||||
"DevRunnerHostNotProxiableError",
|
||||
{
|
||||
mode: Schema.Literals(["dev", "dev:web"]),
|
||||
host: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `--host ${this.host} cannot be combined with ${this.mode}: single-origin browser dev proxies the backend at localhost, and a backend bound only to ${this.host} leaves localhost unanswered, so every proxied request fails. Use a wildcard (0.0.0.0 or ::) to serve that interface and loopback together, or --share for remote access.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const DevRunnerError = Schema.Union([
|
||||
DevRunnerConfigurationError,
|
||||
DevRunnerHostNotProxiableError,
|
||||
DevRunnerInvalidPortOffsetError,
|
||||
DevRunnerPortExhaustedError,
|
||||
DevRunnerProcessError,
|
||||
@@ -230,7 +166,6 @@ const OffsetConfig = Config.all({
|
||||
export function resolveOffset(config: {
|
||||
readonly portOffset: number | undefined;
|
||||
readonly devInstance: string | undefined;
|
||||
readonly worktreePath?: string | undefined;
|
||||
}): Effect.Effect<
|
||||
{ readonly offset: number; readonly source: string },
|
||||
DevRunnerInvalidPortOffsetError
|
||||
@@ -252,30 +187,19 @@ export function resolveOffset(config: {
|
||||
}
|
||||
|
||||
const seed = config.devInstance?.trim();
|
||||
if (seed) {
|
||||
if (/^\d+$/.test(seed)) {
|
||||
return Effect.succeed({
|
||||
offset: Number(seed),
|
||||
source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
|
||||
});
|
||||
}
|
||||
|
||||
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
|
||||
return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
|
||||
if (!seed) {
|
||||
return Effect.succeed({ offset: 0, source: "default ports" });
|
||||
}
|
||||
|
||||
// Worktrees get ports derived from their path so each one is stable across
|
||||
// restarts and distinct from its siblings. Without this every worktree starts
|
||||
// at offset 0 and scan-collides onto whatever happens to be free that minute,
|
||||
// so ports move under you between runs — which breaks any URL you already
|
||||
// shared. The main checkout keeps the documented 5733/13773.
|
||||
const worktreePath = config.worktreePath?.trim();
|
||||
if (worktreePath) {
|
||||
const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
|
||||
return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
|
||||
if (/^\d+$/.test(seed)) {
|
||||
return Effect.succeed({
|
||||
offset: Number(seed),
|
||||
source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
|
||||
});
|
||||
}
|
||||
|
||||
return Effect.succeed({ offset: 0, source: "default ports" });
|
||||
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
|
||||
return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
|
||||
}
|
||||
|
||||
function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
|
||||
@@ -321,9 +245,7 @@ export function createDevRunnerEnv({
|
||||
return Effect.gen(function* () {
|
||||
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
|
||||
const webPort = BASE_WEB_PORT + webOffset;
|
||||
// Precedence (--home-dir > worktree .t3 > ambient T3CODE_HOME) is resolved
|
||||
// by the caller; an unset t3Home here genuinely means "use the default".
|
||||
const configuredBaseDir = t3Home?.trim() || undefined;
|
||||
const configuredBaseDir = t3Home?.trim() || baseEnv.T3CODE_HOME?.trim() || undefined;
|
||||
const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
|
||||
const isDesktopMode = mode === "dev:desktop";
|
||||
|
||||
@@ -343,41 +265,12 @@ export function createDevRunnerEnv({
|
||||
|
||||
if (!isDesktopMode) {
|
||||
output.T3CODE_PORT = String(serverPort);
|
||||
// HOST is Vite's own bind address, and the desktop branch below is the
|
||||
// only place we set it. An inherited one (an exported HOST, a container,
|
||||
// a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
|
||||
// its HMR socket to that address — see the `explicitHost` gate in
|
||||
// apps/web/vite.config.ts. Over a shared origin that is invisible: the
|
||||
// page loads and only HMR quietly dials the wrong machine.
|
||||
delete output.HOST;
|
||||
if (mode === "dev" || mode === "dev:web") {
|
||||
// Browser dev is single-origin: everything (including /ws) is proxied
|
||||
// through Vite, so the client must resolve its backend from
|
||||
// window.location.origin rather than a baked-in localhost URL. See
|
||||
// resolveConfiguredPrimaryTarget in apps/web/src/environments/primary/target.ts
|
||||
// — it only defers to the origin when both of these are absent. Baking
|
||||
// localhost here is what breaks any non-localhost origin (tailnet, LAN,
|
||||
// phone): the remote browser dials its own machine.
|
||||
delete output.VITE_HTTP_URL;
|
||||
delete output.VITE_WS_URL;
|
||||
// Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
|
||||
// which merges `.env`/`.env.local` *under* this env, so a developer
|
||||
// with either URL in their `.env` would get it back and silently lose
|
||||
// single-origin mode. This states the intent positively so Vite can
|
||||
// ignore those values rather than infer from their absence.
|
||||
output.T3CODE_SINGLE_ORIGIN_DEV = "1";
|
||||
} else {
|
||||
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
|
||||
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
|
||||
delete output.T3CODE_SINGLE_ORIGIN_DEV;
|
||||
}
|
||||
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
|
||||
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
|
||||
} else {
|
||||
output.T3CODE_PORT = String(serverPort);
|
||||
output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
|
||||
output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
|
||||
// Desktop pins the renderer to loopback on purpose; an ambient marker
|
||||
// must not make Vite drop those URLs.
|
||||
delete output.T3CODE_SINGLE_ORIGIN_DEV;
|
||||
delete output.T3CODE_MODE;
|
||||
delete output.T3CODE_NO_BROWSER;
|
||||
delete output.T3CODE_HOST;
|
||||
@@ -448,41 +341,13 @@ export function checkPortAvailabilityOnHosts<R>(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hosts to probe for a dev server bound to `configuredHost`.
|
||||
*
|
||||
* Loopback is always checked because the web server and the desktop renderer
|
||||
* target reach it there. When `--host`/`T3CODE_HOST` moves the backend onto
|
||||
* another interface, that interface decides whether the bind actually
|
||||
* succeeds — probing only loopback would hand back a port that is free here
|
||||
* and taken there, and the server would fail to start.
|
||||
*
|
||||
* `configuredHost` applies to the *backend* only. Vite takes its bind address
|
||||
* from `HOST`, which the runner sets for desktop alone, so the web port stays
|
||||
* on loopback and must not be judged against the backend's interface —
|
||||
* a port free on loopback but busy on that interface would otherwise be
|
||||
* rejected for a server that was never going to bind there.
|
||||
*/
|
||||
export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
|
||||
const host = configuredHost?.trim();
|
||||
if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
|
||||
return DEV_PORT_PROBE_HOSTS;
|
||||
}
|
||||
return [...DEV_PORT_PROBE_HOSTS, host];
|
||||
}
|
||||
|
||||
const makeDefaultCheckPortAvailability =
|
||||
(configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
|
||||
(port, role) =>
|
||||
Effect.gen(function* () {
|
||||
const net = yield* NetService.NetService;
|
||||
const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
|
||||
return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
|
||||
net.canListenOnHost(candidatePort, host),
|
||||
);
|
||||
});
|
||||
|
||||
const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
|
||||
const defaultCheckPortAvailability: PortAvailabilityCheck<NetService.NetService> = (port) =>
|
||||
Effect.gen(function* () {
|
||||
const net = yield* NetService.NetService;
|
||||
return yield* checkPortAvailabilityOnHosts(port, DEV_PORT_PROBE_HOSTS, (candidatePort, host) =>
|
||||
net.canListenOnHost(candidatePort, host),
|
||||
);
|
||||
});
|
||||
|
||||
interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
|
||||
readonly startOffset: number;
|
||||
@@ -514,16 +379,12 @@ export function findFirstAvailableOffset<R = NetService.NetService>({
|
||||
break;
|
||||
}
|
||||
|
||||
if (requireWebPort && !isBrowserAllowedPort(webPort)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const checks: Array<Effect.Effect<boolean, never, R>> = [];
|
||||
if (requireServerPort) {
|
||||
checks.push(checkPort(serverPort, "server"));
|
||||
checks.push(checkPort(serverPort));
|
||||
}
|
||||
if (requireWebPort) {
|
||||
checks.push(checkPort(webPort, "web"));
|
||||
checks.push(checkPort(webPort));
|
||||
}
|
||||
|
||||
if (checks.length === 0) {
|
||||
@@ -619,7 +480,6 @@ interface DevRunnerCliInput {
|
||||
readonly port: number | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly dryRun: boolean;
|
||||
readonly share: boolean;
|
||||
readonly runArgs: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
@@ -635,55 +495,22 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
),
|
||||
);
|
||||
|
||||
// Single-origin browser dev proxies the backend at localhost. A wildcard
|
||||
// bind still answers there; a specific non-loopback interface does not,
|
||||
// which breaks every proxied request in a way that reads as "server is
|
||||
// broken" rather than "flag combination is unsupported". Reject it up
|
||||
// front instead. (dev:server and dev:desktop don't proxy — untouched.)
|
||||
if (
|
||||
(input.mode === "dev" || input.mode === "dev:web") &&
|
||||
input.host !== undefined &&
|
||||
!isProxiableBindHost(input.host)
|
||||
) {
|
||||
return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
|
||||
}
|
||||
|
||||
const worktreePath = yield* resolveGitWorktreePath(yield* HostProcessWorkingDirectory);
|
||||
|
||||
const { offset, source } = yield* resolveOffset({
|
||||
portOffset,
|
||||
devInstance,
|
||||
worktreePath,
|
||||
});
|
||||
const { offset, source } = yield* resolveOffset({ portOffset, devInstance });
|
||||
|
||||
const { serverOffset, webOffset } = yield* resolveModePortOffsets({
|
||||
mode: input.mode,
|
||||
startOffset: offset,
|
||||
hasExplicitServerPort: input.port !== undefined,
|
||||
hasExplicitDevUrl: input.devUrl !== undefined,
|
||||
// A non-loopback bind host decides whether the backend can actually take
|
||||
// the port, so it has to be probed alongside loopback.
|
||||
checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
|
||||
});
|
||||
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
// A dev server started inside a worktree defaults to that worktree's own
|
||||
// (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
|
||||
// outrank an ambient T3CODE_HOME. `--home-dir` still wins.
|
||||
const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcessWorkingDirectory);
|
||||
// Trim before choosing: `--home-dir ""` is not a selection, and treating it
|
||||
// as one would skip the worktree default and land on the shared home —
|
||||
// exactly the outcome this precedence exists to prevent.
|
||||
const resolvedT3Home =
|
||||
(input.t3Home?.trim() || undefined) ??
|
||||
worktreeHome ??
|
||||
(hostEnvironment.T3CODE_HOME?.trim() || undefined);
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: input.mode,
|
||||
baseEnv: hostEnvironment,
|
||||
serverOffset,
|
||||
webOffset,
|
||||
t3Home: resolvedT3Home,
|
||||
t3Home: input.t3Home,
|
||||
browser: input.browser,
|
||||
autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents: input.logWebSocketEvents,
|
||||
@@ -702,86 +529,10 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
|
||||
);
|
||||
|
||||
// Before the share block: --dry-run only resolves and prints. Sharing would
|
||||
// replace, then tear down, whatever mapping the port already had — a
|
||||
// surprising side effect from a command documented as inert.
|
||||
if (input.dryRun) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sharedWebPort = BASE_WEB_PORT + webOffset;
|
||||
if (input.share) {
|
||||
if (input.mode === "dev:server") {
|
||||
yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
|
||||
} else if (input.mode === "dev:desktop") {
|
||||
// Desktop is not single-origin: the renderer gets VITE_HTTP_URL and
|
||||
// VITE_WS_URL baked to loopback, so a tailnet visitor would load the UI
|
||||
// and then watch it dial its own 127.0.0.1 for the backend. Worse,
|
||||
// sharing would overwrite VITE_DEV_SERVER_URL, which is the origin
|
||||
// Electron itself loads the renderer from. Refuse rather than hand out
|
||||
// a URL that is broken in a way the user cannot see.
|
||||
yield* Effect.logWarning(
|
||||
"[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
|
||||
);
|
||||
} else {
|
||||
const path = yield* Path.Path;
|
||||
// acquireRelease, not share-then-addFinalizer: the mapping outlives this
|
||||
// process (and reboots), so the cleanup has to be registered atomically
|
||||
// with creating it. An interrupt landing in between would otherwise
|
||||
// leave a mapping pointing at a port nothing is listening on.
|
||||
//
|
||||
// A tailnet that isn't up shouldn't stop the dev server from starting —
|
||||
// warn, and carry on serving locally.
|
||||
const shared = yield* Effect.gen(function* () {
|
||||
const lease = {
|
||||
leasePath: path.join(baseDir, "dev-share", `${String(sharedWebPort)}.owner`),
|
||||
ownerId: `${String(process.pid)}:${NodeCrypto.randomUUID()}`,
|
||||
webPort: sharedWebPort,
|
||||
};
|
||||
return yield* Effect.acquireRelease(acquireDevShare(lease), () =>
|
||||
cleanupOwnedDevShare(lease).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.status !== "failed"
|
||||
? Effect.void
|
||||
: Effect.logWarning(
|
||||
`[dev-runner] could not safely clean up the tailnet mapping for port ${String(sharedWebPort)}: ${result.explanation}`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.tapError((error: DevShareError) =>
|
||||
Effect.logWarning(
|
||||
`[dev-runner] could not share on the tailnet: ${error.message}${
|
||||
error.hint ? ` — ${error.hint}` : ""
|
||||
}`,
|
||||
),
|
||||
),
|
||||
Effect.option,
|
||||
Effect.map(Option.getOrUndefined),
|
||||
);
|
||||
|
||||
if (shared) {
|
||||
// The app is reached from the tailnet origin. Vite already allows
|
||||
// *.ts.net hosts; the backend needs the origin for credentialed
|
||||
// requests that bypass the proxy (desktop renderer, direct calls).
|
||||
env.T3CODE_DEV_ALLOWED_ORIGINS = [
|
||||
env.T3CODE_DEV_ALLOWED_ORIGINS,
|
||||
new URL(shared.url).origin,
|
||||
]
|
||||
.filter((entry) => entry && entry.length > 0)
|
||||
.join(",");
|
||||
// The server builds its pairing URL from this, so the URL printed at
|
||||
// startup is already the shareable one — no rewriting by hand. An
|
||||
// explicit --dev-url still wins.
|
||||
if (input.devUrl === undefined) {
|
||||
env.VITE_DEV_SERVER_URL = shared.url;
|
||||
}
|
||||
yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
"vp",
|
||||
[...MODE_ARGS[input.mode], ...input.runArgs],
|
||||
@@ -841,10 +592,9 @@ const devRunnerCli = Command.make("dev-runner", {
|
||||
),
|
||||
t3Home: Flag.string("home-dir").pipe(
|
||||
Flag.withDescription(
|
||||
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME). Inside a git worktree this defaults to that worktree's own .t3 so dev state stays off the shared home.",
|
||||
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
|
||||
),
|
||||
Flag.optional,
|
||||
Flag.map(Option.getOrUndefined),
|
||||
Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOME")),
|
||||
),
|
||||
browser: Flag.boolean("browser").pipe(
|
||||
Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
|
||||
@@ -881,12 +631,6 @@ const devRunnerCli = Command.make("dev-runner", {
|
||||
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
share: Flag.boolean("share").pipe(
|
||||
Flag.withDescription(
|
||||
"Publish the web dev server on this machine's tailnet over HTTPS (via `tailscale serve`) and print the pairing URL for it. Removed again on exit.",
|
||||
),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
runArgs: Argument.string("run-arg").pipe(
|
||||
Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
|
||||
Argument.variadic(),
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - exercises the executable path guard in a child process.
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
const runDevSeed = (input: {
|
||||
readonly root: string;
|
||||
readonly targetBaseDir: string;
|
||||
readonly t3Home: string;
|
||||
}) =>
|
||||
NodeChildProcess.spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
NodePath.join(import.meta.dirname, "dev-seed.ts"),
|
||||
"--from",
|
||||
NodePath.join(input.root, "source"),
|
||||
"--to",
|
||||
input.targetBaseDir,
|
||||
],
|
||||
{
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, NO_COLOR: "1", T3CODE_HOME: input.t3Home },
|
||||
},
|
||||
);
|
||||
|
||||
const assertSharedHomeRefusal = (result: ReturnType<typeof runDevSeed>) => {
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.include(
|
||||
`${result.stdout}${result.stderr}`,
|
||||
"that database lives in the shared T3 Code home",
|
||||
);
|
||||
};
|
||||
|
||||
it("refuses to seed a target inside T3CODE_HOME through a symlink", () => {
|
||||
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-dev-seed-cli-"));
|
||||
try {
|
||||
const sharedHome = NodePath.join(root, "shared");
|
||||
const sharedStateDir = NodePath.join(sharedHome, "userdata");
|
||||
const targetBaseDir = NodePath.join(root, "target");
|
||||
NodeFS.mkdirSync(sharedStateDir, { recursive: true });
|
||||
NodeFS.mkdirSync(targetBaseDir, { recursive: true });
|
||||
NodeFS.writeFileSync(NodePath.join(sharedStateDir, "state.sqlite"), "must stay untouched");
|
||||
NodeFS.symlinkSync(sharedStateDir, NodePath.join(targetBaseDir, "userdata"), "dir");
|
||||
|
||||
const result = runDevSeed({ root, targetBaseDir, t3Home: sharedHome });
|
||||
|
||||
assertSharedHomeRefusal(result);
|
||||
assert.equal(
|
||||
NodeFS.readFileSync(NodePath.join(sharedStateDir, "state.sqlite"), "utf8"),
|
||||
"must stay untouched",
|
||||
);
|
||||
} finally {
|
||||
NodeFS.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses targets when T3CODE_HOME resolves to the filesystem root", () => {
|
||||
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-dev-seed-root-cli-"));
|
||||
try {
|
||||
const sharedHome = NodePath.join(root, "shared");
|
||||
const targetBaseDir = NodePath.join(root, "target");
|
||||
const targetStateDir = NodePath.join(targetBaseDir, "userdata");
|
||||
NodeFS.symlinkSync(NodePath.parse(root).root, sharedHome, "dir");
|
||||
NodeFS.mkdirSync(targetStateDir, { recursive: true });
|
||||
NodeFS.writeFileSync(NodePath.join(targetStateDir, "state.sqlite"), "must stay untouched");
|
||||
|
||||
const result = runDevSeed({ root, targetBaseDir, t3Home: sharedHome });
|
||||
|
||||
assertSharedHomeRefusal(result);
|
||||
assert.equal(
|
||||
NodeFS.readFileSync(NodePath.join(targetStateDir, "state.sqlite"), "utf8"),
|
||||
"must stay untouched",
|
||||
);
|
||||
} finally {
|
||||
NodeFS.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,397 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard.
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as Console from "effect/Console";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
|
||||
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
|
||||
|
||||
import { DevSeedError, MAX_SEED_THREAD_LIMIT, seedDevDatabase } from "./lib/dev-seed.ts";
|
||||
import { findRunningServerPid, findRunningServerPidSync } from "./lib/server-runtime-probe.ts";
|
||||
|
||||
const DEFAULT_THREAD_LIMIT = 25;
|
||||
const DEFAULT_ACTIVITY_LIMIT = 200;
|
||||
|
||||
const resolveSharedHome = (path: Path.Path): string => {
|
||||
const configured = process.env.T3CODE_HOME?.trim();
|
||||
if (!configured) {
|
||||
return path.join(NodeOS.homedir(), ".t3");
|
||||
}
|
||||
if (configured === "~") {
|
||||
return NodeOS.homedir();
|
||||
}
|
||||
return path.resolve(
|
||||
configured.startsWith("~/") || configured.startsWith("~\\")
|
||||
? path.join(NodeOS.homedir(), configured.slice(2))
|
||||
: configured,
|
||||
);
|
||||
};
|
||||
|
||||
const isPathWithin = (path: Path.Path, parent: string, candidate: string): boolean => {
|
||||
const relative = path.relative(parent, candidate);
|
||||
return (
|
||||
relative === "" ||
|
||||
(relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
|
||||
);
|
||||
};
|
||||
|
||||
class DevSeedTargetError extends Schema.TaggedErrorClass<DevSeedTargetError>()(
|
||||
"DevSeedTargetError",
|
||||
{
|
||||
reason: Schema.Literals([
|
||||
"shared-home",
|
||||
"missing-target",
|
||||
"not-a-worktree",
|
||||
"server-running",
|
||||
"same-source",
|
||||
]),
|
||||
detail: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
switch (this.reason) {
|
||||
case "shared-home":
|
||||
return [
|
||||
`Refusing to seed ${this.detail}: that database lives in the shared T3 Code home.`,
|
||||
"This command overwrites projection tables. Run it from a worktree, or pass --to <base-dir>.",
|
||||
].join("\n");
|
||||
case "missing-target":
|
||||
return [
|
||||
`No database at ${this.detail}.`,
|
||||
"Start the dev server once so migrations run (`bun run dev`), then seed.",
|
||||
].join("\n");
|
||||
case "not-a-worktree":
|
||||
return [
|
||||
"Not inside a git worktree, so there is no worktree-local data directory to seed.",
|
||||
"Pass --to <base-dir> to choose one explicitly.",
|
||||
].join("\n");
|
||||
case "server-running":
|
||||
return [
|
||||
`A T3 Code server (pid ${this.detail}) is running against this data directory.`,
|
||||
"Seeding replaces its projections and empties its event log while it holds them open,",
|
||||
"which leaves the running server's in-memory read model describing rows that no longer exist.",
|
||||
"Stop it, run the seed, then start it again.",
|
||||
].join("\n");
|
||||
case "same-source":
|
||||
return [
|
||||
`Refusing to seed ${this.detail} from itself.`,
|
||||
"The copy would restore what the delete removed, but the event log and the",
|
||||
"projector cursors are cleared either way — so the directory loses its history",
|
||||
"and keeps only whatever the thread and activity caps selected.",
|
||||
].join("\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The state directory holding a base directory's database.
|
||||
*
|
||||
* `deriveServerPaths` picks `dev` for an implicit dev home and `userdata`
|
||||
* otherwise — a split that depends on how the server was started, which the
|
||||
* person seeding has no reason to know. Hard-coding `userdata` made a
|
||||
* main-checkout `bun run dev` (whose state lives in `<base>/dev`) unreachable:
|
||||
* the seed reported "no database, start the dev server so migrations run" about
|
||||
* a server that was already running.
|
||||
*
|
||||
* When both exist, neither is categorically right — a worktree run gets
|
||||
* `userdata` (the dev runner passes an explicit home), a main-checkout run gets
|
||||
* `dev` — so the tie goes to whichever was written most recently, i.e. the one
|
||||
* the last server to run actually opened. The chosen path is printed, so a
|
||||
* wrong guess is visible rather than silent.
|
||||
*
|
||||
* Recency is the newest of the database and its `-wal` sidecar. The server runs
|
||||
* SQLite in WAL mode, where writes land in the sidecar and the main file's
|
||||
* mtime can sit unchanged until a checkpoint — so reading the database alone
|
||||
* makes a busy directory look older than a dormant one.
|
||||
*/
|
||||
const resolveStateDir = Effect.fn("devSeed.resolveStateDir")(function* (baseDir: string) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const modifiedAtMs = (info: FileSystem.File.Info): number =>
|
||||
Option.match(info.mtime, { onSome: (mtime) => mtime.getTime(), onNone: () => 0 });
|
||||
|
||||
const candidates: Array<{ readonly stateDir: string; readonly modifiedAtMs: number }> = [];
|
||||
for (const stateDir of ["userdata", "dev"] as const) {
|
||||
const dbPath = path.join(baseDir, stateDir, "state.sqlite");
|
||||
const info = yield* fileSystem.stat(dbPath).pipe(Effect.option);
|
||||
if (Option.isNone(info)) {
|
||||
continue;
|
||||
}
|
||||
// The sidecar is absent outside WAL mode, and after a clean checkpoint.
|
||||
const walInfo = yield* fileSystem.stat(`${dbPath}-wal`).pipe(Effect.option);
|
||||
candidates.push({
|
||||
stateDir,
|
||||
modifiedAtMs: Math.max(
|
||||
modifiedAtMs(info.value),
|
||||
Option.match(walInfo, { onSome: modifiedAtMs, onNone: () => 0 }),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
// `userdata` first above, so an equal or missing mtime keeps the old default.
|
||||
return (
|
||||
candidates.reduce<{ readonly stateDir: string; readonly modifiedAtMs: number } | undefined>(
|
||||
(best, candidate) =>
|
||||
best === undefined || candidate.modifiedAtMs > best.modifiedAtMs ? candidate : best,
|
||||
undefined,
|
||||
)?.stateDir ?? "userdata"
|
||||
);
|
||||
});
|
||||
|
||||
const stateDbPath = (path: Path.Path, baseDir: string, stateDir: string) =>
|
||||
path.join(baseDir, stateDir, "state.sqlite");
|
||||
|
||||
/**
|
||||
* Copies the files behind the copied messages' attachment references.
|
||||
*
|
||||
* The rows carry only metadata; the bytes sit in a flat directory beside the
|
||||
* database as `<attachmentId><ext>` (apps/server/src/attachmentStore.ts). Copy
|
||||
* the rows alone and a seeded thread renders an image whose request 404s.
|
||||
*
|
||||
* Matched by directory listing rather than by reconstructing the extension: the
|
||||
* server infers it from mime type and file name at upload, and duplicating that
|
||||
* inference here would rot independently of it.
|
||||
*/
|
||||
const copyAttachments = Effect.fn("devSeed.copyAttachments")(function* (input: {
|
||||
readonly sourceDir: string;
|
||||
readonly targetDir: string;
|
||||
readonly attachmentIds: ReadonlyArray<string>;
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
if (input.attachmentIds.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(input.sourceDir)
|
||||
.pipe(Effect.orElseSucceed(() => [] as Array<string>));
|
||||
const wanted = new Set(input.attachmentIds);
|
||||
const matches = entries.filter((entry) => wanted.has(path.parse(entry).name));
|
||||
if (matches.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Attachments are decoration on a dev fixture: one unreadable file should
|
||||
// leave the rest of the seed intact rather than fail a completed database
|
||||
// copy. The directory itself is subject to the same rule.
|
||||
return yield* fileSystem.makeDirectory(input.targetDir, { recursive: true }).pipe(
|
||||
Effect.andThen(
|
||||
Effect.forEach(matches, (entry) =>
|
||||
fileSystem
|
||||
.copyFile(path.join(input.sourceDir, entry), path.join(input.targetDir, entry))
|
||||
.pipe(
|
||||
Effect.as(1),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((copied) => copied.reduce((total, one) => total + one, 0)),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
});
|
||||
|
||||
const devSeedCli = Command.make("dev-seed", {
|
||||
from: Flag.string("from").pipe(
|
||||
Flag.withDescription(
|
||||
"Base directory to copy from (default: T3CODE_HOME, or ~/.t3). Read-only.",
|
||||
),
|
||||
Flag.optional,
|
||||
Flag.map(Option.getOrUndefined),
|
||||
),
|
||||
to: Flag.string("to").pipe(
|
||||
Flag.withDescription(
|
||||
"Base directory to seed (default: this worktree's .t3). Its projection tables are replaced.",
|
||||
),
|
||||
Flag.optional,
|
||||
Flag.map(Option.getOrUndefined),
|
||||
),
|
||||
// Bounded below: SQLite reads a negative LIMIT as "no limit", which would
|
||||
// quietly turn a capped copy into a full-table one. The upper bound comes
|
||||
// from the seeder itself, which binds one variable per selected thread —
|
||||
// stating it separately here is what previously let the two drift apart.
|
||||
threads: Flag.integer("threads").pipe(
|
||||
Flag.withSchema(
|
||||
Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(MAX_SEED_THREAD_LIMIT)),
|
||||
),
|
||||
Flag.withDescription(
|
||||
`How many recent threads to copy (default ${String(DEFAULT_THREAD_LIMIT)}, max ${String(MAX_SEED_THREAD_LIMIT)}).`,
|
||||
),
|
||||
Flag.withDefault(DEFAULT_THREAD_LIMIT),
|
||||
),
|
||||
activities: Flag.integer("activities").pipe(
|
||||
Flag.withSchema(Schema.Int.check(Schema.isGreaterThan(0))),
|
||||
Flag.withDescription(
|
||||
`Newest activities kept per thread (default ${String(DEFAULT_ACTIVITY_LIMIT)}).`,
|
||||
),
|
||||
Flag.withDefault(DEFAULT_ACTIVITY_LIMIT),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription(
|
||||
"Copy recent projects and threads from a T3 Code data directory into an isolated dev one.",
|
||||
),
|
||||
Command.withHandler((input) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const sharedHome = resolveSharedHome(path);
|
||||
const sourceBaseDir = input.from ? path.resolve(input.from) : sharedHome;
|
||||
|
||||
const defaultTarget = yield* resolveWorktreeT3Home(process.cwd());
|
||||
const targetBaseDir = input.to ? path.resolve(input.to) : defaultTarget;
|
||||
if (targetBaseDir === undefined) {
|
||||
return yield* new DevSeedTargetError({ reason: "not-a-worktree", detail: process.cwd() });
|
||||
}
|
||||
|
||||
const [sourceStateDir, targetStateDir] = yield* Effect.all([
|
||||
resolveStateDir(sourceBaseDir),
|
||||
resolveStateDir(targetBaseDir),
|
||||
]);
|
||||
const sourceDbPath = stateDbPath(path, sourceBaseDir, sourceStateDir);
|
||||
const targetDbPath = stateDbPath(path, targetBaseDir, targetStateDir);
|
||||
|
||||
// The whole point is to keep dev data off the real home; overwriting it
|
||||
// here would be the exact accident this command exists to avoid.
|
||||
//
|
||||
// Guarded on the canonical *database* paths, not the base directories: a
|
||||
// base can canonicalize to itself while its `userdata` or `dev`
|
||||
// subdirectory is a symlink into the shared home, and comparing bases
|
||||
// then waves through a seed whose actual write target is the real
|
||||
// database. Resolve the full path first — the file itself can be the
|
||||
// symlink — and fall back to resolving the directory and re-joining the
|
||||
// filename when the file does not exist yet: a nonexistent file cannot
|
||||
// be a link to anything, but its directory still can be, and this is
|
||||
// exactly the case where the missing-target advice ("start the dev
|
||||
// server") would otherwise create the database in the shared home.
|
||||
const canonicalDbPath = (databasePath: string) =>
|
||||
fileSystem.realPath(databasePath).pipe(
|
||||
Effect.catch(() =>
|
||||
fileSystem
|
||||
.realPath(path.dirname(databasePath))
|
||||
.pipe(Effect.map((directory) => path.join(directory, path.basename(databasePath)))),
|
||||
),
|
||||
Effect.orElseSucceed(() => databasePath),
|
||||
);
|
||||
const [canonicalTargetDb, canonicalSourceDb, canonicalShared] = yield* Effect.all([
|
||||
canonicalDbPath(targetDbPath),
|
||||
canonicalDbPath(sourceDbPath),
|
||||
fileSystem.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
|
||||
]);
|
||||
if (isPathWithin(path, canonicalShared, canonicalTargetDb)) {
|
||||
return yield* new DevSeedTargetError({ reason: "shared-home", detail: canonicalTargetDb });
|
||||
}
|
||||
// After the shared-home refusal: that one must come first because the
|
||||
// missing-target advice below — start a dev server, which creates the
|
||||
// database — is exactly wrong for the shared home. Everywhere else, a
|
||||
// missing database is the more actionable diagnosis, so it outranks
|
||||
// same-source: aliased paths with nothing behind them are a setup
|
||||
// problem, not a self-seed.
|
||||
if (!(yield* fileSystem.exists(targetDbPath))) {
|
||||
return yield* new DevSeedTargetError({ reason: "missing-target", detail: targetDbPath });
|
||||
}
|
||||
|
||||
// Seeding a database from itself is not the data loss it looks like —
|
||||
// the source reads a pre-transaction snapshot, so the copy puts the rows
|
||||
// back. What does not come back is the event log and the cursors, and
|
||||
// anything outside the caps. Nobody means to ask for that.
|
||||
if (canonicalTargetDb === canonicalSourceDb) {
|
||||
return yield* new DevSeedTargetError({ reason: "same-source", detail: canonicalTargetDb });
|
||||
}
|
||||
|
||||
// SQLite locking is not enough on its own: the seed's transaction can take
|
||||
// the write lock between a running server's own writes and commit cleanly.
|
||||
// What it cannot do is tell that server the projections it is holding in
|
||||
// memory, and the event log it is appending to, were both replaced under
|
||||
// it. Its next write then lands on top of a read model it never built.
|
||||
//
|
||||
// Scoped to the state directory being seeded: a server using only the
|
||||
// other directory's database is not touching this one, and blocking on it
|
||||
// would refuse seeds that are perfectly safe.
|
||||
const runningPid = yield* findRunningServerPid(targetBaseDir, targetStateDir);
|
||||
if (Option.isSome(runningPid)) {
|
||||
return yield* new DevSeedTargetError({
|
||||
reason: "server-running",
|
||||
detail: String(runningPid.value),
|
||||
});
|
||||
}
|
||||
|
||||
const seededAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const summary = yield* Effect.try({
|
||||
try: () =>
|
||||
seedDevDatabase({
|
||||
sourceDbPath,
|
||||
targetDbPath,
|
||||
threadLimit: input.threads,
|
||||
activityLimit: input.activities,
|
||||
seededAt,
|
||||
// The check above happens before the copy, which can take seconds.
|
||||
// Re-checked just before the commit so a server that started in
|
||||
// between aborts the seed instead of having its database swapped.
|
||||
findRunningServerPid: () => findRunningServerPidSync(targetBaseDir, targetStateDir),
|
||||
}),
|
||||
catch: (cause) => cause as DevSeedError,
|
||||
});
|
||||
|
||||
// Attachments sit beside the database, so they follow the same state dir.
|
||||
const copiedAttachments = yield* copyAttachments({
|
||||
sourceDir: path.join(sourceBaseDir, sourceStateDir, "attachments"),
|
||||
targetDir: path.join(targetBaseDir, targetStateDir, "attachments"),
|
||||
attachmentIds: summary.attachmentIds,
|
||||
});
|
||||
|
||||
yield* Console.log(
|
||||
[
|
||||
`Seeded ${targetDbPath}`,
|
||||
` from ${sourceDbPath}`,
|
||||
` projects ${String(summary.projects)}`,
|
||||
` threads ${String(summary.threads)}`,
|
||||
` messages ${String(summary.messages)}`,
|
||||
` activity ${String(summary.activities)}`,
|
||||
` turns ${String(summary.turns)} sessions ${String(summary.sessions)}`,
|
||||
...(summary.attachmentIds.length > 0
|
||||
? [
|
||||
` files ${String(copiedAttachments)}/${String(summary.attachmentIds.length)} attachment(s)`,
|
||||
]
|
||||
: []),
|
||||
...(summary.skippedColumns.length > 0
|
||||
? [
|
||||
` note: skipped ${String(summary.skippedColumns.length)} column(s) absent from the target schema`,
|
||||
` (${summary.skippedColumns.join(", ")})`,
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
"Restart the dev server to pick it up.",
|
||||
].join("\n"),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.logError(
|
||||
error instanceof DevSeedError
|
||||
? `${error.message}${error.hint ? `\n${error.hint}` : ""}`
|
||||
: error.message,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (import.meta.main) {
|
||||
Command.run(devSeedCli, { version: "0.0.0" }).pipe(
|
||||
Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
}
|
||||
@@ -1,971 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - test fixtures build real SQLite files on disk.
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeSqlite from "node:sqlite";
|
||||
|
||||
import { DevSeedError, MAX_SEED_THREAD_LIMIT, seedDevDatabase } from "./dev-seed.ts";
|
||||
|
||||
const SEEDED_AT = "2026-07-26T00:00:00.000Z";
|
||||
/**
|
||||
* A completion timestamp left on a still-running turn by a settle that a later
|
||||
* checkpoint reverted. Far enough in the future to be unmistakable if it leaks
|
||||
* into a seeded row.
|
||||
*/
|
||||
const STALE_COMPLETED_AT = "2099-01-01T00:00:00.000Z";
|
||||
|
||||
/**
|
||||
* The subset of the real schema the seeder touches. `monitor_json` is included
|
||||
* only in the source, to stand in for the migration drift between an installed
|
||||
* app and a worktree that is a migration behind.
|
||||
*/
|
||||
function createSchema(
|
||||
database: NodeSqlite.DatabaseSync,
|
||||
options: { readonly withMonitor: boolean; readonly legacyThreads?: boolean },
|
||||
) {
|
||||
database.exec(`CREATE TABLE projection_projects (
|
||||
project_id TEXT PRIMARY KEY, title TEXT NOT NULL, workspace_root TEXT NOT NULL,
|
||||
scripts_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT)`);
|
||||
// A pre-017/023 source has neither archived_at nor latest_user_message_at.
|
||||
database.exec(`CREATE TABLE projection_threads (
|
||||
thread_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, title TEXT NOT NULL,
|
||||
latest_turn_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
|
||||
deleted_at TEXT${options.legacyThreads ? "" : ", archived_at TEXT, latest_user_message_at TEXT"},
|
||||
pending_approval_count INTEGER NOT NULL DEFAULT 0,
|
||||
pending_user_input_count INTEGER NOT NULL DEFAULT 0
|
||||
${options.withMonitor ? ", monitor_json TEXT" : ""})`);
|
||||
database.exec(`CREATE TABLE projection_thread_messages (
|
||||
message_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, role TEXT NOT NULL,
|
||||
text TEXT NOT NULL, is_streaming INTEGER NOT NULL, attachments_json TEXT,
|
||||
created_at TEXT NOT NULL, updated_at TEXT NOT NULL)`);
|
||||
// `sequence` (migration 008) is what the app orders activities by, ahead of
|
||||
// created_at, so the copy's per-thread cap has to see it.
|
||||
database.exec(`CREATE TABLE projection_thread_activities (
|
||||
activity_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, tone TEXT NOT NULL,
|
||||
kind TEXT NOT NULL, summary TEXT NOT NULL, payload_json TEXT NOT NULL,
|
||||
sequence INTEGER, created_at TEXT NOT NULL)`);
|
||||
database.exec(`CREATE TABLE projection_thread_sessions (
|
||||
thread_id TEXT PRIMARY KEY, status TEXT NOT NULL, provider_name TEXT,
|
||||
active_turn_id TEXT, last_error TEXT, updated_at TEXT NOT NULL)`);
|
||||
// Mirrors migration 005: `checkpoint_turn_count` matters because
|
||||
// dropPendingTurnStarts keys its guard on it, and a fixture without the
|
||||
// column only ever exercises the degraded path.
|
||||
database.exec(`CREATE TABLE projection_turns (
|
||||
row_id INTEGER PRIMARY KEY AUTOINCREMENT, thread_id TEXT NOT NULL, turn_id TEXT,
|
||||
state TEXT NOT NULL, requested_at TEXT NOT NULL, completed_at TEXT,
|
||||
checkpoint_turn_count INTEGER, checkpoint_files_json TEXT NOT NULL,
|
||||
UNIQUE (thread_id, turn_id))`);
|
||||
database.exec(`CREATE TABLE projection_thread_proposed_plans (
|
||||
plan_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, plan_markdown TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL, updated_at TEXT NOT NULL)`);
|
||||
database.exec(`CREATE TABLE projection_pending_approvals (
|
||||
request_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, status TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL)`);
|
||||
database.exec(`CREATE TABLE projection_state (
|
||||
projector TEXT PRIMARY KEY, last_applied_sequence INTEGER NOT NULL, updated_at TEXT NOT NULL)`);
|
||||
database.exec(`CREATE TABLE orchestration_events (
|
||||
sequence INTEGER PRIMARY KEY AUTOINCREMENT, event_id TEXT NOT NULL UNIQUE,
|
||||
stream_id TEXT NOT NULL, event_type TEXT NOT NULL, payload_json TEXT NOT NULL)`);
|
||||
database.exec(`CREATE TABLE provider_session_runtime (
|
||||
thread_id TEXT PRIMARY KEY, provider_name TEXT NOT NULL, adapter_key TEXT NOT NULL,
|
||||
status TEXT NOT NULL, last_seen_at TEXT NOT NULL)`);
|
||||
// Cleared alongside the event log: a receipt records a command whose events
|
||||
// the seed just deleted, so a retry of that command would be treated as
|
||||
// already applied.
|
||||
database.exec(`CREATE TABLE orchestration_command_receipts (
|
||||
command_id TEXT PRIMARY KEY, aggregate_kind TEXT NOT NULL, aggregate_id TEXT NOT NULL,
|
||||
accepted_at TEXT NOT NULL, result_sequence INTEGER NOT NULL, status TEXT NOT NULL,
|
||||
error TEXT)`);
|
||||
}
|
||||
|
||||
/** Source DB with `threadCount` threads, oldest first so recency ordering is testable. */
|
||||
function makeSource(
|
||||
path: string,
|
||||
threadCount: number,
|
||||
activitiesPerThread = 3,
|
||||
options?: { readonly legacyThreads?: boolean; readonly minimalRows?: boolean },
|
||||
) {
|
||||
const legacyThreads = options?.legacyThreads ?? false;
|
||||
// Thread rows only, for the scale test: building sessions and messages for
|
||||
// 32k threads costs half a minute and proves nothing the thread-keyed
|
||||
// statements don't already exercise.
|
||||
const minimalRows = options?.minimalRows ?? false;
|
||||
const database = new NodeSqlite.DatabaseSync(path);
|
||||
createSchema(database, { withMonitor: true, legacyThreads });
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO projection_projects VALUES ('p1','Project','/repo','[]','${SEEDED_AT}','${SEEDED_AT}',NULL)`,
|
||||
)
|
||||
.run();
|
||||
|
||||
// One transaction rather than one per insert: at 32k threads the implicit
|
||||
// per-statement commits dominate the fixture's runtime.
|
||||
database.exec("BEGIN");
|
||||
for (let index = 0; index < threadCount; index += 1) {
|
||||
const threadId = `t${String(index)}`;
|
||||
// Later index → later timestamp → more recent.
|
||||
const at = `2026-07-${String(10 + index).padStart(2, "0")}T00:00:00.000Z`;
|
||||
if (legacyThreads) {
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO projection_threads (thread_id, project_id, title, latest_turn_id,
|
||||
created_at, updated_at, pending_approval_count, pending_user_input_count, monitor_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)`,
|
||||
)
|
||||
.run(threadId, "p1", `Thread ${String(index)}`, `turn-${threadId}`, at, at, 4, 2, "{}");
|
||||
} else {
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO projection_threads (thread_id, project_id, title, latest_turn_id,
|
||||
created_at, updated_at, latest_user_message_at, pending_approval_count,
|
||||
pending_user_input_count, monitor_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?)`,
|
||||
)
|
||||
.run(threadId, "p1", `Thread ${String(index)}`, `turn-${threadId}`, at, at, at, 4, 2, "{}");
|
||||
}
|
||||
// The newest thread is left mid-turn, as a copy taken while an agent is
|
||||
// working would be: a running turn with no completion, and a message still
|
||||
// streaming into it. The one before it is left "pending" — a user message
|
||||
// accepted but whose provider turn never started.
|
||||
const midFlight = index === threadCount - 1;
|
||||
const queued = index === threadCount - 2;
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO projection_turns (thread_id, turn_id, state, requested_at, completed_at, checkpoint_files_json)
|
||||
VALUES (?,?,?,?,?,'[]')`,
|
||||
)
|
||||
.run(
|
||||
threadId,
|
||||
// A pending start has no turn id — that is what identifies it.
|
||||
queued ? null : `turn-${threadId}`,
|
||||
midFlight ? "running" : queued ? "pending" : "completed",
|
||||
at,
|
||||
// The running turn carries a stale completion from an earlier settle
|
||||
// that a later checkpoint reverted, which must not survive as the
|
||||
// interruption time.
|
||||
midFlight ? STALE_COMPLETED_AT : queued ? null : at,
|
||||
);
|
||||
if (minimalRows) {
|
||||
continue;
|
||||
}
|
||||
database
|
||||
.prepare(`INSERT INTO projection_thread_sessions VALUES (?,'running','claude',?,'boom',?)`)
|
||||
.run(threadId, `turn-${threadId}`, at);
|
||||
database
|
||||
.prepare(`INSERT INTO projection_thread_messages VALUES (?,?, 'user','hello',?,?,?,?)`)
|
||||
.run(
|
||||
`m-${threadId}`,
|
||||
threadId,
|
||||
midFlight ? 1 : 0,
|
||||
JSON.stringify([{ type: "image", id: `${threadId}-image`, name: "shot.png" }]),
|
||||
at,
|
||||
at,
|
||||
);
|
||||
for (let a = 0; a < activitiesPerThread; a += 1) {
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO projection_thread_activities VALUES (?,?,'neutral','tool','ran',?,?,?)`,
|
||||
)
|
||||
.run(
|
||||
`a-${threadId}-${String(a)}`,
|
||||
threadId,
|
||||
"{}",
|
||||
a,
|
||||
`2026-07-10T00:00:0${String(a)}.000Z`,
|
||||
);
|
||||
}
|
||||
}
|
||||
database.exec("COMMIT");
|
||||
database.close();
|
||||
}
|
||||
|
||||
function makeTarget(path: string, options?: { readonly dropProposedPlans?: boolean }) {
|
||||
const database = new NodeSqlite.DatabaseSync(path);
|
||||
// No monitor_json: the target is a migration behind, as a worktree often is.
|
||||
createSchema(database, { withMonitor: false });
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO projection_projects VALUES ('stale','Stale','/old','[]','${SEEDED_AT}','${SEEDED_AT}',NULL)`,
|
||||
)
|
||||
.run();
|
||||
// History from the target's own past life, which must not survive the seed.
|
||||
database
|
||||
.prepare(`INSERT INTO orchestration_events (event_id, stream_id, event_type, payload_json)
|
||||
VALUES ('old-event','stale-thread','thread.created','{}')`)
|
||||
.run();
|
||||
// A binding for a thread the seed is about to delete.
|
||||
database
|
||||
.prepare(`INSERT INTO provider_session_runtime
|
||||
VALUES ('stale-thread','claude','claude-code','running','${SEEDED_AT}')`)
|
||||
.run();
|
||||
// A receipt for a command whose events the seed is about to delete.
|
||||
database
|
||||
.prepare(`INSERT INTO orchestration_command_receipts
|
||||
VALUES ('old-command','thread','stale-thread','${SEEDED_AT}',1,'accepted',NULL)`)
|
||||
.run();
|
||||
if (options?.dropProposedPlans) {
|
||||
// A target far enough behind that a whole table is missing (migration 013).
|
||||
database.exec("DROP TABLE projection_thread_proposed_plans");
|
||||
}
|
||||
database.close();
|
||||
}
|
||||
|
||||
const withDatabases = <A>(
|
||||
run: (paths: { readonly source: string; readonly target: string }) => A,
|
||||
options?: {
|
||||
readonly threads?: number;
|
||||
readonly activities?: number;
|
||||
readonly dropProposedPlans?: boolean;
|
||||
readonly legacySource?: boolean;
|
||||
readonly minimalRows?: boolean;
|
||||
},
|
||||
): A => {
|
||||
const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-dev-seed-"));
|
||||
const source = NodePath.join(directory, "source.sqlite");
|
||||
const target = NodePath.join(directory, "target.sqlite");
|
||||
makeSource(source, options?.threads ?? 5, options?.activities ?? 3, {
|
||||
legacyThreads: options?.legacySource ?? false,
|
||||
minimalRows: options?.minimalRows ?? false,
|
||||
});
|
||||
makeTarget(target, { dropProposedPlans: options?.dropProposedPlans ?? false });
|
||||
try {
|
||||
return run({ source, target });
|
||||
} finally {
|
||||
NodeFS.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
const query = <T>(path: string, sql: string): Array<T> => {
|
||||
const database = new NodeSqlite.DatabaseSync(path, { readOnly: true });
|
||||
try {
|
||||
return database.prepare(sql).all() as Array<T>;
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
};
|
||||
|
||||
describe("seedDevDatabase", () => {
|
||||
it("copies the most recent threads and their project", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 2,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.equal(summary.threads, 2);
|
||||
assert.equal(summary.projects, 1);
|
||||
|
||||
const titles = query<{ title: string }>(
|
||||
target,
|
||||
"SELECT title FROM projection_threads ORDER BY latest_user_message_at DESC",
|
||||
).map((row) => row.title);
|
||||
// Threads 4 and 3 are the newest of the five.
|
||||
assert.deepStrictEqual(titles, ["Thread 4", "Thread 3"]);
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces whatever the target held before", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const projects = query<{ project_id: string }>(
|
||||
target,
|
||||
"SELECT project_id FROM projection_projects",
|
||||
).map((row) => row.project_id);
|
||||
assert.deepStrictEqual(projects, ["p1"]);
|
||||
});
|
||||
});
|
||||
|
||||
// The target can be a migration behind the source; copying its columns
|
||||
// blindly would fail on the first schema change.
|
||||
it("skips columns the target does not have", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(summary.skippedColumns, ["projection_threads.monitor_json"]);
|
||||
assert.equal(summary.threads, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// A copied "running" session has no agent behind it, so the thread would spin
|
||||
// forever and the session reaper would skip it.
|
||||
it("neutralizes live session state", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const sessions = query<{ status: string; active_turn_id: string | null }>(
|
||||
target,
|
||||
"SELECT status, active_turn_id FROM projection_thread_sessions",
|
||||
);
|
||||
assert.isAbove(sessions.length, 0);
|
||||
for (const session of sessions) {
|
||||
assert.equal(session.status, "stopped");
|
||||
assert.isNull(session.active_turn_id);
|
||||
}
|
||||
const [threadsWithLatestTurn] = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM projection_threads WHERE latest_turn_id IS NOT NULL",
|
||||
);
|
||||
assert.equal(threadsWithLatestTurn?.count, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// Approvals are not copied, so the badge counts must not survive.
|
||||
it("clears pending counts that have no rows behind them", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const [counts] = query<{ approvals: number; inputs: number }>(
|
||||
target,
|
||||
"SELECT SUM(pending_approval_count) approvals, SUM(pending_user_input_count) inputs FROM projection_threads",
|
||||
);
|
||||
assert.equal(counts?.approvals, 0);
|
||||
assert.equal(counts?.inputs, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// A copied running turn has no agent left to finish it. The session override
|
||||
// alone does not cover it: the turn is read independently, and an unsettled
|
||||
// one keeps the thread spinning and its timeline unfoldable forever.
|
||||
it("settles turns copied while still running", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const turns = query<{ state: string; completed_at: string | null }>(
|
||||
target,
|
||||
"SELECT state, completed_at FROM projection_turns",
|
||||
);
|
||||
assert.isAbove(turns.length, 0);
|
||||
for (const turn of turns) {
|
||||
assert.notEqual(turn.state, "running");
|
||||
assert.isNotNull(turn.completed_at);
|
||||
// A settle that a later checkpoint reverted can leave a completion on a
|
||||
// running turn; carrying it over would date the interruption to then.
|
||||
assert.notEqual(turn.completed_at, STALE_COMPLETED_AT);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// The server deletes pending starts rather than settling them
|
||||
// (clearPendingProjectionTurnsByThread). They also cannot be settled
|
||||
// coherently: turn_id is NULL, so an "interrupted" one is a terminal turn
|
||||
// with no id — a shape no real turn has.
|
||||
it("drops pending turn starts instead of settling them", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const [pending] = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM projection_turns WHERE state = 'pending' OR turn_id IS NULL",
|
||||
);
|
||||
assert.equal(pending?.count, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// A burst of tool activity lands many rows on the same timestamp. Capping on
|
||||
// created_at alone then cuts arbitrarily among them, and can keep exactly the
|
||||
// rows the timeline treats as oldest.
|
||||
it("caps activities by the order the app displays them", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
const sourceDatabase = new NodeSqlite.DatabaseSync(source);
|
||||
sourceDatabase.exec("DELETE FROM projection_thread_activities");
|
||||
const insert = sourceDatabase.prepare(
|
||||
`INSERT INTO projection_thread_activities
|
||||
VALUES (?, 't4', 'neutral', 'tool', 'ran', '{}', ?, ?)`,
|
||||
);
|
||||
const tied = "2026-07-10T00:00:00.000Z";
|
||||
// Timestamps tie within a burst...
|
||||
for (const sequence of [1, 2, 3]) {
|
||||
insert.run(`tie-${String(sequence)}`, sequence, tied);
|
||||
}
|
||||
// ...and can disagree with sequence outright under clock skew. The app
|
||||
// ranks by sequence first, so this row outranks every tied one despite
|
||||
// its older timestamp.
|
||||
insert.run("skewed-4", 4, "2026-07-09T00:00:00.000Z");
|
||||
sourceDatabase.close();
|
||||
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 2,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const kept = query<{ activity_id: string }>(
|
||||
target,
|
||||
"SELECT activity_id FROM projection_thread_activities ORDER BY sequence DESC",
|
||||
).map((row) => row.activity_id);
|
||||
// The two highest sequences — not the two newest timestamps, and not
|
||||
// whichever two the storage order yielded.
|
||||
assert.deepStrictEqual(kept, ["skewed-4", "tie-3"]);
|
||||
});
|
||||
});
|
||||
|
||||
it("uses activity id as the final cap tiebreaker", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
const sourceDatabase = new NodeSqlite.DatabaseSync(source);
|
||||
sourceDatabase.exec("DELETE FROM projection_thread_activities");
|
||||
const insert = sourceDatabase.prepare(
|
||||
`INSERT INTO projection_thread_activities
|
||||
VALUES (?, 't4', 'neutral', 'tool', 'ran', '{}', 7, ?)`,
|
||||
);
|
||||
const tied = "2026-07-10T00:00:00.000Z";
|
||||
insert.run("tie-a", tied);
|
||||
insert.run("tie-z", tied);
|
||||
sourceDatabase.close();
|
||||
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 1,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const kept = query<{ activity_id: string }>(
|
||||
target,
|
||||
"SELECT activity_id FROM projection_thread_activities",
|
||||
);
|
||||
assert.deepStrictEqual(kept, [{ activity_id: "tie-z" }]);
|
||||
});
|
||||
});
|
||||
|
||||
// The delete mirrors the server's predicate, which spares rows carrying a
|
||||
// checkpoint. Without the `checkpoint_turn_count IS NULL` clause a checkpoint
|
||||
// row that happened to be pending would be destroyed along with the starts.
|
||||
it("spares a pending row that carries a checkpoint", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
// A checkpoint row on a thread inside the copied range.
|
||||
const sourceDatabase = new NodeSqlite.DatabaseSync(source);
|
||||
sourceDatabase
|
||||
.prepare(
|
||||
`INSERT INTO projection_turns (thread_id, turn_id, state, requested_at,
|
||||
checkpoint_turn_count, checkpoint_files_json) VALUES ('t4', NULL, 'pending', ?, 7, '[]')`,
|
||||
)
|
||||
.run(SEEDED_AT);
|
||||
sourceDatabase.close();
|
||||
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const checkpoints = query<{ checkpoint_turn_count: number }>(
|
||||
target,
|
||||
"SELECT checkpoint_turn_count FROM projection_turns WHERE checkpoint_turn_count IS NOT NULL",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
checkpoints.map((row) => row.checkpoint_turn_count),
|
||||
[7],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// Nothing will ever stream into a copied message, so a carried-over flag
|
||||
// renders a caret that never resolves.
|
||||
it("clears the streaming flag on copied messages", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const streaming = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM projection_thread_messages WHERE is_streaming <> 0",
|
||||
);
|
||||
assert.equal(streaming[0]?.count, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// The rows carry attachment metadata but the bytes live on disk, so the
|
||||
// caller has to be told which files to bring along.
|
||||
it("reports the attachment ids the copied messages reference", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 2,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual([...summary.attachmentIds].sort(), ["t3-image", "t4-image"]);
|
||||
});
|
||||
});
|
||||
|
||||
// Bindings are keyed by thread id and are not copied; left behind they name
|
||||
// threads the seed just deleted, which the session reaper then tries to stop.
|
||||
it("clears provider runtime bindings the seed orphans", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const [bindings] = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM provider_session_runtime",
|
||||
);
|
||||
assert.equal(bindings?.count, 0);
|
||||
});
|
||||
});
|
||||
|
||||
it("caps activities per thread, keeping the newest", () => {
|
||||
withDatabases(
|
||||
({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 2,
|
||||
activityLimit: 2,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.equal(summary.activities, 4); // 2 threads × 2 kept
|
||||
const ids = query<{ activity_id: string }>(
|
||||
target,
|
||||
"SELECT activity_id FROM projection_thread_activities ORDER BY activity_id",
|
||||
).map((row) => row.activity_id);
|
||||
// Of a-*-0/1/2, the newest two are 1 and 2.
|
||||
assert.deepStrictEqual(ids, ["a-t3-1", "a-t3-2", "a-t4-1", "a-t4-2"]);
|
||||
},
|
||||
// One more per thread than the cap keeps, so the cap is observable.
|
||||
{ activities: 3 },
|
||||
);
|
||||
});
|
||||
|
||||
// Required, or computeSnapshotSequence reports 0 for every shell snapshot.
|
||||
it("writes a cursor row for every projector", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const rows = query<{ projector: string; last_applied_sequence: number }>(
|
||||
target,
|
||||
"SELECT projector, last_applied_sequence FROM projection_state",
|
||||
);
|
||||
assert.equal(rows.length, 9);
|
||||
// All at 0. The cursor is exclusive and the event log was emptied, so
|
||||
// any positive value would make each projector skip that many of the
|
||||
// user's first real events — a different count each, which desynchronizes
|
||||
// the projections permanently.
|
||||
for (const row of rows) {
|
||||
assert.equal(row.last_applied_sequence, 0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// The copied projections describe a different world than whatever history
|
||||
// the target still holds; replaying it would resurrect the target's own
|
||||
// deleted threads and projects over the seed.
|
||||
it("empties the target event log", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const [events] = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM orchestration_events",
|
||||
);
|
||||
assert.equal(events?.count, 0);
|
||||
|
||||
// Receipts go with them: one left behind records a command whose events
|
||||
// no longer exist, so re-issuing that command would be treated as
|
||||
// already applied and produce nothing.
|
||||
const [receipts] = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM orchestration_command_receipts",
|
||||
);
|
||||
assert.equal(receipts?.count, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// A target behind on migrations can be missing a table outright; that should
|
||||
// degrade like column drift does, not abort the seed.
|
||||
it("tolerates a table the target does not have", () => {
|
||||
withDatabases(
|
||||
({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 2,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.equal(summary.threads, 2);
|
||||
},
|
||||
{ dropProposedPlans: true },
|
||||
);
|
||||
});
|
||||
|
||||
// The recency columns arrived in migrations 017 and 023; a source older than
|
||||
// those must still be readable, since the rest of the copy tolerates drift.
|
||||
it("reads a source that predates the recency columns", () => {
|
||||
withDatabases(
|
||||
({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 2,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.equal(summary.threads, 2);
|
||||
const titles = query<{ title: string }>(
|
||||
target,
|
||||
"SELECT title FROM projection_threads ORDER BY updated_at DESC",
|
||||
).map((row) => row.title);
|
||||
assert.deepStrictEqual(titles, ["Thread 4", "Thread 3"]);
|
||||
},
|
||||
{ legacySource: true },
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to user messages when stored recency is missing", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
const sourceDatabase = new NodeSqlite.DatabaseSync(source);
|
||||
sourceDatabase.exec("UPDATE projection_threads SET latest_user_message_at = NULL");
|
||||
sourceDatabase
|
||||
.prepare(
|
||||
`UPDATE projection_thread_messages
|
||||
SET created_at = '2099-01-01T00:00:00.000Z'
|
||||
WHERE thread_id = 't0' AND role = 'user'`,
|
||||
)
|
||||
.run();
|
||||
sourceDatabase.close();
|
||||
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const threads = query<{ thread_id: string }>(
|
||||
target,
|
||||
"SELECT thread_id FROM projection_threads",
|
||||
);
|
||||
assert.deepStrictEqual(threads, [{ thread_id: "t0" }]);
|
||||
});
|
||||
});
|
||||
|
||||
// Every statement keyed on thread ids must cost exactly one bound variable
|
||||
// per thread: the limit *is* SQLite's ceiling, so a single extra binding
|
||||
// makes the maximum fail — after the target has already been emptied. Runs
|
||||
// the real seed, since the point is that no code path adds a binding, not
|
||||
// that one hand-written statement doesn't.
|
||||
it("seeds at the maximum thread limit without exhausting SQL variables", () => {
|
||||
withDatabases(
|
||||
({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: MAX_SEED_THREAD_LIMIT,
|
||||
activityLimit: 1,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.equal(summary.threads, MAX_SEED_THREAD_LIMIT);
|
||||
const [unsettled] = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM projection_turns WHERE state IN ('running','pending')",
|
||||
);
|
||||
assert.equal(unsettled?.count, 0);
|
||||
},
|
||||
// Threads only: the per-thread tables are what drive the binding count,
|
||||
// and skipping their rows keeps the fixture cheap to build.
|
||||
{ threads: MAX_SEED_THREAD_LIMIT, activities: 0, minimalRows: true },
|
||||
);
|
||||
});
|
||||
|
||||
// SQLite reads a negative LIMIT as "no limit", so an unchecked value turns a
|
||||
// capped copy into a full-table one rather than failing.
|
||||
for (const limits of [
|
||||
{ threadLimit: 0, activityLimit: 10 },
|
||||
{ threadLimit: -1, activityLimit: 10 },
|
||||
{ threadLimit: 5, activityLimit: 0 },
|
||||
{ threadLimit: 5, activityLimit: -1 },
|
||||
]) {
|
||||
it(`refuses threadLimit ${String(limits.threadLimit)} / activityLimit ${String(limits.activityLimit)}`, () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
assert.throws(
|
||||
() =>
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
...limits,
|
||||
seededAt: SEEDED_AT,
|
||||
}),
|
||||
DevSeedError,
|
||||
);
|
||||
|
||||
// Rejected before the destructive transaction opened.
|
||||
const projects = query<{ project_id: string }>(
|
||||
target,
|
||||
"SELECT project_id FROM projection_projects",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
projects.map((row) => row.project_id),
|
||||
["stale"],
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// The CLI checks for a running server before calling, but a copy takes time
|
||||
// and a server can start during it. The pre-commit re-check has to abort
|
||||
// rather than persist a swap underneath that server.
|
||||
it("aborts without committing when a server appears mid-copy", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
assert.throws(
|
||||
() =>
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
findRunningServerPid: () => 4242,
|
||||
}),
|
||||
DevSeedError,
|
||||
);
|
||||
|
||||
// Everything destructive ran inside the transaction, so the rollback
|
||||
// leaves the target's own rows intact.
|
||||
const projects = query<{ project_id: string }>(
|
||||
target,
|
||||
"SELECT project_id FROM projection_projects",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
projects.map((row) => row.project_id),
|
||||
["stale"],
|
||||
);
|
||||
const [events] = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM orchestration_events",
|
||||
);
|
||||
assert.equal(events?.count, 1);
|
||||
});
|
||||
});
|
||||
|
||||
it("commits when no server appeared during the copy", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
findRunningServerPid: () => undefined,
|
||||
});
|
||||
|
||||
assert.equal(summary.threads, 3);
|
||||
});
|
||||
});
|
||||
|
||||
// A caller that bypasses the CLI flag would otherwise discover the ceiling
|
||||
// only after the target had been emptied and the copy rolled back.
|
||||
it("refuses a thread limit above the ceiling before touching the target", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
assert.throws(
|
||||
() =>
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: MAX_SEED_THREAD_LIMIT + 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
}),
|
||||
DevSeedError,
|
||||
);
|
||||
|
||||
// The target's own row is still there: nothing was deleted.
|
||||
const projects = query<{ project_id: string }>(
|
||||
target,
|
||||
"SELECT project_id FROM projection_projects",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
projects.map((row) => row.project_id),
|
||||
["stale"],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// Down to one recency column, the ordering expression cannot be a COALESCE:
|
||||
// SQLite requires at least two arguments and throws otherwise, which would
|
||||
// abort the seed on exactly the old schema the column filter exists to serve.
|
||||
it("reads a source with only one recency column", () => {
|
||||
const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-dev-seed-1col-"));
|
||||
const source = NodePath.join(directory, "source.sqlite");
|
||||
const target = NodePath.join(directory, "target.sqlite");
|
||||
try {
|
||||
const database = new NodeSqlite.DatabaseSync(source);
|
||||
// created_at alone: no updated_at, no archived_at, no latest_user_message_at.
|
||||
database.exec(`CREATE TABLE projection_threads (
|
||||
thread_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, title TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL, deleted_at TEXT)`);
|
||||
// Matches the target's project columns; only the thread recency columns
|
||||
// are being varied here.
|
||||
database.exec(`CREATE TABLE projection_projects (
|
||||
project_id TEXT PRIMARY KEY, title TEXT NOT NULL, workspace_root TEXT NOT NULL,
|
||||
scripts_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
|
||||
deleted_at TEXT)`);
|
||||
database.exec(`CREATE TABLE projection_state (projector TEXT PRIMARY KEY,
|
||||
last_applied_sequence INTEGER NOT NULL, updated_at TEXT NOT NULL)`);
|
||||
database
|
||||
.prepare(`INSERT INTO projection_projects VALUES ('p1','P','/repo','[]',?,?,NULL)`)
|
||||
.run(SEEDED_AT, SEEDED_AT);
|
||||
for (const thread of [
|
||||
{ id: "old", at: "2026-07-10T00:00:00.000Z" },
|
||||
{ id: "new", at: "2026-07-20T00:00:00.000Z" },
|
||||
]) {
|
||||
database
|
||||
.prepare(`INSERT INTO projection_threads VALUES (?,?,?,?,NULL)`)
|
||||
.run(thread.id, "p1", thread.id, thread.at);
|
||||
}
|
||||
database.close();
|
||||
|
||||
// The target mirrors the source's thread columns: this test varies the
|
||||
// recency columns, and a target demanding one the source lacks would fail
|
||||
// on the NOT NULL rather than on the ordering expression under test.
|
||||
const targetDatabase = new NodeSqlite.DatabaseSync(target);
|
||||
targetDatabase.exec(`CREATE TABLE projection_threads (
|
||||
thread_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, title TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL, deleted_at TEXT)`);
|
||||
targetDatabase.exec(`CREATE TABLE projection_projects (
|
||||
project_id TEXT PRIMARY KEY, title TEXT NOT NULL, workspace_root TEXT NOT NULL,
|
||||
scripts_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
|
||||
deleted_at TEXT)`);
|
||||
targetDatabase.exec(`CREATE TABLE projection_state (projector TEXT PRIMARY KEY,
|
||||
last_applied_sequence INTEGER NOT NULL, updated_at TEXT NOT NULL)`);
|
||||
targetDatabase.close();
|
||||
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.equal(summary.threads, 1);
|
||||
// Ordering still applies: the newer thread is the one kept.
|
||||
const titles = query<{ title: string }>(target, "SELECT title FROM projection_threads");
|
||||
assert.deepStrictEqual(
|
||||
titles.map((row) => row.title),
|
||||
["new"],
|
||||
);
|
||||
} finally {
|
||||
NodeFS.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("reports a source with nothing to copy", () => {
|
||||
withDatabases(
|
||||
({ source, target }) => {
|
||||
assert.throws(
|
||||
() =>
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 5,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
}),
|
||||
DevSeedError,
|
||||
);
|
||||
},
|
||||
{ threads: 0 },
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves the target untouched when the source cannot be opened", () => {
|
||||
withDatabases(({ target }) => {
|
||||
assert.throws(
|
||||
() =>
|
||||
seedDevDatabase({
|
||||
sourceDbPath: NodePath.join(NodePath.dirname(target), "missing.sqlite"),
|
||||
targetDbPath: target,
|
||||
threadLimit: 5,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
}),
|
||||
DevSeedError,
|
||||
);
|
||||
|
||||
// The pre-existing row survives: nothing was deleted before the failure.
|
||||
const projects = query<{ project_id: string }>(
|
||||
target,
|
||||
"SELECT project_id FROM projection_projects",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
projects.map((row) => row.project_id),
|
||||
["stale"],
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,698 +0,0 @@
|
||||
/**
|
||||
* Copies recent projects and threads from one T3 Code database into another, so
|
||||
* an isolated dev server opens on something recognisable instead of an empty
|
||||
* sidebar.
|
||||
*
|
||||
* Projections only — no event history is copied, and the target's own log is
|
||||
* emptied. The copied projections describe a different world than whatever the
|
||||
* target recorded, so replaying its retained events over them would resurrect
|
||||
* threads and projects it had deleted; copying a *partial* source range is
|
||||
* worse still, since the projector would replay a tail whose creating events
|
||||
* are missing. With the log empty and every projector cursor at 0, bootstrap
|
||||
* streams nothing and leaves the copied rows alone.
|
||||
*
|
||||
* Everything that would otherwise wait on an agent is settled too — sessions,
|
||||
* turns, streaming messages, badge counts, provider bindings — because no agent
|
||||
* process comes with the copy. See
|
||||
* .agents/skills/test-t3-app/references/sqlite-fixtures.md.
|
||||
*/
|
||||
|
||||
import * as NodeSqlite from "node:sqlite";
|
||||
|
||||
import { PROJECTION_TABLES_IN_DEPENDENCY_ORDER, PROJECTOR_NAMES } from "./projection-tables.ts";
|
||||
|
||||
/**
|
||||
* The most threads one call can copy: SQLite's default
|
||||
* SQLITE_MAX_VARIABLE_NUMBER, because the statements below bind one variable
|
||||
* per selected thread.
|
||||
*
|
||||
* Exported so the CLI's `--threads` bound comes from the code that actually has
|
||||
* to satisfy it. When the two were stated separately, a statement that bound
|
||||
* two extra literals put the CLI's own documented maximum over the ceiling —
|
||||
* and it failed after the target had been emptied. Anything added to those
|
||||
* statements has to stay free of per-call bindings, or this has to come down.
|
||||
*/
|
||||
export const MAX_SEED_THREAD_LIMIT = 32_766;
|
||||
|
||||
/** Inputs to {@link seedDevDatabase}. Both limits must be positive. */
|
||||
export interface DevSeedOptions {
|
||||
readonly sourceDbPath: string;
|
||||
/** Emptied and rewritten. Must not be a database a server has open. */
|
||||
readonly targetDbPath: string;
|
||||
/** How many recent threads to copy. Capped at {@link MAX_SEED_THREAD_LIMIT}. */
|
||||
readonly threadLimit: number;
|
||||
/**
|
||||
* Newest activities kept per thread. The real table runs to six figures, and
|
||||
* the tail is what makes a thread look alive, so a cap keeps the copy quick
|
||||
* without making it look empty.
|
||||
*/
|
||||
readonly activityLimit: number;
|
||||
/** ISO-8601 timestamp stamped on the projector cursor rows. */
|
||||
readonly seededAt: string;
|
||||
/**
|
||||
* Re-checked just before the commit, after every destructive statement has
|
||||
* run but while a rollback still costs nothing. The caller's own check
|
||||
* happens before this function is entered, leaving a window in which a server
|
||||
* can start; returning a pid here aborts rather than persisting a swap
|
||||
* underneath it.
|
||||
*
|
||||
* Cannot close the window completely — a server starting between this call
|
||||
* and the commit is still possible, since a filesystem read and a SQLite
|
||||
* transaction have no common lock — but it shrinks it from the whole copy to
|
||||
* the commit itself.
|
||||
*/
|
||||
readonly findRunningServerPid?: () => number | undefined;
|
||||
}
|
||||
|
||||
/** What {@link seedDevDatabase} copied, for the CLI's summary output. */
|
||||
export interface DevSeedSummary {
|
||||
readonly projects: number;
|
||||
readonly threads: number;
|
||||
readonly messages: number;
|
||||
readonly activities: number;
|
||||
readonly turns: number;
|
||||
readonly sessions: number;
|
||||
readonly skippedColumns: ReadonlyArray<string>;
|
||||
/**
|
||||
* Attachment ids the copied messages reference. The rows carry the metadata
|
||||
* but the bytes live on disk beside the database, so the caller has to copy
|
||||
* those files too — otherwise a seeded thread renders an image that 404s.
|
||||
*/
|
||||
readonly attachmentIds: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A seed that could not proceed. `hint` carries the actionable half — the
|
||||
* underlying cause, or what to do about it — which the CLI prints on its own
|
||||
* line beneath the message.
|
||||
*/
|
||||
export class DevSeedError extends Error {
|
||||
override readonly name = "DevSeedError";
|
||||
readonly hint: string | undefined;
|
||||
constructor(message: string, hint?: string) {
|
||||
super(message);
|
||||
this.hint = hint;
|
||||
}
|
||||
}
|
||||
|
||||
const columnsOf = (database: NodeSqlite.DatabaseSync, table: string): ReadonlyArray<string> =>
|
||||
database
|
||||
.prepare(`SELECT name FROM pragma_table_info(?)`)
|
||||
.all(table)
|
||||
.map((row) => String((row as { name: unknown }).name));
|
||||
|
||||
/**
|
||||
* Columns present in both databases. The two can sit on different migrations —
|
||||
* a dev worktree is often a migration behind or ahead of the installed app — so
|
||||
* `SELECT *` would fail on the first schema change. Copying the intersection
|
||||
* degrades gracefully instead: a column only the target knows about keeps its
|
||||
* default.
|
||||
*/
|
||||
function sharedColumns(
|
||||
source: NodeSqlite.DatabaseSync,
|
||||
target: NodeSqlite.DatabaseSync,
|
||||
table: string,
|
||||
): { readonly shared: ReadonlyArray<string>; readonly skipped: ReadonlyArray<string> } {
|
||||
const sourceColumns = columnsOf(source, table);
|
||||
const targetColumns = new Set(columnsOf(target, table));
|
||||
const shared = sourceColumns.filter((column) => targetColumns.has(column));
|
||||
const skipped = sourceColumns
|
||||
.filter((column) => !targetColumns.has(column))
|
||||
.map((column) => `${table}.${column}`);
|
||||
return { shared, skipped };
|
||||
}
|
||||
|
||||
const placeholders = (count: number) => Array.from({ length: count }, () => "?").join(", ");
|
||||
|
||||
const hasTable = (database: NodeSqlite.DatabaseSync, table: string): boolean =>
|
||||
database.prepare(`SELECT 1 FROM pragma_table_info(?)`).get(table) !== undefined;
|
||||
|
||||
const hasColumn = (database: NodeSqlite.DatabaseSync, table: string, column: string): boolean =>
|
||||
columnsOf(database, table).includes(column);
|
||||
|
||||
/**
|
||||
* Attachment ids referenced by the copied messages, so the caller can copy the
|
||||
* files that back them. `attachments_json` is a JSON array of ChatAttachment
|
||||
* (packages/contracts/src/orchestration.ts); anything unparseable is skipped
|
||||
* rather than failing the seed, since a missing image is a cosmetic problem and
|
||||
* an aborted seed is not.
|
||||
*/
|
||||
function collectAttachmentIds(
|
||||
target: NodeSqlite.DatabaseSync,
|
||||
threadIds: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> {
|
||||
if (
|
||||
threadIds.length === 0 ||
|
||||
!hasColumn(target, "projection_thread_messages", "attachments_json")
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const ids = new Set<string>();
|
||||
const rows = target
|
||||
.prepare(
|
||||
`SELECT attachments_json FROM projection_thread_messages
|
||||
WHERE attachments_json IS NOT NULL AND thread_id IN (${placeholders(threadIds.length)})`,
|
||||
)
|
||||
.iterate(...threadIds) as Iterable<{ attachments_json: unknown }>;
|
||||
for (const row of rows) {
|
||||
if (typeof row.attachments_json !== "string") {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(row.attachments_json);
|
||||
if (!Array.isArray(parsed)) {
|
||||
continue;
|
||||
}
|
||||
for (const attachment of parsed) {
|
||||
const id: unknown = (attachment as { id?: unknown } | null)?.id;
|
||||
if (typeof id === "string" && id.length > 0) {
|
||||
ids.add(id);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A row whose JSON does not parse cannot name a file to copy.
|
||||
}
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies rows for `table` whose `keyColumn` is in `keys`, optionally keeping
|
||||
* only the newest `perKeyLimit` rows per key.
|
||||
*/
|
||||
function copyRows(input: {
|
||||
readonly source: NodeSqlite.DatabaseSync;
|
||||
readonly target: NodeSqlite.DatabaseSync;
|
||||
readonly table: string;
|
||||
readonly keyColumn: string;
|
||||
readonly keys: ReadonlyArray<string>;
|
||||
readonly omitColumns?: ReadonlyArray<string>;
|
||||
readonly perKeyLimit?: { readonly orderBy: string; readonly limit: number };
|
||||
readonly overrides?: Readonly<Record<string, unknown>>;
|
||||
}): { readonly copied: number; readonly skipped: ReadonlyArray<string> } {
|
||||
if (input.keys.length === 0) {
|
||||
return { copied: 0, skipped: [] };
|
||||
}
|
||||
|
||||
const { shared, skipped } = sharedColumns(input.source, input.target, input.table);
|
||||
const omit = new Set(input.omitColumns ?? []);
|
||||
const columns = shared.filter((column) => !omit.has(column));
|
||||
if (columns.length === 0) {
|
||||
return { copied: 0, skipped };
|
||||
}
|
||||
|
||||
const selectList = columns.map((column) => `"${column}"`).join(", ");
|
||||
// OR REPLACE never fires after the wholesale DELETE, but keeps the copy
|
||||
// robust if the delete list and the copy list ever drift apart.
|
||||
const insert = input.target.prepare(
|
||||
`INSERT OR REPLACE INTO ${input.table} (${selectList}) VALUES (${placeholders(columns.length)})`,
|
||||
);
|
||||
const overrides = input.overrides ?? {};
|
||||
let copied = 0;
|
||||
// Iterate rather than materialize: messages are uncapped, and buffering
|
||||
// every row of a large copy into a JS array costs memory for nothing —
|
||||
// the target transaction is already open.
|
||||
const insertFrom = (rows: Iterable<unknown>) => {
|
||||
for (const row of rows as Iterable<Record<string, unknown>>) {
|
||||
insert.run(
|
||||
...columns.map((column) => {
|
||||
const value = Object.hasOwn(overrides, column) ? overrides[column] : row[column];
|
||||
// node:sqlite binds only null/number/bigint/string/Uint8Array; every
|
||||
// projection column is one of those, and undefined means "absent".
|
||||
return (value ?? null) as null | number | bigint | string | Uint8Array;
|
||||
}),
|
||||
);
|
||||
copied += 1;
|
||||
}
|
||||
};
|
||||
|
||||
if (input.perKeyLimit) {
|
||||
// Per-key cap: one bounded query per key beats a window function — the
|
||||
// (thread_id, created_at) index lets each query walk backwards and stop
|
||||
// at the limit instead of ranking every row.
|
||||
const statement = input.source.prepare(
|
||||
`SELECT ${selectList} FROM ${input.table} WHERE "${input.keyColumn}" = ?
|
||||
ORDER BY ${input.perKeyLimit.orderBy} LIMIT ?`,
|
||||
);
|
||||
for (const key of input.keys) {
|
||||
insertFrom(statement.iterate(key, input.perKeyLimit.limit));
|
||||
}
|
||||
} else {
|
||||
insertFrom(
|
||||
input.source
|
||||
.prepare(
|
||||
`SELECT ${selectList} FROM ${input.table} WHERE "${input.keyColumn}" IN (${placeholders(input.keys.length)})`,
|
||||
)
|
||||
.iterate(...input.keys),
|
||||
);
|
||||
}
|
||||
|
||||
return { copied, skipped };
|
||||
}
|
||||
|
||||
/**
|
||||
* Settles turns copied while still running, matching what the server does to a
|
||||
* turn whose session leaves "running": `settledTurnStateForSessionStatus` in
|
||||
* apps/server/src/orchestration/Layers/ProjectionPipeline.ts maps the "stopped"
|
||||
* status the sessions are copied with to "interrupted".
|
||||
*
|
||||
* "pending" rows are deleted rather than settled — see `dropPendingTurnStarts`.
|
||||
*
|
||||
* An UPDATE rather than a copy override, because only the rows that were
|
||||
* actually running should change; the rest keep their real recorded state.
|
||||
*/
|
||||
function settleRunningTurns(
|
||||
target: NodeSqlite.DatabaseSync,
|
||||
threadIds: ReadonlyArray<string>,
|
||||
): void {
|
||||
if (threadIds.length === 0 || !hasColumn(target, "projection_turns", "state")) {
|
||||
return;
|
||||
}
|
||||
// A settled turn needs a completion time, and `requested_at` is the only
|
||||
// timestamp guaranteed present. Overwritten unconditionally rather than
|
||||
// COALESCEd: a running turn can carry a stale `completed_at` from an earlier
|
||||
// settle that a later checkpoint reverted to "running" (the `...existingTurn`
|
||||
// spread in ProjectionPipeline preserves it), and keeping that value would
|
||||
// date the interruption to whenever that checkpoint landed.
|
||||
const setCompletedAt = hasColumn(target, "projection_turns", "completed_at")
|
||||
? `, completed_at = requested_at`
|
||||
: "";
|
||||
// `turn_id IS NOT NULL` mirrors the server's own settle filter
|
||||
// (ProjectionPipeline, on the session leaving "running"). No writer produces
|
||||
// a row that is both null-id and running today — the only null-id insert
|
||||
// writes 'pending' — so this is guarding the invariant rather than a case,
|
||||
// and it keeps the two predicates comparable if that ever changes.
|
||||
//
|
||||
// 'running' is inlined, not bound: `--threads` is capped at SQLite's variable
|
||||
// ceiling, so every binding beyond one per thread puts the maximum over the
|
||||
// limit. Safe to interpolate — an internal literal, never input.
|
||||
target
|
||||
.prepare(
|
||||
`UPDATE projection_turns SET state = 'interrupted'${setCompletedAt}
|
||||
WHERE state = 'running'
|
||||
AND turn_id IS NOT NULL
|
||||
AND thread_id IN (${placeholders(threadIds.length)})`,
|
||||
)
|
||||
.run(...threadIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops turn rows copied in the "pending" state — a user message accepted
|
||||
* before its provider turn started.
|
||||
*
|
||||
* Deleted rather than settled, because that is what the server does with them:
|
||||
* `clearPendingProjectionTurnsByThread` removes them once the turn starts or
|
||||
* the thread is stopped, and nothing settles them in place. They also cannot be
|
||||
* settled coherently — `turn_id` is NULL, so an "interrupted" pending row is a
|
||||
* terminal turn with no id, a shape no real turn ever has.
|
||||
*
|
||||
* Matches the server's own predicate exactly, so a checkpoint row is never
|
||||
* caught by it.
|
||||
*/
|
||||
function dropPendingTurnStarts(
|
||||
target: NodeSqlite.DatabaseSync,
|
||||
threadIds: ReadonlyArray<string>,
|
||||
): void {
|
||||
if (threadIds.length === 0 || !hasColumn(target, "projection_turns", "state")) {
|
||||
return;
|
||||
}
|
||||
// The checkpoint guard is only meaningful where the column exists; an older
|
||||
// target without it has no checkpoint rows to protect.
|
||||
const excludeCheckpoints = hasColumn(target, "projection_turns", "checkpoint_turn_count")
|
||||
? "AND checkpoint_turn_count IS NULL"
|
||||
: "";
|
||||
target
|
||||
.prepare(
|
||||
`DELETE FROM projection_turns
|
||||
WHERE state = 'pending'
|
||||
AND turn_id IS NULL
|
||||
${excludeCheckpoints}
|
||||
AND thread_id IN (${placeholders(threadIds.length)})`,
|
||||
)
|
||||
.run(...threadIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the target's projections with a recent slice of the source's.
|
||||
*
|
||||
* Destructive and not incremental: every projection table, the event log, and
|
||||
* the command receipts are emptied first, inside one transaction that rolls
|
||||
* back on any failure. Validation that can reject the whole run happens before
|
||||
* that transaction opens, so a rejected seed leaves the target as it was.
|
||||
*
|
||||
* The caller must ensure no server is using the target — see the guard in
|
||||
* scripts/dev-seed.ts. Returns counts plus the attachment ids whose files the
|
||||
* caller still has to copy.
|
||||
*
|
||||
* @throws {DevSeedError} on bad limits, an unopenable database, or a source
|
||||
* with no active threads.
|
||||
*/
|
||||
export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
// Checked before anything is opened, and certainly before the target is
|
||||
// emptied: overrunning the ceiling mid-copy destroys the target's data and
|
||||
// rolls back without replacing it.
|
||||
if (options.threadLimit > MAX_SEED_THREAD_LIMIT) {
|
||||
throw new DevSeedError(
|
||||
`cannot copy more than ${String(MAX_SEED_THREAD_LIMIT)} threads in one pass`,
|
||||
"Each thread costs one SQLite bound variable, and that is the engine's limit.",
|
||||
);
|
||||
}
|
||||
// Both limits are bound straight into `LIMIT ?`, where SQLite reads a
|
||||
// negative value as "no limit" — so a caller bypassing the CLI flags turns a
|
||||
// capped copy into a full-table one, silently. The flags already reject this;
|
||||
// enforcing it here keeps the options contract true of the function itself.
|
||||
for (const [name, value] of [
|
||||
["threadLimit", options.threadLimit],
|
||||
["activityLimit", options.activityLimit],
|
||||
] as const) {
|
||||
if (!Number.isSafeInteger(value) || value < 1) {
|
||||
throw new DevSeedError(
|
||||
`${name} must be a positive integer, got ${String(value)}`,
|
||||
"SQLite reads a negative LIMIT as unbounded, which would copy the whole table.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let source: NodeSqlite.DatabaseSync;
|
||||
try {
|
||||
source = new NodeSqlite.DatabaseSync(options.sourceDbPath, { readOnly: true });
|
||||
} catch (cause) {
|
||||
throw new DevSeedError(
|
||||
`could not open the source database at ${options.sourceDbPath}`,
|
||||
`${String(cause)}. Has T3 Code run at least once?`,
|
||||
);
|
||||
}
|
||||
|
||||
let target: NodeSqlite.DatabaseSync;
|
||||
try {
|
||||
target = new NodeSqlite.DatabaseSync(options.targetDbPath);
|
||||
} catch (cause) {
|
||||
source.close();
|
||||
throw new DevSeedError(
|
||||
`could not open the target database at ${options.targetDbPath}`,
|
||||
`${String(cause)}. Start the dev server once so migrations run, then retry.`,
|
||||
);
|
||||
}
|
||||
|
||||
// The source is normally the *live* installed app's database — only the
|
||||
// target is guarded against a running server, because reading is harmless.
|
||||
// Reading it across a dozen separate implicit transactions is not: the app
|
||||
// can delete a project between the query that picks it up and the copy that
|
||||
// reads its row, leaving a copied thread whose project no longer exists (no
|
||||
// foreign keys are declared, so nothing catches it). One deferred read
|
||||
// transaction pins every query below to a single snapshot.
|
||||
let sourceTransactionOpen = false;
|
||||
try {
|
||||
source.exec("BEGIN");
|
||||
sourceTransactionOpen = true;
|
||||
} catch {
|
||||
// A concurrent writer can leave the connection unable to start one. The
|
||||
// copy is still worth doing — it just loses snapshot isolation.
|
||||
}
|
||||
|
||||
try {
|
||||
// Threads the user actually touched most recently. Mirrors the sidebar's
|
||||
// own ordering (packages/client-runtime/src/state/threadSort.ts), including
|
||||
// its user-message scan when the materialized timestamp is null. Both
|
||||
// recency columns arrived in later migrations, so an older source database
|
||||
// is read with whichever inputs it actually has.
|
||||
const recencyExpressions: Array<string> = [];
|
||||
if (hasColumn(source, "projection_threads", "latest_user_message_at")) {
|
||||
recencyExpressions.push('threads."latest_user_message_at"');
|
||||
}
|
||||
if (
|
||||
hasTable(source, "projection_thread_messages") &&
|
||||
["thread_id", "role", "created_at"].every((column) =>
|
||||
hasColumn(source, "projection_thread_messages", column),
|
||||
)
|
||||
) {
|
||||
recencyExpressions.push(`(
|
||||
SELECT MAX(messages."created_at")
|
||||
FROM projection_thread_messages AS messages
|
||||
WHERE messages."thread_id" = threads."thread_id"
|
||||
AND messages."role" = 'user'
|
||||
)`);
|
||||
}
|
||||
for (const column of ["updated_at", "created_at"]) {
|
||||
if (hasColumn(source, "projection_threads", column)) {
|
||||
recencyExpressions.push(`threads."${column}"`);
|
||||
}
|
||||
}
|
||||
// SQLite's COALESCE requires at least two arguments, so a source down to a
|
||||
// single recency column — the pre-migration-017 case this filter exists to
|
||||
// support — would throw rather than degrade. `created_at` is NOT NULL from
|
||||
// migration 005 on, so there is always at least one.
|
||||
const recencyOrder =
|
||||
recencyExpressions.length > 1
|
||||
? `COALESCE(${recencyExpressions.join(", ")})`
|
||||
: (recencyExpressions[0] ?? "threads.rowid");
|
||||
const activeFilters = ["deleted_at", "archived_at"]
|
||||
.filter((column) => hasColumn(source, "projection_threads", column))
|
||||
.map((column) => `threads."${column}" IS NULL`);
|
||||
const threadIds = (
|
||||
source
|
||||
.prepare(
|
||||
`SELECT threads."thread_id" AS thread_id
|
||||
FROM projection_threads AS threads
|
||||
${activeFilters.length > 0 ? `WHERE ${activeFilters.join(" AND ")}` : ""}
|
||||
ORDER BY ${recencyOrder} DESC, threads."thread_id" DESC
|
||||
LIMIT ?`,
|
||||
)
|
||||
.all(options.threadLimit) as Array<{ thread_id: string }>
|
||||
).map((row) => row.thread_id);
|
||||
|
||||
if (threadIds.length === 0) {
|
||||
throw new DevSeedError(
|
||||
"the source database has no active threads to copy",
|
||||
"Use T3 Code normally first, or point --from at a different data directory.",
|
||||
);
|
||||
}
|
||||
|
||||
const projectIds = (
|
||||
source
|
||||
.prepare(
|
||||
`SELECT DISTINCT project_id FROM projection_threads
|
||||
WHERE thread_id IN (${placeholders(threadIds.length)})`,
|
||||
)
|
||||
.all(...threadIds) as Array<{ project_id: string }>
|
||||
).map((row) => row.project_id);
|
||||
|
||||
const skipped: Array<string> = [];
|
||||
const record = (result: {
|
||||
readonly copied: number;
|
||||
readonly skipped: ReadonlyArray<string>;
|
||||
}) => {
|
||||
skipped.push(...result.skipped);
|
||||
return result.copied;
|
||||
};
|
||||
|
||||
target.exec("BEGIN IMMEDIATE");
|
||||
|
||||
for (const table of PROJECTION_TABLES_IN_DEPENDENCY_ORDER) {
|
||||
// A target behind on migrations may not have every table yet; skipping is
|
||||
// consistent with how column drift is handled, and beats aborting the seed.
|
||||
if (hasTable(target, table)) {
|
||||
target.exec(`DELETE FROM ${table}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Projections are copied wholesale, so any event history the target still
|
||||
// holds describes a different world. Replaying it over the copied rows
|
||||
// would resurrect the target's own deleted threads and projects.
|
||||
if (hasTable(target, "orchestration_events")) {
|
||||
target.exec("DELETE FROM orchestration_events");
|
||||
}
|
||||
if (hasTable(target, "orchestration_command_receipts")) {
|
||||
target.exec("DELETE FROM orchestration_command_receipts");
|
||||
}
|
||||
// Provider bindings are keyed by thread id and are not copied (no agent
|
||||
// process comes with the seed). Left in place they outlive the threads they
|
||||
// name: ProviderSessionReaper sweeps every non-stopped binding, finds no
|
||||
// thread behind it, and so never hits its active-turn guard — it just tries
|
||||
// to stop a session for a thread that no longer exists, against a provider
|
||||
// instance this worktree may not even define.
|
||||
if (hasTable(target, "provider_session_runtime")) {
|
||||
target.exec("DELETE FROM provider_session_runtime");
|
||||
}
|
||||
|
||||
const projects = record(
|
||||
copyRows({
|
||||
source,
|
||||
target,
|
||||
table: "projection_projects",
|
||||
keyColumn: "project_id",
|
||||
keys: projectIds,
|
||||
}),
|
||||
);
|
||||
const threads = record(
|
||||
copyRows({
|
||||
source,
|
||||
target,
|
||||
table: "projection_threads",
|
||||
keyColumn: "thread_id",
|
||||
keys: threadIds,
|
||||
// Approvals are not copied (see below), so the badge must not claim any.
|
||||
// Sessions are copied as stopped with no active turn, matching the
|
||||
// thread.session-set projection by clearing its latest turn pointer.
|
||||
overrides: {
|
||||
latest_turn_id: null,
|
||||
pending_approval_count: 0,
|
||||
pending_user_input_count: 0,
|
||||
},
|
||||
}),
|
||||
);
|
||||
// row_id is an AUTOINCREMENT surrogate; let the target assign its own.
|
||||
const turns = record(
|
||||
copyRows({
|
||||
source,
|
||||
target,
|
||||
table: "projection_turns",
|
||||
keyColumn: "thread_id",
|
||||
keys: threadIds,
|
||||
omitColumns: ["row_id"],
|
||||
}),
|
||||
);
|
||||
// A thread copied mid-turn has no agent to finish it. The session status is
|
||||
// forced to "stopped" below, but the turn is read independently: an
|
||||
// unfinished turn keeps the thread unsettled and unfoldable forever
|
||||
// (deriveUnsettledTurnId in MessagesTimeline.logic.ts). Interrupted is what
|
||||
// the server itself settles an abandoned turn to; a pending start is
|
||||
// something it deletes outright.
|
||||
settleRunningTurns(target, threadIds);
|
||||
dropPendingTurnStarts(target, threadIds);
|
||||
const messages = record(
|
||||
copyRows({
|
||||
source,
|
||||
target,
|
||||
table: "projection_thread_messages",
|
||||
keyColumn: "thread_id",
|
||||
keys: threadIds,
|
||||
// Same reason: a message copied while streaming has nothing left to
|
||||
// stream into it, so it would render with a caret that never resolves.
|
||||
overrides: { is_streaming: 0 },
|
||||
}),
|
||||
);
|
||||
const activities = record(
|
||||
copyRows({
|
||||
source,
|
||||
target,
|
||||
table: "projection_thread_activities",
|
||||
keyColumn: "thread_id",
|
||||
keys: threadIds,
|
||||
// Ordered the way the app reads these back — `sequence`, `created_at`,
|
||||
// then `activity_id` (ProjectionSnapshotQuery). Any other key order can keep
|
||||
// rows the timeline treats as oldest: timestamps tie within a burst of
|
||||
// tool activity, and can even disagree with `sequence` outright when
|
||||
// events arrive with skewed clocks. Descending, a NULL `sequence`
|
||||
// sorts last, mirroring where the app's ascending reads place it.
|
||||
//
|
||||
// `sequence` arrived in migration 008, so a source without it falls
|
||||
// back to the timestamp — same drift tolerance as the rest of the copy.
|
||||
perKeyLimit: {
|
||||
orderBy: hasColumn(source, "projection_thread_activities", "sequence")
|
||||
? `"sequence" DESC, "created_at" DESC, "activity_id" DESC`
|
||||
: `"created_at" DESC, "activity_id" DESC`,
|
||||
limit: options.activityLimit,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const sessions = record(
|
||||
copyRows({
|
||||
source,
|
||||
target,
|
||||
table: "projection_thread_sessions",
|
||||
keyColumn: "thread_id",
|
||||
keys: threadIds,
|
||||
// No agent process is attached in the copy. A carried-over "running"
|
||||
// status with an active turn renders a thread that spins forever, and
|
||||
// ProviderSessionReaper skips reaping anything with an active turn.
|
||||
// "ready"/"idle" are live-session completion signals to agent
|
||||
// awareness, so preserving those would publish historical fixtures as
|
||||
// newly completed work. Every copied session is intentionally stopped.
|
||||
overrides: { status: "stopped", active_turn_id: null, last_error: null },
|
||||
}),
|
||||
);
|
||||
record(
|
||||
copyRows({
|
||||
source,
|
||||
target,
|
||||
table: "projection_thread_proposed_plans",
|
||||
keyColumn: "thread_id",
|
||||
keys: threadIds,
|
||||
}),
|
||||
);
|
||||
// projection_pending_approvals is deliberately skipped: migration 025 deletes
|
||||
// approvals with no matching `approval.requested` activity, and the activity
|
||||
// cap above can easily drop it.
|
||||
|
||||
// Required: computeSnapshotSequence returns 0 unless every projector has a
|
||||
// row, which makes every shell snapshot advertise sequence 0.
|
||||
//
|
||||
// Zero, not the source's cursors. `orchestration_events.sequence` is
|
||||
// AUTOINCREMENT, so emptying the log does not reset its high-water mark and
|
||||
// the next real event continues from wherever the target left off. A cursor
|
||||
// carried over from the source is unrelated to that number: it could sit
|
||||
// above it (each projector then silently skipping a different count of the
|
||||
// user's first real events, desynchronizing the projections for good) or
|
||||
// below it (replaying events over rows they never produced). Zero is below
|
||||
// every future sequence, so bootstrap streams the empty log, finds nothing,
|
||||
// and leaves the copied rows exactly as they are.
|
||||
const insertState = target.prepare(
|
||||
`INSERT OR REPLACE INTO projection_state (projector, last_applied_sequence, updated_at)
|
||||
VALUES (?, 0, ?)`,
|
||||
);
|
||||
for (const projector of PROJECTOR_NAMES) {
|
||||
insertState.run(projector, options.seededAt);
|
||||
}
|
||||
|
||||
// Read back inside the transaction: these are the rows that were just
|
||||
// written, not the source's, so a column the target lacks is already gone.
|
||||
const attachmentIds = collectAttachmentIds(target, threadIds);
|
||||
|
||||
// Last moment a rollback is still free. The caller checked before calling,
|
||||
// but a server can start during a copy that takes seconds; checking again
|
||||
// here narrows the window to the commit itself. Everything above is inside
|
||||
// the transaction, so aborting now leaves the target exactly as it was.
|
||||
const lateRunningPid = options.findRunningServerPid?.();
|
||||
if (lateRunningPid !== undefined) {
|
||||
throw new DevSeedError(
|
||||
`a T3 Code server (pid ${String(lateRunningPid)}) started while the seed was running`,
|
||||
"Nothing was changed. Stop it and run the seed again.",
|
||||
);
|
||||
}
|
||||
|
||||
target.exec("COMMIT");
|
||||
|
||||
return {
|
||||
projects,
|
||||
threads,
|
||||
messages,
|
||||
activities,
|
||||
turns,
|
||||
sessions,
|
||||
skippedColumns: [...new Set(skipped)].sort(),
|
||||
attachmentIds,
|
||||
};
|
||||
} catch (cause) {
|
||||
try {
|
||||
target.exec("ROLLBACK");
|
||||
} catch {
|
||||
// Already rolled back, or the transaction never opened.
|
||||
}
|
||||
throw cause instanceof DevSeedError
|
||||
? cause
|
||||
: new DevSeedError(`could not seed the dev database: ${String(cause)}`);
|
||||
} finally {
|
||||
if (sourceTransactionOpen) {
|
||||
try {
|
||||
// Read-only, so there is nothing to commit; end it before closing so
|
||||
// the snapshot is released explicitly rather than by teardown.
|
||||
source.exec("ROLLBACK");
|
||||
} catch {
|
||||
// Already ended, which is equally fine for a read-only transaction.
|
||||
}
|
||||
}
|
||||
source.close();
|
||||
target.close();
|
||||
}
|
||||
}
|
||||
@@ -1,353 +0,0 @@
|
||||
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 Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
acquireDevShare,
|
||||
claimDevShareLease,
|
||||
cleanupOwnedDevShare,
|
||||
type DevShareError,
|
||||
DevShareLeaseClaimError,
|
||||
DevServeFailedError,
|
||||
shareDevServer,
|
||||
unshareDevServer,
|
||||
} from "./dev-share.ts";
|
||||
|
||||
const TAILNET_STATUS = JSON.stringify({ Self: { DNSName: "host.example.ts.net." } });
|
||||
const NO_HANDLER_STDERR = "error: failed to remove web serve: handler does not exist";
|
||||
|
||||
interface CallResult {
|
||||
readonly exitCode: number;
|
||||
readonly stderr?: string;
|
||||
}
|
||||
|
||||
const encode = (value: string) => Stream.make(new TextEncoder().encode(value));
|
||||
|
||||
/**
|
||||
* Answers `tailscale status --json` with a valid tailnet name, and lets each
|
||||
* test set the outcome of the `off` (pre-clear) and `serve` calls separately —
|
||||
* they are the same subcommand and are told apart by the trailing `off`.
|
||||
*/
|
||||
const spawnerLayer = (input: {
|
||||
readonly off?: CallResult;
|
||||
readonly serve?: CallResult;
|
||||
readonly onOff?: Effect.Effect<void>;
|
||||
readonly calls?: Array<ReadonlyArray<string>>;
|
||||
}) =>
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const args = "args" in command ? (command.args as ReadonlyArray<string>) : [];
|
||||
input.calls?.push(args);
|
||||
const result: CallResult = args.includes("status")
|
||||
? { exitCode: 0 }
|
||||
: args.includes("off")
|
||||
? (input.off ?? { exitCode: 0 })
|
||||
: (input.serve ?? { exitCode: 0 });
|
||||
|
||||
return Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: (args.includes("off") ? (input.onOff ?? Effect.void) : Effect.void).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(result.exitCode)),
|
||||
),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: args.includes("status") ? encode(TAILNET_STATUS) : Stream.empty,
|
||||
stderr: result.stderr ? encode(result.stderr) : Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
describe("unshareDevServer", () => {
|
||||
it.effect("treats a removed mapping as cleared", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* unshareDevServer(5788).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 0 } })),
|
||||
);
|
||||
assert.isTrue(result.cleared);
|
||||
}),
|
||||
);
|
||||
|
||||
// `tailscale serve … off` exits 1 when the port had no mapping, which is the
|
||||
// normal first-share case — the port is clear, so this must not be an error.
|
||||
it.effect("treats a missing handler as cleared", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* unshareDevServer(5788).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: NO_HANDLER_STDERR } })),
|
||||
);
|
||||
assert.isTrue(result.cleared);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a genuine removal failure as not cleared", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* unshareDevServer(5788).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: "permission denied" } })),
|
||||
);
|
||||
assert.isFalse(result.cleared);
|
||||
assert.include(result.explanation, "permission denied");
|
||||
// Structured, so a wrapping error can keep the real chain.
|
||||
assert.equal(result.cause?._tag, "TailscaleCommandExitError");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("shareDevServer", () => {
|
||||
it.effect("returns the tailnet URL for the same port", () =>
|
||||
Effect.gen(function* () {
|
||||
const shared = yield* shareDevServer({ webPort: 5788 }).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: NO_HANDLER_STDERR } })),
|
||||
);
|
||||
|
||||
assert.equal(shared.host, "host.example.ts.net");
|
||||
assert.equal(shared.url, "https://host.example.ts.net:5788/");
|
||||
}),
|
||||
);
|
||||
|
||||
// The stale-mapping clear runs before serve, so a failure here leaves the
|
||||
// port serving nothing. Saying only "serve failed" would let an operator
|
||||
// assume their previous mapping survived.
|
||||
it.effect("reports that the prior mapping was cleared when serve fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
|
||||
Effect.provide(
|
||||
spawnerLayer({
|
||||
off: { exitCode: 0 },
|
||||
serve: { exitCode: 1, stderr: "port already in use" },
|
||||
}),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, DevServeFailedError);
|
||||
assert.equal(error.stage, "serve");
|
||||
assert.equal(error.webPort, 5788);
|
||||
// The underlying failure is preserved rather than flattened to a string.
|
||||
assert.equal(
|
||||
(error.cause as { _tag?: string } | undefined)?._tag,
|
||||
"TailscaleCommandExitError",
|
||||
);
|
||||
// Unclassifiable stderr is never quoted (it can carry auth keys), so the
|
||||
// message points at the command instead of echoing the CLI.
|
||||
assert.notInclude(error.message, "port already in use");
|
||||
assert.include(error.message, "run the command by hand");
|
||||
assert.include(error.message, "no longer served");
|
||||
assert.include(error.message, "5788");
|
||||
}),
|
||||
);
|
||||
|
||||
// A recognized failure gets our own wording for it — enough to act on
|
||||
// without passing CLI text through.
|
||||
it.effect("explains a recognized serve failure without quoting stderr", () =>
|
||||
Effect.gen(function* () {
|
||||
const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
|
||||
Effect.provide(
|
||||
spawnerLayer({
|
||||
off: { exitCode: 0 },
|
||||
serve: {
|
||||
exitCode: 1,
|
||||
stderr: "permission denied for tskey-auth-secret-token-value",
|
||||
},
|
||||
}),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, DevServeFailedError);
|
||||
assert.equal(error.stage, "serve");
|
||||
assert.include(error.message, "permission denied");
|
||||
assert.include(error.message, "elevated privileges");
|
||||
assert.notInclude(error.message, "tskey-auth-secret-token-value");
|
||||
}),
|
||||
);
|
||||
|
||||
// Serving over routes we could not remove yields a URL that loads but whose
|
||||
// /ws and /api quietly point at a dead backend.
|
||||
it.effect("refuses to serve when the existing mapping could not be cleared", () =>
|
||||
Effect.gen(function* () {
|
||||
const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
|
||||
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: "permission denied" } })),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, DevServeFailedError);
|
||||
// A distinct stage: the prior mapping survived, so nothing was replaced.
|
||||
assert.equal(error.stage, "clear-existing");
|
||||
assert.include(error.message, "could not clear the existing mapping");
|
||||
assert.include(error.message, "permission denied");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("dev share cleanup ownership", (it) => {
|
||||
it.effect("claims ownership via an atomic rename", () =>
|
||||
Effect.gen(function* () {
|
||||
const leasePath = "/leases/5788.owner";
|
||||
const tempDirectory = "/leases/5788.owner.temp";
|
||||
const writes: Array<readonly [path: string, contents: string]> = [];
|
||||
const renames: Array<readonly [from: string, to: string]> = [];
|
||||
|
||||
yield* claimDevShareLease({ leasePath, ownerId: "new-runner", webPort: 5788 }).pipe(
|
||||
Effect.provideService(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
makeDirectory: () => Effect.void,
|
||||
makeTempDirectoryScoped: (options) => {
|
||||
assert.equal(options?.directory, "/leases");
|
||||
assert.equal(options?.prefix, "5788.owner.");
|
||||
return Effect.succeed(tempDirectory);
|
||||
},
|
||||
writeFileString: (path, contents) => {
|
||||
writes.push([path, contents]);
|
||||
return Effect.void;
|
||||
},
|
||||
rename: (from, to) => {
|
||||
renames.push([from, to]);
|
||||
return Effect.void;
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepEqual(writes, [[`${tempDirectory}/owner.tmp`, "new-runner"]]);
|
||||
assert.deepEqual(renames, [[`${tempDirectory}/owner.tmp`, leasePath]]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the prior owner when clearing its mapping fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-dev-share-lease-",
|
||||
});
|
||||
const leasePath = `${directory}/5788.owner`;
|
||||
const calls: Array<ReadonlyArray<string>> = [];
|
||||
|
||||
yield* fileSystem.writeFileString(leasePath, "old-runner");
|
||||
yield* acquireDevShare({
|
||||
leasePath,
|
||||
ownerId: "new-runner",
|
||||
webPort: 5788,
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
spawnerLayer({
|
||||
calls,
|
||||
off: { exitCode: 1, stderr: "permission denied" },
|
||||
}),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.equal(yield* fileSystem.readFileString(leasePath), "old-runner");
|
||||
assert.equal(calls.filter((args) => args.includes("off")).length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("claims ownership after clearing and before publishing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-dev-share-lease-",
|
||||
});
|
||||
const leasePath = `${directory}/5788.owner`;
|
||||
|
||||
yield* fileSystem.writeFileString(leasePath, "old-runner");
|
||||
yield* acquireDevShare({
|
||||
leasePath,
|
||||
ownerId: "new-runner",
|
||||
webPort: 5788,
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
spawnerLayer({
|
||||
off: { exitCode: 0 },
|
||||
serve: { exitCode: 1, stderr: "permission denied" },
|
||||
}),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.equal(yield* fileSystem.readFileString(leasePath), "new-runner");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores the mapping when ownership cannot be claimed", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-dev-share-lease-",
|
||||
});
|
||||
const blockedDirectory = `${directory}/not-a-directory`;
|
||||
const calls: Array<ReadonlyArray<string>> = [];
|
||||
|
||||
yield* fileSystem.writeFileString(blockedDirectory, "blocked");
|
||||
const error = yield* acquireDevShare({
|
||||
leasePath: `${blockedDirectory}/5788.owner`,
|
||||
ownerId: "new-runner",
|
||||
webPort: 5788,
|
||||
}).pipe(Effect.provide(spawnerLayer({ calls })), Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DevShareLeaseClaimError);
|
||||
assert.isTrue(calls.some((args) => args.includes("off")));
|
||||
assert.isTrue(calls.some((args) => args.includes("http://127.0.0.1:5788")));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores a newer runner's mapping when ownership changes during cleanup", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-dev-share-lease-",
|
||||
});
|
||||
const leasePath = `${directory}/5788.owner`;
|
||||
const oldLease = { leasePath, ownerId: "old-runner", webPort: 5788 };
|
||||
const calls: Array<ReadonlyArray<string>> = [];
|
||||
|
||||
yield* claimDevShareLease(oldLease);
|
||||
const result = yield* cleanupOwnedDevShare(oldLease).pipe(
|
||||
Effect.provide(
|
||||
spawnerLayer({
|
||||
calls,
|
||||
onOff: fileSystem.writeFileString(leasePath, "new-runner").pipe(Effect.orDie),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(result.status, "restored");
|
||||
assert.isTrue(calls.some((args) => args.includes("off")));
|
||||
assert.isTrue(calls.some((args) => args.includes("http://127.0.0.1:5788")));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("leaves the mapping alone when a newer runner already owns it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-dev-share-lease-",
|
||||
});
|
||||
const leasePath = `${directory}/5788.owner`;
|
||||
const oldLease = { leasePath, ownerId: "old-runner", webPort: 5788 };
|
||||
const calls: Array<ReadonlyArray<string>> = [];
|
||||
|
||||
yield* claimDevShareLease(oldLease);
|
||||
yield* claimDevShareLease({ ...oldLease, ownerId: "new-runner" });
|
||||
const result = yield* cleanupOwnedDevShare(oldLease).pipe(
|
||||
Effect.provide(spawnerLayer({ calls })),
|
||||
);
|
||||
|
||||
assert.equal(result.status, "superseded");
|
||||
assert.isEmpty(calls);
|
||||
}),
|
||||
);
|
||||
});
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user