Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ed20241d2 | ||
|
|
827f921c02 | ||
|
|
89c5a192f4 | ||
|
|
23b5502217 | ||
|
|
a17cbc3b40 | ||
|
|
5719e8ac40 | ||
|
|
38cfc25e54 | ||
|
|
41a430a88e | ||
|
|
ece05087a7 | ||
|
|
a7ee3092c3 | ||
|
|
f7cc776488 | ||
|
|
15e875a2d9 | ||
|
|
5d173547ff | ||
|
|
202e5609ff |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
description: Launch, retain, and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, cross-turn dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, iteratively test UI behavior with a human, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
---
|
||||
|
||||
# Test T3 App
|
||||
@@ -13,13 +13,35 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
|
||||
2. Choose a base directory that belongs only to the current worktree or test:
|
||||
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
|
||||
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
|
||||
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
|
||||
3. Start the full web stack with `vp run dev`. Add `--share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.
|
||||
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
|
||||
|
||||
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
|
||||
|
||||
The worktree-local default deliberately outranks an ambient `T3CODE_HOME`; do not pass the shared home through to a worktree dev server.
|
||||
|
||||
Ports are derived from the worktree path but can shift when occupied. Always read the actual values from the `[dev-runner]` line.
|
||||
|
||||
Shared browser dev is single-origin: Vite proxies the backend paths, so never set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
|
||||
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
|
||||
|
||||
### Verify a shared environment before human handoff
|
||||
|
||||
When another person will use the printed pairing URL, first open the shared origin without the pairing path or fragment in the controlled browser and confirm the T3 Code app loads. This browser navigation is required even when curl succeeds because browsers block some otherwise reachable ports before making a network request.
|
||||
|
||||
Do not open the other person's complete pairing URL during this reachability check; doing so consumes its one-time token. If the agent also needs an authenticated browser, create and consume a separate pairing token, then leave a fresh token for the other person.
|
||||
|
||||
## Preserve the environment while iterating
|
||||
|
||||
Treat the overall testing or implementation loop—not an assistant turn or one verification pass—as the environment lifecycle boundary.
|
||||
|
||||
- Keep the dev process, base directory, selected ports, authenticated browser tab, registered projects, and seeded fixtures alive while the user may inspect the result or request follow-up changes.
|
||||
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
|
||||
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
|
||||
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
|
||||
@@ -45,7 +67,7 @@ T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
|
||||
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
|
||||
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
@@ -58,9 +80,17 @@ Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before chang
|
||||
|
||||
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
|
||||
|
||||
## Finish the test
|
||||
## Tear down only when the testing loop is finished
|
||||
|
||||
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
Tear down when the user explicitly asks, confirms the iteration is finished, or the overall task is genuinely complete with no pending human review. Do not infer completion from the end of an assistant turn.
|
||||
|
||||
When teardown is appropriate:
|
||||
|
||||
1. Stop the dev process with its terminal interrupt.
|
||||
2. Preserve the isolated base directory when it contains useful reproduction evidence or state for a likely follow-up.
|
||||
3. Otherwise remove only a path created for this test after resolving and verifying the exact target.
|
||||
|
||||
If completion is uncertain, keep the environment alive and mention that it is retained for further iteration. A fresh isolated base directory remains the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
|
||||
## Troubleshoot predictably
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
interface:
|
||||
display_name: "T3 App Testing"
|
||||
short_description: "Launch and seed isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
|
||||
short_description: "Launch and retain isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 environment and iteratively test it in the browser while preserving state."
|
||||
@@ -13,6 +13,14 @@
|
||||
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
|
||||
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
|
||||
|
||||
## Dev Servers
|
||||
|
||||
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
|
||||
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
|
||||
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
|
||||
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
|
||||
|
||||
## Package Roles
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
|
||||
@@ -472,6 +472,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -493,8 +497,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
@@ -504,20 +518,38 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProjectGroup,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
@@ -813,11 +845,31 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. Pending tasks render in the header, so the
|
||||
// list showing them isn't empty in the user's eyes.
|
||||
// fact when a query is active. Snoozed threads outrank the rest: "No
|
||||
// threads yet" over an inbox that is merely all-snoozed reads as data
|
||||
// loss. Pending tasks render in the header, so the list showing them
|
||||
// isn't empty in the user's eyes.
|
||||
const v2SnoozedCount = threadListV2Layout.snoozedCount;
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={
|
||||
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
|
||||
}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
|
||||
@@ -399,6 +399,10 @@ function ThreadNavigationSidebarPane(
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -420,8 +424,18 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
@@ -429,20 +443,38 @@ function ThreadNavigationSidebarPane(
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Enabled,
|
||||
threads,
|
||||
selectedProjectScope,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const listItems = useMemo<readonly SidebarListItem[]>(() => {
|
||||
if (!threadListV2Enabled) return listLayout.items;
|
||||
// Queued offline tasks render above the thread rows (mirrors the
|
||||
@@ -930,15 +962,28 @@ function ThreadNavigationSidebarPane(
|
||||
}),
|
||||
[filterIcon, filterMenu, props.onOpenSettings],
|
||||
);
|
||||
// "No threads yet" over an inbox that is merely all-snoozed reads as
|
||||
// data loss; name the snoozed threads instead.
|
||||
const snoozedCount = threadListV2Layout.snoozedCount;
|
||||
const listEmpty = (
|
||||
<Text className="px-2 py-4 text-sm text-foreground-muted">
|
||||
{catalogState.isLoadingConnections
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
? snoozedCount > 0
|
||||
? // Snoozed matches passed this same search filter — "No
|
||||
// matching threads" would misreport them as nonexistent.
|
||||
snoozedCount === 1
|
||||
? "1 matching thread snoozed"
|
||||
: "All matching threads snoozed"
|
||||
: "No matching threads"
|
||||
: snoozedCount > 0
|
||||
? snoozedCount === 1
|
||||
? "1 thread snoozed"
|
||||
: `${snoozedCount} threads snoozed`
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
|
||||
@@ -77,6 +77,85 @@ describe("sortThreadsForListV2", () => {
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("hides snoozed threads and counts them — visibility parity with web", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("woken"),
|
||||
title: "Woken",
|
||||
// Wake time already passed: back in the active list.
|
||||
snoozedUntil: "2026-06-01T18:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
// Same createdAt → static sort tiebreaks by id; the point is the woken
|
||||
// thread is BACK in the card block and the snoozed one is gone.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("classifies snooze with the second-precise clock and reports the next wake", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("just-woke"),
|
||||
title: "Just woke",
|
||||
// Woke 30s ago: hidden under the minute-floored clock, visible
|
||||
// under the precise one.
|
||||
snoozedUntil: "2026-06-02T00:00:30.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("still-snoozed"),
|
||||
title: "Still snoozed",
|
||||
snoozedUntil: "2026-06-02T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
// Minute-floored partition clock vs precise snooze clock.
|
||||
now: "2026-06-02T00:01:00.000Z",
|
||||
snoozeNow: "2026-06-02T00:01:07.500Z",
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["just-woke"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
|
||||
});
|
||||
|
||||
it("keeps snoozed threads visible on environments without the snooze capability", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
snoozeEnvironmentIds: new Set(),
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
|
||||
expect(layout.snoozedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("partitions settled threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
@@ -84,6 +84,13 @@ export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
/** Snoozed threads hidden from the list (visibility parity with web's
|
||||
collapsed Snoozed shelf; mobile has no shelf UI yet). */
|
||||
readonly snoozedCount: number;
|
||||
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
|
||||
a timeout at this boundary so the list re-partitions the moment a
|
||||
snooze expires instead of on the next minute tick. */
|
||||
readonly nextSnoozeWakeAt: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,13 +113,22 @@ export function buildThreadListV2Items(input: {
|
||||
other environments never classify as settled — the user could neither
|
||||
un-settle nor pin them. Absent = no gating (tests). */
|
||||
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
/** Environments whose server supports thread.snooze/unsnooze. Same
|
||||
contract as settlementEnvironmentIds. */
|
||||
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
readonly now?: string;
|
||||
/** Second-precise clock for snooze classification. Callers pass a
|
||||
minute-quantized `now` for memoization; snooze wake times are
|
||||
second-precise, so classifying with the floored minute would hold a
|
||||
woken thread hidden for up to a minute. Defaults to `now`. */
|
||||
readonly snoozeNow?: string;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const projectKeys = input.projectRefs
|
||||
@@ -121,6 +137,8 @@ export function buildThreadListV2Items(input: {
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
let snoozedCount = 0;
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
@@ -130,8 +148,23 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: a snoozed thread leaves the list until it
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozedCount += 1;
|
||||
if (
|
||||
thread.snoozedUntil != null &&
|
||||
(nextSnoozeWakeAt === null ||
|
||||
parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
|
||||
) {
|
||||
nextSnoozeWakeAt = thread.snoozedUntil;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
@@ -168,5 +201,10 @@ export function buildThreadListV2Items(input: {
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
}
|
||||
@@ -60,6 +60,8 @@ function threadDetailToShell(
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
snoozedUntil: thread.snoozedUntil ?? null,
|
||||
snoozedAt: thread.snoozedAt ?? null,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: latestUserMessageAt(thread),
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -8,9 +8,13 @@ import * as ServerConfig from "../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as PairingGrantStore from "./PairingGrantStore.ts";
|
||||
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
|
||||
import { resolveSessionCookieName } from "./utils.ts";
|
||||
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
/** Pinned so dev-mode cookie tests can assert the port-scoped name. */
|
||||
const TEST_SERVER_PORT = 13_773;
|
||||
|
||||
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
|
||||
Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
@@ -19,6 +23,12 @@ 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-" })));
|
||||
@@ -35,7 +45,11 @@ const makeCookieRequest = (
|
||||
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
t3_session: sessionToken,
|
||||
// Derived, not hardcoded: the name is port-scoped so concurrent servers
|
||||
// on one hostname don't share a cookie. Mode and devUrl mirror
|
||||
// ServerConfig.layerTest, so this resolves to whatever the server reads.
|
||||
[resolveSessionCookieName({ mode: "web", port: TEST_SERVER_PORT, devUrl: undefined })]:
|
||||
sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<
|
||||
|
||||
@@ -438,6 +438,7 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput,
|
||||
@@ -746,11 +747,13 @@ export const make = Effect.gen(function* () {
|
||||
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) =>
|
||||
createPairingLink({
|
||||
scopes: input.scopes,
|
||||
subject: input.subject,
|
||||
...(input.label ? { label: input.label } : {}),
|
||||
...(input.purpose ? { purpose: input.purpose } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
@@ -774,6 +777,7 @@ export const make = Effect.gen(function* () {
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
...(input?.purpose ? { purpose: input.purpose } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
@@ -872,6 +876,7 @@ export const make = Effect.gen(function* () {
|
||||
issuePairingCredentialForSubject({
|
||||
scopes: AuthAdministrativeScopes,
|
||||
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
|
||||
purpose: "startup",
|
||||
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
|
||||
|
||||
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
|
||||
|
||||
@@ -34,6 +34,9 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
// Packaged desktop has no devUrl, but still needs the port scope: it
|
||||
// scans upward from 3773 for a free port and binds 127.0.0.1, so a second
|
||||
// instance shares this one's hostname on a different port.
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
@@ -45,6 +48,22 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps desktop cookies port-scoped on the port a second instance lands on", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3774");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3774,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
@@ -75,6 +94,24 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
port: 13773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("scopes web session cookies by port only in development", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
port: 13773,
|
||||
devUrl: new URL("http://127.0.0.1:5733"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -41,6 +41,7 @@ export const make = Effect.gen(function* () {
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
devUrl: config.devUrl,
|
||||
}),
|
||||
};
|
||||
|
||||
|
||||
@@ -202,6 +202,11 @@ export class PairingGrantStore extends Context.Service<
|
||||
readonly subject?: string;
|
||||
readonly label?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
/**
|
||||
* "startup" marks the credential the server mints for itself at boot,
|
||||
* which gets the long dev TTL when a dev URL is configured.
|
||||
*/
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthPairingLink>,
|
||||
@@ -243,6 +248,15 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
||||
// window can still recover by re-bootstrapping rather than locking
|
||||
// the user out of the backend.
|
||||
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
|
||||
// A dev server's startup token is read off a log by whoever (or whatever) is
|
||||
// driving the session, often minutes later — after a `node --watch` restart, a
|
||||
// detour into another task, or a hand-off to the person actually doing the
|
||||
// testing. Five minutes turns that into a restart-the-server loop for no
|
||||
// security benefit: the token only unlocks a local dev backend, and its holder
|
||||
// could read the log anyway. Same reasoning (and duration) as the desktop
|
||||
// bootstrap grant above. Only applies when a dev URL is configured; user-issued
|
||||
// pairing links and real servers keep the 5-minute default.
|
||||
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
|
||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
const PAIRING_TOKEN_LENGTH = 12;
|
||||
const PAIRING_TOKEN_REJECTION_LIMIT =
|
||||
@@ -371,7 +385,10 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const credential = yield* generatePairingToken;
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
|
||||
const ttl =
|
||||
input?.ttl ??
|
||||
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
|
||||
@@ -470,6 +470,7 @@ export const make = Effect.gen(function* () {
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
devUrl: serverConfig.devUrl,
|
||||
});
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
|
||||
@@ -10,15 +10,29 @@ import * as Result from "effect/Result";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
/**
|
||||
* Cookies are scoped by host but *not* by port, so any two servers that can be
|
||||
* live on one hostname at once need separate names — otherwise the second
|
||||
* clobbers the first's session and both sides see "Invalid session token
|
||||
* signature" until someone clears cookies by hand.
|
||||
*
|
||||
* Two populations qualify, for the same reason but from different causes:
|
||||
*
|
||||
* - **Dev servers** (`devUrl` set), which run several at a time across worktrees.
|
||||
* - **Desktop**, which scans upward from 3773 for a free port and binds
|
||||
* 127.0.0.1, so a second instance lands on a different port and the same host.
|
||||
*
|
||||
* Hosted deployments keep the stable production name: their public port can
|
||||
* change between releases, and scoping it would log every user out.
|
||||
*/
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
readonly devUrl: URL | undefined;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
return input.devUrl === undefined && input.mode !== "desktop"
|
||||
? SESSION_COOKIE_NAME
|
||||
: `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
|
||||
@@ -84,6 +84,7 @@ const makeCliTestServerConfig = (baseDir: string) =>
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -48,6 +48,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
devAllowedOrigins: [],
|
||||
} as const;
|
||||
|
||||
const openBootstrapFd = Effect.fn(function* (payload: DesktopBackendBootstrapValue) {
|
||||
@@ -95,6 +96,8 @@ 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",
|
||||
@@ -117,6 +120,7 @@ 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,6 +106,15 @@ 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),
|
||||
@@ -363,6 +372,7 @@ export const resolveServerConfig = (
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
devAllowedOrigins: env.devAllowedOrigins,
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
|
||||
@@ -72,6 +72,7 @@ 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;
|
||||
@@ -187,6 +188,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
});
|
||||
|
||||
@@ -43,6 +43,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
|
||||
@@ -141,6 +141,7 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
+14
-1
@@ -4,6 +4,7 @@ import {
|
||||
AuthOrchestrationReadScope,
|
||||
EnvironmentHttpApi,
|
||||
} from "@t3tools/contracts";
|
||||
import { isDevProxiedPath } from "@t3tools/shared/devProxy";
|
||||
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -48,9 +49,17 @@ export const browserApiCorsLayer = Layer.unwrap(
|
||||
const devOrigin = config.devUrl?.origin;
|
||||
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
|
||||
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
|
||||
//
|
||||
// T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
|
||||
// origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
|
||||
// through Vite and is same-origin (no preflight at all), so this is a
|
||||
// safety net for the desktop renderer and any direct-to-backend caller.
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
? {
|
||||
allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
|
||||
credentials: true,
|
||||
}
|
||||
: {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
@@ -216,6 +225,10 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
|
||||
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
|
||||
status: 302,
|
||||
|
||||
@@ -609,6 +609,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -679,6 +681,38 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.snoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: event.payload.snoozedUntil,
|
||||
snoozedAt: event.payload.snoozedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unsnoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -310,6 +310,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -422,6 +424,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
|
||||
@@ -336,6 +336,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -366,6 +368,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -398,6 +402,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -762,6 +768,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -1196,6 +1204,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1396,6 +1406,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1527,6 +1539,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1663,6 +1677,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1905,6 +1921,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
@@ -2001,6 +2019,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
|
||||
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -38,6 +40,8 @@ export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSet
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
|
||||
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
// The decider's clock is the Effect test clock, pinned to the epoch, so
|
||||
// "future" wake times are relative to 1970-01-01T00:00:00.000Z.
|
||||
const FUTURE_WAKE = "1970-01-02T09:00:00.000Z";
|
||||
const PAST_WAKE = "1969-12-31T09:00:00.000Z";
|
||||
const SNOOZED_AT = "1969-12-30T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(input: {
|
||||
readonly snoozedUntil?: string | null;
|
||||
readonly snoozedAt?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
readonly activities?: OrchestrationThread["activities"];
|
||||
readonly messages?: OrchestrationThread["messages"];
|
||||
}): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: input.archivedAt ?? null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: input.snoozedUntil ?? null,
|
||||
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
|
||||
deletedAt: null,
|
||||
messages: input.messages ?? [],
|
||||
proposedPlans: [],
|
||||
activities: input.activities ?? [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("snoozed thread decider", (it) => {
|
||||
it.effect("snoozes a thread to a future wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.snoozed");
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe(FUTURE_WAKE);
|
||||
expect(events[0].payload.snoozedAt).toBe(events[0].payload.updatedAt);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a wake time that is not in the future", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-past"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: PAST_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects an unparseable wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
// IsoDateTime is structurally a string, so garbage can reach the
|
||||
// decider; a NaN wake time must never persist as snooze state.
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-garbage"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "not-a-date",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing blocked-on-you work", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestActivity = {
|
||||
id: EventId.make("activity-req-1"),
|
||||
tone: "approval" as const,
|
||||
kind: "approval.requested",
|
||||
summary: "approval.requested",
|
||||
payload: { requestId: "req-1" },
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
} as OrchestrationThread["activities"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-blocked"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ activities: [requestActivity] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-emits idempotently for a duplicate snooze to the same wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const reEmit = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(reEmit) ? reEmit : [reEmit];
|
||||
expect(events).toHaveLength(1);
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
// Original snoozedAt preserved; updatedAt must not churn.
|
||||
expect(events[0].payload.snoozedAt).toBe(SNOOZED_AT);
|
||||
expect(events[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-snoozing to a DIFFERENT wake time stamps fresh", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-extend"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "1970-01-03T09:00:00.000Z",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe("1970-01-03T09:00:00.000Z");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unsnoozes with reason user and re-emits idempotently when awake", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events[0]?.type).toBe("thread.unsnoozed");
|
||||
if (events[0]?.type === "thread.unsnoozed") {
|
||||
expect(events[0].payload.reason).toBe("user");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
|
||||
const awake = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze-awake"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const awakeEvents = Array.isArray(awake) ? awake : [awake];
|
||||
expect(awakeEvents[0]?.type).toBe("thread.unsnoozed");
|
||||
if (awakeEvents[0]?.type === "thread.unsnoozed") {
|
||||
// No state change — keep the existing updatedAt.
|
||||
expect(awakeEvents[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing a thread with a queued turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
// The decider clock is the Effect test clock pinned to the epoch: a
|
||||
// user message 30s before it with no adopting turn is queued work.
|
||||
const queuedMessage = {
|
||||
id: MessageId.make("message-queued"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "1969-12-31T23:59:30.000Z",
|
||||
updatedAt: "1969-12-31T23:59:30.000Z",
|
||||
} as OrchestrationThread["messages"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-queued"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ messages: [queuedMessage] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing an archived thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ archivedAt: NOW }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("a user message spends the snooze return ticket (activity wake)", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-1"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
|
||||
expect(unsnoozed).toBeDefined();
|
||||
if (unsnoozed?.type === "thread.unsnoozed") {
|
||||
expect(unsnoozed.payload.reason).toBe("activity");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -53,6 +53,13 @@ function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): b
|
||||
);
|
||||
}
|
||||
|
||||
// Scans the read model's activities, which the projector caps at the most
|
||||
// recent 500. That bound is safe here: an OPEN approval/user-input request
|
||||
// blocks its turn, so the thread cannot accumulate hundreds of later
|
||||
// activities while one is outstanding — a request that has scrolled out of
|
||||
// the window is one whose turn kept running, i.e. it was resolved or went
|
||||
// stale. (The projection pipeline's pendingApprovalCount reads the same
|
||||
// capped stream and stays consistent with this view.)
|
||||
function hasOpenBlockingRequest(thread: {
|
||||
readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
|
||||
}): boolean {
|
||||
@@ -79,6 +86,62 @@ function hasOpenBlockingRequest(thread: {
|
||||
return openRequestIds.size > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A queued turn start — a user message no turn has picked up yet — is work
|
||||
* in flight even though session is still null (turn.start emits
|
||||
* message-sent + turn-start-requested; the session arrives later). Detection
|
||||
* mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
* strictly newer than every latestTurn timestamp (adoption stamps the new
|
||||
* turn's requestedAt with the message time, clearing this), and only within
|
||||
* the adoption grace window — historical threads whose last user message
|
||||
* postdates their turn timestamps (older-server data, mid-turn messages)
|
||||
* must not be blocked forever. A failed session start (status "error")
|
||||
* clears the block immediately.
|
||||
*
|
||||
* The age check is bounded on BOTH sides: message timestamps are
|
||||
* client-supplied, so a client clock ahead of the server yields a negative
|
||||
* age. Without the lower bound that negative age satisfies `<= grace` for
|
||||
* as long as the skew lasts, extending the block far past the intended two
|
||||
* minutes.
|
||||
*/
|
||||
function threadHasQueuedTurnStart(
|
||||
thread: {
|
||||
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
|
||||
readonly latestTurn: {
|
||||
readonly requestedAt: string;
|
||||
readonly startedAt: string | null;
|
||||
readonly completedAt: string | null;
|
||||
} | null;
|
||||
readonly session: { readonly status: string } | null;
|
||||
},
|
||||
occurredAt: string,
|
||||
): boolean {
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
return (
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS
|
||||
);
|
||||
}
|
||||
|
||||
function withEventBase(
|
||||
input: Pick<OrchestrationCommand, "commandId"> & {
|
||||
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
|
||||
@@ -411,46 +474,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
);
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
// A queued turn start — a user message no turn has picked up yet — is
|
||||
// work in flight even though session is still null (turn.start emits
|
||||
// message-sent + turn-start-requested; the session arrives later).
|
||||
// Settling in that window would hide just-requested work. Detection
|
||||
// mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
// strictly newer than every latestTurn timestamp (adoption stamps the
|
||||
// new turn's requestedAt with the message time, clearing this), and
|
||||
// only within the adoption grace window — historical threads whose
|
||||
// last user message postdates their turn timestamps (older-server
|
||||
// data, mid-turn messages) must stay settleable. A failed session
|
||||
// start (status "error") clears the block immediately.
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
// The age check is bounded on BOTH sides: message timestamps are
|
||||
// client-supplied, so a client clock ahead of the server yields a
|
||||
// negative age. Without the lower bound that negative age satisfies
|
||||
// `<= grace` for as long as the skew lasts, extending the settle
|
||||
// block far past the intended two minutes.
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
const hasQueuedTurnStart =
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS;
|
||||
if (hasQueuedTurnStart) {
|
||||
// Settling inside the adoption window would hide just-requested work.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
@@ -508,6 +533,103 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.snooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
// A wake time in the past would create a thread that is snoozed and
|
||||
// woken at once — the row would never leave the inbox but still carry
|
||||
// snooze state. Reject instead of silently normalizing. The negated
|
||||
// comparison also catches unparseable wake times (IsoDateTime is
|
||||
// structurally just a string): NaN fails every comparison, and an
|
||||
// unparseable snoozedUntil must never persist.
|
||||
if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Blocked-on-you work must not be snoozed away: a pending approval or
|
||||
// user-input request is the agent waiting on the user, and hiding it
|
||||
// defeats the request. (A running session IS snoozable — snooze only
|
||||
// affects visibility, never the agent.)
|
||||
if (hasOpenBlockingRequest(thread)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// A queued turn start — a user message no turn has adopted yet — is
|
||||
// invisible pending work: no session, no pending flags. Snoozing in
|
||||
// that window would hide a just-requested turn exactly the way settle
|
||||
// would.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Re-snoozing an already-snoozed thread to the SAME wake time is a
|
||||
// duplicate (double-click, raced clients): re-emit with the original
|
||||
// timestamps so the projection is a no-op. A different wake time is a
|
||||
// real change and stamps fresh.
|
||||
const existingSnoozedAt =
|
||||
thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
|
||||
? thread.snoozedAt
|
||||
: null;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.snoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
snoozedUntil: command.snoozedUntil,
|
||||
snoozedAt: existingSnoozedAt ?? occurredAt,
|
||||
updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unsnooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Idempotent by re-emission (see thread.settle): waking a thread that
|
||||
// is not snoozed lands on the same null state without churning
|
||||
// updatedAt.
|
||||
const alreadyAwake = thread.snoozedUntil == null;
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: command.reason,
|
||||
updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
@@ -663,24 +785,42 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
// Real activity resets ANY override: it wakes an explicitly settled
|
||||
// thread, and it clears a keep-active pin back to neutral so the
|
||||
// thread can auto-settle again after this burst of work goes stale.
|
||||
if (targetThread.settledOverride === null) {
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
// A snooze clears the same way — sending a message to a snoozed
|
||||
// thread is the user re-engaging, so the return ticket is spent.
|
||||
const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
if (targetThread.settledOverride !== null) {
|
||||
lifecycleResetEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
|
||||
if (targetThread.snoozedUntil != null) {
|
||||
lifecycleResetEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
|
||||
case "thread.turn.interrupt": {
|
||||
@@ -822,7 +962,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
// Only a session coming alive is activity worth waking a settled thread
|
||||
// for — status writes like ready/stopped/error arrive after the fact and
|
||||
// must not fight a user's explicit settle.
|
||||
// must not fight a user's explicit settle. Snooze is deliberately NOT
|
||||
// cleared here: snooze never pauses the agent, so its session starting
|
||||
// or erroring is not the user re-engaging. Blocked/failed work still
|
||||
// surfaces immediately — effectiveSnoozed refuses to classify a thread
|
||||
// with a raised hand (approval / input / failure / fresh completion)
|
||||
// as snoozed, without spending the return ticket.
|
||||
const isSessionActivity =
|
||||
command.session.status === "starting" || command.session.status === "running";
|
||||
// Real activity resets ANY override (settled wakes, active unpins).
|
||||
|
||||
@@ -91,6 +91,8 @@ describe("orchestration projector", () => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -23,8 +23,10 @@ import {
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadSnoozedPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadUnsnoozedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -290,6 +292,8 @@ export function projectEvent(
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -365,6 +369,30 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.snoozed":
|
||||
return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: payload.snoozedUntil,
|
||||
snoozedAt: payload.snoozedAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unsnoozed":
|
||||
return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
@@ -93,6 +93,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -153,6 +155,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-03-25T00:00:00.000Z",
|
||||
snoozedUntil: "2026-03-26T09:00:00.000Z",
|
||||
snoozedAt: "2026-03-25T00:00:00.000Z",
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -169,12 +173,17 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
}
|
||||
assert.strictEqual(row.settledOverride, "settled");
|
||||
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
|
||||
|
||||
// Un-settle to the keep-active pin and confirm the flip persists.
|
||||
// Un-settle to the keep-active pin and wake the snooze; confirm the
|
||||
// flips persist.
|
||||
yield* threads.upsert({
|
||||
...row,
|
||||
settledOverride: "active",
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
});
|
||||
const repersisted = yield* threads.getById({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
@@ -182,6 +191,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
const updated = Option.getOrNull(repersisted);
|
||||
assert.strictEqual(updated?.settledOverride, "active");
|
||||
assert.strictEqual(updated?.settledAt, null);
|
||||
assert.strictEqual(updated?.snoozedUntil, null);
|
||||
assert.strictEqual(updated?.snoozedAt, null);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -45,6 +45,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
snoozed_until,
|
||||
snoozed_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
@@ -66,6 +68,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.archivedAt},
|
||||
${row.settledOverride},
|
||||
${row.settledAt},
|
||||
${row.snoozedUntil},
|
||||
${row.snoozedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -87,6 +91,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at = excluded.archived_at,
|
||||
settled_override = excluded.settled_override,
|
||||
settled_at = excluded.settled_at,
|
||||
snoozed_until = excluded.snoozed_until,
|
||||
snoozed_at = excluded.snoozed_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
@@ -115,6 +121,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -145,6 +153,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
|
||||
@@ -46,6 +46,7 @@ import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.
|
||||
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
|
||||
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
|
||||
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
|
||||
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -91,6 +92,7 @@ export const migrationEntries = [
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (!columns.some((column) => column.name === "snoozed_until")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_until TEXT
|
||||
`;
|
||||
}
|
||||
|
||||
if (!columns.some((column) => column.name === "snoozed_at")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_at TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -38,6 +38,8 @@ export const ProjectionThread = Schema.Struct({
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
|
||||
settledAt: Schema.NullOr(IsoDateTime),
|
||||
snoozedUntil: Schema.NullOr(IsoDateTime),
|
||||
snoozedAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
|
||||
@@ -530,6 +530,29 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("preserves xhigh effort for Claude Opus 5", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
"claude-opus-5",
|
||||
[{ id: "effort", value: "xhigh" }],
|
||||
),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, "xhigh");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -51,6 +51,7 @@ const CLAUDE_PRESENTATION = {
|
||||
displayName: "Claude",
|
||||
showInteractionModeToggle: true,
|
||||
} as const;
|
||||
const MINIMUM_CLAUDE_OPUS_5_VERSION = "2.1.219";
|
||||
const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
|
||||
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
|
||||
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
|
||||
@@ -87,6 +88,42 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-5",
|
||||
name: "Claude Opus 5",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultracode", label: "Ultracode" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
// Claude Code selects the 1M variant explicitly (`claude-opus-5[1m]`).
|
||||
options: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-8",
|
||||
name: "Claude Opus 4.8",
|
||||
@@ -272,6 +309,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
},
|
||||
];
|
||||
|
||||
function supportsClaudeOpus5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;
|
||||
}
|
||||
|
||||
function supportsClaudeFable5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
|
||||
}
|
||||
@@ -288,6 +329,9 @@ function getBuiltInClaudeModelsForVersion(
|
||||
version: string | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
return BUILT_IN_MODELS.filter((model) => {
|
||||
if (model.slug === "claude-opus-5") {
|
||||
return supportsClaudeOpus5(version);
|
||||
}
|
||||
if (model.slug === "claude-fable-5") {
|
||||
return supportsClaudeFable5(version);
|
||||
}
|
||||
@@ -301,6 +345,11 @@ function getBuiltInClaudeModelsForVersion(
|
||||
});
|
||||
}
|
||||
|
||||
function formatClaudeOpus5UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Opus 5. Upgrade to v${MINIMUM_CLAUDE_OPUS_5_VERSION} or newer to access it.`;
|
||||
}
|
||||
|
||||
function formatClaudeFable5UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;
|
||||
@@ -360,6 +409,7 @@ export function normalizeClaudeCliEffort(
|
||||
if (
|
||||
effort === "xhigh" &&
|
||||
model !== "claude-fable-5" &&
|
||||
model !== "claude-opus-5" &&
|
||||
model !== "claude-opus-4-8" &&
|
||||
model !== "claude-sonnet-5"
|
||||
) {
|
||||
@@ -837,13 +887,15 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const versionUpgradeMessage = supportsClaudeFable5(parsedVersion)
|
||||
const versionUpgradeMessage = supportsClaudeOpus5(parsedVersion)
|
||||
? undefined
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
: supportsClaudeFable5(parsedVersion)
|
||||
? formatClaudeOpus5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
|
||||
const capabilities = resolveCapabilities
|
||||
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
|
||||
|
||||
@@ -1842,6 +1842,62 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes Claude Opus 5 on supported Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
const opus5 = status.models.find((model) => model.slug === "claude-opus-5");
|
||||
assert.strictEqual(opus5?.name, "Claude Opus 5");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.219\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides Claude Opus 5 on older Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.models.some((model) => model.slug === "claude-opus-5"),
|
||||
false,
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Code v2.1.218 is too old for Claude Opus 5. Upgrade to v2.1.219 or newer to access it.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.218\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes Claude Fable 5 on supported Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
|
||||
@@ -380,6 +380,7 @@ const buildAppUnderTest = (options?: {
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: defaultDesktopBootstrapToken,
|
||||
@@ -1328,6 +1329,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
"bearer-access-token",
|
||||
"dpop-access-token",
|
||||
]);
|
||||
// Desktop, so port-scoped: instances scan for a free port and share
|
||||
// 127.0.0.1, and cookies are not scoped by port.
|
||||
assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
@@ -3246,6 +3249,34 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("allows configured development origins through ServerConfig", () =>
|
||||
Effect.gen(function* () {
|
||||
const tailnetOrigin = "https://host.example.ts.net";
|
||||
yield* buildAppUnderTest({
|
||||
config: {
|
||||
devUrl: new URL(crossOriginClientOrigin),
|
||||
devAllowedOrigins: [tailnetOrigin],
|
||||
},
|
||||
});
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const response = yield* fetchEffect(sessionUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: tailnetOrigin,
|
||||
"access-control-request-method": "GET",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assertBrowserApiCorsPreflightHeaders(response.headers, {
|
||||
origin: tailnetOrigin,
|
||||
credentials: true,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
|
||||
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
<meta name="theme-color" content="#161616" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<script>
|
||||
performance.mark("navigation.start");
|
||||
</script>
|
||||
<script>
|
||||
(() => {
|
||||
const LIGHT_BACKGROUND = "#ffffff";
|
||||
|
||||
@@ -2,23 +2,20 @@ import { Children, isValidElement, type ReactElement, type ReactNode } from "rea
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
import { AppRoot } from "./AppRoot";
|
||||
|
||||
describe("AppRoot", () => {
|
||||
it("shares the application atom registry with routed UI and renderer-wide desktop hosts", () => {
|
||||
it("shares the application atom registry with routed UI and lazy runtime hosts", () => {
|
||||
const root = AppRoot({ router: {} as AppRouter });
|
||||
|
||||
expect(root.type).toBe(AppAtomRegistryProvider);
|
||||
const children = Children.toArray(
|
||||
(root as ReactElement<{ readonly children: ReactNode }>).props.children,
|
||||
);
|
||||
expect(children).toHaveLength(3);
|
||||
expect(children).toHaveLength(2);
|
||||
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
|
||||
expect(isValidElement(children[1]) && children[1].type).toBe(PreviewAutomationHosts);
|
||||
expect(isValidElement(children[2]) && children[2].type).toBe(ElectronBrowserHost);
|
||||
expect(isValidElement(children[1])).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,34 @@
|
||||
import { lazy, Suspense } from "react";
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
|
||||
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
|
||||
import { isElectron } from "./env";
|
||||
import { STARTUP_OPTIONAL_UI_DELAY_MS, useAfterFirstPaint } from "./hooks/useAfterFirstPaint";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
|
||||
const PreviewAutomationHosts = lazy(() =>
|
||||
import("./components/preview/PreviewAutomationHosts").then((module) => ({
|
||||
default: module.PreviewAutomationHosts,
|
||||
})),
|
||||
);
|
||||
const ElectronBrowserHost = lazy(() =>
|
||||
import("./browser/ElectronBrowserHost").then((module) => ({
|
||||
default: module.ElectronBrowserHost,
|
||||
})),
|
||||
);
|
||||
|
||||
function DeferredRuntimeHosts() {
|
||||
const ready = useAfterFirstPaint(STARTUP_OPTIONAL_UI_DELAY_MS);
|
||||
if (!ready) return null;
|
||||
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<PreviewAutomationHosts />
|
||||
{isElectron ? <ElectronBrowserHost /> : null}
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns renderer-wide providers. The Electron browser host intentionally sits
|
||||
* outside the router so its webviews survive route transitions, but it must
|
||||
@@ -14,8 +38,7 @@ export function AppRoot({ router }: { readonly router: AppRouter }) {
|
||||
return (
|
||||
<AppAtomRegistryProvider>
|
||||
<RouterProvider router={router} />
|
||||
<PreviewAutomationHosts />
|
||||
<ElectronBrowserHost />
|
||||
<DeferredRuntimeHosts />
|
||||
</AppAtomRegistryProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ClerkProvider } from "@clerk/react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { ManagedRelayAuthProvider } from "./managedAuth";
|
||||
|
||||
export default function CloudAuthRoot({
|
||||
children,
|
||||
publishableKey,
|
||||
}: {
|
||||
readonly children: ReactNode;
|
||||
readonly publishableKey: string;
|
||||
}) {
|
||||
return (
|
||||
<ClerkProvider publishableKey={publishableKey}>
|
||||
<ManagedRelayAuthProvider>{children}</ManagedRelayAuthProvider>
|
||||
</ClerkProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { passkeys } from "@clerk/electron/passkeys";
|
||||
import { ClerkProvider } from "@clerk/electron/react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { ManagedRelayAuthProvider } from "./managedAuth";
|
||||
|
||||
export default function ElectronCloudAuthRoot({
|
||||
children,
|
||||
publishableKey,
|
||||
}: {
|
||||
readonly children: ReactNode;
|
||||
readonly publishableKey: string;
|
||||
}) {
|
||||
return (
|
||||
<ClerkProvider publishableKey={publishableKey} passkeys={passkeys}>
|
||||
<ManagedRelayAuthProvider>{children}</ManagedRelayAuthProvider>
|
||||
</ClerkProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { ConnectOnboardingDialog } from "./cloud/ConnectOnboardingDialog";
|
||||
import { RelayClientInstallDialog } from "./cloud/RelayClientInstallDialog";
|
||||
import { SshPasswordPromptDialog } from "./desktop/SshPasswordPromptDialog";
|
||||
import { SlowRpcRequestToastCoordinator } from "./SlowRpcRequestToastCoordinator";
|
||||
|
||||
export default function AppOverlays() {
|
||||
return (
|
||||
<>
|
||||
<RelayClientInstallDialog />
|
||||
<ConnectOnboardingDialog />
|
||||
<SshPasswordPromptDialog />
|
||||
<SlowRpcRequestToastCoordinator />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { lazy, Suspense, useEffect, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { useAfterFirstPaint } from "../hooks/useAfterFirstPaint";
|
||||
import { getLocalStorageItem } from "../hooks/useLocalStorage";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import { cn, isMacPlatform } from "../lib/utils";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import ThreadSidebarV2 from "./SidebarV2";
|
||||
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
|
||||
import {
|
||||
resolveInitialThreadSidebarWidth,
|
||||
@@ -30,6 +29,8 @@ import {
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px";
|
||||
const ThreadSidebar = lazy(() => import("./Sidebar"));
|
||||
const ThreadSidebarV2 = lazy(() => import("./SidebarV2"));
|
||||
|
||||
function readInitialThreadSidebarWidth(): number {
|
||||
try {
|
||||
@@ -100,6 +101,7 @@ function SidebarControl() {
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const loadSidebarContent = useAfterFirstPaint();
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
// Settings routes render the settings nav, which lives in the v1 component
|
||||
// and is identical for both sidebars — so v1 stays mounted there.
|
||||
@@ -178,7 +180,11 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
onResize: setSidebarWidth,
|
||||
}}
|
||||
>
|
||||
{useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
|
||||
{loadSidebarContent ? (
|
||||
<Suspense fallback={null}>
|
||||
{useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
|
||||
</Suspense>
|
||||
) : null}
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
{children}
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
@@ -140,6 +140,7 @@ import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import {
|
||||
AlarmClockIcon,
|
||||
CheckCircle2Icon,
|
||||
ChevronDownIcon,
|
||||
GitBranchIcon,
|
||||
@@ -3844,7 +3845,24 @@ 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, {
|
||||
@@ -3890,6 +3908,34 @@ 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
|
||||
@@ -3999,29 +4045,48 @@ 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 settled banner last — it must never cover another.
|
||||
const settledComposerBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
|
||||
if (!activeThreadSettled) {
|
||||
// and the informational parked-thread banner last — it must never cover another.
|
||||
const parkedThreadBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
|
||||
if (!activeThreadSnoozed && !activeThreadSettled) {
|
||||
return null;
|
||||
}
|
||||
const isSnoozed = activeThreadSnoozed;
|
||||
return {
|
||||
id: `thread-settled:${activeThread?.id ?? "unknown"}`,
|
||||
id: `thread-${isSnoozed ? "snoozed" : "settled"}:${activeThread?.id ?? "unknown"}`,
|
||||
variant: "info",
|
||||
icon: <CheckCircle2Icon />,
|
||||
title: "This thread is settled",
|
||||
description: "Sending a message moves it back to Active in the sidebar.",
|
||||
icon: isSnoozed ? <AlarmClockIcon /> : <CheckCircle2Icon />,
|
||||
title: `This thread is ${isSnoozed ? "snoozed" : "settled"}`,
|
||||
description: isSnoozed
|
||||
? "Sending a message wakes it and moves it back to Active in the sidebar."
|
||||
: "Sending a message moves it back to Active in the sidebar.",
|
||||
actions: (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isUnsettling}
|
||||
onClick={() => void handleUnsettleActiveThread()}
|
||||
disabled={isSnoozed ? isUnsnoozing : isUnsettling}
|
||||
onClick={() =>
|
||||
void (isSnoozed ? handleUnsnoozeActiveThread() : handleUnsettleActiveThread())
|
||||
}
|
||||
>
|
||||
{isUnsettling ? "Un-settling..." : "Un-settle"}
|
||||
{isSnoozed
|
||||
? isUnsnoozing
|
||||
? "Waking..."
|
||||
: "Wake now"
|
||||
: isUnsettling
|
||||
? "Un-settling..."
|
||||
: "Un-settle"}
|
||||
</Button>
|
||||
),
|
||||
};
|
||||
}, [activeThread?.id, activeThreadSettled, handleUnsettleActiveThread, isUnsettling]);
|
||||
}, [
|
||||
activeThread?.id,
|
||||
activeThreadSettled,
|
||||
activeThreadSnoozed,
|
||||
handleUnsnoozeActiveThread,
|
||||
handleUnsettleActiveThread,
|
||||
isUnsnoozing,
|
||||
isUnsettling,
|
||||
]);
|
||||
const handleRestoreThreadBranch = useCallback(() => {
|
||||
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
|
||||
setBranchRestoreConfirmOpen(true);
|
||||
@@ -4030,9 +4095,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
void handleSwitchCheckoutToThread();
|
||||
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const settledItems = settledComposerBannerItem === null ? [] : [settledComposerBannerItem];
|
||||
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
|
||||
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
|
||||
return [...systemComposerBannerItems, ...settledItems];
|
||||
return [...systemComposerBannerItems, ...parkedThreadItems];
|
||||
}
|
||||
return [
|
||||
...systemComposerBannerItems,
|
||||
@@ -4075,14 +4140,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setBranchMismatchDismissTick((tick) => tick + 1);
|
||||
},
|
||||
},
|
||||
...settledItems,
|
||||
...parkedThreadItems,
|
||||
];
|
||||
}, [
|
||||
activeBranchMismatchKey,
|
||||
handleRestoreThreadBranch,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
settledComposerBannerItem,
|
||||
parkedThreadBannerItem,
|
||||
showBranchMismatchBanner,
|
||||
systemComposerBannerItems,
|
||||
]);
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
type SourceControlRepositoryInfo,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import * as Option from "effect/Option";
|
||||
import {
|
||||
ArrowDownIcon,
|
||||
@@ -33,11 +33,8 @@ import {
|
||||
import {
|
||||
useCallback,
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
@@ -74,12 +71,9 @@ import {
|
||||
isUnsupportedWindowsProjectPath,
|
||||
resolveProjectPathForDispatch,
|
||||
} from "../lib/projectPaths";
|
||||
import { onOpenCommandPalette } from "../commandPaletteBus";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";
|
||||
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import { buildThreadRouteParams } from "../threadRoutes";
|
||||
import {
|
||||
applyWslEnvironmentConfiguration,
|
||||
parseWslUncPath,
|
||||
@@ -124,8 +118,7 @@ import { Button } from "./ui/button";
|
||||
import { Kbd, KbdGroup } from "./ui/kbd";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
import { useComposerHandleContext } from "../composerHandleContext";
|
||||
import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";
|
||||
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
@@ -343,127 +336,15 @@ interface CommandPaletteOpenIntent {
|
||||
readonly kind: "add-project" | "new-thread-in";
|
||||
}
|
||||
|
||||
interface CommandPaletteUiState {
|
||||
readonly open: boolean;
|
||||
readonly openIntent: CommandPaletteOpenIntent | null;
|
||||
}
|
||||
|
||||
type CommandPaletteUiAction =
|
||||
| { readonly _tag: "SetOpen"; readonly open: boolean }
|
||||
| { readonly _tag: "Toggle" }
|
||||
| { readonly _tag: "OpenAddProject" }
|
||||
| { readonly _tag: "OpenNewThreadIn" }
|
||||
| { readonly _tag: "ClearOpenIntent" };
|
||||
|
||||
function reduceCommandPaletteUiState(
|
||||
state: CommandPaletteUiState,
|
||||
action: CommandPaletteUiAction,
|
||||
): CommandPaletteUiState {
|
||||
switch (action._tag) {
|
||||
case "SetOpen":
|
||||
return {
|
||||
open: action.open,
|
||||
openIntent: action.open ? state.openIntent : null,
|
||||
};
|
||||
case "Toggle":
|
||||
return { open: !state.open, openIntent: null };
|
||||
case "OpenAddProject":
|
||||
return { open: true, openIntent: { kind: "add-project" } };
|
||||
case "OpenNewThreadIn":
|
||||
return { open: true, openIntent: { kind: "new-thread-in" } };
|
||||
case "ClearOpenIntent":
|
||||
return state.openIntent ? { ...state, openIntent: null } : state;
|
||||
}
|
||||
}
|
||||
|
||||
export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reduceCommandPaletteUiState, {
|
||||
open: false,
|
||||
openIntent: null,
|
||||
});
|
||||
const setOpen = useCallback((open: boolean) => dispatch({ _tag: "SetOpen", open }), []);
|
||||
const toggleOpen = useCallback(() => dispatch({ _tag: "Toggle" }), []);
|
||||
const openAddProject = useCallback(() => dispatch({ _tag: "OpenAddProject" }), []);
|
||||
const openNewThreadIn = useCallback(() => dispatch({ _tag: "OpenNewThreadIn" }), []);
|
||||
const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
|
||||
const routeTarget = useParams({
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
|
||||
const terminalOpen = useTerminalUiStateStore((state) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
|
||||
: false,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
context: {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen,
|
||||
},
|
||||
});
|
||||
if (command !== "commandPalette.toggle") {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleOpen();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
onOpenCommandPalette((detail) => {
|
||||
if (detail.open === "new-thread-in") {
|
||||
openNewThreadIn();
|
||||
} else if (detail.open === "add-project") {
|
||||
openAddProject();
|
||||
} else {
|
||||
setOpen(true);
|
||||
}
|
||||
}),
|
||||
[openAddProject, openNewThreadIn, setOpen],
|
||||
);
|
||||
|
||||
return (
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
<CommandDialog open={state.open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CommandPaletteDialog
|
||||
open={state.open}
|
||||
openIntent={state.openIntent}
|
||||
setOpen={setOpen}
|
||||
clearOpenIntent={clearOpenIntent}
|
||||
/>
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandPaletteDialog(props: {
|
||||
readonly open: boolean;
|
||||
export function CommandPaletteDialog(props: {
|
||||
readonly openIntent: CommandPaletteOpenIntent | null;
|
||||
readonly setOpen: (open: boolean) => void;
|
||||
readonly clearOpenIntent: () => void;
|
||||
}) {
|
||||
if (!props.open) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<OpenCommandPaletteDialog
|
||||
openIntent={props.openIntent}
|
||||
setOpen={props.setOpen}
|
||||
clearOpenIntent={props.clearOpenIntent}
|
||||
/>
|
||||
<CommandDialog open onOpenChange={props.setOpen}>
|
||||
<OpenCommandPaletteDialog {...props} />
|
||||
</CommandDialog>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
import { onOpenCommandPalette } from "../commandPaletteBus";
|
||||
import { ComposerHandleContext } from "../composerHandleContext";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
|
||||
const CommandPaletteDialog = lazy(() =>
|
||||
import("./CommandPalette").then((module) => ({
|
||||
default: module.CommandPaletteDialog,
|
||||
})),
|
||||
);
|
||||
|
||||
interface CommandPaletteOpenIntent {
|
||||
readonly kind: "add-project" | "new-thread-in";
|
||||
}
|
||||
|
||||
interface CommandPaletteState {
|
||||
readonly open: boolean;
|
||||
readonly openIntent: CommandPaletteOpenIntent | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the command-palette keyboard/event bridge in the startup graph while
|
||||
* deferring its filesystem, source-control, and dialog implementation until
|
||||
* the palette is opened.
|
||||
*/
|
||||
export function CommandPaletteShell({ children }: { readonly children: ReactNode }) {
|
||||
const [state, setState] = useState<CommandPaletteState>({
|
||||
open: false,
|
||||
openIntent: null,
|
||||
});
|
||||
const setOpen = useCallback(
|
||||
(open: boolean) =>
|
||||
setState((current) => ({
|
||||
open,
|
||||
openIntent: open ? current.openIntent : null,
|
||||
})),
|
||||
[],
|
||||
);
|
||||
const toggleOpen = useCallback(
|
||||
() => setState((current) => ({ open: !current.open, openIntent: null })),
|
||||
[],
|
||||
);
|
||||
const clearOpenIntent = useCallback(
|
||||
() => setState((current) => ({ ...current, openIntent: null })),
|
||||
[],
|
||||
);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
|
||||
const routeTarget = useParams({
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
|
||||
const terminalOpen = useTerminalUiStateStore((value) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalUiState(value.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
|
||||
: false,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
context: {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen,
|
||||
},
|
||||
});
|
||||
if (command !== "commandPalette.toggle") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleOpen();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
onOpenCommandPalette((detail) => {
|
||||
if (!detail.open) {
|
||||
setOpen(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setState({ open: true, openIntent: { kind: detail.open } });
|
||||
}),
|
||||
[setOpen],
|
||||
);
|
||||
|
||||
return (
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
{children}
|
||||
{state.open ? (
|
||||
<Suspense fallback={null}>
|
||||
<CommandPaletteDialog
|
||||
openIntent={state.openIntent}
|
||||
setOpen={setOpen}
|
||||
clearOpenIntent={clearOpenIntent}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
</ComposerHandleContext>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsDownUpIcon,
|
||||
ChevronsUpDownIcon,
|
||||
Columns2Icon,
|
||||
PilcrowIcon,
|
||||
Rows3Icon,
|
||||
@@ -32,6 +34,7 @@ import {
|
||||
resolveDiffThemeName,
|
||||
resolveFileDiffPath,
|
||||
} from "../lib/diffRendering";
|
||||
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
@@ -39,6 +42,7 @@ import { useClientSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
|
||||
import { Button } from "./ui/button";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
import { Switch } from "./ui/switch";
|
||||
import {
|
||||
@@ -446,6 +450,8 @@ export default function DiffPanel({
|
||||
}),
|
||||
[collapsedDiffFileKeys, renderableFiles],
|
||||
);
|
||||
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
|
||||
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath) return;
|
||||
@@ -496,6 +502,18 @@ export default function DiffPanel({
|
||||
[collapseScopeKey],
|
||||
);
|
||||
|
||||
const toggleDiffFileCollapse = useCallback(() => {
|
||||
setCollapsedDiffFiles((current) => {
|
||||
const currentKeys =
|
||||
current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
|
||||
|
||||
return {
|
||||
scopeKey: collapseScopeKey,
|
||||
fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
|
||||
};
|
||||
});
|
||||
}, [collapseScopeKey, diffFileKeys]);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!routeThreadRef) return;
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
|
||||
@@ -695,6 +713,30 @@ export default function DiffPanel({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
|
||||
{codeViewFiles.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
|
||||
onClick={toggleDiffFileCollapse}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDiffFilesCollapsed ? (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<ToggleGroup
|
||||
className="shrink-0"
|
||||
variant="outline"
|
||||
@@ -824,7 +866,7 @@ export default function DiffPanel({
|
||||
<AnnotatableCodeView
|
||||
viewerRef={codeViewRef}
|
||||
key={collapseScopeKey ?? reviewSectionId}
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto [&>div>div:last-child]:top-0! [&>div>div:last-child]:bottom-auto!"
|
||||
files={codeViewFiles}
|
||||
sectionId={reviewSectionId}
|
||||
sectionTitle={reviewSectionTitle}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveSnoozePresets, snoozeWakeDescription, snoozeWakeLabel } from "./Sidebar.snooze";
|
||||
|
||||
// Local-time constructor so preset math is timezone-stable in tests.
|
||||
function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
|
||||
return new Date(year, month - 1, day, hour, minute, 0, 0);
|
||||
}
|
||||
|
||||
describe("resolveSnoozePresets", () => {
|
||||
it("offers hour, evening, tomorrow, next week in the morning", () => {
|
||||
// Wednesday 2026-04-08 10:00 local.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
expect(presets.map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"evening",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
const evening = presets.find((preset) => preset.id === "evening");
|
||||
expect(new Date(evening!.snoozedUntil).getHours()).toBe(18);
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
const tomorrowDate = new Date(tomorrow!.snoozedUntil);
|
||||
expect(tomorrowDate.getDate()).toBe(9);
|
||||
expect(tomorrowDate.getHours()).toBe(9);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
const nextWeekDate = new Date(nextWeek!.snoozedUntil);
|
||||
expect(nextWeekDate.getDay()).toBe(1);
|
||||
expect(nextWeekDate.getDate()).toBe(13);
|
||||
});
|
||||
|
||||
it("whenLabel complements the label instead of repeating it", () => {
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
for (const preset of presets) {
|
||||
// Day words live in the label column; the time column is time-only
|
||||
// (plus a weekday for next week, which names a different day).
|
||||
expect(preset.whenLabel.toLowerCase()).not.toContain("tomorrow");
|
||||
}
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
expect(tomorrow!.whenLabel).toMatch(/9/);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
expect(nextWeek!.whenLabel).toMatch(/Mon/);
|
||||
});
|
||||
|
||||
it("drops the evening preset once evening is near or past", () => {
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 17, 30)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 21)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
});
|
||||
|
||||
it("puts next week a full week out when today is Monday", () => {
|
||||
// Monday 2026-04-06.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 6, 10));
|
||||
const nextWeek = new Date(presets.find((preset) => preset.id === "next-week")!.snoozedUntil);
|
||||
expect(nextWeek.getDay()).toBe(1);
|
||||
expect(nextWeek.getDate()).toBe(13);
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeLabel", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("formats minutes, hours, and days, rounding up", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 30 * 60_000).toISOString(), now)).toBe("30m");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 90 * 60_000).toISOString(), now)).toBe("2h");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 26 * 3_600_000).toISOString(), now)).toBe("2d");
|
||||
});
|
||||
|
||||
it("reports now for past and malformed wake times", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() - 1000).toISOString(), now)).toBe("now");
|
||||
expect(snoozeWakeLabel("not-a-date", now)).toBe("now");
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeDescription", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("uses bare time today, 'tomorrow' next day, weekday within the week", () => {
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now)).not.toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 9, 9).toISOString(), now)).toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 13, 9).toISOString(), now)).toMatch(/Mon/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Snooze preset resolution for the sidebar snooze menu. Pure functions so
|
||||
* the preset math (evening/tomorrow/next-week boundaries) is unit-testable
|
||||
* without a DOM.
|
||||
*
|
||||
* Presets deliberately skew short: agent-thread rhythms are hours (a CI
|
||||
* run, a teammate review, the next work session), not days.
|
||||
*/
|
||||
import { parseTimestampDate } from "../timestampFormat";
|
||||
|
||||
type SnoozePresetId = "hour" | "evening" | "tomorrow" | "next-week";
|
||||
|
||||
export interface SnoozePreset {
|
||||
readonly id: SnoozePresetId;
|
||||
readonly label: string;
|
||||
/** Menu-row time column. Complements the label instead of repeating it:
|
||||
"Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
|
||||
readonly whenLabel: string;
|
||||
/** ISO wake time. */
|
||||
readonly snoozedUntil: string;
|
||||
}
|
||||
|
||||
function timeOfDayLabel(date: Date): string {
|
||||
return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
}
|
||||
|
||||
const EVENING_HOUR = 18;
|
||||
const MORNING_HOUR = 9;
|
||||
const HOUR_MS = 60 * 60 * 1_000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
|
||||
function atHour(base: Date, hour: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setHours(hour, 0, 0, 0);
|
||||
return next;
|
||||
}
|
||||
|
||||
// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
|
||||
// land on the wrong local day across DST transitions (a spring-forward day
|
||||
// is 23 hours, so 23:30 + 24h skips the whole next day).
|
||||
function addDays(base: Date, days: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setDate(next.getDate() + days);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Presets for "snooze until", computed against local time. "This evening"
|
||||
* only appears while it is still meaningfully before evening; after that
|
||||
* the list starts at "Tomorrow".
|
||||
*/
|
||||
export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
|
||||
const inAnHour = new Date(now.getTime() + HOUR_MS);
|
||||
const presets: SnoozePreset[] = [
|
||||
{
|
||||
id: "hour",
|
||||
label: "In 1 hour",
|
||||
whenLabel: timeOfDayLabel(inAnHour),
|
||||
snoozedUntil: inAnHour.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
const evening = atHour(now, EVENING_HOUR);
|
||||
// Suppress the evening preset once it is within an hour (or past): it
|
||||
// would duplicate "In 1 hour" or point at the past.
|
||||
if (evening.getTime() - now.getTime() > HOUR_MS) {
|
||||
presets.push({
|
||||
id: "evening",
|
||||
label: "This evening",
|
||||
whenLabel: timeOfDayLabel(evening),
|
||||
snoozedUntil: evening.toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
const tomorrow = atHour(addDays(now, 1), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "tomorrow",
|
||||
label: "Tomorrow",
|
||||
whenLabel: timeOfDayLabel(tomorrow),
|
||||
snoozedUntil: tomorrow.toISOString(),
|
||||
});
|
||||
|
||||
// Next Monday 9:00 (a week out when today is Monday).
|
||||
const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
|
||||
const nextWeek = atHour(addDays(now, daysUntilMonday), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "next-week",
|
||||
label: "Next week",
|
||||
whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${timeOfDayLabel(nextWeek)}`,
|
||||
snoozedUntil: nextWeek.toISOString(),
|
||||
});
|
||||
|
||||
return presets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
|
||||
* round up so a snooze never reads "0m" while still hidden.
|
||||
*/
|
||||
export function snoozeWakeLabel(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "now";
|
||||
const remainingMs = wake.getTime() - now.getTime();
|
||||
if (remainingMs <= 0) return "now";
|
||||
if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
|
||||
if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
|
||||
return `${Math.ceil(remainingMs / DAY_MS)}d`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human wake time for menus and toasts: "tomorrow 9:00", "Mon 9:00",
|
||||
* "17:30" (today).
|
||||
*/
|
||||
export function snoozeWakeDescription(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "";
|
||||
const time = wake.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
const startOfToday = new Date(now);
|
||||
startOfToday.setHours(0, 0, 0, 0);
|
||||
const dayDelta = Math.floor((wake.getTime() - startOfToday.getTime()) / DAY_MS);
|
||||
if (dayDelta === 0) return time;
|
||||
if (dayDelta === 1) return `tomorrow ${time}`;
|
||||
const weekday = wake.toLocaleDateString(undefined, { weekday: "short" });
|
||||
if (dayDelta < 7) return `${weekday} ${time}`;
|
||||
const date = wake.toLocaleDateString(undefined, { month: "short", day: "numeric" });
|
||||
return `${date}, ${time}`;
|
||||
}
|
||||
@@ -189,7 +189,6 @@ import { sortThreads } from "../lib/threadSort";
|
||||
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useIsMobile } from "~/hooks/useMediaQuery";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import {
|
||||
@@ -2827,14 +2826,12 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
<SidebarGroup className="px-2 pt-2 pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="h-8 gap-2 rounded-md px-2 py-1.5 text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-0"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
type="button"
|
||||
className="h-8 gap-2 rounded-md px-2 py-1.5 text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-0"
|
||||
data-testid="command-palette-trigger"
|
||||
onClick={() => openCommandPalette()}
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<span className="flex-1 truncate text-left text-sm font-medium">Search</span>
|
||||
@@ -2843,7 +2840,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,11 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
import {
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
settledPrHoverColorClass,
|
||||
} from "./ThreadStatusIndicators";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
@@ -70,4 +74,23 @@ describe("prStatusIndicator", () => {
|
||||
tooltipTitle: "PR branch",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses red for closed pull requests", () => {
|
||||
const closedPr = status().pr;
|
||||
if (!closedPr) throw new Error("Expected pull request fixture");
|
||||
|
||||
expect(prStatusIndicator({ ...closedPr, state: "closed" }, undefined)?.colorClass).toContain(
|
||||
"text-red-600",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("settledPrHoverColorClass", () => {
|
||||
it.each([
|
||||
["open", "text-emerald-600"],
|
||||
["merged", "text-violet-600"],
|
||||
["closed", "text-red-600"],
|
||||
] as const)("restores the %s pull request color on row hover", (state, colorClass) => {
|
||||
expect(settledPrHoverColorClass(state)).toContain(`group-hover/v2-row:${colorClass}`);
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,17 @@ export interface TerminalStatusIndicator {
|
||||
|
||||
export type ThreadPr = VcsStatusResult["pr"];
|
||||
|
||||
export function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"]): string {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return "group-hover/v2-row:text-emerald-600 dark:group-hover/v2-row:text-emerald-300/90";
|
||||
case "merged":
|
||||
return "group-hover/v2-row:text-violet-600 dark:group-hover/v2-row:text-violet-300/90";
|
||||
case "closed":
|
||||
return "group-hover/v2-row:text-red-600 dark:group-hover/v2-row:text-red-300/90";
|
||||
}
|
||||
}
|
||||
|
||||
export function prStatusIndicator(
|
||||
pr: ThreadPr,
|
||||
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
|
||||
@@ -65,7 +76,7 @@ export function prStatusIndicator(
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: `${presentation.shortName} closed`,
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
colorClass: "text-red-600 dark:text-red-300/90",
|
||||
tooltip,
|
||||
tooltipLead,
|
||||
tooltipTitle: pr.title,
|
||||
|
||||
@@ -434,6 +434,7 @@ describe("MessagesTimeline", () => {
|
||||
|
||||
expect(markup).not.toContain("Show full message");
|
||||
expect(markup).toContain('data-user-message-collapsible="false"');
|
||||
expect(markup).toContain("rounded-2xl bg-accent p-3");
|
||||
});
|
||||
|
||||
it("renders inline terminal labels with the composer chip UI", () => {
|
||||
|
||||
@@ -890,7 +890,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
|
||||
return (
|
||||
<div className="group flex flex-col items-end gap-1">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-secondary p-3">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-accent p-3">
|
||||
{regularImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
|
||||
@@ -51,7 +51,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
contentClassName="flex w-full items-center gap-3"
|
||||
className={cn(
|
||||
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
|
||||
"data-highlighted:bg-muted/56 data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0",
|
||||
"hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-highlighted:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0 [&[data-highlighted][data-selected]]:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))]",
|
||||
props.disabledReason &&
|
||||
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
|
||||
)}
|
||||
|
||||
@@ -521,7 +521,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
<div
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-xl text-popover-foreground"
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
data-model-picker-content="true"
|
||||
>
|
||||
{/* Sidebar */}
|
||||
@@ -568,18 +568,23 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
handleModelSelect(slug, instanceId);
|
||||
}}
|
||||
>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
|
||||
showSidebar && "border-l",
|
||||
)}
|
||||
>
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px rounded-lg bg-accent px-2 py-1">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm placeholder:text-muted-foreground/80"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/80" />
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
|
||||
@@ -97,7 +97,10 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
|
||||
|
||||
return (
|
||||
<div className="w-12 shrink-0 overflow-hidden bg-muted/60" data-model-picker-sidebar="true">
|
||||
<div
|
||||
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
|
||||
data-model-picker-sidebar="true"
|
||||
>
|
||||
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<div
|
||||
ref={sidebarContentRef}
|
||||
@@ -115,14 +118,14 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
) : null}
|
||||
{/* Favorites section */}
|
||||
{showFavorites ? (
|
||||
<div className="mb-1 pb-1">
|
||||
<div className="mb-1 border-b pb-1">
|
||||
<div className="relative w-full">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
)}
|
||||
onClick={() => handleSelect("favorites")}
|
||||
type="button"
|
||||
@@ -169,7 +172,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
<button
|
||||
data-model-picker-provider={entry.instanceId}
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
|
||||
)}
|
||||
data-provider-accent-color={entry.accentColor}
|
||||
|
||||
@@ -187,8 +187,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup
|
||||
align="start"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0]"
|
||||
viewportClassName="!overflow-hidden p-0"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [-webkit-backdrop-filter:none]! [--viewport-inline-padding:0] [backdrop-filter:none]!"
|
||||
viewportClassName="rounded-lg !overflow-hidden p-0"
|
||||
>
|
||||
<ModelPickerContent
|
||||
activeInstanceId={activeInstanceId}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
import { buildTraitsTriggerDisplay } from "./TraitsPicker";
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
options: ReadonlyArray<{ id: string; label: string }>,
|
||||
currentValue: string,
|
||||
): Extract<ProviderOptionDescriptor, { type: "select" }> {
|
||||
return { id, label: id, type: "select", options: [...options], currentValue };
|
||||
}
|
||||
|
||||
function fastModeDescriptor(
|
||||
currentValue: boolean,
|
||||
): Extract<ProviderOptionDescriptor, { type: "boolean" }> {
|
||||
return { id: "fastMode", label: "Fast Mode", type: "boolean", currentValue };
|
||||
}
|
||||
|
||||
const EFFORT = selectDescriptor(
|
||||
"effort",
|
||||
[
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "max", label: "Max" },
|
||||
],
|
||||
"high",
|
||||
);
|
||||
const CONTEXT_WINDOW = selectDescriptor(
|
||||
"contextWindow",
|
||||
[
|
||||
{ id: "200k", label: "200k" },
|
||||
{ id: "1m", label: "1M" },
|
||||
],
|
||||
"1m",
|
||||
);
|
||||
|
||||
function display(descriptors: ReadonlyArray<ProviderOptionDescriptor>, fastModeEnabled: boolean) {
|
||||
return buildTraitsTriggerDisplay({
|
||||
descriptors,
|
||||
primarySelectDescriptorId: "effort",
|
||||
ultrathinkPromptControlled: false,
|
||||
fastModeEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
describe("buildTraitsTriggerDisplay", () => {
|
||||
it("omits fast mode from the label entirely when it is off", () => {
|
||||
expect(display([EFFORT, fastModeDescriptor(false), CONTEXT_WINDOW], false)).toEqual({
|
||||
label: "High · 1M",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the bolt instead of a text label when fast mode is on", () => {
|
||||
expect(display([EFFORT, fastModeDescriptor(true), CONTEXT_WINDOW], true)).toEqual({
|
||||
label: "High · 1M",
|
||||
showFastModeIcon: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps non-fastMode booleans as text labels", () => {
|
||||
const thinking: Extract<ProviderOptionDescriptor, { type: "boolean" }> = {
|
||||
id: "thinking",
|
||||
label: "Thinking",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
};
|
||||
expect(display([EFFORT, thinking], false)).toEqual({
|
||||
label: "High · Thinking On",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to a text label when fast mode is the only trait", () => {
|
||||
expect(display([fastModeDescriptor(true)], true)).toEqual({
|
||||
label: "Fast",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
expect(display([fastModeDescriptor(false)], false)).toEqual({
|
||||
label: "Normal",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("stays blank when descriptors resolve to no label and there is no fast mode", () => {
|
||||
// A select with neither a currentValue nor an isDefault option yields no
|
||||
// label. Without a fastMode descriptor present that must stay blank rather
|
||||
// than falling through to a bogus "Normal".
|
||||
const unresolved: Extract<ProviderOptionDescriptor, { type: "select" }> = {
|
||||
id: "effort",
|
||||
label: "effort",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "high", label: "High" },
|
||||
],
|
||||
};
|
||||
expect(display([unresolved], false)).toEqual({ label: "", showFastModeIcon: false });
|
||||
});
|
||||
|
||||
it("still renders the prompt-controlled ultrathink label alongside the bolt", () => {
|
||||
expect(
|
||||
buildTraitsTriggerDisplay({
|
||||
descriptors: [EFFORT, fastModeDescriptor(true)],
|
||||
primarySelectDescriptorId: "effort",
|
||||
ultrathinkPromptControlled: true,
|
||||
fastModeEnabled: true,
|
||||
}),
|
||||
).toEqual({ label: "Ultrathink", showFastModeIcon: true });
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { ChevronDownIcon, ZapIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -379,6 +379,46 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Build the traits trigger's text label plus whether the fast-mode bolt should
|
||||
* render. Fast mode is a lightning bolt when on and nothing at all when off —
|
||||
* "Normal" is the near-universal case and isn't worth the horizontal space. The
|
||||
* one exception is when fast mode is the only trait, where a bare bolt (or bare
|
||||
* chevron) would leave the trigger unreadable.
|
||||
*/
|
||||
export function buildTraitsTriggerDisplay(input: {
|
||||
descriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
primarySelectDescriptorId: string | null;
|
||||
ultrathinkPromptControlled: boolean;
|
||||
fastModeEnabled: boolean;
|
||||
}): { label: string; showFastModeIcon: boolean } {
|
||||
let hasFastMode = false;
|
||||
const labels: Array<string> = [];
|
||||
for (const descriptor of input.descriptors) {
|
||||
if (descriptor.id === "fastMode" && descriptor.type === "boolean") {
|
||||
hasFastMode = true;
|
||||
continue;
|
||||
}
|
||||
const label =
|
||||
input.ultrathinkPromptControlled && descriptor.id === input.primarySelectDescriptorId
|
||||
? "Ultrathink"
|
||||
: descriptor.type === "boolean"
|
||||
? `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
|
||||
: getProviderOptionCurrentLabel(descriptor);
|
||||
if (typeof label === "string" && label.length > 0) {
|
||||
labels.push(label);
|
||||
}
|
||||
}
|
||||
|
||||
// Only fall back to text when fast mode is genuinely the sole trait. Keying
|
||||
// off an empty label list alone would also catch descriptors that resolved to
|
||||
// no label at all, printing a bogus "Normal" for a model without fast mode.
|
||||
if (labels.length === 0 && hasFastMode) {
|
||||
return { label: input.fastModeEnabled ? "Fast" : "Normal", showFastModeIcon: false };
|
||||
}
|
||||
return { label: labels.join(" · "), showFastModeIcon: input.fastModeEnabled };
|
||||
}
|
||||
|
||||
export const TraitsPicker = memo(function TraitsPicker({
|
||||
provider,
|
||||
instanceId,
|
||||
@@ -393,7 +433,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
...persistence
|
||||
}: TraitsMenuContentProps & TraitsPersistence) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled, fastModeEnabled } =
|
||||
getTraitsSectionVisibility({
|
||||
provider,
|
||||
models,
|
||||
@@ -415,23 +455,18 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
return null;
|
||||
}
|
||||
|
||||
const triggerLabels: Array<string> = [];
|
||||
for (const descriptor of descriptors) {
|
||||
const label =
|
||||
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
|
||||
? "Ultrathink"
|
||||
: descriptor.type === "boolean"
|
||||
? descriptor.id === "fastMode"
|
||||
? descriptor.currentValue === true
|
||||
? "Fast"
|
||||
: "Normal"
|
||||
: `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
|
||||
: getProviderOptionCurrentLabel(descriptor);
|
||||
if (typeof label === "string" && label.length > 0) {
|
||||
triggerLabels.push(label);
|
||||
}
|
||||
}
|
||||
const triggerLabel = triggerLabels.join(" · ");
|
||||
const { label: triggerLabel, showFastModeIcon } = buildTraitsTriggerDisplay({
|
||||
descriptors,
|
||||
primarySelectDescriptorId: primarySelectDescriptor?.id ?? null,
|
||||
ultrathinkPromptControlled,
|
||||
fastModeEnabled,
|
||||
});
|
||||
const fastModeIcon = showFastModeIcon ? (
|
||||
<>
|
||||
<ZapIcon aria-hidden="true" className="size-3 shrink-0 text-foreground/80 opacity-100" />
|
||||
<span className="sr-only">Fast mode on</span>
|
||||
</>
|
||||
) : null;
|
||||
|
||||
const isCodexStyle = provider === "codex";
|
||||
|
||||
@@ -457,12 +492,14 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
}
|
||||
>
|
||||
{isCodexStyle ? (
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
|
||||
{fastModeIcon}
|
||||
<span className="min-w-0 truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{fastModeIcon}
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</>
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
|
||||
import { PrimaryEnvironmentHttpClient } from "./httpClient";
|
||||
import { runPrimaryHttp } from "../../lib/runtime";
|
||||
import { markStartupMilestone } from "../../startupPerformance";
|
||||
|
||||
const PrimaryEnvironmentRequestOperation = Schema.Literals([
|
||||
"fetch-session-state",
|
||||
@@ -333,6 +334,7 @@ async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
|
||||
|
||||
try {
|
||||
await exchangeBootstrapCredential(bootstrapCredential);
|
||||
markStartupMilestone("pairing.exchanged");
|
||||
await waitForAuthenticatedSessionAfterBootstrap();
|
||||
return { status: "authenticated" };
|
||||
} catch (error) {
|
||||
@@ -354,6 +356,7 @@ export async function submitServerAuthCredential(credential: string): Promise<vo
|
||||
|
||||
resolvedAuthenticatedGateState = null;
|
||||
await exchangeBootstrapCredential(trimmedCredential);
|
||||
markStartupMilestone("pairing.exchanged");
|
||||
bootstrapPromise = null;
|
||||
stripPairingTokenFromUrl();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export const STARTUP_OPTIONAL_UI_DELAY_MS = 2_500;
|
||||
|
||||
/**
|
||||
* Lets the first usable shell paint before optional runtime UI starts loading.
|
||||
*/
|
||||
export function useAfterFirstPaint(delayMs = 0): boolean {
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let timeout: number | undefined;
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
if (delayMs <= 0) {
|
||||
setReady(true);
|
||||
} else {
|
||||
timeout = window.setTimeout(() => setReady(true), delayMs);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frame);
|
||||
if (timeout !== undefined) window.clearTimeout(timeout);
|
||||
};
|
||||
}, [delayMs]);
|
||||
|
||||
return ready;
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { canSettle, canSnooze } 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,6 +22,7 @@ import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsStat
|
||||
import { readLocalApi } from "../localApi";
|
||||
import {
|
||||
readEnvironmentSupportsSettlement,
|
||||
readEnvironmentSupportsSnooze,
|
||||
readEnvironmentThreadRefs,
|
||||
readProject,
|
||||
readThreadShell,
|
||||
@@ -69,6 +70,30 @@ 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, {
|
||||
@@ -86,6 +111,12 @@ 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,
|
||||
@@ -441,6 +472,61 @@ 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();
|
||||
@@ -477,14 +563,18 @@ export function useThreadActions() {
|
||||
confirmAndDeleteThread,
|
||||
settleThread,
|
||||
unsettleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
}),
|
||||
[
|
||||
archiveThread,
|
||||
confirmAndDeleteThread,
|
||||
deleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
],
|
||||
);
|
||||
}
|
||||
+18
-2
@@ -574,7 +574,6 @@ 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));
|
||||
@@ -588,6 +587,19 @@ 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%);
|
||||
}
|
||||
@@ -602,7 +614,11 @@ 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(--background) var(--glass-opacity), transparent);
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--popover) 18%,
|
||||
color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)
|
||||
);
|
||||
}
|
||||
|
||||
.dark .dialog-glass {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
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());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
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);
|
||||
}
|
||||
+12
-14
@@ -1,8 +1,5 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import { ClerkProvider } from "@clerk/react";
|
||||
import { passkeys } from "@clerk/electron/passkeys";
|
||||
import { ClerkProvider as ElectronClerkProvider } from "@clerk/electron/react";
|
||||
import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";
|
||||
|
||||
import "@fontsource-variable/dm-sans/index.css";
|
||||
@@ -12,7 +9,6 @@ import "@xterm/xterm/css/xterm.css";
|
||||
import "./index.css";
|
||||
|
||||
import { isElectron } from "./env";
|
||||
import { ManagedRelayAuthProvider } from "./cloud/managedAuth";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig";
|
||||
import { getRouter } from "./router";
|
||||
import {
|
||||
@@ -20,8 +16,11 @@ import {
|
||||
syncDocumentWindowControlsOverlayClass,
|
||||
} from "./lib/windowControlsOverlay";
|
||||
import { AppRoot } from "./AppRoot";
|
||||
import { markStartupMilestone } from "./startupPerformance";
|
||||
|
||||
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
|
||||
markStartupMilestone("entry.loaded");
|
||||
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
|
||||
const router = getRouter(history);
|
||||
@@ -32,21 +31,20 @@ if (isElectron) {
|
||||
}
|
||||
|
||||
const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined;
|
||||
const CloudAuthRoot = React.lazy(() =>
|
||||
isElectron ? import("./cloud/ElectronCloudAuthRoot") : import("./cloud/CloudAuthRoot"),
|
||||
);
|
||||
|
||||
const app = <AppRoot router={router} />;
|
||||
const cloudAuthPublishableKey =
|
||||
clerkPublishableKey && hasCloudPublicConfig() ? clerkPublishableKey : null;
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
{clerkPublishableKey && hasCloudPublicConfig() ? (
|
||||
isElectron ? (
|
||||
<ElectronClerkProvider publishableKey={clerkPublishableKey} passkeys={passkeys}>
|
||||
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
|
||||
</ElectronClerkProvider>
|
||||
) : (
|
||||
<ClerkProvider publishableKey={clerkPublishableKey}>
|
||||
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
|
||||
</ClerkProvider>
|
||||
)
|
||||
{cloudAuthPublishableKey ? (
|
||||
<React.Suspense fallback={null}>
|
||||
<CloudAuthRoot publishableKey={cloudAuthPublishableKey}>{app}</CloudAuthRoot>
|
||||
</React.Suspense>
|
||||
) : (
|
||||
app
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
|
||||
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
|
||||
import { stackedThreadToast, toastManager } from "../components/ui/toast";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import { startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import { isPreviewFocused } from "../lib/previewFocus";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { selectProjectGroupingSettings } from "../logicalProject";
|
||||
import { isPreviewSupportedInRuntime } from "../previewStateStore";
|
||||
import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
|
||||
import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
|
||||
import { usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useProjects } from "../state/entities";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
|
||||
export default function ChatRouteGlobalShortcuts() {
|
||||
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
|
||||
const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
|
||||
useHandleNewThread();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const projects = useProjects();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const projectGroupCount = useMemo(
|
||||
() =>
|
||||
buildSidebarProjectSnapshots({
|
||||
projects,
|
||||
settings: projectGroupingSettings,
|
||||
primaryEnvironmentId,
|
||||
resolveEnvironmentLabel: () => null,
|
||||
}).length,
|
||||
[primaryEnvironmentId, projectGroupingSettings, projects],
|
||||
);
|
||||
const terminalOpen = useTerminalUiStateStore((state) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
|
||||
: false,
|
||||
);
|
||||
// The `previewOpen` shortcut-context flag here uses the store-only value;
|
||||
// the URL-aware arbitration lives inside ChatView's `onTogglePreview`,
|
||||
// which we invoke via the action bus to avoid duplicating the rule.
|
||||
const previewOpen = useRightPanelStore((state) =>
|
||||
routeThreadRef
|
||||
? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
|
||||
: false,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
context: {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen,
|
||||
previewFocus: isPreviewFocused(),
|
||||
previewOpen,
|
||||
},
|
||||
});
|
||||
|
||||
if (isCommandPaletteOpen()) return;
|
||||
|
||||
if (event.key === "Escape" && selectedThreadKeysSize > 0) {
|
||||
event.preventDefault();
|
||||
clearSelection();
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "chat.newLocal" || command === "chat.new") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (command === "chat.new" && sidebarV2Enabled && projectGroupCount > 1) {
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
return;
|
||||
}
|
||||
void startNewThreadFromContext({
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "preview.toggle") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!routeThreadRef) return;
|
||||
if (!isPreviewSupportedInRuntime()) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "info",
|
||||
title: "Preview is desktop-only",
|
||||
description: "Open T3 Code in the desktop app to use the in-app preview.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
dispatchPreviewAction("toggle-panel");
|
||||
return;
|
||||
}
|
||||
|
||||
// The remaining preview commands only fire when the panel is the
|
||||
// currently-focused tenant. The `when: previewFocus` rule already
|
||||
// gates this, but defend against the keybinding being misconfigured.
|
||||
if (
|
||||
command === "preview.refresh" ||
|
||||
command === "preview.focusUrl" ||
|
||||
command === "preview.zoomIn" ||
|
||||
command === "preview.zoomOut" ||
|
||||
command === "preview.resetZoom"
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const action =
|
||||
command === "preview.refresh"
|
||||
? "refresh"
|
||||
: command === "preview.focusUrl"
|
||||
? "focus-url"
|
||||
: command === "preview.zoomIn"
|
||||
? "zoom-in"
|
||||
: command === "preview.zoomOut"
|
||||
? "zoom-out"
|
||||
: "reset-zoom";
|
||||
dispatchPreviewAction(action);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
return () => window.removeEventListener("keydown", onWindowKeyDown);
|
||||
}, [
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
clearSelection,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
keybindings,
|
||||
previewOpen,
|
||||
projectGroupCount,
|
||||
routeThreadRef,
|
||||
selectedThreadKeysSize,
|
||||
sidebarV2Enabled,
|
||||
terminalOpen,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
import { useEffect, useEffectEvent, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
createKeybindingsUpdateToastController,
|
||||
type KeybindingsUpdateToastController,
|
||||
} from "../components/KeybindingsUpdateToast.logic";
|
||||
import { stackedThreadToast, toastManager } from "../components/ui/toast";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
derivePhysicalProjectKeyFromPath,
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import { shellEnvironment } from "../state/shell";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { usePrimaryEnvironment } from "../state/environments";
|
||||
import { readProject, setActiveEnvironmentId } from "../state/entities";
|
||||
import {
|
||||
primaryServerConfigAtom,
|
||||
primaryServerConfigEventAtom,
|
||||
primaryServerWelcomeAtom,
|
||||
} from "../state/server";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
|
||||
export default function EventRouter() {
|
||||
const navigate = useNavigate();
|
||||
const pathname = useLocation({ select: (loc) => loc.pathname });
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const serverConfig = useAtomValue(primaryServerConfigAtom);
|
||||
const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
|
||||
const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
|
||||
const readPathname = useEffectEvent(() => pathname);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
const handledConfigEventRef = useRef(serverConfigEvent);
|
||||
const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
|
||||
createKeybindingsUpdateToastController({}),
|
||||
);
|
||||
|
||||
const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
|
||||
if (!payload) return;
|
||||
|
||||
setActiveEnvironmentId(payload.environment.environmentId);
|
||||
void (async () => {
|
||||
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) return;
|
||||
const bootstrapProject = readProject(
|
||||
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
|
||||
);
|
||||
const bootstrapProjectKey =
|
||||
(bootstrapProject
|
||||
? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
|
||||
: null) ??
|
||||
(serverConfig?.cwd
|
||||
? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
|
||||
: null) ??
|
||||
scopedProjectKey(
|
||||
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
|
||||
);
|
||||
useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
|
||||
|
||||
if (
|
||||
readPathname() !== "/" ||
|
||||
handledBootstrapThreadIdRef.current === payload.bootstrapThreadId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: {
|
||||
environmentId: payload.environment.environmentId,
|
||||
threadId: payload.bootstrapThreadId,
|
||||
},
|
||||
replace: true,
|
||||
});
|
||||
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
|
||||
})().catch(() => undefined);
|
||||
});
|
||||
|
||||
const handleServerConfigUpdated = useEffectEvent(() => {
|
||||
const decision = keybindingsToastController.handle(serverConfigEvent);
|
||||
if (!decision) return;
|
||||
|
||||
if (decision._tag === "Success") {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Keybindings updated",
|
||||
description: "Keybindings configuration reloaded successfully.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: "Invalid keybindings configuration",
|
||||
description: decision.message,
|
||||
actionVariant: "outline",
|
||||
actionProps: {
|
||||
children: "Open keybindings.json",
|
||||
onClick: () => {
|
||||
if (!serverConfig || !primaryEnvironment) return;
|
||||
const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
|
||||
if (!editor) return;
|
||||
void (async () => {
|
||||
const result = await openInEditor({
|
||||
environmentId: primaryEnvironment.environmentId,
|
||||
input: {
|
||||
cwd: serverConfig.keybindingsConfigPath,
|
||||
editor,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Success") return;
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open keybindings file",
|
||||
description:
|
||||
error instanceof Error ? error.message : "Unknown error opening file.",
|
||||
}),
|
||||
);
|
||||
})();
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (serverConfig) setActiveEnvironmentId(serverConfig.environment.environmentId);
|
||||
}, [serverConfig]);
|
||||
|
||||
useEffect(() => {
|
||||
handleWelcome(serverWelcome);
|
||||
}, [serverWelcome]);
|
||||
|
||||
useEffect(() => {
|
||||
if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) return;
|
||||
handledConfigEventRef.current = serverConfigEvent;
|
||||
handleServerConfigUpdated();
|
||||
}, [serverConfigEvent]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { RotateCcwIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
|
||||
import { SidebarInset } from "../components/ui/sidebar";
|
||||
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
|
||||
export default function ExistingProjectIndex() {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const handleNewThread = useNewThreadHandler();
|
||||
const startingRef = useRef(false);
|
||||
const [startState, setStartState] = useState({ failed: false, retryRequest: 0 });
|
||||
const mostRecentProject = useMemo(
|
||||
() => sortScopedProjectsForSidebar(projects, threads, "updated_at")[0] ?? null,
|
||||
[projects, threads],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (mostRecentProject === null || startingRef.current) return;
|
||||
startingRef.current = true;
|
||||
void handleNewThread(scopeProjectRef(mostRecentProject.environmentId, mostRecentProject.id), {
|
||||
replace: true,
|
||||
}).catch(() => {
|
||||
startingRef.current = false;
|
||||
setStartState((state) => ({ ...state, failed: true }));
|
||||
});
|
||||
}, [handleNewThread, mostRecentProject, startState.retryRequest]);
|
||||
|
||||
return startState.failed ? (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<Empty className="flex-1">
|
||||
<EmptyHeader className="max-w-md">
|
||||
<EmptyTitle className="text-foreground text-xl">Couldn’t start a new thread</EmptyTitle>
|
||||
<EmptyDescription className="mt-2 text-sm text-muted-foreground/78">
|
||||
The project is still available. Try opening the draft again.
|
||||
</EmptyDescription>
|
||||
<div className="mt-5 flex justify-center">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setStartState((state) => ({
|
||||
failed: false,
|
||||
retryRequest: state.retryRequest + 1,
|
||||
}));
|
||||
}}
|
||||
>
|
||||
<RotateCcwIcon className="size-4" />
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
</SidebarInset>
|
||||
) : null;
|
||||
}
|
||||
+71
-204
@@ -1,80 +1,52 @@
|
||||
import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
|
||||
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
Outlet,
|
||||
createRootRoute,
|
||||
type ErrorComponentProps,
|
||||
useLocation,
|
||||
useNavigate,
|
||||
} from "@tanstack/react-router";
|
||||
import { useEffect, useEffectEvent, useRef, useState } from "react";
|
||||
import { lazy, Suspense, useEffect } from "react";
|
||||
|
||||
import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../branding";
|
||||
import { resolveServerBackedAppDisplayName } from "../branding.logic";
|
||||
import { AppSidebarLayout } from "../components/AppSidebarLayout";
|
||||
import { CommandPalette } from "../components/CommandPalette";
|
||||
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
|
||||
import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
|
||||
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
|
||||
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
|
||||
import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
|
||||
import { CommandPaletteShell } from "../components/CommandPaletteShell";
|
||||
import { Button } from "../components/ui/button";
|
||||
import {
|
||||
AnchoredToastProvider,
|
||||
stackedThreadToast,
|
||||
ToastProvider,
|
||||
toastManager,
|
||||
} from "../components/ui/toast";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
|
||||
import { STARTUP_OPTIONAL_UI_DELAY_MS, useAfterFirstPaint } from "../hooks/useAfterFirstPaint";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
derivePhysicalProjectKeyFromPath,
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { syncBrowserChromeTheme } from "../hooks/useTheme";
|
||||
import { configureClientTracing } from "../observability/clientTracing";
|
||||
import { markStartupMilestone } from "../startupPerformance";
|
||||
import { resolveInitialServerAuthGateState } from "../environments/primary";
|
||||
import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
|
||||
import { shellEnvironment } from "../state/shell";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
|
||||
import { primaryServerConfigAtom } from "../state/server";
|
||||
import {
|
||||
primaryServerConfigAtom,
|
||||
primaryServerConfigEventAtom,
|
||||
primaryServerWelcomeAtom,
|
||||
} from "../state/server";
|
||||
import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
|
||||
import {
|
||||
createKeybindingsUpdateToastController,
|
||||
type KeybindingsUpdateToastController,
|
||||
} from "../components/KeybindingsUpdateToast.logic";
|
||||
setActiveEnvironmentId,
|
||||
useActiveEnvironmentId,
|
||||
useAllEnvironmentShellsBootstrapped,
|
||||
} from "../state/entities";
|
||||
|
||||
const AppOverlays = lazy(() => import("../components/AppOverlays"));
|
||||
const EventRouter = lazy(() => import("./-EventRouter"));
|
||||
const ProviderUpdateLaunchNotification = lazy(() =>
|
||||
import("../components/ProviderUpdateLaunchNotification").then((module) => ({
|
||||
default: module.ProviderUpdateLaunchNotification,
|
||||
})),
|
||||
);
|
||||
|
||||
export const Route = createRootRoute({
|
||||
beforeLoad: async ({ location }) => {
|
||||
if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
|
||||
return {
|
||||
authGateState: {
|
||||
status: "hosted-pairing",
|
||||
} as const,
|
||||
};
|
||||
}
|
||||
|
||||
if (isHostedStaticApp(new URL(window.location.href))) {
|
||||
return {
|
||||
authGateState: {
|
||||
status: "hosted-static",
|
||||
} as const,
|
||||
};
|
||||
}
|
||||
|
||||
const authGateState = await resolveInitialServerAuthGateState();
|
||||
return {
|
||||
authGateState,
|
||||
};
|
||||
const url = new URL(window.location.href);
|
||||
const authGateState =
|
||||
location.pathname === "/pair" && hasHostedPairingRequest(url)
|
||||
? ({ status: "hosted-pairing" } as const)
|
||||
: isHostedStaticApp(url)
|
||||
? ({ status: "hosted-static" } as const)
|
||||
: await resolveInitialServerAuthGateState();
|
||||
markStartupMilestone("auth.gate.resolved");
|
||||
return { authGateState };
|
||||
},
|
||||
component: RootRouteView,
|
||||
errorComponent: RootRouteErrorView,
|
||||
@@ -87,6 +59,12 @@ function RootRouteView() {
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
const { authGateState } = Route.useRouteContext();
|
||||
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
|
||||
const loadEventRouter = useAfterFirstPaint();
|
||||
const loadOptionalUi = useAfterFirstPaint(STARTUP_OPTIONAL_UI_DELAY_MS);
|
||||
|
||||
useEffect(() => {
|
||||
markStartupMilestone("react.usable");
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
@@ -116,11 +94,11 @@ function RootRouteView() {
|
||||
}
|
||||
|
||||
const appShell = (
|
||||
<CommandPalette>
|
||||
<CommandPaletteShell>
|
||||
<AppSidebarLayout>
|
||||
<Outlet />
|
||||
</AppSidebarLayout>
|
||||
</CommandPalette>
|
||||
</CommandPaletteShell>
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -129,13 +107,19 @@ function RootRouteView() {
|
||||
<DocumentTitleSync />
|
||||
<GlassAppearanceSync />
|
||||
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
|
||||
<RelayClientInstallDialog />
|
||||
<ConnectOnboardingDialog />
|
||||
<SshPasswordPromptDialog />
|
||||
<SlowRpcRequestToastCoordinator />
|
||||
{primaryEnvironmentAuthenticated ? <StartupConnectionMilestones /> : null}
|
||||
{loadOptionalUi ? (
|
||||
<Suspense fallback={null}>
|
||||
<AppOverlays />
|
||||
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
|
||||
</Suspense>
|
||||
) : null}
|
||||
<HostedStaticEnvironmentBootstrap />
|
||||
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
|
||||
{primaryEnvironmentAuthenticated && loadEventRouter ? (
|
||||
<Suspense fallback={null}>
|
||||
<EventRouter />
|
||||
</Suspense>
|
||||
) : null}
|
||||
{appShell}
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
@@ -165,6 +149,30 @@ function DocumentTitleSync() {
|
||||
useEffect(() => {
|
||||
document.title = title;
|
||||
}, [title]);
|
||||
useEffect(() => {
|
||||
if (primaryServerVersion !== null) {
|
||||
markStartupMilestone("config.received");
|
||||
}
|
||||
}, [primaryServerVersion]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function StartupConnectionMilestones() {
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const shellsBootstrapped = useAllEnvironmentShellsBootstrapped();
|
||||
|
||||
useEffect(() => {
|
||||
if (primaryEnvironment?.connection.phase === "connected") {
|
||||
markStartupMilestone("ws.open");
|
||||
}
|
||||
}, [primaryEnvironment?.connection.phase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (shellsBootstrapped) {
|
||||
markStartupMilestone("shell.live");
|
||||
}
|
||||
}, [shellsBootstrapped]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -275,144 +283,3 @@ function AuthenticatedTracingBootstrap() {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function EventRouter() {
|
||||
const navigate = useNavigate();
|
||||
const pathname = useLocation({ select: (loc) => loc.pathname });
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const serverConfig = useAtomValue(primaryServerConfigAtom);
|
||||
const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
|
||||
const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
|
||||
const readPathname = useEffectEvent(() => pathname);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
const handledConfigEventRef = useRef(serverConfigEvent);
|
||||
const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
|
||||
createKeybindingsUpdateToastController({}),
|
||||
);
|
||||
|
||||
const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
|
||||
if (!payload) return;
|
||||
|
||||
setActiveEnvironmentId(payload.environment.environmentId);
|
||||
void (async () => {
|
||||
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
const bootstrapProject = readProject(
|
||||
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
|
||||
);
|
||||
const bootstrapProjectKey =
|
||||
(bootstrapProject
|
||||
? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
|
||||
: null) ??
|
||||
(serverConfig?.cwd
|
||||
? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
|
||||
: null) ??
|
||||
scopedProjectKey(
|
||||
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
|
||||
);
|
||||
useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
|
||||
|
||||
if (readPathname() !== "/") {
|
||||
return;
|
||||
}
|
||||
if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: {
|
||||
environmentId: payload.environment.environmentId,
|
||||
threadId: payload.bootstrapThreadId,
|
||||
},
|
||||
replace: true,
|
||||
});
|
||||
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
|
||||
})().catch(() => undefined);
|
||||
});
|
||||
|
||||
const handleServerConfigUpdated = useEffectEvent(() => {
|
||||
const decision = keybindingsToastController.handle(serverConfigEvent);
|
||||
if (!decision) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (decision._tag === "Success") {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Keybindings updated",
|
||||
description: "Keybindings configuration reloaded successfully.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: "Invalid keybindings configuration",
|
||||
description: decision.message,
|
||||
actionVariant: "outline",
|
||||
actionProps: {
|
||||
children: "Open keybindings.json",
|
||||
onClick: () => {
|
||||
if (!serverConfig || !primaryEnvironment) {
|
||||
return;
|
||||
}
|
||||
|
||||
const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
|
||||
if (!editor) {
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
const result = await openInEditor({
|
||||
environmentId: primaryEnvironment.environmentId,
|
||||
input: {
|
||||
cwd: serverConfig.keybindingsConfigPath,
|
||||
editor,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
return;
|
||||
}
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open keybindings file",
|
||||
description:
|
||||
error instanceof Error ? error.message : "Unknown error opening file.",
|
||||
}),
|
||||
);
|
||||
})();
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
setActiveEnvironmentId(serverConfig.environment.environmentId);
|
||||
}, [serverConfig]);
|
||||
|
||||
useEffect(() => {
|
||||
handleWelcome(serverWelcome);
|
||||
}, [serverWelcome]);
|
||||
|
||||
useEffect(() => {
|
||||
if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
|
||||
return;
|
||||
}
|
||||
handledConfigEventRef.current = serverConfigEvent;
|
||||
handleServerConfigUpdated();
|
||||
}, [serverConfigEvent]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,25 +1,20 @@
|
||||
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { createFileRoute, Link } from "@tanstack/react-router";
|
||||
import { LinkIcon, PlusIcon, RotateCcwIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { LinkIcon, PlusIcon } from "lucide-react";
|
||||
import { lazy, Suspense, useCallback } from "react";
|
||||
|
||||
import { openCommandPalette } from "../commandPaletteBus";
|
||||
import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
|
||||
import { SidebarInset } from "../components/ui/sidebar";
|
||||
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
|
||||
import {
|
||||
useAllEnvironmentShellsBootstrapped,
|
||||
useProjects,
|
||||
useThreadShells,
|
||||
} from "../state/entities";
|
||||
import { useAllEnvironmentShellsBootstrapped, useProjects } from "../state/entities";
|
||||
import { useEnvironments } from "../state/environments";
|
||||
import { APP_DISPLAY_NAME } from "~/branding";
|
||||
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
|
||||
const ExistingProjectIndex = lazy(() => import("./-ExistingProjectIndex"));
|
||||
|
||||
function ChatIndexRouteView() {
|
||||
const { authGateState } = Route.useRouteContext();
|
||||
const { environments } = useEnvironments();
|
||||
@@ -38,72 +33,21 @@ function ChatIndexRouteView() {
|
||||
*/
|
||||
function IndexDraftLanding() {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const bootstrapped = useAllEnvironmentShellsBootstrapped();
|
||||
const handleNewThread = useNewThreadHandler();
|
||||
const startingRef = useRef(false);
|
||||
const [startState, setStartState] = useState({ failed: false, retryRequest: 0 });
|
||||
|
||||
const mostRecentProject = useMemo(
|
||||
() =>
|
||||
bootstrapped
|
||||
? (sortScopedProjectsForSidebar(projects, threads, "updated_at")[0] ?? null)
|
||||
: null,
|
||||
[bootstrapped, projects, threads],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (mostRecentProject === null || startingRef.current) {
|
||||
return;
|
||||
}
|
||||
startingRef.current = true;
|
||||
void handleNewThread(scopeProjectRef(mostRecentProject.environmentId, mostRecentProject.id), {
|
||||
replace: true,
|
||||
}).catch(() => {
|
||||
startingRef.current = false;
|
||||
setStartState((state) => ({ ...state, failed: true }));
|
||||
});
|
||||
}, [handleNewThread, mostRecentProject, startState.retryRequest]);
|
||||
|
||||
if (!bootstrapped) {
|
||||
return null;
|
||||
}
|
||||
if (mostRecentProject !== null) {
|
||||
return startState.failed ? (
|
||||
<DraftStartError
|
||||
onRetry={() => {
|
||||
setStartState((state) => ({
|
||||
failed: false,
|
||||
retryRequest: state.retryRequest + 1,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
) : null;
|
||||
if (projects.length > 0) {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<ExistingProjectIndex />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
return <NoProjectsHero />;
|
||||
}
|
||||
|
||||
function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<Empty className="flex-1">
|
||||
<EmptyHeader className="max-w-md">
|
||||
<EmptyTitle className="text-foreground text-xl">Couldn’t start a new thread</EmptyTitle>
|
||||
<EmptyDescription className="mt-2 text-sm text-muted-foreground/78">
|
||||
The project is still available. Try opening the draft again.
|
||||
</EmptyDescription>
|
||||
<div className="mt-5 flex justify-center">
|
||||
<Button size="sm" onClick={onRetry}>
|
||||
<RotateCcwIcon className="size-4" />
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
</SidebarInset>
|
||||
);
|
||||
}
|
||||
|
||||
function NoProjectsHero() {
|
||||
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
|
||||
|
||||
|
||||
+11
-174
@@ -1,183 +1,20 @@
|
||||
import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
|
||||
import { lazy, Suspense } from "react";
|
||||
|
||||
import { isCommandPaletteOpen } from "../commandPaletteBus";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { openCommandPalette } from "../commandPaletteBus";
|
||||
import { useProjects } from "../state/entities";
|
||||
import { usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { selectProjectGroupingSettings } from "../logicalProject";
|
||||
import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
|
||||
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import { isPreviewFocused } from "../lib/previewFocus";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { isPreviewSupportedInRuntime } from "../previewStateStore";
|
||||
import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
|
||||
import { primaryServerKeybindingsAtom } from "~/state/server";
|
||||
import { STARTUP_OPTIONAL_UI_DELAY_MS, useAfterFirstPaint } from "../hooks/useAfterFirstPaint";
|
||||
|
||||
function ChatRouteGlobalShortcuts() {
|
||||
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
|
||||
const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
|
||||
useHandleNewThread();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const projects = useProjects();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const projectGroupCount = useMemo(
|
||||
() =>
|
||||
buildSidebarProjectSnapshots({
|
||||
projects,
|
||||
settings: projectGroupingSettings,
|
||||
primaryEnvironmentId,
|
||||
resolveEnvironmentLabel: () => null,
|
||||
}).length,
|
||||
[primaryEnvironmentId, projectGroupingSettings, projects],
|
||||
);
|
||||
const terminalOpen = useTerminalUiStateStore((state) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
|
||||
: false,
|
||||
);
|
||||
// The `previewOpen` shortcut-context flag here uses the store-only value;
|
||||
// the URL-aware arbitration lives inside ChatView's `onTogglePreview`,
|
||||
// which we invoke via the action bus to avoid duplicating the rule.
|
||||
const previewOpen = useRightPanelStore((state) =>
|
||||
routeThreadRef
|
||||
? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
|
||||
: false,
|
||||
);
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
context: {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen,
|
||||
previewFocus: isPreviewFocused(),
|
||||
previewOpen,
|
||||
},
|
||||
});
|
||||
|
||||
if (isCommandPaletteOpen()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === "Escape" && selectedThreadKeysSize > 0) {
|
||||
event.preventDefault();
|
||||
clearSelection();
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "chat.newLocal") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void startNewThreadFromContext({
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "chat.new") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// Sidebar v2 routes creation through the command palette whenever
|
||||
// there is a real choice to make; v1 (and single-project setups)
|
||||
// keep the immediate contextual create.
|
||||
if (sidebarV2Enabled && projectGroupCount > 1) {
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
return;
|
||||
}
|
||||
void startNewThreadFromContext({
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "preview.toggle") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!routeThreadRef) return;
|
||||
if (!isPreviewSupportedInRuntime()) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "info",
|
||||
title: "Preview is desktop-only",
|
||||
description: "Open T3 Code in the desktop app to use the in-app preview.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
dispatchPreviewAction("toggle-panel");
|
||||
return;
|
||||
}
|
||||
|
||||
// The remaining preview commands only fire when the panel is the
|
||||
// currently-focused tenant. The `when: previewFocus` rule already
|
||||
// gates this, but defend against the keybinding being misconfigured.
|
||||
if (
|
||||
command === "preview.refresh" ||
|
||||
command === "preview.focusUrl" ||
|
||||
command === "preview.zoomIn" ||
|
||||
command === "preview.zoomOut" ||
|
||||
command === "preview.resetZoom"
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const action =
|
||||
command === "preview.refresh"
|
||||
? "refresh"
|
||||
: command === "preview.focusUrl"
|
||||
? "focus-url"
|
||||
: command === "preview.zoomIn"
|
||||
? "zoom-in"
|
||||
: command === "preview.zoomOut"
|
||||
? "zoom-out"
|
||||
: "reset-zoom";
|
||||
dispatchPreviewAction(action);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
};
|
||||
}, [
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
clearSelection,
|
||||
handleNewThread,
|
||||
keybindings,
|
||||
defaultProjectRef,
|
||||
previewOpen,
|
||||
projectGroupCount,
|
||||
routeThreadRef,
|
||||
selectedThreadKeysSize,
|
||||
sidebarV2Enabled,
|
||||
terminalOpen,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
const ChatRouteGlobalShortcuts = lazy(() => import("./-ChatRouteGlobalShortcuts"));
|
||||
|
||||
function ChatRouteLayout() {
|
||||
const loadGlobalShortcuts = useAfterFirstPaint(STARTUP_OPTIONAL_UI_DELAY_MS);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ChatRouteGlobalShortcuts />
|
||||
{loadGlobalShortcuts ? (
|
||||
<Suspense fallback={null}>
|
||||
<ChatRouteGlobalShortcuts />
|
||||
</Suspense>
|
||||
) : null}
|
||||
<Outlet />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
const markedStartupMilestones = new Set<string>();
|
||||
|
||||
/**
|
||||
* Records startup timing without coupling it to tracing, which is configured
|
||||
* only after authentication.
|
||||
*/
|
||||
export function markStartupMilestone(name: string): void {
|
||||
if (markedStartupMilestones.has(name) || typeof performance === "undefined") {
|
||||
return;
|
||||
}
|
||||
markedStartupMilestones.add(name);
|
||||
performance.mark(name);
|
||||
}
|
||||
@@ -207,6 +207,15 @@ 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;
|
||||
}
|
||||
|
||||
function parseTimestampDate(isoDate: string): Date | null {
|
||||
export function parseTimestampDate(isoDate: string): Date | null {
|
||||
const date = new Date(isoDate);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
+78
-30
@@ -7,14 +7,27 @@ 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 host = process.env.HOST?.trim() || "localhost";
|
||||
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
|
||||
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 configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
|
||||
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
|
||||
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
|
||||
@@ -39,9 +52,9 @@ const configuredHostedAppUrl = (() => {
|
||||
})();
|
||||
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
|
||||
|
||||
// Vite 8.1's experimental bundled dev mode: serves rolldown-bundled chunks in
|
||||
// dev for much faster startup/reload on large module graphs, with HMR served
|
||||
// as hot patches. Opt-in while experimental: T3CODE_BUNDLED_DEV=1 pnpm dev:web
|
||||
// Vite 8.1's experimental bundled dev mode. Keep this opt-in until its cold
|
||||
// build is reliably faster than the regular dev server:
|
||||
// T3CODE_BUNDLED_DEV=1 vp run dev
|
||||
const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
|
||||
const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
|
||||
|
||||
@@ -65,7 +78,20 @@ const unitTestProject = {
|
||||
},
|
||||
} satisfies TestProjectInlineConfiguration;
|
||||
|
||||
function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
|
||||
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.
|
||||
if (!wsUrl) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -86,12 +112,22 @@ function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
|
||||
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];
|
||||
|
||||
export default defineConfig(() => {
|
||||
return {
|
||||
plugins: [
|
||||
tanstackRouter(),
|
||||
tanstackRouter({ autoCodeSplitting: !bundledDev }),
|
||||
react(),
|
||||
babel({
|
||||
// We need to be explicit about the parser options after moving to @vitejs/plugin-react v6.0.0
|
||||
@@ -105,7 +141,6 @@ export default defineConfig(() => {
|
||||
],
|
||||
optimizeDeps: {
|
||||
include: [
|
||||
"@clerk/clerk-js",
|
||||
"@clerk/react/internal",
|
||||
"@pierre/diffs",
|
||||
"@pierre/diffs/editor",
|
||||
@@ -119,6 +154,10 @@ 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),
|
||||
@@ -145,32 +184,41 @@ export default defineConfig(() => {
|
||||
host,
|
||||
port,
|
||||
strictPort: true,
|
||||
allowedHosts,
|
||||
...(devProxyTarget
|
||||
? {
|
||||
proxy: {
|
||||
"/.well-known": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/api": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/attachments": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
// 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,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
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,9 +1,11 @@
|
||||
# Scripts
|
||||
|
||||
- `vp run dev` — Starts contracts, server, and web in watch mode.
|
||||
- `vp run dev --share` — Also publishes the web port over HTTPS on this machine's tailnet. The startup pairing URL is built against the shared origin, and the mapping is removed on exit.
|
||||
- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.
|
||||
- `vp run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands 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 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.
|
||||
- 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`
|
||||
@@ -23,6 +25,7 @@
|
||||
- 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`
|
||||
@@ -36,6 +39,12 @@
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
## Browser development
|
||||
|
||||
`dev` and `dev:web` leave `VITE_HTTP_URL` and `VITE_WS_URL` unset so the browser resolves the backend from `window.location.origin`. Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the server, allowing the same bundle to work from localhost or a tailnet hostname.
|
||||
|
||||
Worktrees derive a preferred port offset from their path. The runner shifts both ports together when either is occupied or the web port is blocked by browsers, so treat the `[dev-runner]` output as authoritative.
|
||||
|
||||
## Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"scripts": {
|
||||
"prepare": "effect-tsgo patch && vp config --no-agent",
|
||||
"dev": "node scripts/dev-runner.ts dev",
|
||||
"dev:share": "node scripts/dev-runner.ts dev --share",
|
||||
"dev:server": "node scripts/dev-runner.ts dev:server",
|
||||
"dev:web": "node scripts/dev-runner.ts dev:web",
|
||||
"dev:marketing": "vp run --filter @t3tools/marketing dev",
|
||||
@@ -14,6 +15,7 @@
|
||||
"start:marketing": "vp run --filter @t3tools/marketing preview",
|
||||
"start:mock-update-server": "node scripts/mock-update-server.ts",
|
||||
"screenshots:mobile": "node scripts/mobile-showcase.ts",
|
||||
"profile:startup": "node scripts/profile-startup.ts",
|
||||
"icons:export": "node scripts/export-brand-icons.ts",
|
||||
"icons:check": "node scripts/export-brand-icons.ts --check",
|
||||
"build": "vp run --filter './apps/*' --filter './packages/*' --filter './oxlint-plugin-t3code' --filter './scripts' build",
|
||||
|
||||
@@ -37,6 +37,8 @@ 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">;
|
||||
@@ -175,6 +177,26 @@ 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,10 +13,12 @@ import {
|
||||
type SetThreadInteractionModeInput,
|
||||
type SetThreadRuntimeModeInput,
|
||||
type SettleThreadInput,
|
||||
type SnoozeThreadInput,
|
||||
type StartThreadTurnInput,
|
||||
type StopThreadSessionInput,
|
||||
type UnarchiveThreadInput,
|
||||
type UnsettleThreadInput,
|
||||
type UnsnoozeThreadInput,
|
||||
type UpdateThreadMetadataInput,
|
||||
archiveThread,
|
||||
createThread,
|
||||
@@ -28,10 +30,12 @@ import {
|
||||
setThreadInteractionMode,
|
||||
setThreadRuntimeMode,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
startThreadTurn,
|
||||
stopThreadSession,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
updateThreadMetadata,
|
||||
} from "../operations/commands.ts";
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
@@ -47,10 +51,12 @@ export type {
|
||||
SetThreadInteractionModeInput,
|
||||
SetThreadRuntimeModeInput,
|
||||
SettleThreadInput,
|
||||
SnoozeThreadInput,
|
||||
StartThreadTurnInput,
|
||||
StopThreadSessionInput,
|
||||
UnarchiveThreadInput,
|
||||
UnsettleThreadInput,
|
||||
UnsnoozeThreadInput,
|
||||
UpdateThreadMetadataInput,
|
||||
} from "../operations/commands.ts";
|
||||
|
||||
@@ -100,6 +106,18 @@ 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,6 +59,8 @@ export function mergeEnvironmentThread(
|
||||
archivedAt: shell.archivedAt,
|
||||
settledOverride: shell.settledOverride,
|
||||
settledAt: shell.settledAt,
|
||||
snoozedUntil: shell.snoozedUntil,
|
||||
snoozedAt: shell.snoozedAt,
|
||||
session: shell.session,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -74,6 +74,8 @@ export function applyThreadDetailEvent(
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
@@ -124,6 +126,28 @@ 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,6 +90,130 @@ 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:
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
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,6 +44,9 @@ 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,7 +176,10 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<
|
||||
"gpt-5.3-spark": "gpt-5.3-codex-spark",
|
||||
},
|
||||
[CLAUDE_DRIVER_KIND]: {
|
||||
opus: "claude-opus-4-8",
|
||||
opus: "claude-opus-5",
|
||||
"opus-5": "claude-opus-5",
|
||||
"claude-opus-5.0": "claude-opus-5",
|
||||
"claude-opus-5-0": "claude-opus-5",
|
||||
"opus-4.8": "claude-opus-4-8",
|
||||
"claude-opus-4.8": "claude-opus-4-8",
|
||||
"opus-4.7": "claude-opus-4-7",
|
||||
|
||||
@@ -361,6 +361,12 @@ 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(
|
||||
@@ -411,6 +417,8 @@ 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,
|
||||
@@ -583,6 +591,27 @@ 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,
|
||||
@@ -727,6 +756,8 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
|
||||
ThreadUnarchiveCommand,
|
||||
ThreadSettleCommand,
|
||||
ThreadUnsettleCommand,
|
||||
ThreadSnoozeCommand,
|
||||
ThreadUnsnoozeCommand,
|
||||
ThreadMetaUpdateCommand,
|
||||
ThreadRuntimeModeSetCommand,
|
||||
ThreadInteractionModeSetCommand,
|
||||
@@ -750,6 +781,8 @@ export const ClientOrchestrationCommand = Schema.Union([
|
||||
ThreadUnarchiveCommand,
|
||||
ThreadSettleCommand,
|
||||
ThreadUnsettleCommand,
|
||||
ThreadSnoozeCommand,
|
||||
ThreadUnsnoozeCommand,
|
||||
ThreadMetaUpdateCommand,
|
||||
ThreadRuntimeModeSetCommand,
|
||||
ThreadInteractionModeSetCommand,
|
||||
@@ -854,6 +887,8 @@ 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",
|
||||
@@ -945,6 +980,23 @@ 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),
|
||||
@@ -1122,6 +1174,16 @@ 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,6 +194,14 @@
|
||||
"./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": {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// @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)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* 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");
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 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,6 +30,13 @@ 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-4-8");
|
||||
expect(normalizeModelSlug("opus", claude)).toBe("claude-opus-5");
|
||||
expect(normalizeCustomModelSlug(" opus ")).toBe("opus");
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,44 @@ 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"]}}`;
|
||||
|
||||
@@ -194,6 +232,26 @@ 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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -253,6 +311,10 @@ 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,6 +23,37 @@ 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",
|
||||
{
|
||||
@@ -54,6 +85,12 @@ 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 {
|
||||
@@ -212,6 +249,9 @@ export const readTailscaleStatus = Effect.gen(function* () {
|
||||
exitCode,
|
||||
stdoutLength: stdout.length,
|
||||
stderrLength: stderr.length,
|
||||
...(stderrDiagnosticOf(stderr) !== undefined
|
||||
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
return yield* parseTailscaleStatus(stdout);
|
||||
@@ -275,6 +315,9 @@ const runTailscaleCommand = (
|
||||
...commandContext,
|
||||
exitCode,
|
||||
stderrLength: stderr.length,
|
||||
...(stderrDiagnosticOf(stderr) !== undefined
|
||||
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user