Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5df247241 | ||
|
|
abc19a4c41 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
description: Launch, retain, and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, cross-turn dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, iteratively test UI behavior with a human, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
---
|
||||
|
||||
# Test T3 App
|
||||
@@ -13,35 +13,13 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
|
||||
2. Choose a base directory that belongs only to the current worktree or test:
|
||||
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
|
||||
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
|
||||
3. Start the full web stack with `vp run dev`. Add `--share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.
|
||||
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
|
||||
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
|
||||
|
||||
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
|
||||
|
||||
The worktree-local default deliberately outranks an ambient `T3CODE_HOME`; do not pass the shared home through to a worktree dev server.
|
||||
|
||||
Ports are derived from the worktree path but can shift when occupied. Always read the actual values from the `[dev-runner]` line.
|
||||
|
||||
Shared browser dev is single-origin: Vite proxies the backend paths, so never set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
|
||||
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
|
||||
|
||||
### Verify a shared environment before human handoff
|
||||
|
||||
When another person will use the printed pairing URL, first open the shared origin without the pairing path or fragment in the controlled browser and confirm the T3 Code app loads. This browser navigation is required even when curl succeeds because browsers block some otherwise reachable ports before making a network request.
|
||||
|
||||
Do not open the other person's complete pairing URL during this reachability check; doing so consumes its one-time token. If the agent also needs an authenticated browser, create and consume a separate pairing token, then leave a fresh token for the other person.
|
||||
|
||||
## Preserve the environment while iterating
|
||||
|
||||
Treat the overall testing or implementation loop—not an assistant turn or one verification pass—as the environment lifecycle boundary.
|
||||
|
||||
- Keep the dev process, base directory, selected ports, authenticated browser tab, registered projects, and seeded fixtures alive while the user may inspect the result or request follow-up changes.
|
||||
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
|
||||
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
|
||||
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
|
||||
@@ -67,7 +45,7 @@ T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
|
||||
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
|
||||
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
@@ -80,17 +58,9 @@ Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before chang
|
||||
|
||||
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
|
||||
|
||||
## Tear down only when the testing loop is finished
|
||||
## Finish the test
|
||||
|
||||
Tear down when the user explicitly asks, confirms the iteration is finished, or the overall task is genuinely complete with no pending human review. Do not infer completion from the end of an assistant turn.
|
||||
|
||||
When teardown is appropriate:
|
||||
|
||||
1. Stop the dev process with its terminal interrupt.
|
||||
2. Preserve the isolated base directory when it contains useful reproduction evidence or state for a likely follow-up.
|
||||
3. Otherwise remove only a path created for this test after resolving and verifying the exact target.
|
||||
|
||||
If completion is uncertain, keep the environment alive and mention that it is retained for further iteration. A fresh isolated base directory remains the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
|
||||
## Troubleshoot predictably
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
interface:
|
||||
display_name: "T3 App Testing"
|
||||
short_description: "Launch and retain isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 environment and iteratively test it in the browser while preserving state."
|
||||
short_description: "Launch and seed isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -88,7 +88,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
ALCHEMY_TELEMETRY_DISABLED: "1"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ jobs:
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
T3_SHOWCASE_ANDROID_ABI: x86_64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -81,7 +81,7 @@ jobs:
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -189,7 +189,7 @@ jobs:
|
||||
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -266,7 +266,7 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
@@ -678,7 +678,7 @@ jobs:
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -799,7 +799,7 @@ jobs:
|
||||
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -909,7 +909,7 @@ jobs:
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
@@ -982,7 +982,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: useblacksmith/checkout@v1
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
|
||||
@@ -13,14 +13,6 @@
|
||||
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
|
||||
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
|
||||
|
||||
## Dev Servers
|
||||
|
||||
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
|
||||
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
|
||||
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
|
||||
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
|
||||
|
||||
## Package Roles
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
|
||||
@@ -472,10 +472,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -497,18 +493,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
@@ -518,38 +504,20 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProjectGroup,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
@@ -845,31 +813,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. Snoozed threads outrank the rest: "No
|
||||
// threads yet" over an inbox that is merely all-snoozed reads as data
|
||||
// loss. Pending tasks render in the header, so the list showing them
|
||||
// isn't empty in the user's eyes.
|
||||
const v2SnoozedCount = threadListV2Layout.snoozedCount;
|
||||
// fact when a query is active. Pending tasks render in the header, so the
|
||||
// list showing them isn't empty in the user's eyes.
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={
|
||||
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
|
||||
}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
|
||||
@@ -399,10 +399,6 @@ function ThreadNavigationSidebarPane(
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -424,18 +420,8 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
@@ -443,38 +429,20 @@ function ThreadNavigationSidebarPane(
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Enabled,
|
||||
threads,
|
||||
selectedProjectScope,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const listItems = useMemo<readonly SidebarListItem[]>(() => {
|
||||
if (!threadListV2Enabled) return listLayout.items;
|
||||
// Queued offline tasks render above the thread rows (mirrors the
|
||||
@@ -962,28 +930,15 @@ function ThreadNavigationSidebarPane(
|
||||
}),
|
||||
[filterIcon, filterMenu, props.onOpenSettings],
|
||||
);
|
||||
// "No threads yet" over an inbox that is merely all-snoozed reads as
|
||||
// data loss; name the snoozed threads instead.
|
||||
const snoozedCount = threadListV2Layout.snoozedCount;
|
||||
const listEmpty = (
|
||||
<Text className="px-2 py-4 text-sm text-foreground-muted">
|
||||
{catalogState.isLoadingConnections
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? snoozedCount > 0
|
||||
? // Snoozed matches passed this same search filter — "No
|
||||
// matching threads" would misreport them as nonexistent.
|
||||
snoozedCount === 1
|
||||
? "1 matching thread snoozed"
|
||||
: "All matching threads snoozed"
|
||||
: "No matching threads"
|
||||
: snoozedCount > 0
|
||||
? snoozedCount === 1
|
||||
? "1 thread snoozed"
|
||||
: `${snoozedCount} threads snoozed`
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
? "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
|
||||
@@ -77,85 +77,6 @@ describe("sortThreadsForListV2", () => {
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("hides snoozed threads and counts them — visibility parity with web", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("woken"),
|
||||
title: "Woken",
|
||||
// Wake time already passed: back in the active list.
|
||||
snoozedUntil: "2026-06-01T18:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
// Same createdAt → static sort tiebreaks by id; the point is the woken
|
||||
// thread is BACK in the card block and the snoozed one is gone.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("classifies snooze with the second-precise clock and reports the next wake", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("just-woke"),
|
||||
title: "Just woke",
|
||||
// Woke 30s ago: hidden under the minute-floored clock, visible
|
||||
// under the precise one.
|
||||
snoozedUntil: "2026-06-02T00:00:30.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("still-snoozed"),
|
||||
title: "Still snoozed",
|
||||
snoozedUntil: "2026-06-02T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
// Minute-floored partition clock vs precise snooze clock.
|
||||
now: "2026-06-02T00:01:00.000Z",
|
||||
snoozeNow: "2026-06-02T00:01:07.500Z",
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["just-woke"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
|
||||
});
|
||||
|
||||
it("keeps snoozed threads visible on environments without the snooze capability", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
snoozeEnvironmentIds: new Set(),
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
|
||||
expect(layout.snoozedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("partitions settled threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
@@ -84,13 +84,6 @@ export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
/** Snoozed threads hidden from the list (visibility parity with web's
|
||||
collapsed Snoozed shelf; mobile has no shelf UI yet). */
|
||||
readonly snoozedCount: number;
|
||||
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
|
||||
a timeout at this boundary so the list re-partitions the moment a
|
||||
snooze expires instead of on the next minute tick. */
|
||||
readonly nextSnoozeWakeAt: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,22 +106,13 @@ export function buildThreadListV2Items(input: {
|
||||
other environments never classify as settled — the user could neither
|
||||
un-settle nor pin them. Absent = no gating (tests). */
|
||||
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
/** Environments whose server supports thread.snooze/unsnooze. Same
|
||||
contract as settlementEnvironmentIds. */
|
||||
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
readonly now?: string;
|
||||
/** Second-precise clock for snooze classification. Callers pass a
|
||||
minute-quantized `now` for memoization; snooze wake times are
|
||||
second-precise, so classifying with the floored minute would hold a
|
||||
woken thread hidden for up to a minute. Defaults to `now`. */
|
||||
readonly snoozeNow?: string;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const projectKeys = input.projectRefs
|
||||
@@ -137,8 +121,6 @@ export function buildThreadListV2Items(input: {
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
let snoozedCount = 0;
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
@@ -148,23 +130,8 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: a snoozed thread leaves the list until it
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozedCount += 1;
|
||||
if (
|
||||
thread.snoozedUntil != null &&
|
||||
(nextSnoozeWakeAt === null ||
|
||||
parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
|
||||
) {
|
||||
nextSnoozeWakeAt = thread.snoozedUntil;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
@@ -201,10 +168,5 @@ export function buildThreadListV2Items(input: {
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
|
||||
}
|
||||
@@ -60,8 +60,6 @@ function threadDetailToShell(
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
snoozedUntil: thread.snoozedUntil ?? null,
|
||||
snoozedAt: thread.snoozedAt ?? null,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: latestUserMessageAt(thread),
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -8,13 +8,9 @@ import * as ServerConfig from "../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as PairingGrantStore from "./PairingGrantStore.ts";
|
||||
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
|
||||
import { resolveSessionCookieName } from "./utils.ts";
|
||||
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
/** Pinned so dev-mode cookie tests can assert the port-scoped name. */
|
||||
const TEST_SERVER_PORT = 13_773;
|
||||
|
||||
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
|
||||
Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
@@ -23,12 +19,6 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
// Last, so the port cannot be overridden out from under
|
||||
// makeCookieRequest — which builds the cookie name from this constant.
|
||||
// An override that changed it would leave the server reading
|
||||
// t3_session_<other> while every request still sent t3_session_13773,
|
||||
// and the tests would fail for a reason unrelated to what they assert.
|
||||
port: TEST_SERVER_PORT,
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
|
||||
@@ -45,11 +35,7 @@ const makeCookieRequest = (
|
||||
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
// Derived, not hardcoded: the name is port-scoped so concurrent servers
|
||||
// on one hostname don't share a cookie. Mode and devUrl mirror
|
||||
// ServerConfig.layerTest, so this resolves to whatever the server reads.
|
||||
[resolveSessionCookieName({ mode: "web", port: TEST_SERVER_PORT, devUrl: undefined })]:
|
||||
sessionToken,
|
||||
t3_session: sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<
|
||||
|
||||
@@ -438,7 +438,6 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput,
|
||||
@@ -747,13 +746,11 @@ export const make = Effect.gen(function* () {
|
||||
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly purpose?: "startup";
|
||||
}) =>
|
||||
createPairingLink({
|
||||
scopes: input.scopes,
|
||||
subject: input.subject,
|
||||
...(input.label ? { label: input.label } : {}),
|
||||
...(input.purpose ? { purpose: input.purpose } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
@@ -777,7 +774,6 @@ export const make = Effect.gen(function* () {
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
...(input?.purpose ? { purpose: input.purpose } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
@@ -876,7 +872,6 @@ export const make = Effect.gen(function* () {
|
||||
issuePairingCredentialForSubject({
|
||||
scopes: AuthAdministrativeScopes,
|
||||
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
|
||||
purpose: "startup",
|
||||
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
|
||||
|
||||
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
|
||||
|
||||
@@ -34,9 +34,6 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
// Packaged desktop has no devUrl, but still needs the port scope: it
|
||||
// scans upward from 3773 for a free port and binds 127.0.0.1, so a second
|
||||
// instance shares this one's hostname on a different port.
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
@@ -48,22 +45,6 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps desktop cookies port-scoped on the port a second instance lands on", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3774");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3774,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
@@ -94,24 +75,6 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
port: 13773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("scopes web session cookies by port only in development", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
port: 13773,
|
||||
devUrl: new URL("http://127.0.0.1:5733"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -41,7 +41,6 @@ export const make = Effect.gen(function* () {
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
devUrl: config.devUrl,
|
||||
}),
|
||||
};
|
||||
|
||||
|
||||
@@ -202,11 +202,6 @@ export class PairingGrantStore extends Context.Service<
|
||||
readonly subject?: string;
|
||||
readonly label?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
/**
|
||||
* "startup" marks the credential the server mints for itself at boot,
|
||||
* which gets the long dev TTL when a dev URL is configured.
|
||||
*/
|
||||
readonly purpose?: "startup";
|
||||
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthPairingLink>,
|
||||
@@ -248,15 +243,6 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
||||
// window can still recover by re-bootstrapping rather than locking
|
||||
// the user out of the backend.
|
||||
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
|
||||
// A dev server's startup token is read off a log by whoever (or whatever) is
|
||||
// driving the session, often minutes later — after a `node --watch` restart, a
|
||||
// detour into another task, or a hand-off to the person actually doing the
|
||||
// testing. Five minutes turns that into a restart-the-server loop for no
|
||||
// security benefit: the token only unlocks a local dev backend, and its holder
|
||||
// could read the log anyway. Same reasoning (and duration) as the desktop
|
||||
// bootstrap grant above. Only applies when a dev URL is configured; user-issued
|
||||
// pairing links and real servers keep the 5-minute default.
|
||||
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
|
||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
const PAIRING_TOKEN_LENGTH = 12;
|
||||
const PAIRING_TOKEN_REJECTION_LIMIT =
|
||||
@@ -385,10 +371,7 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const credential = yield* generatePairingToken;
|
||||
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
|
||||
const ttl =
|
||||
input?.ttl ??
|
||||
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
|
||||
@@ -470,7 +470,6 @@ export const make = Effect.gen(function* () {
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
devUrl: serverConfig.devUrl,
|
||||
});
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
|
||||
@@ -10,29 +10,15 @@ import * as Result from "effect/Result";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
/**
|
||||
* Cookies are scoped by host but *not* by port, so any two servers that can be
|
||||
* live on one hostname at once need separate names — otherwise the second
|
||||
* clobbers the first's session and both sides see "Invalid session token
|
||||
* signature" until someone clears cookies by hand.
|
||||
*
|
||||
* Two populations qualify, for the same reason but from different causes:
|
||||
*
|
||||
* - **Dev servers** (`devUrl` set), which run several at a time across worktrees.
|
||||
* - **Desktop**, which scans upward from 3773 for a free port and binds
|
||||
* 127.0.0.1, so a second instance lands on a different port and the same host.
|
||||
*
|
||||
* Hosted deployments keep the stable production name: their public port can
|
||||
* change between releases, and scoping it would log every user out.
|
||||
*/
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
readonly devUrl: URL | undefined;
|
||||
}): string {
|
||||
return input.devUrl === undefined && input.mode !== "desktop"
|
||||
? SESSION_COOKIE_NAME
|
||||
: `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
|
||||
@@ -84,7 +84,6 @@ const makeCliTestServerConfig = (baseDir: string) =>
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -48,7 +48,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
devAllowedOrigins: [],
|
||||
} as const;
|
||||
|
||||
const openBootstrapFd = Effect.fn(function* (payload: DesktopBackendBootstrapValue) {
|
||||
@@ -96,8 +95,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
T3CODE_HOST: "0.0.0.0",
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
T3CODE_DEV_ALLOWED_ORIGINS:
|
||||
"https://host.example.ts.net, https://phone.example.ts.net ",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
@@ -120,7 +117,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
host: "0.0.0.0",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
devAllowedOrigins: ["https://host.example.ts.net", "https://phone.example.ts.net"],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -106,15 +106,6 @@ const EnvServerConfig = Config.all({
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devAllowedOrigins: Config.string("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
|
||||
Config.withDefault(""),
|
||||
Config.map((value) =>
|
||||
value
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0),
|
||||
),
|
||||
),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
@@ -372,7 +363,6 @@ export const resolveServerConfig = (
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
devAllowedOrigins: env.devAllowedOrigins,
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
|
||||
@@ -72,7 +72,6 @@ export class ServerConfig extends Context.Service<
|
||||
readonly baseDir: string;
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly devAllowedOrigins: ReadonlyArray<string>;
|
||||
readonly noBrowser: boolean;
|
||||
readonly startupPresentation: StartupPresentation;
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
@@ -188,7 +187,6 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
});
|
||||
|
||||
@@ -43,7 +43,6 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
|
||||
@@ -141,8 +141,6 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
reviewSweep: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -365,7 +365,6 @@ function createTextGeneration(
|
||||
}),
|
||||
),
|
||||
),
|
||||
generateThreadReview: () => Effect.die("generateThreadReview is not used by GitManager tests"),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+1
-14
@@ -4,7 +4,6 @@ import {
|
||||
AuthOrchestrationReadScope,
|
||||
EnvironmentHttpApi,
|
||||
} from "@t3tools/contracts";
|
||||
import { isDevProxiedPath } from "@t3tools/shared/devProxy";
|
||||
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -49,17 +48,9 @@ export const browserApiCorsLayer = Layer.unwrap(
|
||||
const devOrigin = config.devUrl?.origin;
|
||||
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
|
||||
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
|
||||
//
|
||||
// T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
|
||||
// origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
|
||||
// through Vite and is same-origin (no preflight at all), so this is a
|
||||
// safety net for the desktop renderer and any direct-to-backend caller.
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin
|
||||
? {
|
||||
allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
|
||||
credentials: true,
|
||||
}
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
: {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
@@ -225,10 +216,6 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
|
||||
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
|
||||
status: 302,
|
||||
|
||||
@@ -609,8 +609,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -681,38 +679,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.snoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: event.payload.snoozedUntil,
|
||||
snoozedAt: event.payload.snoozedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unsnoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -310,8 +310,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -424,8 +422,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
|
||||
@@ -336,8 +336,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -368,8 +366,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -402,8 +398,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -768,8 +762,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -1204,8 +1196,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1406,8 +1396,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1539,8 +1527,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1677,8 +1663,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1921,8 +1905,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
@@ -2019,8 +2001,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
|
||||
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -40,8 +38,6 @@ export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSet
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
|
||||
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -1,286 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
// The decider's clock is the Effect test clock, pinned to the epoch, so
|
||||
// "future" wake times are relative to 1970-01-01T00:00:00.000Z.
|
||||
const FUTURE_WAKE = "1970-01-02T09:00:00.000Z";
|
||||
const PAST_WAKE = "1969-12-31T09:00:00.000Z";
|
||||
const SNOOZED_AT = "1969-12-30T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(input: {
|
||||
readonly snoozedUntil?: string | null;
|
||||
readonly snoozedAt?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
readonly activities?: OrchestrationThread["activities"];
|
||||
readonly messages?: OrchestrationThread["messages"];
|
||||
}): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: input.archivedAt ?? null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: input.snoozedUntil ?? null,
|
||||
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
|
||||
deletedAt: null,
|
||||
messages: input.messages ?? [],
|
||||
proposedPlans: [],
|
||||
activities: input.activities ?? [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("snoozed thread decider", (it) => {
|
||||
it.effect("snoozes a thread to a future wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.snoozed");
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe(FUTURE_WAKE);
|
||||
expect(events[0].payload.snoozedAt).toBe(events[0].payload.updatedAt);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a wake time that is not in the future", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-past"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: PAST_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects an unparseable wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
// IsoDateTime is structurally a string, so garbage can reach the
|
||||
// decider; a NaN wake time must never persist as snooze state.
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-garbage"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "not-a-date",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing blocked-on-you work", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestActivity = {
|
||||
id: EventId.make("activity-req-1"),
|
||||
tone: "approval" as const,
|
||||
kind: "approval.requested",
|
||||
summary: "approval.requested",
|
||||
payload: { requestId: "req-1" },
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
} as OrchestrationThread["activities"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-blocked"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ activities: [requestActivity] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-emits idempotently for a duplicate snooze to the same wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const reEmit = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(reEmit) ? reEmit : [reEmit];
|
||||
expect(events).toHaveLength(1);
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
// Original snoozedAt preserved; updatedAt must not churn.
|
||||
expect(events[0].payload.snoozedAt).toBe(SNOOZED_AT);
|
||||
expect(events[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-snoozing to a DIFFERENT wake time stamps fresh", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-extend"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "1970-01-03T09:00:00.000Z",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe("1970-01-03T09:00:00.000Z");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unsnoozes with reason user and re-emits idempotently when awake", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events[0]?.type).toBe("thread.unsnoozed");
|
||||
if (events[0]?.type === "thread.unsnoozed") {
|
||||
expect(events[0].payload.reason).toBe("user");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
|
||||
const awake = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze-awake"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const awakeEvents = Array.isArray(awake) ? awake : [awake];
|
||||
expect(awakeEvents[0]?.type).toBe("thread.unsnoozed");
|
||||
if (awakeEvents[0]?.type === "thread.unsnoozed") {
|
||||
// No state change — keep the existing updatedAt.
|
||||
expect(awakeEvents[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing a thread with a queued turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
// The decider clock is the Effect test clock pinned to the epoch: a
|
||||
// user message 30s before it with no adopting turn is queued work.
|
||||
const queuedMessage = {
|
||||
id: MessageId.make("message-queued"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "1969-12-31T23:59:30.000Z",
|
||||
updatedAt: "1969-12-31T23:59:30.000Z",
|
||||
} as OrchestrationThread["messages"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-queued"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ messages: [queuedMessage] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing an archived thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ archivedAt: NOW }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("a user message spends the snooze return ticket (activity wake)", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-1"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
|
||||
expect(unsnoozed).toBeDefined();
|
||||
if (unsnoozed?.type === "thread.unsnoozed") {
|
||||
expect(unsnoozed.payload.reason).toBe("activity");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -53,13 +53,6 @@ function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): b
|
||||
);
|
||||
}
|
||||
|
||||
// Scans the read model's activities, which the projector caps at the most
|
||||
// recent 500. That bound is safe here: an OPEN approval/user-input request
|
||||
// blocks its turn, so the thread cannot accumulate hundreds of later
|
||||
// activities while one is outstanding — a request that has scrolled out of
|
||||
// the window is one whose turn kept running, i.e. it was resolved or went
|
||||
// stale. (The projection pipeline's pendingApprovalCount reads the same
|
||||
// capped stream and stays consistent with this view.)
|
||||
function hasOpenBlockingRequest(thread: {
|
||||
readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
|
||||
}): boolean {
|
||||
@@ -86,62 +79,6 @@ function hasOpenBlockingRequest(thread: {
|
||||
return openRequestIds.size > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A queued turn start — a user message no turn has picked up yet — is work
|
||||
* in flight even though session is still null (turn.start emits
|
||||
* message-sent + turn-start-requested; the session arrives later). Detection
|
||||
* mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
* strictly newer than every latestTurn timestamp (adoption stamps the new
|
||||
* turn's requestedAt with the message time, clearing this), and only within
|
||||
* the adoption grace window — historical threads whose last user message
|
||||
* postdates their turn timestamps (older-server data, mid-turn messages)
|
||||
* must not be blocked forever. A failed session start (status "error")
|
||||
* clears the block immediately.
|
||||
*
|
||||
* The age check is bounded on BOTH sides: message timestamps are
|
||||
* client-supplied, so a client clock ahead of the server yields a negative
|
||||
* age. Without the lower bound that negative age satisfies `<= grace` for
|
||||
* as long as the skew lasts, extending the block far past the intended two
|
||||
* minutes.
|
||||
*/
|
||||
function threadHasQueuedTurnStart(
|
||||
thread: {
|
||||
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
|
||||
readonly latestTurn: {
|
||||
readonly requestedAt: string;
|
||||
readonly startedAt: string | null;
|
||||
readonly completedAt: string | null;
|
||||
} | null;
|
||||
readonly session: { readonly status: string } | null;
|
||||
},
|
||||
occurredAt: string,
|
||||
): boolean {
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
return (
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS
|
||||
);
|
||||
}
|
||||
|
||||
function withEventBase(
|
||||
input: Pick<OrchestrationCommand, "commandId"> & {
|
||||
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
|
||||
@@ -474,8 +411,46 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
);
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
// Settling inside the adoption window would hide just-requested work.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
// A queued turn start — a user message no turn has picked up yet — is
|
||||
// work in flight even though session is still null (turn.start emits
|
||||
// message-sent + turn-start-requested; the session arrives later).
|
||||
// Settling in that window would hide just-requested work. Detection
|
||||
// mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
// strictly newer than every latestTurn timestamp (adoption stamps the
|
||||
// new turn's requestedAt with the message time, clearing this), and
|
||||
// only within the adoption grace window — historical threads whose
|
||||
// last user message postdates their turn timestamps (older-server
|
||||
// data, mid-turn messages) must stay settleable. A failed session
|
||||
// start (status "error") clears the block immediately.
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
// The age check is bounded on BOTH sides: message timestamps are
|
||||
// client-supplied, so a client clock ahead of the server yields a
|
||||
// negative age. Without the lower bound that negative age satisfies
|
||||
// `<= grace` for as long as the skew lasts, extending the settle
|
||||
// block far past the intended two minutes.
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
const hasQueuedTurnStart =
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS;
|
||||
if (hasQueuedTurnStart) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
@@ -533,103 +508,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.snooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
// A wake time in the past would create a thread that is snoozed and
|
||||
// woken at once — the row would never leave the inbox but still carry
|
||||
// snooze state. Reject instead of silently normalizing. The negated
|
||||
// comparison also catches unparseable wake times (IsoDateTime is
|
||||
// structurally just a string): NaN fails every comparison, and an
|
||||
// unparseable snoozedUntil must never persist.
|
||||
if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Blocked-on-you work must not be snoozed away: a pending approval or
|
||||
// user-input request is the agent waiting on the user, and hiding it
|
||||
// defeats the request. (A running session IS snoozable — snooze only
|
||||
// affects visibility, never the agent.)
|
||||
if (hasOpenBlockingRequest(thread)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// A queued turn start — a user message no turn has adopted yet — is
|
||||
// invisible pending work: no session, no pending flags. Snoozing in
|
||||
// that window would hide a just-requested turn exactly the way settle
|
||||
// would.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Re-snoozing an already-snoozed thread to the SAME wake time is a
|
||||
// duplicate (double-click, raced clients): re-emit with the original
|
||||
// timestamps so the projection is a no-op. A different wake time is a
|
||||
// real change and stamps fresh.
|
||||
const existingSnoozedAt =
|
||||
thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
|
||||
? thread.snoozedAt
|
||||
: null;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.snoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
snoozedUntil: command.snoozedUntil,
|
||||
snoozedAt: existingSnoozedAt ?? occurredAt,
|
||||
updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unsnooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Idempotent by re-emission (see thread.settle): waking a thread that
|
||||
// is not snoozed lands on the same null state without churning
|
||||
// updatedAt.
|
||||
const alreadyAwake = thread.snoozedUntil == null;
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: command.reason,
|
||||
updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
@@ -785,42 +663,24 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
// Real activity resets ANY override: it wakes an explicitly settled
|
||||
// thread, and it clears a keep-active pin back to neutral so the
|
||||
// thread can auto-settle again after this burst of work goes stale.
|
||||
// A snooze clears the same way — sending a message to a snoozed
|
||||
// thread is the user re-engaging, so the return ticket is spent.
|
||||
const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
if (targetThread.settledOverride !== null) {
|
||||
lifecycleResetEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
});
|
||||
if (targetThread.settledOverride === null) {
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
if (targetThread.snoozedUntil != null) {
|
||||
lifecycleResetEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
|
||||
case "thread.turn.interrupt": {
|
||||
@@ -962,12 +822,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
// Only a session coming alive is activity worth waking a settled thread
|
||||
// for — status writes like ready/stopped/error arrive after the fact and
|
||||
// must not fight a user's explicit settle. Snooze is deliberately NOT
|
||||
// cleared here: snooze never pauses the agent, so its session starting
|
||||
// or erroring is not the user re-engaging. Blocked/failed work still
|
||||
// surfaces immediately — effectiveSnoozed refuses to classify a thread
|
||||
// with a raised hand (approval / input / failure / fresh completion)
|
||||
// as snoozed, without spending the return ticket.
|
||||
// must not fight a user's explicit settle.
|
||||
const isSessionActivity =
|
||||
command.session.status === "starting" || command.session.status === "running";
|
||||
// Real activity resets ANY override (settled wakes, active unpins).
|
||||
|
||||
@@ -91,8 +91,6 @@ describe("orchestration projector", () => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -23,10 +23,8 @@ import {
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadSnoozedPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadUnsnoozedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -292,8 +290,6 @@ export function projectEvent(
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -369,30 +365,6 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.snoozed":
|
||||
return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: payload.snoozedUntil,
|
||||
snoozedAt: payload.snoozedAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unsnoozed":
|
||||
return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
@@ -93,8 +93,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -155,8 +153,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-03-25T00:00:00.000Z",
|
||||
snoozedUntil: "2026-03-26T09:00:00.000Z",
|
||||
snoozedAt: "2026-03-25T00:00:00.000Z",
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -173,17 +169,12 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
}
|
||||
assert.strictEqual(row.settledOverride, "settled");
|
||||
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
|
||||
|
||||
// Un-settle to the keep-active pin and wake the snooze; confirm the
|
||||
// flips persist.
|
||||
// Un-settle to the keep-active pin and confirm the flip persists.
|
||||
yield* threads.upsert({
|
||||
...row,
|
||||
settledOverride: "active",
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
});
|
||||
const repersisted = yield* threads.getById({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
@@ -191,8 +182,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
const updated = Option.getOrNull(repersisted);
|
||||
assert.strictEqual(updated?.settledOverride, "active");
|
||||
assert.strictEqual(updated?.settledAt, null);
|
||||
assert.strictEqual(updated?.snoozedUntil, null);
|
||||
assert.strictEqual(updated?.snoozedAt, null);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -45,8 +45,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
snoozed_until,
|
||||
snoozed_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
@@ -68,8 +66,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.archivedAt},
|
||||
${row.settledOverride},
|
||||
${row.settledAt},
|
||||
${row.snoozedUntil},
|
||||
${row.snoozedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -91,8 +87,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at = excluded.archived_at,
|
||||
settled_override = excluded.settled_override,
|
||||
settled_at = excluded.settled_at,
|
||||
snoozed_until = excluded.snoozed_until,
|
||||
snoozed_at = excluded.snoozed_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
@@ -121,8 +115,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -153,8 +145,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
|
||||
@@ -46,7 +46,6 @@ import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.
|
||||
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
|
||||
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
|
||||
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
|
||||
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -92,7 +91,6 @@ export const migrationEntries = [
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (!columns.some((column) => column.name === "snoozed_until")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_until TEXT
|
||||
`;
|
||||
}
|
||||
|
||||
if (!columns.some((column) => column.name === "snoozed_at")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_at TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -38,8 +38,6 @@ export const ProjectionThread = Schema.Struct({
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
|
||||
settledAt: Schema.NullOr(IsoDateTime),
|
||||
snoozedUntil: Schema.NullOr(IsoDateTime),
|
||||
snoozedAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
|
||||
@@ -530,29 +530,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("preserves xhigh effort for Claude Opus 5", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
"claude-opus-5",
|
||||
[{ id: "effort", value: "xhigh" }],
|
||||
),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, "xhigh");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -51,7 +51,6 @@ const CLAUDE_PRESENTATION = {
|
||||
displayName: "Claude",
|
||||
showInteractionModeToggle: true,
|
||||
} as const;
|
||||
const MINIMUM_CLAUDE_OPUS_5_VERSION = "2.1.219";
|
||||
const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
|
||||
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
|
||||
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
|
||||
@@ -88,42 +87,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-5",
|
||||
name: "Claude Opus 5",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultracode", label: "Ultracode" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
// Claude Code selects the 1M variant explicitly (`claude-opus-5[1m]`).
|
||||
options: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-8",
|
||||
name: "Claude Opus 4.8",
|
||||
@@ -309,10 +272,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
},
|
||||
];
|
||||
|
||||
function supportsClaudeOpus5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;
|
||||
}
|
||||
|
||||
function supportsClaudeFable5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
|
||||
}
|
||||
@@ -329,9 +288,6 @@ function getBuiltInClaudeModelsForVersion(
|
||||
version: string | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
return BUILT_IN_MODELS.filter((model) => {
|
||||
if (model.slug === "claude-opus-5") {
|
||||
return supportsClaudeOpus5(version);
|
||||
}
|
||||
if (model.slug === "claude-fable-5") {
|
||||
return supportsClaudeFable5(version);
|
||||
}
|
||||
@@ -345,11 +301,6 @@ function getBuiltInClaudeModelsForVersion(
|
||||
});
|
||||
}
|
||||
|
||||
function formatClaudeOpus5UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Opus 5. Upgrade to v${MINIMUM_CLAUDE_OPUS_5_VERSION} or newer to access it.`;
|
||||
}
|
||||
|
||||
function formatClaudeFable5UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;
|
||||
@@ -409,7 +360,6 @@ export function normalizeClaudeCliEffort(
|
||||
if (
|
||||
effort === "xhigh" &&
|
||||
model !== "claude-fable-5" &&
|
||||
model !== "claude-opus-5" &&
|
||||
model !== "claude-opus-4-8" &&
|
||||
model !== "claude-sonnet-5"
|
||||
) {
|
||||
@@ -887,15 +837,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const versionUpgradeMessage = supportsClaudeOpus5(parsedVersion)
|
||||
const versionUpgradeMessage = supportsClaudeFable5(parsedVersion)
|
||||
? undefined
|
||||
: supportsClaudeFable5(parsedVersion)
|
||||
? formatClaudeOpus5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
|
||||
const capabilities = resolveCapabilities
|
||||
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
|
||||
|
||||
@@ -1842,62 +1842,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes Claude Opus 5 on supported Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
const opus5 = status.models.find((model) => model.slug === "claude-opus-5");
|
||||
assert.strictEqual(opus5?.name, "Claude Opus 5");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.219\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides Claude Opus 5 on older Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.models.some((model) => model.slug === "claude-opus-5"),
|
||||
false,
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Code v2.1.218 is too old for Claude Opus 5. Upgrade to v2.1.219 or newer to access it.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.218\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes Claude Fable 5 on supported Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
|
||||
@@ -3,85 +3,17 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
ThreadId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadShell,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
import * as ReviewService from "./ReviewService.ts";
|
||||
|
||||
const GhPrViewFixture = Schema.Struct({
|
||||
number: Schema.Int,
|
||||
url: Schema.String,
|
||||
state: Schema.String,
|
||||
reviewDecision: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
mergeable: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
statusCheckRollup: Schema.optionalKey(Schema.Array(Schema.Struct({ conclusion: Schema.String }))),
|
||||
comments: Schema.optionalKey(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
author: Schema.Struct({ login: Schema.String }),
|
||||
body: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
const encodeGhPrViewFixture = Schema.encodeUnknownSync(Schema.fromJsonString(GhPrViewFixture));
|
||||
|
||||
function ghPrViewJson(fixture: typeof GhPrViewFixture.Type): string {
|
||||
return encodeGhPrViewFixture(fixture);
|
||||
}
|
||||
|
||||
function makeShellFromThread(
|
||||
thread: OrchestrationThread,
|
||||
overrides: Partial<OrchestrationThreadShell> = {},
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: thread.modelSelection,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
latestTurn: thread.latestTurn,
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeLayer(input: {
|
||||
readonly workspaceRoot: string;
|
||||
readonly baseDir: string;
|
||||
readonly detectCalls?: Array<{ readonly cwd: string }>;
|
||||
readonly thread?: OrchestrationThread;
|
||||
readonly shellOverrides?: Partial<OrchestrationThreadShell>;
|
||||
readonly generateThreadReview?: TextGeneration.TextGeneration["Service"]["generateThreadReview"];
|
||||
readonly reviewCalls?: Array<TextGeneration.ThreadReviewGenerationInput>;
|
||||
readonly ghExecute?: GitHubCli.GitHubCli["Service"]["execute"];
|
||||
}) {
|
||||
return ReviewService.layer.pipe(
|
||||
Layer.provide(
|
||||
@@ -96,102 +28,11 @@ function makeLayer(input: {
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({
|
||||
getThreadDetailById: (threadId) =>
|
||||
Effect.succeed(
|
||||
input.thread && input.thread.id === threadId
|
||||
? Option.some(input.thread)
|
||||
: Option.none(),
|
||||
),
|
||||
getThreadShellById: (threadId) =>
|
||||
Effect.succeed(
|
||||
input.thread && input.thread.id === threadId
|
||||
? Option.some(makeShellFromThread(input.thread, input.shellOverrides))
|
||||
: Option.none(),
|
||||
),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(TextGeneration.TextGeneration)({
|
||||
generateThreadReview: (reviewInput) => {
|
||||
input.reviewCalls?.push(reviewInput);
|
||||
return (
|
||||
input.generateThreadReview?.(reviewInput) ??
|
||||
Effect.succeed({
|
||||
summary: "Did the thing.",
|
||||
nextStep: "Settle this thread.",
|
||||
suggestedTitle: null,
|
||||
recommendSettle: true,
|
||||
settleReason: "Work concluded.",
|
||||
})
|
||||
);
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(GitHubCli.GitHubCli)({
|
||||
// Threads in these tests have no PR; investigation must degrade to
|
||||
// "no context" without touching gh.
|
||||
execute: input.ghExecute ?? (() => Effect.die("gh not stubbed in this test")),
|
||||
}),
|
||||
),
|
||||
Layer.provide(ServerSettings.layerTest()),
|
||||
Layer.provide(ServerConfig.layerTest(input.workspaceRoot, input.baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
}
|
||||
|
||||
function makeThread(overrides: Partial<OrchestrationThread> = {}): OrchestrationThread {
|
||||
return {
|
||||
id: ThreadId.make("thread_review_1"),
|
||||
projectId: "project_1" as OrchestrationThread["projectId"],
|
||||
title: "New thread",
|
||||
modelSelection: {
|
||||
instanceId: "codex" as OrchestrationThread["modelSelection"]["instanceId"],
|
||||
model: "gpt-5",
|
||||
options: [],
|
||||
},
|
||||
runtimeMode: "local",
|
||||
interactionMode: "chat",
|
||||
branch: null,
|
||||
// Tests mock getProjectShellById to None, so cwd resolution relies on
|
||||
// the worktree path; a thread with neither now fails loudly by design.
|
||||
worktreePath: "/tmp/t3-review-test-worktree",
|
||||
latestTurn: null,
|
||||
createdAt: "2026-07-20T00:00:00.000Z",
|
||||
updatedAt: "2026-07-20T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...overrides,
|
||||
} as OrchestrationThread;
|
||||
}
|
||||
|
||||
function makeMessage(input: {
|
||||
readonly id: string;
|
||||
readonly role: "user" | "assistant" | "system";
|
||||
readonly text: string;
|
||||
readonly streaming?: boolean;
|
||||
}): OrchestrationThread["messages"][number] {
|
||||
return {
|
||||
id: input.id as OrchestrationThread["messages"][number]["id"],
|
||||
role: input.role,
|
||||
text: input.text,
|
||||
turnId: null,
|
||||
streaming: input.streaming ?? false,
|
||||
createdAt: "2026-07-20T00:00:00.000Z",
|
||||
updatedAt: "2026-07-20T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("ReviewService", () => {
|
||||
it.effect("rejects diff preview cwd outside the configured workspace roots", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -256,479 +97,4 @@ describe("ReviewService", () => {
|
||||
assert.deepStrictEqual(detectCalls, []);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread fails with ReviewThreadNotFoundError for unknown threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review
|
||||
.summarizeThread({ threadId: ThreadId.make("thread_missing"), canSettleNow: true })
|
||||
.pipe(Effect.flip);
|
||||
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir })));
|
||||
|
||||
assert.strictEqual(error._tag, "ReviewThreadNotFoundError");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread passes transcript context and returns the review", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({
|
||||
messages: [
|
||||
makeMessage({ id: "msg_1", role: "user", text: "Fix the settle default" }),
|
||||
makeMessage({ id: "msg_2", role: "assistant", text: "Done, merged in PR #1" }),
|
||||
makeMessage({ id: "msg_3", role: "assistant", text: "streaming...", streaming: true }),
|
||||
],
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
generateThreadReview: () =>
|
||||
Effect.succeed({
|
||||
summary: "Bumped the settle default; PR merged.",
|
||||
nextStep: "Nothing left — settle this thread.",
|
||||
suggestedTitle: "Bump settle default",
|
||||
recommendSettle: true,
|
||||
settleReason: "PR merged, nothing pending.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.threadId, thread.id);
|
||||
assert.strictEqual(result.summary, "Bumped the settle default; PR merged.");
|
||||
assert.strictEqual(result.suggestedTitle, "Bump settle default");
|
||||
assert.strictEqual(result.recommendSettle, true);
|
||||
assert.strictEqual(result.settleReason, "PR merged, nothing pending.");
|
||||
|
||||
assert.strictEqual(reviewCalls.length, 1);
|
||||
const call = reviewCalls[0]!;
|
||||
assert.strictEqual(call.title, "New thread");
|
||||
assert.strictEqual(call.isActive, false);
|
||||
assert.strictEqual(call.firstUserMessage, "Fix the settle default");
|
||||
// Streaming messages are excluded from the transcript.
|
||||
assert.deepStrictEqual(
|
||||
call.recentMessages.map((message) => message.text),
|
||||
["Fix the settle default", "Done, merged in PR #1"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread never recommends settling when canSettleNow is false", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: false });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
// Model misbehaves and recommends settle anyway.
|
||||
generateThreadReview: () =>
|
||||
Effect.succeed({
|
||||
summary: "Still working.",
|
||||
nextStep: "Wait for the agent.",
|
||||
suggestedTitle: null,
|
||||
recommendSettle: true,
|
||||
settleReason: "Looks done to me.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(reviewCalls[0]?.isActive, true);
|
||||
assert.strictEqual(result.recommendSettle, false);
|
||||
assert.strictEqual(result.settleReason, null);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"summarizeThread overrides a stale client canSettleNow when the projection shows activity",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "t3-review-workspace-",
|
||||
});
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
// Client believed the thread was settleable, but the server-side
|
||||
// shell says approvals are pending.
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
shellOverrides: { hasPendingApprovals: true },
|
||||
generateThreadReview: () =>
|
||||
Effect.succeed({
|
||||
summary: "Looks finished.",
|
||||
nextStep: "Settle this thread.",
|
||||
suggestedTitle: null,
|
||||
recommendSettle: true,
|
||||
settleReason: "Done.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(reviewCalls[0]?.isActive, true);
|
||||
assert.strictEqual(result.recommendSettle, false);
|
||||
assert.strictEqual(result.settleReason, null);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread fails loudly when no workspace cwd can be resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
// No worktree and (per the mock) no project shell: cwd is unresolvable.
|
||||
const thread = makeThread({ worktreePath: null });
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review
|
||||
.summarizeThread({ threadId: thread.id, canSettleNow: true })
|
||||
.pipe(Effect.flip);
|
||||
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir, thread })));
|
||||
|
||||
assert.strictEqual(error._tag, "TextGenerationError");
|
||||
if (error._tag === "TextGenerationError") {
|
||||
assert.match(error.detail, /Unable to resolve a workspace directory/);
|
||||
}
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread attaches PR status and prompt context when gh finds a PR", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({ branch: "feat/settle-default" });
|
||||
const ghPayload = ghPrViewJson({
|
||||
number: 4415,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/4415",
|
||||
state: "OPEN",
|
||||
reviewDecision: "APPROVED",
|
||||
mergeable: "MERGEABLE",
|
||||
statusCheckRollup: [{ conclusion: "SUCCESS" }, { conclusion: "SKIPPED" }],
|
||||
comments: [
|
||||
{ author: { login: "reviewer" }, body: "LGTM", createdAt: "2026-07-24T00:00:00Z" },
|
||||
],
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
ghExecute: () =>
|
||||
Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: ghPayload,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} as never),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.prStatus?.number, 4415);
|
||||
assert.strictEqual(result.prStatus?.state, "open");
|
||||
assert.strictEqual(result.prStatus?.mergeReady, true);
|
||||
assert.strictEqual(result.prStatus?.checksPassing, true);
|
||||
assert.strictEqual(reviewCalls[0]?.pullRequest?.number, 4415);
|
||||
assert.strictEqual(reviewCalls[0]?.pullRequest?.recentComments[0]?.body, "LGTM");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread degrades to no PR context when gh fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({ branch: "feat/no-pr" });
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
ghExecute: (ghInput) =>
|
||||
Effect.fail(
|
||||
new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: ghInput.cwd,
|
||||
cause: "gh missing in test",
|
||||
}) as never,
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.prStatus, undefined);
|
||||
assert.strictEqual(reviewCalls[0]?.pullRequest, undefined);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("mergePullRequest reports conflict when the branch no longer merges cleanly", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const thread = makeThread({ branch: "feat/conflicting" });
|
||||
const ghPayload = ghPrViewJson({
|
||||
number: 77,
|
||||
url: "https://github.com/x/y/pull/77",
|
||||
state: "OPEN",
|
||||
reviewDecision: "APPROVED",
|
||||
mergeable: "CONFLICTING",
|
||||
statusCheckRollup: [{ conclusion: "SUCCESS" }],
|
||||
comments: [],
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.mergePullRequest({ threadId: thread.id, pullRequestNumber: 77 });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
ghExecute: () =>
|
||||
Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: ghPayload,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} as never),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.outcome, "conflict");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("mergePullRequest merges and reports merged for a ready PR", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const thread = makeThread({ branch: "feat/ready" });
|
||||
const ghCalls: string[] = [];
|
||||
const ghPayload = ghPrViewJson({
|
||||
number: 88,
|
||||
url: "https://github.com/x/y/pull/88",
|
||||
state: "OPEN",
|
||||
reviewDecision: "APPROVED",
|
||||
mergeable: "MERGEABLE",
|
||||
statusCheckRollup: [{ conclusion: "SUCCESS" }],
|
||||
comments: [],
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.mergePullRequest({ threadId: thread.id, pullRequestNumber: 88 });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
ghExecute: (ghInput) => {
|
||||
ghCalls.push(ghInput.args.join(" "));
|
||||
return Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: ghInput.args[1] === "view" ? ghPayload : "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} as never);
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(result.outcome, "merged");
|
||||
assert.ok(ghCalls.some((call) => call.startsWith("pr merge 88")));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread sums diff stats across every ready checkpoint", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
// Checkpoint files are per-TURN deltas, so a multi-turn thread's real
|
||||
// size is the sum — with files deduped by path across turns.
|
||||
const thread = makeThread({
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: "turn_1",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: "ref_1",
|
||||
status: "ready",
|
||||
files: [
|
||||
{ path: "a.ts", kind: "modified", additions: 10, deletions: 2 },
|
||||
{ path: "b.ts", kind: "added", additions: 5, deletions: 0 },
|
||||
],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-07-20T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
turnId: "turn_2",
|
||||
checkpointTurnCount: 2,
|
||||
checkpointRef: "ref_2",
|
||||
status: "ready",
|
||||
files: [{ path: "a.ts", kind: "modified", additions: 3, deletions: 1 }],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-07-20T00:01:00.000Z",
|
||||
},
|
||||
] as unknown as OrchestrationThread["checkpoints"],
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
|
||||
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir, thread })));
|
||||
|
||||
assert.deepStrictEqual(result.diffStats, { files: 2, additions: 18, deletions: 3 });
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread uses the client's model selection when provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({});
|
||||
const clientModel = {
|
||||
instanceId: "claudeAgent",
|
||||
model: "claude-opus-5",
|
||||
options: [],
|
||||
} as unknown as NonNullable<TextGeneration.ThreadReviewGenerationInput["modelSelection"]>;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({
|
||||
threadId: thread.id,
|
||||
canSettleNow: true,
|
||||
modelSelection: clientModel,
|
||||
});
|
||||
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir, thread, reviewCalls })));
|
||||
|
||||
assert.strictEqual(reviewCalls[0]?.modelSelection.model, "claude-opus-5");
|
||||
assert.strictEqual(reviewCalls[0]?.modelSelection.instanceId, "claudeAgent");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread falls back to the server text-gen model", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
|
||||
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir, thread, reviewCalls })));
|
||||
|
||||
// No client model → whatever the server settings carry.
|
||||
assert.ok((reviewCalls[0]?.modelSelection.model.length ?? 0) > 0);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("summarizeThread treats a queued turn start as active", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
|
||||
const reviewCalls: Array<TextGeneration.ThreadReviewGenerationInput> = [];
|
||||
const thread = makeThread({});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
workspaceRoot,
|
||||
baseDir,
|
||||
thread,
|
||||
reviewCalls,
|
||||
// A just-sent user message with no adopting turn: session still
|
||||
// null, but the thread has in-flight work. it.effect runs on the
|
||||
// TestClock (epoch 0), so "just sent" is the epoch.
|
||||
shellOverrides: {
|
||||
latestUserMessageAt: "1970-01-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
session: null,
|
||||
},
|
||||
generateThreadReview: () =>
|
||||
Effect.succeed({
|
||||
summary: "Looks finished.",
|
||||
nextStep: "Settle this thread.",
|
||||
suggestedTitle: null,
|
||||
recommendSettle: true,
|
||||
settleReason: "Done.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(reviewCalls[0]?.isActive, true);
|
||||
assert.strictEqual(result.recommendSettle, false);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -3,35 +3,17 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
ReviewMergeError,
|
||||
ReviewThreadNotFoundError,
|
||||
TextGenerationError,
|
||||
VcsRepositoryDetectionError,
|
||||
VcsUnsupportedOperationError,
|
||||
type ReviewDiffPreviewError,
|
||||
type ReviewDiffPreviewInput,
|
||||
type ReviewDiffPreviewResult,
|
||||
type ReviewMergePullRequestError,
|
||||
type ReviewMergePullRequestInput,
|
||||
type ReviewMergePullRequestResult,
|
||||
type ReviewThreadPrStatus,
|
||||
type ReviewThreadSummaryError,
|
||||
type ReviewThreadSummaryInput,
|
||||
type ReviewThreadSummaryResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../checkpointing/Utils.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
@@ -41,192 +23,15 @@ export class ReviewService extends Context.Service<
|
||||
readonly getDiffPreview: (
|
||||
input: ReviewDiffPreviewInput,
|
||||
) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
|
||||
readonly summarizeThread: (
|
||||
input: ReviewThreadSummaryInput,
|
||||
) => Effect.Effect<ReviewThreadSummaryResult, ReviewThreadSummaryError>;
|
||||
readonly mergePullRequest: (
|
||||
input: ReviewMergePullRequestInput,
|
||||
) => Effect.Effect<ReviewMergePullRequestResult, ReviewMergePullRequestError>;
|
||||
}
|
||||
>()("t3/review/ReviewService") {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PR investigation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Shape of `gh pr view --json <fields>` we rely on. Decoded leniently:
|
||||
a schema miss degrades to "no PR context", never a failed review. */
|
||||
const GhPrView = Schema.Struct({
|
||||
number: Schema.Int,
|
||||
url: Schema.String,
|
||||
state: Schema.String,
|
||||
reviewDecision: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
mergeable: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
statusCheckRollup: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Array(Schema.Struct({ conclusion: Schema.optionalKey(Schema.NullOr(Schema.String)) })),
|
||||
),
|
||||
),
|
||||
comments: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
author: Schema.optionalKey(Schema.NullOr(Schema.Struct({ login: Schema.String }))),
|
||||
body: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
const decodeGhPrView = Schema.decodeUnknownEffect(Schema.fromJsonString(GhPrView));
|
||||
|
||||
const GH_PR_VIEW_FIELDS = "number,url,state,reviewDecision,mergeable,statusCheckRollup,comments";
|
||||
const PR_COMMENT_CONTEXT_COUNT = 5;
|
||||
const PR_COMMENT_CHAR_LIMIT = 500;
|
||||
|
||||
export interface ThreadPrContext {
|
||||
readonly status: ReviewThreadPrStatus;
|
||||
/** Pre-rendered recent-comments block for the review prompt. */
|
||||
readonly recentComments: ReadonlyArray<{
|
||||
readonly author: string;
|
||||
readonly createdAt: string;
|
||||
readonly body: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
function ghStateToPrState(state: string): "open" | "closed" | "merged" | null {
|
||||
const normalized = state.trim().toUpperCase();
|
||||
if (normalized === "OPEN") return "open";
|
||||
if (normalized === "CLOSED") return "closed";
|
||||
if (normalized === "MERGED") return "merged";
|
||||
return null;
|
||||
}
|
||||
|
||||
function rollupToChecksPassing(
|
||||
rollup: ReadonlyArray<{ conclusion?: string | null }> | null | undefined,
|
||||
): boolean | null {
|
||||
if (!rollup || rollup.length === 0) return null;
|
||||
// Neutral/skipped conclusions don't block; pending (null conclusion on some
|
||||
// check types) and failures do.
|
||||
const blocking = rollup.some((check) => {
|
||||
const conclusion = check.conclusion?.trim().toUpperCase() ?? "";
|
||||
return !["SUCCESS", "NEUTRAL", "SKIPPED"].includes(conclusion);
|
||||
});
|
||||
return !blocking;
|
||||
}
|
||||
|
||||
function toPrStatus(view: typeof GhPrView.Type): ReviewThreadPrStatus | null {
|
||||
const state = ghStateToPrState(view.state);
|
||||
if (state === null) return null;
|
||||
const reviewDecision = view.reviewDecision?.trim() || null;
|
||||
const checksPassing = rollupToChecksPassing(view.statusCheckRollup ?? null);
|
||||
const mergeable =
|
||||
view.mergeable == null
|
||||
? null
|
||||
: view.mergeable.trim().toUpperCase() === "MERGEABLE"
|
||||
? true
|
||||
: view.mergeable.trim().toUpperCase() === "CONFLICTING"
|
||||
? false
|
||||
: null;
|
||||
const mergeReady =
|
||||
state === "open" &&
|
||||
mergeable === true &&
|
||||
checksPassing !== false &&
|
||||
reviewDecision !== "CHANGES_REQUESTED" &&
|
||||
reviewDecision !== "REVIEW_REQUIRED";
|
||||
return {
|
||||
number: view.number,
|
||||
url: view.url,
|
||||
state,
|
||||
reviewDecision,
|
||||
checksPassing,
|
||||
mergeable,
|
||||
mergeReady,
|
||||
recentCommentCount: view.comments?.length ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Mirrors QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts and
|
||||
// the decider's thread.settle guard.
|
||||
const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
|
||||
|
||||
/** A user message no turn has adopted yet is in-flight work even though the
|
||||
session is still null. Mirrors the decider's settle guard and the
|
||||
client's hasQueuedTurnStart: newest user message strictly newer than
|
||||
every latestTurn timestamp, within the adoption grace window, and not
|
||||
already surfaced as a failed session start. */
|
||||
function hasQueuedTurnStart(
|
||||
shell: {
|
||||
readonly latestUserMessageAt: string | null;
|
||||
readonly latestTurn: {
|
||||
readonly requestedAt: string | null;
|
||||
readonly startedAt: string | null;
|
||||
readonly completedAt: string | null;
|
||||
} | null;
|
||||
readonly session: { readonly status: string } | null;
|
||||
},
|
||||
nowMs: number,
|
||||
): boolean {
|
||||
if (shell.latestUserMessageAt === null) return false;
|
||||
if (shell.session?.status === "error") return false;
|
||||
const messageAt = Date.parse(shell.latestUserMessageAt);
|
||||
if (Number.isNaN(messageAt)) return false;
|
||||
// Bounded on both sides: message timestamps originate on client devices,
|
||||
// so a clock ahead of the server must not hold the queued state open.
|
||||
if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
|
||||
const turn = shell.latestTurn;
|
||||
if (turn === null) return true;
|
||||
return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
|
||||
(candidate) => candidate === null || Date.parse(candidate) < messageAt,
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const textGeneration = yield* TextGeneration.TextGeneration;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const gitHubCli = yield* GitHubCli.GitHubCli;
|
||||
|
||||
/** Look up the thread branch's PR with one `gh pr view`. Every failure —
|
||||
no PR, gh unauthenticated, schema drift — degrades to null: PR context
|
||||
enriches a review but must never fail it. */
|
||||
const investigateThreadPr = Effect.fn("ReviewService.investigateThreadPr")(function* (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
): Effect.fn.Return<ThreadPrContext | null, never> {
|
||||
const context = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: ["pr", "view", branch, "--json", GH_PR_VIEW_FIELDS],
|
||||
timeoutMs: 20_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((output) => decodeGhPrView(output.stdout)),
|
||||
Effect.map((view): ThreadPrContext | null => {
|
||||
const status = toPrStatus(view);
|
||||
if (status === null) return null;
|
||||
const recentComments = (view.comments ?? [])
|
||||
.slice(-PR_COMMENT_CONTEXT_COUNT)
|
||||
.map((comment) => ({
|
||||
author: comment.author?.login ?? "unknown",
|
||||
createdAt: comment.createdAt,
|
||||
body:
|
||||
comment.body.length > PR_COMMENT_CHAR_LIMIT
|
||||
? `${comment.body.slice(0, PR_COMMENT_CHAR_LIMIT)}…`
|
||||
: comment.body,
|
||||
}));
|
||||
return { status, recentComments };
|
||||
}),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
return context;
|
||||
});
|
||||
|
||||
const canonicalizePath = (value: string) => {
|
||||
const resolvedPath = path.resolve(value);
|
||||
@@ -301,258 +106,8 @@ export const make = Effect.gen(function* () {
|
||||
return yield* getDriverDiffPreview(input);
|
||||
});
|
||||
|
||||
const summarizeThread: ReviewService["Service"]["summarizeThread"] = Effect.fn(
|
||||
"ReviewService.summarizeThread",
|
||||
)(function* (input) {
|
||||
const mapProjectionError = (cause: unknown) =>
|
||||
new TextGenerationError({
|
||||
operation: "generateThreadReview",
|
||||
detail: "Failed to read the thread projection for review.",
|
||||
cause,
|
||||
});
|
||||
|
||||
const threadOption = yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(input.threadId)
|
||||
.pipe(Effect.mapError(mapProjectionError));
|
||||
if (Option.isNone(threadOption)) {
|
||||
return yield* new ReviewThreadNotFoundError({ threadId: input.threadId });
|
||||
}
|
||||
const thread = threadOption.value;
|
||||
|
||||
const projectOption = yield* projectionSnapshotQuery
|
||||
.getProjectShellById(thread.projectId)
|
||||
.pipe(Effect.mapError(mapProjectionError));
|
||||
// No silent process.cwd() fallback: the cwd is handed to the provider
|
||||
// CLI spawn, which reads local context files (AGENTS.md, CLAUDE.md) from
|
||||
// it — reviewing "the server's own directory" would leak unrelated
|
||||
// content into an external LLM prompt. Fail the item instead; the client
|
||||
// shows it as a retry-able error card.
|
||||
const cwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: Option.isSome(projectOption) ? [projectOption.value] : [],
|
||||
});
|
||||
if (cwd === undefined) {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadReview",
|
||||
detail: `Unable to resolve a workspace directory for thread '${input.threadId}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const settled = thread.messages.filter((message) => !message.streaming);
|
||||
const firstUserMessage = settled.find((message) => message.role === "user")?.text ?? null;
|
||||
const recentMessages = settled.map((message) => ({
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
}));
|
||||
// Never trust the client's canSettleNow alone: re-derive activity from the
|
||||
// server's own projection so a session that started (or approval/input
|
||||
// that appeared) after the client read its shell still blocks settling.
|
||||
// The shell is deliberately read AFTER the transcript: the two reads are
|
||||
// separate transactions, and reading the activity view last means a
|
||||
// session starting in between is still caught. The reverse skew (activity
|
||||
// ending in between) only staleness-affects the summary text — an actual
|
||||
// settle is re-validated by the client at apply time and by the decider's
|
||||
// thread.settle guards, so a recommendation can never settle live work.
|
||||
const shellOption = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(input.threadId)
|
||||
.pipe(Effect.mapError(mapProjectionError));
|
||||
const shell = Option.isSome(shellOption) ? shellOption.value : null;
|
||||
const now = yield* DateTime.now;
|
||||
const serverSideActive =
|
||||
shell === null ||
|
||||
shell.hasPendingApprovals ||
|
||||
shell.hasPendingUserInput ||
|
||||
shell.session?.status === "starting" ||
|
||||
shell.session?.status === "running" ||
|
||||
hasQueuedTurnStart(shell, DateTime.toEpochMillis(now));
|
||||
const canSettleNow = input.canSettleNow && !serverSideActive;
|
||||
const isActive = !canSettleNow;
|
||||
|
||||
// The client picks the model (defaulting to the user's last-used model
|
||||
// from the composer picker); the server's text-generation setting is
|
||||
// only the fallback for older clients that don't send one.
|
||||
const settings = yield* serverSettings.getSettings.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: "generateThreadReview",
|
||||
detail: "Failed to load server settings for review generation.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const modelSelection = input.modelSelection ?? settings.textGenerationModelSelection;
|
||||
|
||||
// Deeper investigation: live PR state + recent comments, when the
|
||||
// thread has a branch. Failures degrade to "no PR context".
|
||||
const prContext =
|
||||
thread.branch !== null ? yield* investigateThreadPr(cwd, thread.branch) : null;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadReview({
|
||||
cwd,
|
||||
title: thread.title,
|
||||
isActive,
|
||||
firstUserMessage,
|
||||
recentMessages,
|
||||
modelSelection,
|
||||
...(prContext !== null
|
||||
? {
|
||||
pullRequest: {
|
||||
number: prContext.status.number,
|
||||
state: prContext.status.state,
|
||||
reviewDecision: prContext.status.reviewDecision,
|
||||
checksPassing: prContext.status.checksPassing,
|
||||
mergeable: prContext.status.mergeable,
|
||||
recentComments: prContext.recentComments,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
// Belt and braces on top of prompt rules + normalizeThreadReview: an
|
||||
// active thread must never carry a settle recommendation.
|
||||
const recommendSettle = generated.recommendSettle && canSettleNow;
|
||||
|
||||
// Each checkpoint's files are that TURN's delta (CheckpointReactor diffs
|
||||
// previous→current), not a cumulative thread diff — so sum every ready
|
||||
// checkpoint. Line counts add up across turns; the file count dedupes by
|
||||
// path so a file edited in three turns counts once.
|
||||
const readyCheckpoints = thread.checkpoints.filter(
|
||||
(checkpoint) => checkpoint.status === "ready",
|
||||
);
|
||||
const touchedPaths = new Set<string>();
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
for (const checkpoint of readyCheckpoints) {
|
||||
for (const file of checkpoint.files) {
|
||||
touchedPaths.add(file.path);
|
||||
additions += file.additions;
|
||||
deletions += file.deletions;
|
||||
}
|
||||
}
|
||||
const diffStats =
|
||||
touchedPaths.size > 0 ? { files: touchedPaths.size, additions, deletions } : undefined;
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
summary: generated.summary,
|
||||
nextStep: generated.nextStep,
|
||||
suggestedTitle: generated.suggestedTitle,
|
||||
recommendSettle,
|
||||
settleReason: recommendSettle ? generated.settleReason : null,
|
||||
...(diffStats !== undefined ? { diffStats } : {}),
|
||||
...(prContext !== null ? { prStatus: prContext.status } : {}),
|
||||
...(generated.usage !== undefined
|
||||
? {
|
||||
usage: {
|
||||
inputTokens: generated.usage.inputTokens,
|
||||
outputTokens: generated.usage.outputTokens,
|
||||
durationMs: generated.usage.durationMs,
|
||||
...(generated.usage.costUsd !== undefined
|
||||
? { costUsd: generated.usage.costUsd }
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const mergePullRequest: ReviewService["Service"]["mergePullRequest"] = Effect.fn(
|
||||
"ReviewService.mergePullRequest",
|
||||
)(function* (input) {
|
||||
const mapProjectionError = (cause: unknown) =>
|
||||
new ReviewMergeError({
|
||||
threadId: input.threadId,
|
||||
detail: "Failed to read the thread projection for merge.",
|
||||
cause,
|
||||
});
|
||||
const threadOption = yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(input.threadId)
|
||||
.pipe(Effect.mapError(mapProjectionError));
|
||||
if (Option.isNone(threadOption)) {
|
||||
return yield* new ReviewThreadNotFoundError({ threadId: input.threadId });
|
||||
}
|
||||
const thread = threadOption.value;
|
||||
const projectOption = yield* projectionSnapshotQuery
|
||||
.getProjectShellById(thread.projectId)
|
||||
.pipe(Effect.mapError(mapProjectionError));
|
||||
const cwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: Option.isSome(projectOption) ? [projectOption.value] : [],
|
||||
});
|
||||
if (cwd === undefined || thread.branch === null) {
|
||||
return yield* new ReviewMergeError({
|
||||
threadId: input.threadId,
|
||||
detail: "Thread has no resolvable workspace or branch to merge from.",
|
||||
});
|
||||
}
|
||||
|
||||
// Re-validate against LIVE GitHub state: in a merge queue, an earlier
|
||||
// merge may have landed since the review ran and made this branch
|
||||
// conflict (or someone merged/closed the PR out of band).
|
||||
const prContext = yield* investigateThreadPr(cwd, thread.branch);
|
||||
if (prContext === null || prContext.status.number !== input.pullRequestNumber) {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "not-ready" as const,
|
||||
detail: "The pull request could not be re-validated against GitHub.",
|
||||
};
|
||||
}
|
||||
const status = prContext.status;
|
||||
if (status.state !== "open") {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "already-closed" as const,
|
||||
detail: `PR #${status.number} is already ${status.state}.`,
|
||||
};
|
||||
}
|
||||
if (status.mergeable === false) {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "conflict" as const,
|
||||
detail: `PR #${status.number} no longer merges cleanly onto its base branch.`,
|
||||
};
|
||||
}
|
||||
if (!status.mergeReady) {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "not-ready" as const,
|
||||
detail: `PR #${status.number} is not merge-ready (checks: ${String(status.checksPassing)}, review: ${status.reviewDecision ?? "none"}).`,
|
||||
};
|
||||
}
|
||||
|
||||
const mergeResult = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: ["pr", "merge", String(status.number), "--squash"],
|
||||
timeoutMs: 60_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(() => ({ merged: true as const, detail: null as string | null })),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
merged: false as const,
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!mergeResult.merged) {
|
||||
// gh merge failures at this point are usually races (base advanced,
|
||||
// check flipped). Surface as conflict so the queue hands it to the
|
||||
// thread's agent rather than aborting the whole run.
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
outcome: "conflict" as const,
|
||||
detail: mergeResult.detail ?? "gh pr merge failed.",
|
||||
};
|
||||
}
|
||||
return { threadId: input.threadId, outcome: "merged" as const, detail: null };
|
||||
});
|
||||
|
||||
return ReviewService.of({
|
||||
getDiffPreview,
|
||||
summarizeThread,
|
||||
mergePullRequest,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -86,9 +86,7 @@ import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
|
||||
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
|
||||
import * as ServerSettings from "./serverSettings.ts";
|
||||
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
|
||||
import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
@@ -382,7 +380,6 @@ const buildAppUnderTest = (options?: {
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: defaultDesktopBootstrapToken,
|
||||
@@ -525,24 +522,6 @@ const buildAppUnderTest = (options?: {
|
||||
: ReviewService.layer.pipe(
|
||||
Layer.provideMerge(gitVcsDriverLayer),
|
||||
Layer.provide(vcsDriverRegistryLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(TextGeneration.TextGeneration)({
|
||||
generateThreadReview: () => Effect.die("TextGeneration not stubbed in this test"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
...options?.layers?.projectionSnapshotQuery,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(GitHubCli.GitHubCli)({
|
||||
execute: () => Effect.die("GitHubCli not stubbed in this test"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(ServerSettings.layerTest()),
|
||||
);
|
||||
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
|
||||
? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
|
||||
@@ -1349,8 +1328,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
"bearer-access-token",
|
||||
"dpop-access-token",
|
||||
]);
|
||||
// Desktop, so port-scoped: instances scan for a free port and share
|
||||
// 127.0.0.1, and cookies are not scoped by port.
|
||||
assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
@@ -3269,34 +3246,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("allows configured development origins through ServerConfig", () =>
|
||||
Effect.gen(function* () {
|
||||
const tailnetOrigin = "https://host.example.ts.net";
|
||||
yield* buildAppUnderTest({
|
||||
config: {
|
||||
devUrl: new URL(crossOriginClientOrigin),
|
||||
devAllowedOrigins: [tailnetOrigin],
|
||||
},
|
||||
});
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const response = yield* fetchEffect(sessionUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: tailnetOrigin,
|
||||
"access-control-request-method": "GET",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assertBrowserApiCorsPreflightHeaders(response.headers, {
|
||||
origin: tailnetOrigin,
|
||||
credentials: true,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
|
||||
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -222,8 +222,6 @@ const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.l
|
||||
const ReviewLayerLive = ReviewService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provide(TextGeneration.layer),
|
||||
Layer.provide(GitHubCli.layer),
|
||||
);
|
||||
|
||||
const VcsLayerLive = Layer.empty.pipe(
|
||||
|
||||
@@ -23,12 +23,10 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -51,34 +49,12 @@ const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
/**
|
||||
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
|
||||
* `structured_output` is the payload; the usage/cost fields are optional
|
||||
* telemetry surfaced to callers that ask for it (the review sweep shows
|
||||
* per-thread tokens and cost while it runs).
|
||||
* We only care about `structured_output`.
|
||||
*/
|
||||
const ClaudeOutputEnvelope = Schema.Struct({
|
||||
structured_output: Schema.Unknown,
|
||||
total_cost_usd: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
duration_api_ms: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
usage: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
input_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
output_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
cache_creation_input_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
cache_read_input_tokens: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
/** Telemetry a caller can opt into by passing an `onUsage` sink. */
|
||||
export interface ClaudeGenerationUsage {
|
||||
readonly inputTokens: number;
|
||||
readonly outputTokens: number;
|
||||
readonly costUsd?: number | undefined;
|
||||
readonly durationMs: number;
|
||||
}
|
||||
|
||||
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
const decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));
|
||||
|
||||
@@ -109,8 +85,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview",
|
||||
| "generateThreadTitle",
|
||||
value: unknown,
|
||||
detail: string,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
@@ -135,20 +110,16 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
onUsage,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ModelSelection;
|
||||
/** Optional sink for the CLI's reported token/cost telemetry. */
|
||||
onUsage?: ((usage: ClaudeGenerationUsage) => void) | undefined;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const jsonSchemaStr = yield* encodeJsonForOperation(
|
||||
operation,
|
||||
@@ -275,24 +246,6 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
}),
|
||||
);
|
||||
|
||||
if (onUsage) {
|
||||
const usage = envelope.usage ?? null;
|
||||
// Cache-creation and cache-read tokens are still input the model
|
||||
// processed; fold them in so the reported number matches billing.
|
||||
const inputTokens =
|
||||
(usage?.input_tokens ?? 0) +
|
||||
(usage?.cache_creation_input_tokens ?? 0) +
|
||||
(usage?.cache_read_input_tokens ?? 0);
|
||||
onUsage({
|
||||
inputTokens: Math.round(inputTokens),
|
||||
outputTokens: Math.round(usage?.output_tokens ?? 0),
|
||||
...(typeof envelope.total_cost_usd === "number"
|
||||
? { costUsd: envelope.total_cost_usd }
|
||||
: {}),
|
||||
durationMs: Math.round(envelope.duration_api_ms ?? 0),
|
||||
});
|
||||
}
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(outputSchemaJson);
|
||||
return yield* decodeOutput(envelope.structured_output).pipe(
|
||||
Effect.catchTags({
|
||||
@@ -402,39 +355,10 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("ClaudeTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
let usage: TextGeneration.ThreadReviewGenerationUsage | undefined;
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
onUsage: (reported) => {
|
||||
usage = reported;
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
...normalizeThreadReview(generated, input.isActive),
|
||||
...(usage !== undefined ? { usage } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -21,12 +21,10 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -100,8 +98,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview",
|
||||
| "generateThreadTitle",
|
||||
value: unknown,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
encodeJsonString(value).pipe(
|
||||
@@ -120,8 +117,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview",
|
||||
| "generateThreadTitle",
|
||||
attachments: TextGeneration.BranchNameGenerationInput["attachments"],
|
||||
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
@@ -163,8 +159,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
@@ -403,33 +398,10 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
} satisfies TextGeneration.ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("CodexTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
imagePaths: [],
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -15,11 +15,9 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -56,8 +54,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
@@ -258,32 +255,10 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
} satisfies TextGeneration.ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("CursorTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -16,11 +16,9 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -54,8 +52,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
@@ -250,32 +247,10 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
} satisfies TextGeneration.ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("GrokTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -22,12 +22,10 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
import {
|
||||
normalizeThreadReview,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -41,7 +39,6 @@ const OpenCodeTextGenerationOperation = Schema.Literals([
|
||||
"generatePrContent",
|
||||
"generateBranchName",
|
||||
"generateThreadTitle",
|
||||
"generateThreadReview",
|
||||
]);
|
||||
|
||||
type OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;
|
||||
@@ -256,8 +253,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
| "generateThreadTitle";
|
||||
}) =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
@@ -615,32 +611,10 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadReview: TextGeneration.TextGeneration["Service"]["generateThreadReview"] =
|
||||
Effect.fn("OpenCodeTextGeneration.generateThreadReview")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadReviewPrompt({
|
||||
title: input.title,
|
||||
isActive: input.isActive,
|
||||
firstUserMessage: input.firstUserMessage,
|
||||
recentMessages: input.recentMessages,
|
||||
pullRequest: input.pullRequest,
|
||||
});
|
||||
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateThreadReview",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return normalizeThreadReview(generated, input.isActive);
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
generateThreadReview,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -21,8 +21,6 @@ const makeStubTextGeneration = (
|
||||
generatePrContent: () => Effect.die("generatePrContent stub not configured for this test"),
|
||||
generateBranchName: () => Effect.die("generateBranchName stub not configured for this test"),
|
||||
generateThreadTitle: () => Effect.die("generateThreadTitle stub not configured for this test"),
|
||||
generateThreadReview: () =>
|
||||
Effect.die("generateThreadReview stub not configured for this test"),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
|
||||
@@ -67,48 +67,6 @@ export interface ThreadTitleGenerationResult {
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface ThreadReviewPullRequestContext {
|
||||
number: number;
|
||||
state: "open" | "closed" | "merged";
|
||||
reviewDecision: string | null;
|
||||
checksPassing: boolean | null;
|
||||
mergeable: boolean | null;
|
||||
recentComments: ReadonlyArray<{ author: string; createdAt: string; body: string }>;
|
||||
}
|
||||
|
||||
export interface ThreadReviewGenerationInput {
|
||||
cwd: string;
|
||||
title: string;
|
||||
/** Active threads (running session or awaiting the user) never get a settle
|
||||
recommendation. */
|
||||
isActive: boolean;
|
||||
firstUserMessage: string | null;
|
||||
recentMessages: ReadonlyArray<{ role: "user" | "assistant" | "system"; text: string }>;
|
||||
/** Live PR state + recent comments when the thread has one. */
|
||||
pullRequest?: ThreadReviewPullRequestContext | undefined;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
export interface ThreadReviewGenerationUsage {
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
costUsd?: number | undefined;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface ThreadReviewGenerationResult {
|
||||
/** Provider-reported cost of this generation, when available. */
|
||||
usage?: ThreadReviewGenerationUsage | undefined;
|
||||
summary: string;
|
||||
/** One imperative sentence: the user's single next action. */
|
||||
nextStep: string;
|
||||
/** Null when the current title is still accurate. */
|
||||
suggestedTitle: string | null;
|
||||
recommendSettle: boolean;
|
||||
settleReason: string | null;
|
||||
}
|
||||
|
||||
export interface TextGenerationService {
|
||||
generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
@@ -116,7 +74,6 @@ export interface TextGenerationService {
|
||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
|
||||
generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;
|
||||
generateThreadReview(input: ThreadReviewGenerationInput): Promise<ThreadReviewGenerationResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,14 +109,6 @@ export class TextGeneration extends Context.Service<
|
||||
readonly generateThreadTitle: (
|
||||
input: ThreadTitleGenerationInput,
|
||||
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
|
||||
|
||||
/**
|
||||
* Review a thread transcript for the work-review sweep: summary,
|
||||
* optional corrected title, and a settle recommendation.
|
||||
*/
|
||||
readonly generateThreadReview: (
|
||||
input: ThreadReviewGenerationInput,
|
||||
) => Effect.Effect<ThreadReviewGenerationResult, TextGenerationError>;
|
||||
}
|
||||
>()("t3/textGeneration/TextGeneration") {}
|
||||
|
||||
@@ -170,8 +119,7 @@ type TextGenerationOp =
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle"
|
||||
| "generateThreadReview";
|
||||
| "generateThreadTitle";
|
||||
|
||||
const resolveInstance = (
|
||||
registry: ProviderInstanceRegistry.ProviderInstanceRegistry["Service"],
|
||||
@@ -211,10 +159,6 @@ export const makeTextGenerationFromRegistry = (
|
||||
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),
|
||||
),
|
||||
generateThreadReview: (input) =>
|
||||
resolveInstance(registry, "generateThreadReview", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((textGeneration) => textGeneration.generateThreadReview(input)),
|
||||
),
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
|
||||
@@ -4,14 +4,9 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadReviewPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
normalizeThreadReview,
|
||||
sanitizeThreadTitle,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import { normalizeCliError, sanitizeThreadTitle } from "./TextGenerationUtils.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
describe("buildCommitMessagePrompt", () => {
|
||||
@@ -141,91 +136,6 @@ describe("buildThreadTitlePrompt", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadReviewPrompt", () => {
|
||||
it("includes title, first user message, and transcript", () => {
|
||||
const result = buildThreadReviewPrompt({
|
||||
title: "New thread",
|
||||
isActive: false,
|
||||
firstUserMessage: "Fix the settle default",
|
||||
recentMessages: [
|
||||
{ role: "user", text: "Fix the settle default" },
|
||||
{ role: "assistant", text: "Done, merged." },
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Current title: New thread");
|
||||
expect(result.prompt).toContain("Fix the settle default");
|
||||
expect(result.prompt).toContain("[assistant] Done, merged.");
|
||||
expect(result.prompt).not.toContain("ACTIVE");
|
||||
});
|
||||
|
||||
it("adds the never-settle rule for active threads", () => {
|
||||
const result = buildThreadReviewPrompt({
|
||||
title: "Working thread",
|
||||
isActive: true,
|
||||
firstUserMessage: "Do a thing",
|
||||
recentMessages: [],
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("recommendSettle must be false");
|
||||
expect(result.prompt).toContain("(no messages)");
|
||||
});
|
||||
|
||||
it("caps the transcript to the most recent 20 messages", () => {
|
||||
const result = buildThreadReviewPrompt({
|
||||
title: "Long thread",
|
||||
isActive: false,
|
||||
firstUserMessage: "start",
|
||||
recentMessages: Array.from({ length: 30 }, (_, index) => ({
|
||||
role: "assistant" as const,
|
||||
text: `message-${index}`,
|
||||
})),
|
||||
});
|
||||
|
||||
expect(result.prompt).not.toContain("message-9\n");
|
||||
expect(result.prompt).toContain("message-10");
|
||||
expect(result.prompt).toContain("message-29");
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeThreadReview", () => {
|
||||
const raw = {
|
||||
summary: " Work finished. ",
|
||||
nextStep: " Settle it. ",
|
||||
suggestedTitle: '"Ship settle default"',
|
||||
recommendSettle: true,
|
||||
settleReason: " PR merged. ",
|
||||
};
|
||||
|
||||
it("sanitizes fields and keeps settle recommendation for inactive threads", () => {
|
||||
expect(normalizeThreadReview(raw, false)).toEqual({
|
||||
summary: "Work finished.",
|
||||
nextStep: "Settle it.",
|
||||
suggestedTitle: "Ship settle default",
|
||||
recommendSettle: true,
|
||||
settleReason: "PR merged.",
|
||||
});
|
||||
});
|
||||
|
||||
it("forces recommendSettle off for active threads even if the model says settle", () => {
|
||||
const result = normalizeThreadReview(raw, true);
|
||||
expect(result.recommendSettle).toBe(false);
|
||||
expect(result.settleReason).toBeNull();
|
||||
});
|
||||
|
||||
it("drops empty and placeholder title suggestions", () => {
|
||||
expect(
|
||||
normalizeThreadReview({ ...raw, suggestedTitle: " " }, false).suggestedTitle,
|
||||
).toBeNull();
|
||||
expect(
|
||||
normalizeThreadReview({ ...raw, suggestedTitle: "New thread" }, false).suggestedTitle,
|
||||
).toBeNull();
|
||||
expect(
|
||||
normalizeThreadReview({ ...raw, suggestedTitle: null }, false).suggestedTitle,
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeThreadTitle", () => {
|
||||
it("truncates long titles with the shared sidebar-safe limit", () => {
|
||||
expect(
|
||||
|
||||
@@ -216,116 +216,3 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
||||
|
||||
return { prompt, outputSchema };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread review (work-review sweep)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ThreadReviewMessage {
|
||||
role: "user" | "assistant" | "system";
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ThreadReviewPromptInput {
|
||||
title: string;
|
||||
/** True when the thread has a running session or pending approvals/input.
|
||||
Active threads must never get a settle recommendation. */
|
||||
isActive: boolean;
|
||||
firstUserMessage: string | null;
|
||||
recentMessages: ReadonlyArray<ThreadReviewMessage>;
|
||||
pullRequest?:
|
||||
| {
|
||||
number: number;
|
||||
state: "open" | "closed" | "merged";
|
||||
reviewDecision: string | null;
|
||||
checksPassing: boolean | null;
|
||||
mergeable: boolean | null;
|
||||
recentComments: ReadonlyArray<{ author: string; createdAt: string; body: string }>;
|
||||
}
|
||||
| undefined;
|
||||
}
|
||||
|
||||
function renderPullRequestSection(
|
||||
pullRequest: NonNullable<ThreadReviewPromptInput["pullRequest"]>,
|
||||
): string {
|
||||
const lines = [
|
||||
`PR #${pullRequest.number}: state=${pullRequest.state}`,
|
||||
`review decision: ${pullRequest.reviewDecision ?? "none required"}`,
|
||||
`CI checks passing: ${pullRequest.checksPassing === null ? "unknown" : String(pullRequest.checksPassing)}`,
|
||||
`mergeable: ${pullRequest.mergeable === null ? "unknown" : String(pullRequest.mergeable)}`,
|
||||
];
|
||||
if (pullRequest.recentComments.length > 0) {
|
||||
lines.push("Recent PR comments (newest last):");
|
||||
for (const comment of pullRequest.recentComments) {
|
||||
lines.push(`[${comment.author} @ ${comment.createdAt}] ${comment.body}`);
|
||||
}
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
const THREAD_REVIEW_RECENT_MESSAGE_COUNT = 20;
|
||||
const THREAD_REVIEW_MESSAGE_CHAR_LIMIT = 2_000;
|
||||
|
||||
export function buildThreadReviewPrompt(input: ThreadReviewPromptInput) {
|
||||
const recent = input.recentMessages.slice(-THREAD_REVIEW_RECENT_MESSAGE_COUNT);
|
||||
const transcript = recent
|
||||
.map(
|
||||
(message) =>
|
||||
`[${message.role}] ${limitSection(message.text, THREAD_REVIEW_MESSAGE_CHAR_LIMIT)}`,
|
||||
)
|
||||
.join("\n\n");
|
||||
|
||||
const prompt = [
|
||||
"You review a coding-agent conversation thread and report its state.",
|
||||
"Return a JSON object with keys: summary, nextStep, suggestedTitle, recommendSettle, settleReason.",
|
||||
"Rules:",
|
||||
"- summary: ONE sentence, max ~25 words: what was asked and where it landed",
|
||||
"- nextStep: a COMMAND to the user, max 10 words. Start with a verb. Never describe status.",
|
||||
" GOOD: 'Merge PR #4415.'",
|
||||
" GOOD: 'Answer the agent's question about auth scopes.'",
|
||||
" GOOD: 'Settle this thread.'",
|
||||
" GOOD: 'Wait — agent still working.'",
|
||||
" BAD: 'The requested comparison and hosted write-up are complete, and...' (status recap, not a command)",
|
||||
" BAD: 'You should probably consider reviewing the PR when you have time.' (hedging filler)",
|
||||
"- suggestedTitle: a corrected 3-8 word title ONLY if the current title is misleading or a placeholder like 'New thread'; otherwise null",
|
||||
"- recommendSettle: true ONLY when the work clearly concluded (done, abandoned, or superseded) and nothing awaits the user",
|
||||
"- settleReason: one short sentence justifying recommendSettle, or null when recommendSettle is false",
|
||||
"- be conservative: when in doubt, do not suggest a title change and do not recommend settling",
|
||||
...(input.isActive
|
||||
? [
|
||||
"- this thread is still ACTIVE (running or awaiting the user): recommendSettle must be false",
|
||||
]
|
||||
: []),
|
||||
...(input.pullRequest
|
||||
? [
|
||||
"- weigh the PR context heavily: an open PR awaiting the user's review/merge is NOT settleable; a merged PR with no follow-up work is",
|
||||
"- if the PR is open, CI is green, reviews approve it, and it is mergeable, nextStep should be to merge it",
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
`Current title: ${input.title}`,
|
||||
...(input.pullRequest
|
||||
? [
|
||||
"",
|
||||
"Pull request status:",
|
||||
limitSection(renderPullRequestSection(input.pullRequest), 6_000),
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
"First user message:",
|
||||
limitSection(input.firstUserMessage ?? "(none)", THREAD_REVIEW_MESSAGE_CHAR_LIMIT),
|
||||
"",
|
||||
`Most recent messages (up to ${THREAD_REVIEW_RECENT_MESSAGE_COUNT}):`,
|
||||
limitSection(transcript.length > 0 ? transcript : "(no messages)", 24_000),
|
||||
].join("\n");
|
||||
|
||||
const outputSchema = Schema.Struct({
|
||||
summary: Schema.String,
|
||||
nextStep: Schema.String,
|
||||
suggestedTitle: Schema.NullOr(Schema.String),
|
||||
recommendSettle: Schema.Boolean,
|
||||
settleReason: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
return { prompt, outputSchema };
|
||||
}
|
||||
@@ -63,58 +63,6 @@ export function sanitizeThreadTitle(raw: string): string {
|
||||
return `${normalized.slice(0, 47).trimEnd()}...`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise a raw thread-review generation into the service result shape:
|
||||
* collapse whitespace, drop empty/no-op title suggestions, and force
|
||||
* `recommendSettle` off for active threads regardless of model output.
|
||||
*/
|
||||
export function normalizeThreadReview(
|
||||
raw: {
|
||||
summary: string;
|
||||
nextStep: string;
|
||||
suggestedTitle: string | null;
|
||||
recommendSettle: boolean;
|
||||
settleReason: string | null;
|
||||
},
|
||||
isActive: boolean,
|
||||
): {
|
||||
summary: string;
|
||||
nextStep: string;
|
||||
suggestedTitle: string | null;
|
||||
recommendSettle: boolean;
|
||||
settleReason: string | null;
|
||||
} {
|
||||
const summary = raw.summary.trim().replace(/\s+/g, " ");
|
||||
// Backstop against rambling: first sentence only, hard-capped. The prompt
|
||||
// asks for a <=10-word command, but models drift — never render a recap.
|
||||
const nextStepFirstSentence =
|
||||
raw.nextStep
|
||||
.trim()
|
||||
.replace(/\s+/g, " ")
|
||||
.match(/^[^.!?]*[.!?]?/)?.[0]
|
||||
?.trim() ?? "";
|
||||
const nextStep =
|
||||
nextStepFirstSentence.length > 80
|
||||
? `${nextStepFirstSentence.slice(0, 77).trimEnd()}...`
|
||||
: nextStepFirstSentence;
|
||||
const suggestedTitle =
|
||||
raw.suggestedTitle && raw.suggestedTitle.trim().length > 0
|
||||
? sanitizeThreadTitle(raw.suggestedTitle)
|
||||
: null;
|
||||
const recommendSettle = raw.recommendSettle && !isActive;
|
||||
const settleReason =
|
||||
recommendSettle && raw.settleReason && raw.settleReason.trim().length > 0
|
||||
? raw.settleReason.trim().replace(/\s+/g, " ")
|
||||
: null;
|
||||
return {
|
||||
summary: summary.length > 0 ? summary : "No summary available.",
|
||||
nextStep: nextStep.length > 0 ? nextStep : "Review this thread.",
|
||||
suggestedTitle: suggestedTitle === "New thread" ? null : suggestedTitle,
|
||||
recommendSettle,
|
||||
settleReason,
|
||||
};
|
||||
}
|
||||
|
||||
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
|
||||
function cliLabel(cliName: string): string {
|
||||
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
|
||||
|
||||
@@ -332,8 +332,6 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.vcsSwitchRef, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.vcsInit, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.reviewGetDiffPreview, AuthReviewWriteScope],
|
||||
[WS_METHODS.reviewSummarizeThread, AuthReviewWriteScope],
|
||||
[WS_METHODS.reviewMergePullRequest, AuthReviewWriteScope],
|
||||
[WS_METHODS.terminalOpen, AuthTerminalOperateScope],
|
||||
[WS_METHODS.terminalAttach, AuthTerminalOperateScope],
|
||||
[WS_METHODS.terminalWrite, AuthTerminalOperateScope],
|
||||
@@ -1854,14 +1852,6 @@ const makeWsRpcLayer = (
|
||||
observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {
|
||||
"rpc.aggregate": "review",
|
||||
}),
|
||||
[WS_METHODS.reviewSummarizeThread]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.reviewSummarizeThread, review.summarizeThread(input), {
|
||||
"rpc.aggregate": "review",
|
||||
}),
|
||||
[WS_METHODS.reviewMergePullRequest]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.reviewMergePullRequest, review.mergePullRequest(input), {
|
||||
"rpc.aggregate": "review",
|
||||
}),
|
||||
[WS_METHODS.terminalOpen]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
|
||||
"rpc.aggregate": "terminal",
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
@@ -140,7 +140,6 @@ import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import {
|
||||
AlarmClockIcon,
|
||||
CheckCircle2Icon,
|
||||
ChevronDownIcon,
|
||||
GitBranchIcon,
|
||||
@@ -3845,24 +3844,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
hasDedicatedWorktree: (activeThread?.worktreePath ?? null) !== null,
|
||||
});
|
||||
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
|
||||
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
|
||||
const nowMinute = useNowMinute();
|
||||
const activeThreadSnoozed =
|
||||
activeThreadShell !== null &&
|
||||
supportsSnooze &&
|
||||
effectiveSnoozed(activeThreadShell, { now: new Date().toISOString() });
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
void snoozeWakeTick;
|
||||
if (!activeThreadSnoozed) return;
|
||||
const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
|
||||
if (!Number.isFinite(wakeAtMs)) return;
|
||||
const id = window.setTimeout(
|
||||
() => bumpSnoozeWakeTick((tick) => tick + 1),
|
||||
Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
|
||||
);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
|
||||
const activeThreadSettled = useMemo(() => {
|
||||
if (activeThreadShell === null || !supportsSettlement) return false;
|
||||
return effectiveSettled(activeThreadShell, {
|
||||
@@ -3908,34 +3890,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
|
||||
}
|
||||
}, [activeThreadRef, unsettleThreadMutation]);
|
||||
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
|
||||
const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
|
||||
const handleUnsnoozeActiveThread = useCallback(async () => {
|
||||
if (!activeThreadRef) return;
|
||||
const threadKey = scopedThreadKey(activeThreadRef);
|
||||
setUnsnoozingThreadKey(threadKey);
|
||||
try {
|
||||
const result = await unsnoozeThreadMutation({
|
||||
environmentId: activeThreadRef.environmentId,
|
||||
input: { threadId: activeThreadRef.threadId, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to wake thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
|
||||
}
|
||||
}, [activeThreadRef, unsnoozeThreadMutation]);
|
||||
const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
|
||||
const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
|
||||
// Once revealed for a given mismatch, the banner stays mounted until the
|
||||
@@ -4045,48 +3999,29 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
]);
|
||||
// The stack renders items[0] front-most and tucks the rest behind hover, so
|
||||
// ordering is priority: system banners, then the branch-mismatch notice,
|
||||
// and the informational parked-thread banner last — it must never cover another.
|
||||
const parkedThreadBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
|
||||
if (!activeThreadSnoozed && !activeThreadSettled) {
|
||||
// and the informational settled banner last — it must never cover another.
|
||||
const settledComposerBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
|
||||
if (!activeThreadSettled) {
|
||||
return null;
|
||||
}
|
||||
const isSnoozed = activeThreadSnoozed;
|
||||
return {
|
||||
id: `thread-${isSnoozed ? "snoozed" : "settled"}:${activeThread?.id ?? "unknown"}`,
|
||||
id: `thread-settled:${activeThread?.id ?? "unknown"}`,
|
||||
variant: "info",
|
||||
icon: isSnoozed ? <AlarmClockIcon /> : <CheckCircle2Icon />,
|
||||
title: `This thread is ${isSnoozed ? "snoozed" : "settled"}`,
|
||||
description: isSnoozed
|
||||
? "Sending a message wakes it and moves it back to Active in the sidebar."
|
||||
: "Sending a message moves it back to Active in the sidebar.",
|
||||
icon: <CheckCircle2Icon />,
|
||||
title: "This thread is settled",
|
||||
description: "Sending a message moves it back to Active in the sidebar.",
|
||||
actions: (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isSnoozed ? isUnsnoozing : isUnsettling}
|
||||
onClick={() =>
|
||||
void (isSnoozed ? handleUnsnoozeActiveThread() : handleUnsettleActiveThread())
|
||||
}
|
||||
disabled={isUnsettling}
|
||||
onClick={() => void handleUnsettleActiveThread()}
|
||||
>
|
||||
{isSnoozed
|
||||
? isUnsnoozing
|
||||
? "Waking..."
|
||||
: "Wake now"
|
||||
: isUnsettling
|
||||
? "Un-settling..."
|
||||
: "Un-settle"}
|
||||
{isUnsettling ? "Un-settling..." : "Un-settle"}
|
||||
</Button>
|
||||
),
|
||||
};
|
||||
}, [
|
||||
activeThread?.id,
|
||||
activeThreadSettled,
|
||||
activeThreadSnoozed,
|
||||
handleUnsnoozeActiveThread,
|
||||
handleUnsettleActiveThread,
|
||||
isUnsnoozing,
|
||||
isUnsettling,
|
||||
]);
|
||||
}, [activeThread?.id, activeThreadSettled, handleUnsettleActiveThread, isUnsettling]);
|
||||
const handleRestoreThreadBranch = useCallback(() => {
|
||||
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
|
||||
setBranchRestoreConfirmOpen(true);
|
||||
@@ -4095,9 +4030,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
void handleSwitchCheckoutToThread();
|
||||
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
|
||||
const settledItems = settledComposerBannerItem === null ? [] : [settledComposerBannerItem];
|
||||
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
|
||||
return [...systemComposerBannerItems, ...parkedThreadItems];
|
||||
return [...systemComposerBannerItems, ...settledItems];
|
||||
}
|
||||
return [
|
||||
...systemComposerBannerItems,
|
||||
@@ -4140,14 +4075,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setBranchMismatchDismissTick((tick) => tick + 1);
|
||||
},
|
||||
},
|
||||
...parkedThreadItems,
|
||||
...settledItems,
|
||||
];
|
||||
}, [
|
||||
activeBranchMismatchKey,
|
||||
handleRestoreThreadBranch,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
parkedThreadBannerItem,
|
||||
settledComposerBannerItem,
|
||||
showBranchMismatchBanner,
|
||||
systemComposerBannerItems,
|
||||
]);
|
||||
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsDownUpIcon,
|
||||
ChevronsUpDownIcon,
|
||||
Columns2Icon,
|
||||
PilcrowIcon,
|
||||
Rows3Icon,
|
||||
@@ -34,7 +32,6 @@ import {
|
||||
resolveDiffThemeName,
|
||||
resolveFileDiffPath,
|
||||
} from "../lib/diffRendering";
|
||||
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
@@ -42,7 +39,6 @@ import { useClientSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
|
||||
import { Button } from "./ui/button";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
import { Switch } from "./ui/switch";
|
||||
import {
|
||||
@@ -450,8 +446,6 @@ export default function DiffPanel({
|
||||
}),
|
||||
[collapsedDiffFileKeys, renderableFiles],
|
||||
);
|
||||
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
|
||||
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath) return;
|
||||
@@ -502,18 +496,6 @@ export default function DiffPanel({
|
||||
[collapseScopeKey],
|
||||
);
|
||||
|
||||
const toggleDiffFileCollapse = useCallback(() => {
|
||||
setCollapsedDiffFiles((current) => {
|
||||
const currentKeys =
|
||||
current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
|
||||
|
||||
return {
|
||||
scopeKey: collapseScopeKey,
|
||||
fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
|
||||
};
|
||||
});
|
||||
}, [collapseScopeKey, diffFileKeys]);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!routeThreadRef) return;
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
|
||||
@@ -713,30 +695,6 @@ export default function DiffPanel({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
|
||||
{codeViewFiles.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
|
||||
onClick={toggleDiffFileCollapse}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDiffFilesCollapsed ? (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<ToggleGroup
|
||||
className="shrink-0"
|
||||
variant="outline"
|
||||
@@ -866,7 +824,7 @@ export default function DiffPanel({
|
||||
<AnnotatableCodeView
|
||||
viewerRef={codeViewRef}
|
||||
key={collapseScopeKey ?? reviewSectionId}
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto [&>div>div:last-child]:top-0! [&>div>div:last-child]:bottom-auto!"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto"
|
||||
files={codeViewFiles}
|
||||
sectionId={reviewSectionId}
|
||||
sectionTitle={reviewSectionTitle}
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveSnoozePresets, snoozeWakeDescription, snoozeWakeLabel } from "./Sidebar.snooze";
|
||||
|
||||
// Local-time constructor so preset math is timezone-stable in tests.
|
||||
function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
|
||||
return new Date(year, month - 1, day, hour, minute, 0, 0);
|
||||
}
|
||||
|
||||
describe("resolveSnoozePresets", () => {
|
||||
it("offers hour, evening, tomorrow, next week in the morning", () => {
|
||||
// Wednesday 2026-04-08 10:00 local.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
expect(presets.map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"evening",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
const evening = presets.find((preset) => preset.id === "evening");
|
||||
expect(new Date(evening!.snoozedUntil).getHours()).toBe(18);
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
const tomorrowDate = new Date(tomorrow!.snoozedUntil);
|
||||
expect(tomorrowDate.getDate()).toBe(9);
|
||||
expect(tomorrowDate.getHours()).toBe(9);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
const nextWeekDate = new Date(nextWeek!.snoozedUntil);
|
||||
expect(nextWeekDate.getDay()).toBe(1);
|
||||
expect(nextWeekDate.getDate()).toBe(13);
|
||||
});
|
||||
|
||||
it("whenLabel complements the label instead of repeating it", () => {
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
for (const preset of presets) {
|
||||
// Day words live in the label column; the time column is time-only
|
||||
// (plus a weekday for next week, which names a different day).
|
||||
expect(preset.whenLabel.toLowerCase()).not.toContain("tomorrow");
|
||||
}
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
expect(tomorrow!.whenLabel).toMatch(/9/);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
expect(nextWeek!.whenLabel).toMatch(/Mon/);
|
||||
});
|
||||
|
||||
it("drops the evening preset once evening is near or past", () => {
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 17, 30)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 21)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
});
|
||||
|
||||
it("puts next week a full week out when today is Monday", () => {
|
||||
// Monday 2026-04-06.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 6, 10));
|
||||
const nextWeek = new Date(presets.find((preset) => preset.id === "next-week")!.snoozedUntil);
|
||||
expect(nextWeek.getDay()).toBe(1);
|
||||
expect(nextWeek.getDate()).toBe(13);
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeLabel", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("formats minutes, hours, and days, rounding up", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 30 * 60_000).toISOString(), now)).toBe("30m");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 90 * 60_000).toISOString(), now)).toBe("2h");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 26 * 3_600_000).toISOString(), now)).toBe("2d");
|
||||
});
|
||||
|
||||
it("reports now for past and malformed wake times", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() - 1000).toISOString(), now)).toBe("now");
|
||||
expect(snoozeWakeLabel("not-a-date", now)).toBe("now");
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeDescription", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("uses bare time today, 'tomorrow' next day, weekday within the week", () => {
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now)).not.toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 9, 9).toISOString(), now)).toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 13, 9).toISOString(), now)).toMatch(/Mon/);
|
||||
});
|
||||
});
|
||||
@@ -1,127 +0,0 @@
|
||||
/**
|
||||
* Snooze preset resolution for the sidebar snooze menu. Pure functions so
|
||||
* the preset math (evening/tomorrow/next-week boundaries) is unit-testable
|
||||
* without a DOM.
|
||||
*
|
||||
* Presets deliberately skew short: agent-thread rhythms are hours (a CI
|
||||
* run, a teammate review, the next work session), not days.
|
||||
*/
|
||||
import { parseTimestampDate } from "../timestampFormat";
|
||||
|
||||
type SnoozePresetId = "hour" | "evening" | "tomorrow" | "next-week";
|
||||
|
||||
export interface SnoozePreset {
|
||||
readonly id: SnoozePresetId;
|
||||
readonly label: string;
|
||||
/** Menu-row time column. Complements the label instead of repeating it:
|
||||
"Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
|
||||
readonly whenLabel: string;
|
||||
/** ISO wake time. */
|
||||
readonly snoozedUntil: string;
|
||||
}
|
||||
|
||||
function timeOfDayLabel(date: Date): string {
|
||||
return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
}
|
||||
|
||||
const EVENING_HOUR = 18;
|
||||
const MORNING_HOUR = 9;
|
||||
const HOUR_MS = 60 * 60 * 1_000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
|
||||
function atHour(base: Date, hour: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setHours(hour, 0, 0, 0);
|
||||
return next;
|
||||
}
|
||||
|
||||
// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
|
||||
// land on the wrong local day across DST transitions (a spring-forward day
|
||||
// is 23 hours, so 23:30 + 24h skips the whole next day).
|
||||
function addDays(base: Date, days: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setDate(next.getDate() + days);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Presets for "snooze until", computed against local time. "This evening"
|
||||
* only appears while it is still meaningfully before evening; after that
|
||||
* the list starts at "Tomorrow".
|
||||
*/
|
||||
export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
|
||||
const inAnHour = new Date(now.getTime() + HOUR_MS);
|
||||
const presets: SnoozePreset[] = [
|
||||
{
|
||||
id: "hour",
|
||||
label: "In 1 hour",
|
||||
whenLabel: timeOfDayLabel(inAnHour),
|
||||
snoozedUntil: inAnHour.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
const evening = atHour(now, EVENING_HOUR);
|
||||
// Suppress the evening preset once it is within an hour (or past): it
|
||||
// would duplicate "In 1 hour" or point at the past.
|
||||
if (evening.getTime() - now.getTime() > HOUR_MS) {
|
||||
presets.push({
|
||||
id: "evening",
|
||||
label: "This evening",
|
||||
whenLabel: timeOfDayLabel(evening),
|
||||
snoozedUntil: evening.toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
const tomorrow = atHour(addDays(now, 1), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "tomorrow",
|
||||
label: "Tomorrow",
|
||||
whenLabel: timeOfDayLabel(tomorrow),
|
||||
snoozedUntil: tomorrow.toISOString(),
|
||||
});
|
||||
|
||||
// Next Monday 9:00 (a week out when today is Monday).
|
||||
const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
|
||||
const nextWeek = atHour(addDays(now, daysUntilMonday), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "next-week",
|
||||
label: "Next week",
|
||||
whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${timeOfDayLabel(nextWeek)}`,
|
||||
snoozedUntil: nextWeek.toISOString(),
|
||||
});
|
||||
|
||||
return presets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
|
||||
* round up so a snooze never reads "0m" while still hidden.
|
||||
*/
|
||||
export function snoozeWakeLabel(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "now";
|
||||
const remainingMs = wake.getTime() - now.getTime();
|
||||
if (remainingMs <= 0) return "now";
|
||||
if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
|
||||
if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
|
||||
return `${Math.ceil(remainingMs / DAY_MS)}d`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human wake time for menus and toasts: "tomorrow 9:00", "Mon 9:00",
|
||||
* "17:30" (today).
|
||||
*/
|
||||
export function snoozeWakeDescription(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "";
|
||||
const time = wake.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
const startOfToday = new Date(now);
|
||||
startOfToday.setHours(0, 0, 0, 0);
|
||||
const dayDelta = Math.floor((wake.getTime() - startOfToday.getTime()) / DAY_MS);
|
||||
if (dayDelta === 0) return time;
|
||||
if (dayDelta === 1) return `tomorrow ${time}`;
|
||||
const weekday = wake.toLocaleDateString(undefined, { weekday: "short" });
|
||||
if (dayDelta < 7) return `${weekday} ${time}`;
|
||||
const date = wake.toLocaleDateString(undefined, { month: "short", day: "numeric" });
|
||||
return `${date}, ${time}`;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,7 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
settledPrHoverColorClass,
|
||||
} from "./ThreadStatusIndicators";
|
||||
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
@@ -74,23 +70,4 @@ describe("prStatusIndicator", () => {
|
||||
tooltipTitle: "PR branch",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses red for closed pull requests", () => {
|
||||
const closedPr = status().pr;
|
||||
if (!closedPr) throw new Error("Expected pull request fixture");
|
||||
|
||||
expect(prStatusIndicator({ ...closedPr, state: "closed" }, undefined)?.colorClass).toContain(
|
||||
"text-red-600",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("settledPrHoverColorClass", () => {
|
||||
it.each([
|
||||
["open", "text-emerald-600"],
|
||||
["merged", "text-violet-600"],
|
||||
["closed", "text-red-600"],
|
||||
] as const)("restores the %s pull request color on row hover", (state, colorClass) => {
|
||||
expect(settledPrHoverColorClass(state)).toContain(`group-hover/v2-row:${colorClass}`);
|
||||
});
|
||||
});
|
||||
@@ -35,17 +35,6 @@ export interface TerminalStatusIndicator {
|
||||
|
||||
export type ThreadPr = VcsStatusResult["pr"];
|
||||
|
||||
export function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"]): string {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return "group-hover/v2-row:text-emerald-600 dark:group-hover/v2-row:text-emerald-300/90";
|
||||
case "merged":
|
||||
return "group-hover/v2-row:text-violet-600 dark:group-hover/v2-row:text-violet-300/90";
|
||||
case "closed":
|
||||
return "group-hover/v2-row:text-red-600 dark:group-hover/v2-row:text-red-300/90";
|
||||
}
|
||||
}
|
||||
|
||||
export function prStatusIndicator(
|
||||
pr: ThreadPr,
|
||||
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
|
||||
@@ -76,7 +65,7 @@ export function prStatusIndicator(
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: `${presentation.shortName} closed`,
|
||||
colorClass: "text-red-600 dark:text-red-300/90",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip,
|
||||
tooltipLead,
|
||||
tooltipTitle: pr.title,
|
||||
|
||||
@@ -434,7 +434,6 @@ describe("MessagesTimeline", () => {
|
||||
|
||||
expect(markup).not.toContain("Show full message");
|
||||
expect(markup).toContain('data-user-message-collapsible="false"');
|
||||
expect(markup).toContain("rounded-2xl bg-accent p-3");
|
||||
});
|
||||
|
||||
it("renders inline terminal labels with the composer chip UI", () => {
|
||||
|
||||
@@ -890,7 +890,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
|
||||
return (
|
||||
<div className="group flex flex-col items-end gap-1">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-accent p-3">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-secondary p-3">
|
||||
{regularImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
|
||||
@@ -51,7 +51,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
contentClassName="flex w-full items-center gap-3"
|
||||
className={cn(
|
||||
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
|
||||
"hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-highlighted:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0 [&[data-highlighted][data-selected]]:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))]",
|
||||
"data-highlighted:bg-muted/56 data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0",
|
||||
props.disabledReason &&
|
||||
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
|
||||
)}
|
||||
|
||||
@@ -521,7 +521,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
<div
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-xl text-popover-foreground"
|
||||
data-model-picker-content="true"
|
||||
>
|
||||
{/* Sidebar */}
|
||||
@@ -568,23 +568,18 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
handleModelSelect(slug, instanceId);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
|
||||
showSidebar && "border-l",
|
||||
)}
|
||||
>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<div className="-translate-y-px rounded-lg bg-accent px-2 py-1">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
inputClassName="rounded-none bg-transparent text-sm placeholder:text-muted-foreground/80"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/80" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
|
||||
@@ -97,10 +97,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
|
||||
data-model-picker-sidebar="true"
|
||||
>
|
||||
<div className="w-12 shrink-0 overflow-hidden bg-muted/60" data-model-picker-sidebar="true">
|
||||
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<div
|
||||
ref={sidebarContentRef}
|
||||
@@ -118,14 +115,14 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
) : null}
|
||||
{/* Favorites section */}
|
||||
{showFavorites ? (
|
||||
<div className="mb-1 border-b pb-1">
|
||||
<div className="mb-1 pb-1">
|
||||
<div className="relative w-full">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
)}
|
||||
onClick={() => handleSelect("favorites")}
|
||||
type="button"
|
||||
@@ -172,7 +169,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
<button
|
||||
data-model-picker-provider={entry.instanceId}
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
|
||||
)}
|
||||
data-provider-accent-color={entry.accentColor}
|
||||
|
||||
@@ -187,8 +187,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup
|
||||
align="start"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [-webkit-backdrop-filter:none]! [--viewport-inline-padding:0] [backdrop-filter:none]!"
|
||||
viewportClassName="rounded-lg !overflow-hidden p-0"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0]"
|
||||
viewportClassName="!overflow-hidden p-0"
|
||||
>
|
||||
<ModelPickerContent
|
||||
activeInstanceId={activeInstanceId}
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
import { buildTraitsTriggerDisplay } from "./TraitsPicker";
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
options: ReadonlyArray<{ id: string; label: string }>,
|
||||
currentValue: string,
|
||||
): Extract<ProviderOptionDescriptor, { type: "select" }> {
|
||||
return { id, label: id, type: "select", options: [...options], currentValue };
|
||||
}
|
||||
|
||||
function fastModeDescriptor(
|
||||
currentValue: boolean,
|
||||
): Extract<ProviderOptionDescriptor, { type: "boolean" }> {
|
||||
return { id: "fastMode", label: "Fast Mode", type: "boolean", currentValue };
|
||||
}
|
||||
|
||||
const EFFORT = selectDescriptor(
|
||||
"effort",
|
||||
[
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "max", label: "Max" },
|
||||
],
|
||||
"high",
|
||||
);
|
||||
const CONTEXT_WINDOW = selectDescriptor(
|
||||
"contextWindow",
|
||||
[
|
||||
{ id: "200k", label: "200k" },
|
||||
{ id: "1m", label: "1M" },
|
||||
],
|
||||
"1m",
|
||||
);
|
||||
|
||||
function display(descriptors: ReadonlyArray<ProviderOptionDescriptor>, fastModeEnabled: boolean) {
|
||||
return buildTraitsTriggerDisplay({
|
||||
descriptors,
|
||||
primarySelectDescriptorId: "effort",
|
||||
ultrathinkPromptControlled: false,
|
||||
fastModeEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
describe("buildTraitsTriggerDisplay", () => {
|
||||
it("omits fast mode from the label entirely when it is off", () => {
|
||||
expect(display([EFFORT, fastModeDescriptor(false), CONTEXT_WINDOW], false)).toEqual({
|
||||
label: "High · 1M",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the bolt instead of a text label when fast mode is on", () => {
|
||||
expect(display([EFFORT, fastModeDescriptor(true), CONTEXT_WINDOW], true)).toEqual({
|
||||
label: "High · 1M",
|
||||
showFastModeIcon: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps non-fastMode booleans as text labels", () => {
|
||||
const thinking: Extract<ProviderOptionDescriptor, { type: "boolean" }> = {
|
||||
id: "thinking",
|
||||
label: "Thinking",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
};
|
||||
expect(display([EFFORT, thinking], false)).toEqual({
|
||||
label: "High · Thinking On",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to a text label when fast mode is the only trait", () => {
|
||||
expect(display([fastModeDescriptor(true)], true)).toEqual({
|
||||
label: "Fast",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
expect(display([fastModeDescriptor(false)], false)).toEqual({
|
||||
label: "Normal",
|
||||
showFastModeIcon: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("stays blank when descriptors resolve to no label and there is no fast mode", () => {
|
||||
// A select with neither a currentValue nor an isDefault option yields no
|
||||
// label. Without a fastMode descriptor present that must stay blank rather
|
||||
// than falling through to a bogus "Normal".
|
||||
const unresolved: Extract<ProviderOptionDescriptor, { type: "select" }> = {
|
||||
id: "effort",
|
||||
label: "effort",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "high", label: "High" },
|
||||
],
|
||||
};
|
||||
expect(display([unresolved], false)).toEqual({ label: "", showFastModeIcon: false });
|
||||
});
|
||||
|
||||
it("still renders the prompt-controlled ultrathink label alongside the bolt", () => {
|
||||
expect(
|
||||
buildTraitsTriggerDisplay({
|
||||
descriptors: [EFFORT, fastModeDescriptor(true)],
|
||||
primarySelectDescriptorId: "effort",
|
||||
ultrathinkPromptControlled: true,
|
||||
fastModeEnabled: true,
|
||||
}),
|
||||
).toEqual({ label: "Ultrathink", showFastModeIcon: true });
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon, ZapIcon } from "lucide-react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -379,46 +379,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Build the traits trigger's text label plus whether the fast-mode bolt should
|
||||
* render. Fast mode is a lightning bolt when on and nothing at all when off —
|
||||
* "Normal" is the near-universal case and isn't worth the horizontal space. The
|
||||
* one exception is when fast mode is the only trait, where a bare bolt (or bare
|
||||
* chevron) would leave the trigger unreadable.
|
||||
*/
|
||||
export function buildTraitsTriggerDisplay(input: {
|
||||
descriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
primarySelectDescriptorId: string | null;
|
||||
ultrathinkPromptControlled: boolean;
|
||||
fastModeEnabled: boolean;
|
||||
}): { label: string; showFastModeIcon: boolean } {
|
||||
let hasFastMode = false;
|
||||
const labels: Array<string> = [];
|
||||
for (const descriptor of input.descriptors) {
|
||||
if (descriptor.id === "fastMode" && descriptor.type === "boolean") {
|
||||
hasFastMode = true;
|
||||
continue;
|
||||
}
|
||||
const label =
|
||||
input.ultrathinkPromptControlled && descriptor.id === input.primarySelectDescriptorId
|
||||
? "Ultrathink"
|
||||
: descriptor.type === "boolean"
|
||||
? `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
|
||||
: getProviderOptionCurrentLabel(descriptor);
|
||||
if (typeof label === "string" && label.length > 0) {
|
||||
labels.push(label);
|
||||
}
|
||||
}
|
||||
|
||||
// Only fall back to text when fast mode is genuinely the sole trait. Keying
|
||||
// off an empty label list alone would also catch descriptors that resolved to
|
||||
// no label at all, printing a bogus "Normal" for a model without fast mode.
|
||||
if (labels.length === 0 && hasFastMode) {
|
||||
return { label: input.fastModeEnabled ? "Fast" : "Normal", showFastModeIcon: false };
|
||||
}
|
||||
return { label: labels.join(" · "), showFastModeIcon: input.fastModeEnabled };
|
||||
}
|
||||
|
||||
export const TraitsPicker = memo(function TraitsPicker({
|
||||
provider,
|
||||
instanceId,
|
||||
@@ -433,7 +393,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
...persistence
|
||||
}: TraitsMenuContentProps & TraitsPersistence) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled, fastModeEnabled } =
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
|
||||
getTraitsSectionVisibility({
|
||||
provider,
|
||||
models,
|
||||
@@ -455,18 +415,23 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
return null;
|
||||
}
|
||||
|
||||
const { label: triggerLabel, showFastModeIcon } = buildTraitsTriggerDisplay({
|
||||
descriptors,
|
||||
primarySelectDescriptorId: primarySelectDescriptor?.id ?? null,
|
||||
ultrathinkPromptControlled,
|
||||
fastModeEnabled,
|
||||
});
|
||||
const fastModeIcon = showFastModeIcon ? (
|
||||
<>
|
||||
<ZapIcon aria-hidden="true" className="size-3 shrink-0 text-foreground/80 opacity-100" />
|
||||
<span className="sr-only">Fast mode on</span>
|
||||
</>
|
||||
) : null;
|
||||
const triggerLabels: Array<string> = [];
|
||||
for (const descriptor of descriptors) {
|
||||
const label =
|
||||
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
|
||||
? "Ultrathink"
|
||||
: descriptor.type === "boolean"
|
||||
? descriptor.id === "fastMode"
|
||||
? descriptor.currentValue === true
|
||||
? "Fast"
|
||||
: "Normal"
|
||||
: `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
|
||||
: getProviderOptionCurrentLabel(descriptor);
|
||||
if (typeof label === "string" && label.length > 0) {
|
||||
triggerLabels.push(label);
|
||||
}
|
||||
}
|
||||
const triggerLabel = triggerLabels.join(" · ");
|
||||
|
||||
const isCodexStyle = provider === "codex";
|
||||
|
||||
@@ -492,14 +457,12 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
}
|
||||
>
|
||||
{isCodexStyle ? (
|
||||
<span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
|
||||
{fastModeIcon}
|
||||
<span className="min-w-0 truncate">{triggerLabel}</span>
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{fastModeIcon}
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</>
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { useRouter } from "@tanstack/react-router";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { setSweepResultsNavigator, useReviewSweepStore } from "../../reviewSweepStore";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Dialog, DialogDescription, DialogHeader, DialogPopup, DialogTitle } from "../ui/dialog";
|
||||
import { SweepPreRunSummary } from "./ReviewSweepView";
|
||||
|
||||
/** Launch modal for the work-review sweep. The sweep itself runs in the
|
||||
background (module-level runner), so the modal just confirms scope/cost
|
||||
and closes; a toast announces completion with a link to the results. */
|
||||
export function ReviewSweepLaunchDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const phase = useReviewSweepStore((state) => state.phase);
|
||||
|
||||
// Install the navigator the store's completion toast uses. The dialog is
|
||||
// mounted for the sidebar's lifetime, so this stays registered.
|
||||
useEffect(() => {
|
||||
setSweepResultsNavigator(() => {
|
||||
void router.navigate({ to: "/review-sweep" });
|
||||
});
|
||||
return () => setSweepResultsNavigator(null);
|
||||
}, [router]);
|
||||
|
||||
const handleStarted = () => {
|
||||
onOpenChange(false);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "info",
|
||||
title: "Reviewing your work in the background",
|
||||
description: "You'll get a notification when the results are ready.",
|
||||
actionVariant: "outline",
|
||||
actionProps: {
|
||||
children: "Watch progress",
|
||||
onClick: () => void router.navigate({ to: "/review-sweep" }),
|
||||
},
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogPopup className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Review unsettled work</DialogTitle>
|
||||
<DialogDescription>
|
||||
{phase === "running"
|
||||
? "A review is already running — results will arrive as a notification."
|
||||
: "One AI review per unsettled thread, run in the background."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{phase === "running" ? null : <SweepPreRunSummary onStarted={handleStarted} />}
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,958 +0,0 @@
|
||||
import {
|
||||
scopedProjectKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { hasQueuedTurnStart } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArrowRightIcon,
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
GitMergeIcon,
|
||||
InfoIcon,
|
||||
ListChecksIcon,
|
||||
LoaderIcon,
|
||||
PencilLineIcon,
|
||||
RotateCcwIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
import { useClientSettings, usePrimarySettings } from "../../hooks/useSettings";
|
||||
import { getCustomModelOptionsByInstance } from "../../modelSelection";
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
deriveProviderInstanceEntries,
|
||||
sortProviderInstanceEntries,
|
||||
} from "../../providerInstances";
|
||||
import { primaryServerProvidersAtom } from "../../state/server";
|
||||
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { TraitsPicker } from "../chat/TraitsPicker";
|
||||
import {
|
||||
applyAllSweepRecommendations,
|
||||
applySweepSettle,
|
||||
applySweepTitle,
|
||||
dismissSweepItem,
|
||||
isSweepCandidate,
|
||||
mergeSweepItem,
|
||||
readSweepModelSelection,
|
||||
retrySweepItem,
|
||||
setSweepModelSelection,
|
||||
runMergeQueue,
|
||||
sortSweepCandidates,
|
||||
startReviewSweep,
|
||||
SWEEP_MAX_THREADS,
|
||||
sweepNowIso,
|
||||
useReviewSweepStore,
|
||||
type SweepItem,
|
||||
} from "../../reviewSweepStore";
|
||||
import {
|
||||
readThreadShell,
|
||||
useProjects,
|
||||
useServerConfigs,
|
||||
useThreadShells,
|
||||
} from "../../state/entities";
|
||||
import { formatRelativeTimeLabel } from "../../timestampFormat";
|
||||
import { buildThreadRouteParams } from "../../threadRoutes";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Card } from "../ui/card";
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty";
|
||||
import { SidebarInset } from "../ui/sidebar";
|
||||
import { Spinner } from "../ui/spinner";
|
||||
import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Triage buckets: ordered by "how fast can you clear this" — one-click
|
||||
// settles first, quick title fixes second, then threads that need real
|
||||
// reading, then no-action-possible tails.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type SweepBucket =
|
||||
| "mergeReady"
|
||||
| "settle"
|
||||
| "title"
|
||||
| "attention"
|
||||
| "inFlight"
|
||||
| "failed"
|
||||
| "reviewing";
|
||||
|
||||
const BUCKET_ORDER: readonly SweepBucket[] = [
|
||||
"mergeReady",
|
||||
"settle",
|
||||
"title",
|
||||
"attention",
|
||||
"inFlight",
|
||||
"failed",
|
||||
"reviewing",
|
||||
];
|
||||
|
||||
const BUCKET_META: Record<
|
||||
SweepBucket,
|
||||
{
|
||||
title: string;
|
||||
hint: string;
|
||||
/** Tinted icon chip beside the section title. */
|
||||
iconChip: string;
|
||||
icon: typeof ArchiveIcon;
|
||||
}
|
||||
> = {
|
||||
mergeReady: {
|
||||
title: "Merge ready",
|
||||
hint: "Open PRs with green CI, approvals, and clean merges.",
|
||||
iconChip: "bg-violet-500/12 text-violet-400",
|
||||
icon: GitMergeIcon,
|
||||
},
|
||||
settle: {
|
||||
title: "Ready to settle",
|
||||
hint: "Work concluded — one click clears each from your active list.",
|
||||
iconChip: "bg-emerald-500/12 text-emerald-400",
|
||||
icon: ArchiveIcon,
|
||||
},
|
||||
title: {
|
||||
title: "Title fixes",
|
||||
hint: "Still in progress, but the name no longer matches the work.",
|
||||
iconChip: "bg-sky-500/12 text-sky-400",
|
||||
icon: PencilLineIcon,
|
||||
},
|
||||
attention: {
|
||||
title: "Needs your attention",
|
||||
hint: "Waiting on you — review, input, or a decision.",
|
||||
iconChip: "bg-amber-500/12 text-amber-400",
|
||||
icon: CircleAlertIcon,
|
||||
},
|
||||
inFlight: {
|
||||
title: "In flight",
|
||||
hint: "Agents are still working; nothing to do yet.",
|
||||
iconChip: "bg-muted text-muted-foreground",
|
||||
icon: LoaderIcon,
|
||||
},
|
||||
failed: {
|
||||
title: "Review failed",
|
||||
hint: "The reviewer couldn't process these — retry or open them directly.",
|
||||
iconChip: "bg-red-500/12 text-red-400",
|
||||
icon: CircleAlertIcon,
|
||||
},
|
||||
reviewing: {
|
||||
title: "Still reviewing",
|
||||
hint: "",
|
||||
iconChip: "bg-muted text-muted-foreground",
|
||||
icon: LoaderIcon,
|
||||
},
|
||||
};
|
||||
|
||||
function classifySweepItem(item: SweepItem): SweepBucket {
|
||||
if (item.status === "error") return "failed";
|
||||
if (item.status !== "done" || item.result === null) return "reviewing";
|
||||
// Merge-ready wins over everything: it's the highest-leverage one-click.
|
||||
// Items stay in the bucket through the queue lifecycle (queued → merging
|
||||
// → merged/conflicted) so progress is visible in place.
|
||||
if (item.result.prStatus?.mergeReady && !item.settleApplied) return "mergeReady";
|
||||
if (item.result.recommendSettle && !item.settleApplied) return "settle";
|
||||
if (item.result.suggestedTitle && !item.titleApplied) return "title";
|
||||
// Live shell wins over review-time knowledge: a thread blocked on the user
|
||||
// right now belongs in "attention" even if the review predates the block.
|
||||
const shell = readThreadShell(item.ref);
|
||||
const working =
|
||||
shell?.session?.status === "running" ||
|
||||
shell?.session?.status === "starting" ||
|
||||
// A just-sent message no session has adopted yet is in-flight work, not
|
||||
// something waiting on the user.
|
||||
(shell !== null && hasQueuedTurnStart(shell, { now: new Date().toISOString() }));
|
||||
const blocked = shell?.hasPendingApprovals === true || shell?.hasPendingUserInput === true;
|
||||
if (blocked) return "attention";
|
||||
if (working) return "inFlight";
|
||||
return "attention";
|
||||
}
|
||||
|
||||
function DiffStatsLabel({ item }: { item: SweepItem }) {
|
||||
const stats = item.result?.diffStats;
|
||||
if (!stats || stats.files === 0) return null;
|
||||
return (
|
||||
<span className="flex items-center gap-1 font-mono text-[11px]">
|
||||
<span className="text-emerald-500">+{stats.additions}</span>
|
||||
<span className="text-red-400">−{stats.deletions}</span>
|
||||
<span className="text-muted-foreground/70">
|
||||
· {stats.files} {stats.files === 1 ? "file" : "files"}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SweepItemMetaRow({
|
||||
item,
|
||||
projectTitle,
|
||||
workspaceRoot,
|
||||
}: {
|
||||
item: SweepItem;
|
||||
projectTitle: string;
|
||||
workspaceRoot: string | null;
|
||||
}) {
|
||||
const age = formatRelativeTimeLabel(item.lastActivityAt);
|
||||
return (
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
{workspaceRoot ? (
|
||||
<ProjectFavicon
|
||||
environmentId={item.ref.environmentId}
|
||||
cwd={workspaceRoot}
|
||||
className="size-3.5 shrink-0"
|
||||
/>
|
||||
) : null}
|
||||
<span className="truncate">{projectTitle}</span>
|
||||
</span>
|
||||
{item.branch ? (
|
||||
<span className="max-w-56 truncate font-mono text-[11px] text-muted-foreground/80">
|
||||
{item.branch}
|
||||
</span>
|
||||
) : null}
|
||||
{item.result?.prStatus ? (
|
||||
<a
|
||||
href={item.result.prStatus.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="shrink-0 font-mono text-[11px] text-muted-foreground hover:text-foreground hover:underline"
|
||||
>
|
||||
#{item.result.prStatus.number}
|
||||
</a>
|
||||
) : null}
|
||||
{age ? <span className="shrink-0">{age}</span> : null}
|
||||
<DiffStatsLabel item={item} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MergeStatusBadge({ item }: { item: SweepItem }) {
|
||||
switch (item.mergeStatus) {
|
||||
case "queued":
|
||||
return <Badge variant="secondary">Queued</Badge>;
|
||||
case "merging":
|
||||
return (
|
||||
<Badge variant="info">
|
||||
<Spinner className="me-1 size-3" />
|
||||
Merging
|
||||
</Badge>
|
||||
);
|
||||
case "merged":
|
||||
return <Badge variant="success">Merged</Badge>;
|
||||
case "conflicted":
|
||||
return <Badge variant="warning">Conflict — agent rebasing</Badge>;
|
||||
case "failed":
|
||||
return <Badge variant="error">Merge failed</Badge>;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function SweepItemCard({
|
||||
item,
|
||||
bucket,
|
||||
projectTitle,
|
||||
workspaceRoot,
|
||||
}: {
|
||||
item: SweepItem;
|
||||
bucket: SweepBucket;
|
||||
projectTitle: string;
|
||||
workspaceRoot: string | null;
|
||||
}) {
|
||||
const key = scopedThreadKey(item.ref);
|
||||
const [applying, setApplying] = useState(false);
|
||||
const result = item.result;
|
||||
|
||||
const primaryAction =
|
||||
bucket === "mergeReady" ? (
|
||||
item.mergeStatus === "idle" || item.mergeStatus === "failed" ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
disabled={applying}
|
||||
onClick={() => {
|
||||
setApplying(true);
|
||||
void mergeSweepItem(key).finally(() => setApplying(false));
|
||||
}}
|
||||
>
|
||||
<GitMergeIcon className="me-1 size-3.5" />
|
||||
Merge & settle
|
||||
</Button>
|
||||
) : null
|
||||
) : bucket === "settle" ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
disabled={applying}
|
||||
onClick={() => {
|
||||
setApplying(true);
|
||||
void applySweepSettle(key).finally(() => setApplying(false));
|
||||
}}
|
||||
>
|
||||
<ArchiveIcon className="me-1 size-3.5" />
|
||||
Settle
|
||||
</Button>
|
||||
) : bucket === "title" ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
disabled={applying}
|
||||
onClick={() => {
|
||||
setApplying(true);
|
||||
void applySweepTitle(key).finally(() => setApplying(false));
|
||||
}}
|
||||
>
|
||||
Apply title
|
||||
</Button>
|
||||
) : bucket === "failed" ? (
|
||||
<Button size="xs" variant="outline" className="shrink-0" onClick={() => retrySweepItem(key)}>
|
||||
Retry
|
||||
</Button>
|
||||
) : null;
|
||||
|
||||
// The one-line "what should I do" is the card body; the full summary
|
||||
// lives behind the info icon so the grid stays scannable. Results from
|
||||
// pre-nextStep servers fall back to settleReason (settle bucket) or the
|
||||
// summary (attention bucket) so action cards never render bodyless.
|
||||
const nextStepFallback =
|
||||
bucket === "settle"
|
||||
? (result?.settleReason ?? null)
|
||||
: bucket === "attention"
|
||||
? (result?.summary ?? null)
|
||||
: null;
|
||||
const nextStep = item.status === "error" ? null : (result?.nextStep ?? nextStepFallback);
|
||||
|
||||
return (
|
||||
<Card className="group min-w-0 gap-2 p-4">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex min-h-5 items-center gap-1.5">
|
||||
<Link
|
||||
to="/$environmentId/$threadId"
|
||||
params={buildThreadRouteParams(item.ref)}
|
||||
className="min-w-0 truncate text-sm font-medium tracking-[-0.005em] text-foreground hover:underline"
|
||||
>
|
||||
{item.threadTitle}
|
||||
</Link>
|
||||
{bucket === "settle" && item.settleApplied ? (
|
||||
<Badge variant="outline" size="sm">
|
||||
Settled
|
||||
</Badge>
|
||||
) : null}
|
||||
{bucket === "mergeReady" ? <MergeStatusBadge item={item} /> : null}
|
||||
</div>
|
||||
<SweepItemMetaRow item={item} projectTitle={projectTitle} workspaceRoot={workspaceRoot} />
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-0.5 opacity-60 transition-opacity group-hover:opacity-100">
|
||||
{result?.summary ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground/70"
|
||||
aria-label="Show thread summary"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<InfoIcon className="size-3.5" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="bottom" className="max-w-80">
|
||||
{result.summary}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground"
|
||||
aria-label="Dismiss recommendation"
|
||||
onClick={() => dismissSweepItem(key)}
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{item.status === "error" ? (
|
||||
<p className="line-clamp-2 text-[13px] leading-[1.45] text-destructive-foreground">
|
||||
{item.errorMessage}
|
||||
</p>
|
||||
) : item.mergeStatus === "conflicted" || item.mergeStatus === "failed" ? (
|
||||
<p className="line-clamp-2 text-[13px] leading-[1.45] text-warning-foreground">
|
||||
{item.mergeDetail}
|
||||
</p>
|
||||
) : nextStep ? (
|
||||
<p className="line-clamp-2 text-[13px] leading-[1.45] text-muted-foreground">{nextStep}</p>
|
||||
) : null}
|
||||
|
||||
{bucket === "title" && result?.suggestedTitle ? (
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs">
|
||||
<span className="max-w-full truncate text-muted-foreground/70 line-through">
|
||||
{item.threadTitle}
|
||||
</span>
|
||||
<ArrowRightIcon className="size-3 shrink-0 text-muted-foreground/70" />
|
||||
<span className="max-w-full truncate font-medium text-foreground">
|
||||
{result.suggestedTitle}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{result?.suggestedTitle && item.titleApplied ? (
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
Renamed to <span className="font-medium text-foreground">{result.suggestedTitle}</span>.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{primaryAction ? <div className="flex justify-end pt-1">{primaryAction}</div> : null}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function formatDuration(ms: number): string {
|
||||
const totalSeconds = Math.max(0, Math.round(ms / 1000));
|
||||
if (totalSeconds < 60) return `${totalSeconds}s`;
|
||||
return `${Math.floor(totalSeconds / 60)}m ${String(totalSeconds % 60).padStart(2, "0")}s`;
|
||||
}
|
||||
|
||||
function formatTokens(tokens: number): string {
|
||||
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
|
||||
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;
|
||||
return String(tokens);
|
||||
}
|
||||
|
||||
/** Live per-thread progress: what's running, for how long, and what each
|
||||
review cost. Replaces a bare spinner so a multi-minute sweep is
|
||||
legible while it works. */
|
||||
function SweepProgressList({
|
||||
items,
|
||||
projectsByKey,
|
||||
}: {
|
||||
items: ReadonlyArray<SweepItem>;
|
||||
projectsByKey: ReadonlyMap<string, { title: string; workspaceRoot: string }>;
|
||||
}) {
|
||||
// Ticking clock so elapsed times advance without store writes.
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => setNowMs(Date.now()), 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// Running first (that's the live part), then queued, then finished.
|
||||
const ordered = useMemo(() => {
|
||||
const rank = (item: SweepItem) =>
|
||||
item.status === "running" ? 0 : item.status === "pending" ? 1 : 2;
|
||||
return [...items].sort((a, b) => rank(a) - rank(b));
|
||||
}, [items]);
|
||||
|
||||
return (
|
||||
<Card className="flex flex-col gap-0 divide-y divide-border/50 overflow-hidden p-0">
|
||||
{ordered.map((item) => {
|
||||
const project = projectsByKey.get(
|
||||
scopedProjectKey(scopeProjectRef(item.ref.environmentId, item.projectId)),
|
||||
);
|
||||
const elapsedMs =
|
||||
item.startedAtMs === null ? null : (item.finishedAtMs ?? nowMs) - item.startedAtMs;
|
||||
const usage = item.result?.usage;
|
||||
return (
|
||||
<div
|
||||
key={scopedThreadKey(item.ref)}
|
||||
className={cn(
|
||||
"flex items-center gap-3 px-3 py-2 text-sm",
|
||||
item.status === "pending" && "opacity-50",
|
||||
)}
|
||||
>
|
||||
<span className="flex size-4 shrink-0 items-center justify-center">
|
||||
{item.status === "running" ? (
|
||||
<Spinner className="size-3.5 text-sky-400" />
|
||||
) : item.status === "done" ? (
|
||||
<CheckIcon className="size-3.5 text-emerald-500" />
|
||||
) : item.status === "error" ? (
|
||||
<CircleAlertIcon className="size-3.5 text-red-400" />
|
||||
) : (
|
||||
<span className="size-1.5 rounded-full bg-muted-foreground/40" />
|
||||
)}
|
||||
</span>
|
||||
{project?.workspaceRoot ? (
|
||||
<ProjectFavicon
|
||||
environmentId={item.ref.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className="size-3.5 shrink-0"
|
||||
/>
|
||||
) : null}
|
||||
<span className="min-w-0 flex-1 truncate text-foreground/90">{item.threadTitle}</span>
|
||||
{usage ? (
|
||||
<span className="shrink-0 font-mono text-[11px] text-muted-foreground">
|
||||
{formatTokens(usage.inputTokens + usage.outputTokens)} tok
|
||||
{usage.costUsd !== undefined ? ` · $${usage.costUsd.toFixed(2)}` : ""}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="w-16 shrink-0 text-right font-mono text-[11px] text-muted-foreground">
|
||||
{elapsedMs === null ? "—" : formatDuration(elapsedMs)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/** Cost-transparency threshold: at or above this many candidate threads the
|
||||
pre-run screen calls out that the sweep may be slow/expensive. */
|
||||
const SWEEP_COST_NOTE_THRESHOLD = 15;
|
||||
|
||||
/** Pre-run summary: how many threads a sweep would cover and which model
|
||||
each environment's server will use, so starting is an informed choice.
|
||||
Rendered on the idle /review-sweep page and inside the sidebar's launch
|
||||
modal. `onStarted` lets the modal close itself when the sweep kicks off. */
|
||||
export function SweepPreRunSummary({ onStarted }: { onStarted?: () => void } = {}) {
|
||||
const shells = useThreadShells();
|
||||
const serverConfigs = useServerConfigs();
|
||||
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
|
||||
// Recompute when the sidebar publishes fresh PR states — merged-PR
|
||||
// auto-settle changes which threads count as unsettled.
|
||||
const candidateVersion = useReviewSweepStore((state) => state.candidateVersion);
|
||||
|
||||
// Review model: defaults to the composer's last-used pick, overridable
|
||||
// here. Re-read on candidateVersion so the trigger reflects changes.
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const settings = usePrimarySettings();
|
||||
const selectedModel = useMemo(
|
||||
() => readSweepModelSelection(),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- module-level source
|
||||
[candidateVersion],
|
||||
);
|
||||
const instanceEntries = useMemo(
|
||||
() =>
|
||||
sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
),
|
||||
[serverProviders, settings],
|
||||
);
|
||||
const activeInstanceId = selectedModel?.instanceId ?? instanceEntries[0]?.instanceId ?? null;
|
||||
const activeModel = selectedModel?.model ?? instanceEntries[0]?.models[0]?.slug ?? "";
|
||||
const activeOptions = selectedModel?.options ?? [];
|
||||
const modelOptionsByInstance = useMemo(
|
||||
() =>
|
||||
activeInstanceId === null
|
||||
? new Map()
|
||||
: getCustomModelOptionsByInstance(settings, serverProviders, activeInstanceId, activeModel),
|
||||
[activeInstanceId, activeModel, serverProviders, settings],
|
||||
);
|
||||
const activeInstanceEntry = instanceEntries.find(
|
||||
(entry) => entry.instanceId === activeInstanceId,
|
||||
);
|
||||
|
||||
const { candidateCount, reviewedCount, modelsByEnvironment } = useMemo(() => {
|
||||
const now = sweepNowIso();
|
||||
const candidates = sortSweepCandidates(
|
||||
shells.filter((shell) =>
|
||||
isSweepCandidate(shell, serverConfigs.get(shell.environmentId)?.environment.capabilities, {
|
||||
now,
|
||||
autoSettleAfterDays,
|
||||
}),
|
||||
),
|
||||
);
|
||||
// Aggregate only what a run would actually review: the cap is applied
|
||||
// here, in the same most-recently-active order startReviewSweep uses,
|
||||
// so the environment/model rows never overstate the calls.
|
||||
const reviewed = candidates.slice(0, SWEEP_MAX_THREADS);
|
||||
const models = new Map<
|
||||
string,
|
||||
{ environmentId: string; label: string; model: string; threads: number }
|
||||
>();
|
||||
for (const shell of reviewed) {
|
||||
const config = serverConfigs.get(shell.environmentId);
|
||||
const entry = models.get(shell.environmentId);
|
||||
if (entry) {
|
||||
entry.threads += 1;
|
||||
} else {
|
||||
const selection = config?.settings.textGenerationModelSelection;
|
||||
models.set(shell.environmentId, {
|
||||
environmentId: shell.environmentId,
|
||||
label: config?.environment.label ?? shell.environmentId,
|
||||
model: selection ? `${selection.model}` : "server default",
|
||||
threads: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
candidateCount: candidates.length,
|
||||
reviewedCount: reviewed.length,
|
||||
modelsByEnvironment: [...models.values()],
|
||||
};
|
||||
}, [autoSettleAfterDays, candidateVersion, serverConfigs, shells]);
|
||||
|
||||
if (candidateCount === 0) {
|
||||
return (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>All caught up</EmptyTitle>
|
||||
<EmptyDescription>No unsettled threads to review right now.</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>Review your in-progress work</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
This sweep runs one AI review per thread to summarize it, catch stale titles, and find
|
||||
threads ready to settle. Nothing is applied without your click.
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
<div className="flex w-full max-w-md flex-col gap-1.5 rounded-lg border border-border/60 bg-muted/30 px-4 py-3 text-sm text-muted-foreground">
|
||||
<div>
|
||||
<span className="font-medium text-foreground">{reviewedCount}</span>{" "}
|
||||
{reviewedCount === 1 ? "thread" : "threads"} will be reviewed
|
||||
{candidateCount > SWEEP_MAX_THREADS
|
||||
? ` (${candidateCount - SWEEP_MAX_THREADS} least-recently-active skipped)`
|
||||
: ""}
|
||||
</div>
|
||||
{modelsByEnvironment.length > 1 ? (
|
||||
<div className="truncate">
|
||||
Across{" "}
|
||||
{modelsByEnvironment.map((entry, index) => (
|
||||
<span key={entry.environmentId}>
|
||||
{index > 0 ? ", " : ""}
|
||||
{entry.label} ({entry.threads})
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex flex-wrap items-center gap-2 pt-0.5">
|
||||
<span className="shrink-0">Review with</span>
|
||||
{activeInstanceId !== null ? (
|
||||
<>
|
||||
<ProviderModelPicker
|
||||
activeInstanceId={activeInstanceId}
|
||||
model={activeModel}
|
||||
lockedProvider={null}
|
||||
instanceEntries={instanceEntries}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onInstanceModelChange={(instanceId, model) => {
|
||||
// Carry the current traits across a model switch when the
|
||||
// instance is unchanged; a different instance's options
|
||||
// aren't transferable, so start clean there.
|
||||
setSweepModelSelection(
|
||||
createModelSelection(
|
||||
instanceId,
|
||||
model,
|
||||
instanceId === activeInstanceId ? activeOptions : undefined,
|
||||
),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{activeInstanceEntry ? (
|
||||
<TraitsPicker
|
||||
provider={activeInstanceEntry.driverKind}
|
||||
models={activeInstanceEntry.models}
|
||||
model={activeModel}
|
||||
prompt=""
|
||||
onPromptChange={() => {}}
|
||||
modelOptions={activeOptions}
|
||||
allowPromptInjectedEffort={false}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onModelOptionsChange={(nextOptions) => {
|
||||
setSweepModelSelection(
|
||||
createModelSelection(activeInstanceId, activeModel, nextOptions),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-foreground">server default</span>
|
||||
)}
|
||||
</div>
|
||||
{reviewedCount >= SWEEP_COST_NOTE_THRESHOLD ? (
|
||||
<div className="text-warning-foreground">
|
||||
Heads up: {reviewedCount} model calls may take a few minutes and use noticeable credits.
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
startReviewSweep();
|
||||
onStarted?.();
|
||||
}}
|
||||
>
|
||||
<ListChecksIcon className="me-1.5 size-4" />
|
||||
Review {reviewedCount} {reviewedCount === 1 ? "thread" : "threads"}
|
||||
</Button>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReviewSweepView() {
|
||||
const phase = useReviewSweepStore((state) => state.phase);
|
||||
const order = useReviewSweepStore((state) => state.order);
|
||||
const items = useReviewSweepStore((state) => state.items);
|
||||
const truncatedCount = useReviewSweepStore((state) => state.truncatedCount);
|
||||
const projects = useProjects();
|
||||
// classifySweepItem reads live shells (running vs blocked), so bucketing
|
||||
// must recompute when shells change and not only when items do.
|
||||
const shells = useThreadShells();
|
||||
|
||||
// Projects are only unique per (environmentId, projectId) — ids can
|
||||
// collide across connected environments.
|
||||
const projectsByKey = useMemo(() => {
|
||||
const byKey = new Map<string, { title: string; workspaceRoot: string }>();
|
||||
for (const project of projects) {
|
||||
byKey.set(scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), {
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
});
|
||||
}
|
||||
return byKey;
|
||||
}, [projects]);
|
||||
|
||||
const visibleItems = useMemo(
|
||||
() =>
|
||||
order
|
||||
.map((key) => items[key])
|
||||
.filter((item): item is SweepItem => item !== undefined && !item.dismissed),
|
||||
[items, order],
|
||||
);
|
||||
|
||||
const buckets = useMemo(() => {
|
||||
const grouped = new Map<SweepBucket, SweepItem[]>();
|
||||
for (const item of visibleItems) {
|
||||
const bucket = classifySweepItem(item);
|
||||
const group = grouped.get(bucket);
|
||||
if (group) {
|
||||
group.push(item);
|
||||
} else {
|
||||
grouped.set(bucket, [item]);
|
||||
}
|
||||
}
|
||||
// Within a bucket, smallest diff first — clear the easy ones, build
|
||||
// momentum. Unknown diff sizes sink to the bottom.
|
||||
for (const group of grouped.values()) {
|
||||
group.sort((a, b) => {
|
||||
const sizeOf = (item: SweepItem) => {
|
||||
const stats = item.result?.diffStats;
|
||||
return stats ? stats.additions + stats.deletions : Number.MAX_SAFE_INTEGER;
|
||||
};
|
||||
return sizeOf(a) - sizeOf(b);
|
||||
});
|
||||
}
|
||||
return BUCKET_ORDER.flatMap((bucket) => {
|
||||
const group = grouped.get(bucket);
|
||||
return group && group.length > 0 ? [[bucket, group] as const] : [];
|
||||
});
|
||||
// `shells` is a classification input via readThreadShell, not unused.
|
||||
}, [shells, visibleItems]);
|
||||
|
||||
const reviewedCount = visibleItems.filter(
|
||||
(item) => item.status === "done" || item.status === "error",
|
||||
).length;
|
||||
const applicableCount = visibleItems.filter(
|
||||
(item) =>
|
||||
(item.result?.suggestedTitle && !item.titleApplied) ||
|
||||
(item.result?.recommendSettle && !item.settleApplied),
|
||||
).length;
|
||||
const running = phase === "running";
|
||||
const [applyingAll, setApplyingAll] = useState(false);
|
||||
const [mergingAll, setMergingAll] = useState(false);
|
||||
// Aggregate what the run has cost so far, from provider-reported usage.
|
||||
const runTotals = useMemo(
|
||||
() =>
|
||||
visibleItems.reduce(
|
||||
(totals, item) => {
|
||||
const usage = item.result?.usage;
|
||||
if (!usage) return totals;
|
||||
return {
|
||||
tokens: totals.tokens + usage.inputTokens + usage.outputTokens,
|
||||
costUsd: totals.costUsd + (usage.costUsd ?? 0),
|
||||
};
|
||||
},
|
||||
{ tokens: 0, costUsd: 0 },
|
||||
),
|
||||
[visibleItems],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border/60 px-3 py-2 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
|
||||
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
)}
|
||||
>
|
||||
<div className="flex min-h-7 items-center gap-3 sm:min-h-6">
|
||||
<span className="text-sm font-medium text-foreground">Work review</span>
|
||||
{phase !== "idle" ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{running ? (
|
||||
<>
|
||||
{reviewedCount} of {visibleItems.length} reviewed
|
||||
</>
|
||||
) : (
|
||||
<>{visibleItems.length} threads reviewed</>
|
||||
)}
|
||||
</span>
|
||||
) : null}
|
||||
{phase !== "idle" ? (
|
||||
<div className="ms-auto flex items-center gap-2">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={running}
|
||||
onClick={() => startReviewSweep()}
|
||||
>
|
||||
<RotateCcwIcon className="mx-1 size-3.5" />
|
||||
Re-run
|
||||
</Button>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={running || applyingAll || applicableCount === 0}
|
||||
onClick={() => {
|
||||
setApplyingAll(true);
|
||||
void applyAllSweepRecommendations().finally(() => setApplyingAll(false));
|
||||
}}
|
||||
>
|
||||
Apply all{applicableCount > 0 ? ` (${applicableCount})` : ""}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="settings-page-scroll-fade scrollbar-gutter-both min-h-0 flex-1 overflow-y-auto px-4 pt-8 pb-10 sm:px-8">
|
||||
{phase === "idle" ? (
|
||||
<SweepPreRunSummary />
|
||||
) : running ? (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
|
||||
<h2 className="text-sm font-medium text-foreground">
|
||||
Reviewing your work — {reviewedCount} of {visibleItems.length}
|
||||
</h2>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{runTotals.tokens > 0 ? `${formatTokens(runTotals.tokens)} tokens` : null}
|
||||
{runTotals.costUsd > 0 ? ` · $${runTotals.costUsd.toFixed(2)}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1 w-full overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full rounded-full bg-sky-500 transition-[width] duration-500"
|
||||
style={{
|
||||
width: `${visibleItems.length === 0 ? 0 : Math.round((reviewedCount / visibleItems.length) * 100)}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Results appear all at once when every thread is reviewed, so you can triage in one
|
||||
pass. Feel free to navigate away; the sweep keeps running.
|
||||
</p>
|
||||
</div>
|
||||
<SweepProgressList items={visibleItems} projectsByKey={projectsByKey} />
|
||||
</div>
|
||||
) : visibleItems.length === 0 ? (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>All caught up</EmptyTitle>
|
||||
<EmptyDescription>No unsettled threads to review right now.</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
) : (
|
||||
<TooltipProvider>
|
||||
<div className="mx-auto flex w-full max-w-5xl flex-col gap-10">
|
||||
{truncatedCount > 0 ? (
|
||||
<p className="text-[13px] leading-[1.45] text-muted-foreground/80">
|
||||
Reviewed the {visibleItems.length} most recent threads; {truncatedCount} more
|
||||
were skipped this run.
|
||||
</p>
|
||||
) : null}
|
||||
{buckets.map(([bucket, bucketItems]) => {
|
||||
const meta = BUCKET_META[bucket];
|
||||
const BucketIcon = meta.icon;
|
||||
const mergeableCount =
|
||||
bucket === "mergeReady"
|
||||
? bucketItems.filter(
|
||||
(item) => item.mergeStatus === "idle" || item.mergeStatus === "queued",
|
||||
).length
|
||||
: 0;
|
||||
return (
|
||||
<section key={bucket} className="flex flex-col gap-3">
|
||||
<div className="flex min-h-8 items-center gap-3">
|
||||
<span
|
||||
className={cn(
|
||||
"flex size-7 shrink-0 items-center justify-center rounded-lg",
|
||||
meta.iconChip,
|
||||
)}
|
||||
>
|
||||
<BucketIcon className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="flex items-baseline gap-2 text-[15px] font-semibold tracking-[-0.02em] text-foreground">
|
||||
{meta.title}
|
||||
<span className="text-sm font-normal text-muted-foreground">
|
||||
{bucketItems.length}
|
||||
</span>
|
||||
</h2>
|
||||
{meta.hint ? (
|
||||
<p className="truncate text-[13px] leading-[1.45] text-muted-foreground/80">
|
||||
{meta.hint}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
{bucket === "mergeReady" && mergeableCount > 0 ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
disabled={mergingAll}
|
||||
onClick={() => {
|
||||
setMergingAll(true);
|
||||
void runMergeQueue().finally(() => setMergingAll(false));
|
||||
}}
|
||||
>
|
||||
<GitMergeIcon className="me-1 size-3.5" />
|
||||
Merge all ({mergeableCount})
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
|
||||
{bucketItems.map((item) => {
|
||||
const projectKey = scopedProjectKey(
|
||||
scopeProjectRef(item.ref.environmentId, item.projectId),
|
||||
);
|
||||
const project = projectsByKey.get(projectKey);
|
||||
return (
|
||||
<SweepItemCard
|
||||
key={scopedThreadKey(item.ref)}
|
||||
item={item}
|
||||
bucket={bucket}
|
||||
projectTitle={project?.title ?? "Unknown project"}
|
||||
workspaceRoot={project?.workspaceRoot ?? null}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</SidebarInset>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -22,7 +22,6 @@ import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsStat
|
||||
import { readLocalApi } from "../localApi";
|
||||
import {
|
||||
readEnvironmentSupportsSettlement,
|
||||
readEnvironmentSupportsSnooze,
|
||||
readEnvironmentThreadRefs,
|
||||
readProject,
|
||||
readThreadShell,
|
||||
@@ -70,30 +69,6 @@ export class ThreadSettleBlockedError extends Schema.TaggedErrorClass<ThreadSett
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadSnoozeUnsupportedError extends Schema.TaggedErrorClass<ThreadSnoozeUnsupportedError>()(
|
||||
"ThreadSnoozeUnsupportedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "This environment's server does not support snoozing yet. Update the server to use Snooze.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadSnoozeBlockedError extends Schema.TaggedErrorClass<ThreadSnoozeBlockedError>()(
|
||||
"ThreadSnoozeBlockedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "This thread is waiting on you. Respond to the pending request before snoozing it.";
|
||||
}
|
||||
}
|
||||
|
||||
export function useThreadActions() {
|
||||
const closeTerminal = useAtomCommand(terminalEnvironment.close);
|
||||
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
|
||||
@@ -111,12 +86,6 @@ export function useThreadActions() {
|
||||
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const snoozeThreadMutation = useAtomCommand(threadEnvironment.snooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
|
||||
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
|
||||
reportFailure: false,
|
||||
@@ -472,61 +441,6 @@ export function useThreadActions() {
|
||||
[unsettleThreadMutation],
|
||||
);
|
||||
|
||||
const snoozeThread = useCallback(
|
||||
async (target: ScopedThreadRef, snoozedUntil: string) => {
|
||||
// Version skew: never send the command to a server that predates it.
|
||||
if (!readEnvironmentSupportsSnooze(target.environmentId)) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSnoozeUnsupportedError({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
const resolved = resolveThreadTarget(target);
|
||||
// Blocked-on-you work and queued turns can't be snoozed away —
|
||||
// client-side twin of the server invariants so the UI rejects before
|
||||
// a round trip.
|
||||
if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSnoozeBlockedError({
|
||||
environmentId: resolved.threadRef.environmentId,
|
||||
threadId: resolved.threadRef.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
return snoozeThreadMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.threadId, snoozedUntil },
|
||||
});
|
||||
},
|
||||
[resolveThreadTarget, snoozeThreadMutation],
|
||||
);
|
||||
|
||||
const unsnoozeThread = useCallback(
|
||||
async (target: ScopedThreadRef) => {
|
||||
if (!readEnvironmentSupportsSnooze(target.environmentId)) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSnoozeUnsupportedError({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
return unsnoozeThreadMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.threadId, reason: "user" },
|
||||
});
|
||||
},
|
||||
[unsnoozeThreadMutation],
|
||||
);
|
||||
|
||||
const confirmAndDeleteThread = useCallback(
|
||||
async (target: ScopedThreadRef) => {
|
||||
const localApi = readLocalApi();
|
||||
@@ -563,18 +477,14 @@ export function useThreadActions() {
|
||||
confirmAndDeleteThread,
|
||||
settleThread,
|
||||
unsettleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
}),
|
||||
[
|
||||
archiveThread,
|
||||
confirmAndDeleteThread,
|
||||
deleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
],
|
||||
);
|
||||
}
|
||||
+2
-18
@@ -574,6 +574,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
--alert-glass-tint: var(--warning);
|
||||
}
|
||||
|
||||
.dropdown-glass,
|
||||
.dialog-glass {
|
||||
background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
@@ -587,19 +588,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
.dropdown-glass {
|
||||
/*
|
||||
* Elevated glass needs a denser tint than broad ambient surfaces. Nesting
|
||||
* the user-controlled mix inside an 18% popover tint preserves the full
|
||||
* opacity setting range (40% -> 51%, 80% -> 84%, 100% -> 100%) while
|
||||
* keeping high-contrast page content from blooming through menus.
|
||||
*/
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--popover) 18%,
|
||||
color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)
|
||||
);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur));
|
||||
backdrop-filter: blur(var(--glass-blur));
|
||||
border: 1px solid color-mix(in srgb, var(--foreground) 10%, transparent);
|
||||
box-shadow: 0 16px 40px -18px rgb(0 0 0 / 55%);
|
||||
}
|
||||
@@ -614,11 +602,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
.dark .model-picker-surface.model-picker-surface {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--popover) 18%,
|
||||
color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)
|
||||
);
|
||||
background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);
|
||||
}
|
||||
|
||||
.dark .dialog-glass {
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "./diffCollapse";
|
||||
|
||||
const FILE_KEYS = ["src/app.ts", "src/index.ts"];
|
||||
const FIRST_FILE_KEY = FILE_KEYS[0]!;
|
||||
|
||||
describe("diff collapse controls", () => {
|
||||
it("reports whether every rendered file is collapsed", () => {
|
||||
expect(areAllDiffFilesCollapsed(FILE_KEYS, new Set(FILE_KEYS))).toBe(true);
|
||||
expect(areAllDiffFilesCollapsed(FILE_KEYS, new Set([FIRST_FILE_KEY]))).toBe(false);
|
||||
expect(areAllDiffFilesCollapsed([], new Set())).toBe(false);
|
||||
});
|
||||
|
||||
it("collapses all files when any rendered file is expanded", () => {
|
||||
expect(toggleAllDiffFiles(FILE_KEYS, new Set([FIRST_FILE_KEY]))).toEqual(new Set(FILE_KEYS));
|
||||
});
|
||||
|
||||
it("expands all files when every rendered file is collapsed", () => {
|
||||
expect(toggleAllDiffFiles(FILE_KEYS, new Set(FILE_KEYS))).toEqual(new Set());
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
export function areAllDiffFilesCollapsed(
|
||||
fileKeys: ReadonlyArray<string>,
|
||||
collapsedFileKeys: ReadonlySet<string>,
|
||||
): boolean {
|
||||
return fileKeys.length > 0 && fileKeys.every((fileKey) => collapsedFileKeys.has(fileKey));
|
||||
}
|
||||
|
||||
export function toggleAllDiffFiles(
|
||||
fileKeys: ReadonlyArray<string>,
|
||||
collapsedFileKeys: ReadonlySet<string>,
|
||||
): ReadonlySet<string> {
|
||||
return areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? new Set() : new Set(fileKeys);
|
||||
}
|
||||
@@ -1,688 +0,0 @@
|
||||
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
canSettle,
|
||||
effectiveSettled,
|
||||
threadLastActivityAt,
|
||||
} from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { toSortableTimestamp } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";
|
||||
import {
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProjectId,
|
||||
type ReviewThreadSummaryResult,
|
||||
type ScopedThreadRef,
|
||||
} from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
|
||||
import { stackedThreadToast, toastManager } from "./components/ui/toast";
|
||||
import { useComposerDraftStore } from "./composerDraftStore";
|
||||
import { getClientSettings } from "./hooks/useSettings";
|
||||
import { newMessageId } from "~/lib/utils";
|
||||
import { appAtomRegistry } from "./rpc/atomRegistry";
|
||||
import { readThreadShell, readThreadRefs } from "./state/entities";
|
||||
import { reviewEnvironment } from "./state/review";
|
||||
import { environmentServerConfigsAtom } from "./state/server";
|
||||
import { threadEnvironment } from "./state/threads";
|
||||
|
||||
/** PR states mirrored from SidebarV2's per-row VCS subscriptions (keyed by
|
||||
scoped thread key). The sidebar auto-settles merged/closed+idle threads
|
||||
using this data; the sweep must see the same states or it will count
|
||||
those threads as unsettled. Module-level because the sidebar is mounted
|
||||
for the app's lifetime and owns the subscriptions. */
|
||||
let changeRequestStateByKey: ReadonlyMap<string, "open" | "closed" | "merged"> = new Map();
|
||||
|
||||
export function publishSweepChangeRequestStates(
|
||||
states: ReadonlyMap<string, "open" | "closed" | "merged">,
|
||||
): void {
|
||||
// MERGE rather than replace: SidebarV2 remounts (navigating to settings and
|
||||
// back) publish an empty map before its rows re-subscribe, and wiping the
|
||||
// cache would make merged-PR threads look unsettled again. Rows only ever
|
||||
// add states for threads they own, so stale entries are harmless — a
|
||||
// thread whose PR state genuinely changes republishes its own key.
|
||||
const merged = new Map(changeRequestStateByKey);
|
||||
for (const [key, state] of states) {
|
||||
merged.set(key, state);
|
||||
}
|
||||
changeRequestStateByKey = merged;
|
||||
// Bump the store version so the pre-run summary recomputes its candidate
|
||||
// count as PR states stream in from the sidebar rows.
|
||||
useReviewSweepStore.getState().bumpCandidateVersion();
|
||||
}
|
||||
|
||||
/** Model the next run will use. Defaults to the composer's last-used
|
||||
(sticky) selection so reviews run on the model the user actually picks
|
||||
for work, not the server's commit-message text-gen default. Overridable
|
||||
in the launch modal. */
|
||||
let sweepModelSelection: ModelSelection | null = null;
|
||||
|
||||
export function readSweepModelSelection(): ModelSelection | null {
|
||||
return sweepModelSelection ?? readStickyComposerModelSelection();
|
||||
}
|
||||
|
||||
export function setSweepModelSelection(selection: ModelSelection | null): void {
|
||||
sweepModelSelection = selection;
|
||||
useReviewSweepStore.getState().bumpCandidateVersion();
|
||||
}
|
||||
|
||||
/** The composer picker's last-used model, if any. */
|
||||
function readStickyComposerModelSelection(): ModelSelection | null {
|
||||
const store = useComposerDraftStore.getState();
|
||||
const activeProvider = store.stickyActiveProvider;
|
||||
if (activeProvider === null) return null;
|
||||
return store.stickyModelSelectionByProvider[activeProvider] ?? null;
|
||||
}
|
||||
|
||||
const SWEEP_CONCURRENCY = 5;
|
||||
/** Soft cap so a giant backlog doesn't spawn an unbounded number of LLM
|
||||
generations in one click. */
|
||||
export const SWEEP_MAX_THREADS = 50;
|
||||
|
||||
export type SweepItemStatus = "pending" | "running" | "done" | "error";
|
||||
|
||||
/** Merge-queue lifecycle for merge-ready items. "conflicted" means the
|
||||
merge failed and the thread's agent has been asked to resolve it. */
|
||||
export type SweepMergeStatus = "idle" | "queued" | "merging" | "merged" | "conflicted" | "failed";
|
||||
|
||||
export interface SweepItem {
|
||||
readonly ref: ScopedThreadRef;
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadTitle: string;
|
||||
readonly branch: string | null;
|
||||
/** Last activity (falls back to createdAt) for the age label. */
|
||||
readonly lastActivityAt: string;
|
||||
readonly status: SweepItemStatus;
|
||||
readonly result: ReviewThreadSummaryResult | null;
|
||||
readonly errorMessage: string | null;
|
||||
readonly titleApplied: boolean;
|
||||
readonly settleApplied: boolean;
|
||||
readonly dismissed: boolean;
|
||||
readonly mergeStatus: SweepMergeStatus;
|
||||
readonly mergeDetail: string | null;
|
||||
/** Epoch ms when this item's review started (for the live elapsed clock). */
|
||||
readonly startedAtMs: number | null;
|
||||
/** Epoch ms when it finished, successfully or not. */
|
||||
readonly finishedAtMs: number | null;
|
||||
}
|
||||
|
||||
export type SweepPhase = "idle" | "running" | "complete";
|
||||
|
||||
interface ReviewSweepState {
|
||||
phase: SweepPhase;
|
||||
runId: number;
|
||||
/** Scoped thread keys in review order. */
|
||||
order: ReadonlyArray<string>;
|
||||
items: Readonly<Record<string, SweepItem>>;
|
||||
/** Count of candidates dropped by SWEEP_MAX_THREADS (0 = full coverage). */
|
||||
truncatedCount: number;
|
||||
/** Bumped when sidebar-owned PR states change; the pre-run summary
|
||||
subscribes so its candidate count tracks the sidebar's partition. */
|
||||
candidateVersion: number;
|
||||
startRun: (input: {
|
||||
runId: number;
|
||||
items: ReadonlyArray<SweepItem>;
|
||||
truncatedCount: number;
|
||||
}) => void;
|
||||
patchItem: (key: string, patch: Partial<SweepItem>) => void;
|
||||
finishRun: (runId: number) => void;
|
||||
bumpCandidateVersion: () => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
const SWEEP_STORAGE_KEY = "t3code:review-sweep:v1";
|
||||
|
||||
export const useReviewSweepStore = create<ReviewSweepState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
phase: "idle",
|
||||
runId: 0,
|
||||
order: [],
|
||||
items: {},
|
||||
truncatedCount: 0,
|
||||
candidateVersion: 0,
|
||||
startRun: ({ runId, items, truncatedCount }) =>
|
||||
set({
|
||||
phase: "running",
|
||||
runId,
|
||||
order: items.map((item) => scopedThreadKey(item.ref)),
|
||||
items: Object.fromEntries(items.map((item) => [scopedThreadKey(item.ref), item])),
|
||||
truncatedCount,
|
||||
}),
|
||||
patchItem: (key, patch) =>
|
||||
set((state) => {
|
||||
const existing = state.items[key];
|
||||
if (!existing) return state;
|
||||
return { items: { ...state.items, [key]: { ...existing, ...patch } } };
|
||||
}),
|
||||
finishRun: (runId) => set((state) => (state.runId === runId ? { phase: "complete" } : state)),
|
||||
bumpCandidateVersion: () =>
|
||||
set((state) => ({ candidateVersion: state.candidateVersion + 1 })),
|
||||
reset: () => set({ phase: "idle", order: [], items: {}, truncatedCount: 0 }),
|
||||
}),
|
||||
{
|
||||
name: SWEEP_STORAGE_KEY,
|
||||
version: 1,
|
||||
storage: createJSONStorage(() => window.localStorage),
|
||||
// candidateVersion is a live signal, not state worth keeping.
|
||||
partialize: (state) => ({
|
||||
phase: state.phase,
|
||||
runId: state.runId,
|
||||
order: state.order,
|
||||
items: state.items,
|
||||
truncatedCount: state.truncatedCount,
|
||||
}),
|
||||
merge: (persisted, current) => {
|
||||
const restored = { ...current, ...(persisted as Partial<ReviewSweepState>) };
|
||||
// In-flight RPCs don't survive a reload: anything still pending or
|
||||
// running when the page died rehydrates as a retry-able error, and
|
||||
// an interrupted run reports as complete so the header offers
|
||||
// Re-run instead of a progress bar that will never advance.
|
||||
const items = Object.fromEntries(
|
||||
Object.entries(restored.items).map(([key, item]) => [
|
||||
key,
|
||||
item.status === "pending" || item.status === "running"
|
||||
? {
|
||||
...item,
|
||||
status: "error" as const,
|
||||
errorMessage: "Interrupted by reload — retry to review this thread.",
|
||||
finishedAtMs: item.finishedAtMs ?? Date.now(),
|
||||
}
|
||||
: item,
|
||||
]),
|
||||
);
|
||||
return {
|
||||
...restored,
|
||||
items,
|
||||
phase: restored.phase === "running" ? "complete" : restored.phase,
|
||||
};
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
function readServerCapabilities(environmentId: EnvironmentId) {
|
||||
return appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
|
||||
.capabilities;
|
||||
}
|
||||
|
||||
/** The sweep-eligibility predicate, mirroring SidebarV2's active-card
|
||||
partition. Exported so the pre-run confirmation screen counts exactly
|
||||
the threads a run would review. */
|
||||
export function isSweepCandidate(
|
||||
shell: EnvironmentThreadShell,
|
||||
capabilities: { threadSettlement?: boolean; reviewSweep?: boolean } | undefined,
|
||||
options: { readonly now: string; readonly autoSettleAfterDays: number | null },
|
||||
): boolean {
|
||||
if (shell.archivedAt !== null) return false;
|
||||
if (capabilities?.threadSettlement !== true || capabilities.reviewSweep !== true) return false;
|
||||
// PR state comes from SidebarV2's per-row subscriptions via
|
||||
// publishSweepChangeRequestStates, so merged-PR+idle threads classify as
|
||||
// settled here exactly like they do in the sidebar. Rows that haven't
|
||||
// reported yet fall back to null (treated as unsettled) — same as a
|
||||
// freshly mounted sidebar.
|
||||
const changeRequestState =
|
||||
changeRequestStateByKey.get(scopedThreadKey(scopeThreadRef(shell.environmentId, shell.id))) ??
|
||||
null;
|
||||
return !effectiveSettled(shell, {
|
||||
now: options.now,
|
||||
autoSettleAfterDays: options.autoSettleAfterDays,
|
||||
changeRequestState,
|
||||
});
|
||||
}
|
||||
|
||||
/** Minute-quantized clock, matching SidebarV2's `nowMinute`. Using a raw
|
||||
wall clock here would disagree with the sidebar around the merged-PR
|
||||
idle boundary and include threads the sidebar already shows as settled. */
|
||||
export function sweepNowIso(): string {
|
||||
return `${new Date().toISOString().slice(0, 16)}:00.000Z`;
|
||||
}
|
||||
|
||||
/** All unsettled, unarchived threads across every connected environment that
|
||||
supports the sweep, most recently active first — the exact order the
|
||||
SWEEP_MAX_THREADS cap is applied in. */
|
||||
export function collectSweepCandidates(): EnvironmentThreadShell[] {
|
||||
const now = sweepNowIso();
|
||||
const autoSettleAfterDays = getClientSettings().sidebarAutoSettleAfterDays;
|
||||
const candidates: EnvironmentThreadShell[] = [];
|
||||
for (const ref of readThreadRefs()) {
|
||||
const shell = readThreadShell(ref);
|
||||
if (!shell) continue;
|
||||
const capabilities = readServerCapabilities(shell.environmentId);
|
||||
if (!isSweepCandidate(shell, capabilities, { now, autoSettleAfterDays })) continue;
|
||||
candidates.push(shell);
|
||||
}
|
||||
return sortSweepCandidates(candidates);
|
||||
}
|
||||
|
||||
/** Most recently active first, so the SWEEP_MAX_THREADS cap drops the
|
||||
longest-idle threads rather than the oldest-created ones. Exported so
|
||||
the pre-run summary previews the exact capped selection. */
|
||||
export function sortSweepCandidates(
|
||||
candidates: ReadonlyArray<EnvironmentThreadShell>,
|
||||
): EnvironmentThreadShell[] {
|
||||
const activityMs = (shell: EnvironmentThreadShell): number =>
|
||||
toSortableTimestamp(threadLastActivityAt(shell) ?? undefined) ??
|
||||
toSortableTimestamp(shell.createdAt) ??
|
||||
0;
|
||||
return [...candidates].sort((a, b) => activityMs(b) - activityMs(a));
|
||||
}
|
||||
|
||||
async function reviewOne(runId: number, item: SweepItem): Promise<void> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
if (store.runId !== runId) return;
|
||||
const key = scopedThreadKey(item.ref);
|
||||
store.patchItem(key, { status: "running", startedAtMs: Date.now(), finishedAtMs: null });
|
||||
|
||||
const shell = readThreadShell(item.ref);
|
||||
const canSettleNow = shell !== null && canSettle(shell, { now: new Date().toISOString() });
|
||||
const modelSelection = readSweepModelSelection();
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
reviewEnvironment.summarizeThread,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: {
|
||||
threadId: item.ref.threadId,
|
||||
canSettleNow,
|
||||
...(modelSelection !== null ? { modelSelection } : {}),
|
||||
},
|
||||
},
|
||||
{ reportFailure: false, reportDefect: false },
|
||||
);
|
||||
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId !== runId) return;
|
||||
if (result._tag === "Success") {
|
||||
current.patchItem(key, {
|
||||
status: "done",
|
||||
result: result.value,
|
||||
errorMessage: null,
|
||||
finishedAtMs: Date.now(),
|
||||
});
|
||||
} else {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
current.patchItem(key, {
|
||||
status: "error",
|
||||
errorMessage: error instanceof Error ? error.message : "Review failed.",
|
||||
finishedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Navigation callback installed by the app shell so store-level toasts can
|
||||
deep-link to /review-sweep without importing the router. */
|
||||
let navigateToSweepResults: (() => void) | null = null;
|
||||
export function setSweepResultsNavigator(navigate: (() => void) | null): void {
|
||||
navigateToSweepResults = navigate;
|
||||
}
|
||||
|
||||
function isViewingSweepResults(): boolean {
|
||||
return window.location.pathname === "/review-sweep";
|
||||
}
|
||||
|
||||
async function runPool(runId: number, items: ReadonlyArray<SweepItem>): Promise<void> {
|
||||
let next = 0;
|
||||
const workers = Array.from({ length: Math.min(SWEEP_CONCURRENCY, items.length) }, async () => {
|
||||
while (next < items.length) {
|
||||
if (useReviewSweepStore.getState().runId !== runId) return;
|
||||
const item = items[next];
|
||||
next += 1;
|
||||
if (item) await reviewOne(runId, item);
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
const store = useReviewSweepStore.getState();
|
||||
if (store.runId !== runId) return;
|
||||
store.finishRun(runId);
|
||||
// The sweep runs in the background; only toast when the user isn't
|
||||
// already staring at the results page.
|
||||
if (!isViewingSweepResults()) {
|
||||
const actionable = Object.values(store.items).filter(
|
||||
(item) =>
|
||||
!item.dismissed &&
|
||||
((item.result?.suggestedTitle && !item.titleApplied) ||
|
||||
(item.result?.recommendSettle && !item.settleApplied) ||
|
||||
item.result?.prStatus?.mergeReady === true),
|
||||
).length;
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "success",
|
||||
title: "Work review finished",
|
||||
description:
|
||||
actionable > 0
|
||||
? `${actionable} ${actionable === 1 ? "thread has" : "threads have"} recommended actions.`
|
||||
: "No actions recommended — you're caught up.",
|
||||
actionVariant: "outline",
|
||||
actionProps: {
|
||||
children: "View results",
|
||||
onClick: () => navigateToSweepResults?.(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Kick off a sweep over every unsettled thread. Runs outside React so it
|
||||
survives navigation; results land in the store as they arrive. */
|
||||
export function startReviewSweep(): void {
|
||||
const runId = useReviewSweepStore.getState().runId + 1;
|
||||
const candidates = collectSweepCandidates();
|
||||
const reviewed = candidates.slice(0, SWEEP_MAX_THREADS);
|
||||
const items = reviewed.map(
|
||||
(shell): SweepItem => ({
|
||||
ref: scopeThreadRef(shell.environmentId, shell.id),
|
||||
projectId: shell.projectId,
|
||||
threadTitle: shell.title,
|
||||
branch: shell.branch,
|
||||
lastActivityAt: threadLastActivityAt(shell) ?? shell.createdAt,
|
||||
status: "pending",
|
||||
result: null,
|
||||
errorMessage: null,
|
||||
titleApplied: false,
|
||||
settleApplied: false,
|
||||
dismissed: false,
|
||||
mergeStatus: "idle",
|
||||
mergeDetail: null,
|
||||
startedAtMs: null,
|
||||
finishedAtMs: null,
|
||||
}),
|
||||
);
|
||||
useReviewSweepStore.getState().startRun({
|
||||
runId,
|
||||
items,
|
||||
truncatedCount: candidates.length - reviewed.length,
|
||||
});
|
||||
if (items.length === 0) {
|
||||
useReviewSweepStore.getState().finishRun(runId);
|
||||
return;
|
||||
}
|
||||
void runPool(runId, items);
|
||||
}
|
||||
|
||||
export function retrySweepItem(key: string): void {
|
||||
const store = useReviewSweepStore.getState();
|
||||
const item = store.items[key];
|
||||
if (!item || item.status === "running") return;
|
||||
void reviewOne(store.runId, item);
|
||||
}
|
||||
|
||||
export async function applySweepTitle(key: string): Promise<boolean> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
const runId = store.runId;
|
||||
const item = store.items[key];
|
||||
const suggestedTitle = item?.result?.suggestedTitle;
|
||||
if (!item || !suggestedTitle || item.titleApplied) return false;
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
threadEnvironment.updateMetadata,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: { threadId: item.ref.threadId, title: suggestedTitle },
|
||||
},
|
||||
{ reportFailure: false },
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to rename thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// The rename itself succeeded either way, but a Re-run mid-flight replaces
|
||||
// the item set with fresh reviews — don't stamp stale applied-state onto
|
||||
// the new run's card.
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId === runId) {
|
||||
current.patchItem(key, { titleApplied: true, threadTitle: suggestedTitle });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function applySweepSettle(key: string): Promise<boolean> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
const runId = store.runId;
|
||||
const item = store.items[key];
|
||||
if (!item || !item.result?.recommendSettle || item.settleApplied) return false;
|
||||
// Re-check against the live shell: the thread may have gone active since
|
||||
// the review ran, and settling live work would hide it.
|
||||
const shell = readThreadShell(item.ref);
|
||||
if (!shell || !canSettle(shell, { now: new Date().toISOString() })) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: "Thread is active again",
|
||||
description: "This thread picked up new activity since the review, so it stays active.",
|
||||
}),
|
||||
);
|
||||
// The recommendation is now known-stale — withdraw it so the card stops
|
||||
// advertising a settle the live guard just refused.
|
||||
store.patchItem(key, {
|
||||
result: { ...item.result, recommendSettle: false, settleReason: null },
|
||||
});
|
||||
return false;
|
||||
}
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
threadEnvironment.settle,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: { threadId: item.ref.threadId },
|
||||
},
|
||||
{ reportFailure: false },
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to settle thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Same staleness guard as applySweepTitle: never patch a newer run's item.
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId === runId) {
|
||||
current.patchItem(key, { settleApplied: true });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Sequentially apply every un-dismissed recommendation: titles first, then
|
||||
settles, tolerating per-item failures (each failure already toasts).
|
||||
Items are re-read from the store on every step so dismissals (and
|
||||
re-runs) mid-apply are respected. */
|
||||
export async function applyAllSweepRecommendations(): Promise<void> {
|
||||
const { order, runId } = useReviewSweepStore.getState();
|
||||
for (const key of order) {
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId !== runId) return;
|
||||
const item = current.items[key];
|
||||
if (!item || item.dismissed) continue;
|
||||
if (item.result?.suggestedTitle && !item.titleApplied) {
|
||||
await applySweepTitle(key);
|
||||
}
|
||||
}
|
||||
for (const key of order) {
|
||||
const current = useReviewSweepStore.getState();
|
||||
if (current.runId !== runId) return;
|
||||
const item = current.items[key];
|
||||
if (!item || item.dismissed) continue;
|
||||
if (item.result?.recommendSettle && !item.settleApplied) {
|
||||
await applySweepSettle(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function dismissSweepItem(key: string): void {
|
||||
useReviewSweepStore.getState().patchItem(key, { dismissed: true });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Merge queue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Message sent to a thread's agent when its PR stopped merging cleanly
|
||||
because earlier queue entries landed first. */
|
||||
function conflictHandoffMessage(prNumber: number): string {
|
||||
return [
|
||||
`PR #${prNumber} no longer merges cleanly — other pull requests were merged into the base branch ahead of it.`,
|
||||
"Please rebase this branch onto the latest base branch, resolve any merge conflicts, verify the build still passes, and push the updated branch.",
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
function isMergeQueueCandidate(item: SweepItem): boolean {
|
||||
return (
|
||||
!item.dismissed &&
|
||||
item.result?.prStatus?.mergeReady === true &&
|
||||
(item.mergeStatus === "idle" || item.mergeStatus === "queued")
|
||||
);
|
||||
}
|
||||
|
||||
let mergeQueueActive = false;
|
||||
|
||||
/** Merge one item's PR and settle its thread on success. On conflict, mark
|
||||
the card and hand the rebase to the thread's agent. Returns the outcome
|
||||
for queue accounting. */
|
||||
async function mergeOne(
|
||||
runId: number,
|
||||
key: string,
|
||||
): Promise<"merged" | "conflict" | "skipped" | "failed"> {
|
||||
const store = useReviewSweepStore.getState();
|
||||
if (store.runId !== runId) return "skipped";
|
||||
const item = store.items[key];
|
||||
const prNumber = item?.result?.prStatus?.number;
|
||||
if (!item || prNumber === undefined) return "skipped";
|
||||
store.patchItem(key, { mergeStatus: "merging" });
|
||||
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
reviewEnvironment.mergePullRequest,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: { threadId: item.ref.threadId, pullRequestNumber: prNumber },
|
||||
},
|
||||
{ reportFailure: false, reportDefect: false },
|
||||
);
|
||||
|
||||
const after = useReviewSweepStore.getState();
|
||||
if (after.runId !== runId) return "skipped";
|
||||
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
after.patchItem(key, {
|
||||
mergeStatus: "failed",
|
||||
mergeDetail: error instanceof Error ? error.message : "Merge failed.",
|
||||
});
|
||||
return "failed";
|
||||
}
|
||||
|
||||
const outcome = result.value.outcome;
|
||||
if (outcome === "merged" || outcome === "already-closed") {
|
||||
after.patchItem(key, { mergeStatus: "merged", mergeDetail: result.value.detail });
|
||||
// Merged PRs are concluded work: settle right away so the sidebar
|
||||
// reflects the merge without waiting for auto-settle.
|
||||
const settleResult = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
threadEnvironment.settle,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: { threadId: item.ref.threadId },
|
||||
},
|
||||
{ reportFailure: false },
|
||||
);
|
||||
if (settleResult._tag === "Success") {
|
||||
useReviewSweepStore.getState().patchItem(key, { settleApplied: true });
|
||||
}
|
||||
return "merged";
|
||||
}
|
||||
|
||||
if (outcome === "conflict") {
|
||||
after.patchItem(key, { mergeStatus: "conflicted", mergeDetail: result.value.detail });
|
||||
// Hand the conflict to the thread's own agent: it has the branch
|
||||
// checked out and the full context to rebase and resolve.
|
||||
await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
threadEnvironment.startTurn,
|
||||
{
|
||||
environmentId: item.ref.environmentId,
|
||||
input: {
|
||||
threadId: item.ref.threadId,
|
||||
message: {
|
||||
messageId: newMessageId(),
|
||||
role: "user" as const,
|
||||
text: conflictHandoffMessage(prNumber),
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
{ reportFailure: false },
|
||||
);
|
||||
return "conflict";
|
||||
}
|
||||
|
||||
after.patchItem(key, { mergeStatus: "failed", mergeDetail: result.value.detail });
|
||||
return "failed";
|
||||
}
|
||||
|
||||
/** Merge a single card's PR (per-item button). */
|
||||
export async function mergeSweepItem(key: string): Promise<void> {
|
||||
const { runId } = useReviewSweepStore.getState();
|
||||
await mergeOne(runId, key);
|
||||
}
|
||||
|
||||
/** Merge every merge-ready PR SEQUENTIALLY — one at a time, so each merge
|
||||
sees the base branch the previous one produced and the server re-check
|
||||
catches freshly introduced conflicts. Conflicts don't stop the queue:
|
||||
the item is marked conflicted and its thread's agent is asked to rebase
|
||||
and resolve; re-run the sweep once it pushes to pick the PR back up. */
|
||||
export async function runMergeQueue(): Promise<void> {
|
||||
if (mergeQueueActive) return;
|
||||
mergeQueueActive = true;
|
||||
try {
|
||||
const { order, items, runId } = useReviewSweepStore.getState();
|
||||
const queueKeys = order.filter((key) => {
|
||||
const item = items[key];
|
||||
return item !== undefined && isMergeQueueCandidate(item);
|
||||
});
|
||||
for (const key of queueKeys) {
|
||||
useReviewSweepStore.getState().patchItem(key, { mergeStatus: "queued" });
|
||||
}
|
||||
|
||||
let mergedCount = 0;
|
||||
let conflictCount = 0;
|
||||
for (const key of queueKeys) {
|
||||
const outcome = await mergeOne(runId, key);
|
||||
if (outcome === "merged") mergedCount += 1;
|
||||
if (outcome === "conflict") conflictCount += 1;
|
||||
if (useReviewSweepStore.getState().runId !== runId) return;
|
||||
}
|
||||
|
||||
if (queueKeys.length > 0) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: conflictCount > 0 ? "warning" : "success",
|
||||
title: `Merge queue finished: ${mergedCount} of ${queueKeys.length} merged`,
|
||||
description:
|
||||
conflictCount > 0
|
||||
? `${conflictCount} ${conflictCount === 1 ? "PR hit a conflict and was" : "PRs hit conflicts and were"} handed to ${conflictCount === 1 ? "its" : "their"} thread's agent to rebase.`
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
mergeQueueActive = false;
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as SettingsRouteImport } from './routes/settings'
|
||||
import { Route as ReviewSweepRouteImport } from './routes/review-sweep'
|
||||
import { Route as PairRouteImport } from './routes/pair'
|
||||
import { Route as ConnectRouteImport } from './routes/connect'
|
||||
import { Route as ChatRouteImport } from './routes/_chat'
|
||||
@@ -32,11 +31,6 @@ const SettingsRoute = SettingsRouteImport.update({
|
||||
path: '/settings',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ReviewSweepRoute = ReviewSweepRouteImport.update({
|
||||
id: '/review-sweep',
|
||||
path: '/review-sweep',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const PairRoute = PairRouteImport.update({
|
||||
id: '/pair',
|
||||
path: '/pair',
|
||||
@@ -117,7 +111,6 @@ export interface FileRoutesByFullPath {
|
||||
'/': typeof ChatIndexRoute
|
||||
'/connect': typeof ConnectRoute
|
||||
'/pair': typeof PairRoute
|
||||
'/review-sweep': typeof ReviewSweepRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
@@ -134,7 +127,6 @@ export interface FileRoutesByFullPath {
|
||||
export interface FileRoutesByTo {
|
||||
'/connect': typeof ConnectRoute
|
||||
'/pair': typeof PairRoute
|
||||
'/review-sweep': typeof ReviewSweepRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
@@ -154,7 +146,6 @@ export interface FileRoutesById {
|
||||
'/_chat': typeof ChatRouteWithChildren
|
||||
'/connect': typeof ConnectRoute
|
||||
'/pair': typeof PairRoute
|
||||
'/review-sweep': typeof ReviewSweepRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect_/callback': typeof ConnectCallbackRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
@@ -175,7 +166,6 @@ export interface FileRouteTypes {
|
||||
| '/'
|
||||
| '/connect'
|
||||
| '/pair'
|
||||
| '/review-sweep'
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/archived'
|
||||
@@ -192,7 +182,6 @@ export interface FileRouteTypes {
|
||||
to:
|
||||
| '/connect'
|
||||
| '/pair'
|
||||
| '/review-sweep'
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/archived'
|
||||
@@ -211,7 +200,6 @@ export interface FileRouteTypes {
|
||||
| '/_chat'
|
||||
| '/connect'
|
||||
| '/pair'
|
||||
| '/review-sweep'
|
||||
| '/settings'
|
||||
| '/connect_/callback'
|
||||
| '/settings/archived'
|
||||
@@ -231,7 +219,6 @@ export interface RootRouteChildren {
|
||||
ChatRoute: typeof ChatRouteWithChildren
|
||||
ConnectRoute: typeof ConnectRoute
|
||||
PairRoute: typeof PairRoute
|
||||
ReviewSweepRoute: typeof ReviewSweepRoute
|
||||
SettingsRoute: typeof SettingsRouteWithChildren
|
||||
ConnectCallbackRoute: typeof ConnectCallbackRoute
|
||||
}
|
||||
@@ -245,13 +232,6 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/review-sweep': {
|
||||
id: '/review-sweep'
|
||||
path: '/review-sweep'
|
||||
fullPath: '/review-sweep'
|
||||
preLoaderRoute: typeof ReviewSweepRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/pair': {
|
||||
id: '/pair'
|
||||
path: '/pair'
|
||||
@@ -404,7 +384,6 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
ChatRoute: ChatRouteWithChildren,
|
||||
ConnectRoute: ConnectRoute,
|
||||
PairRoute: PairRoute,
|
||||
ReviewSweepRoute: ReviewSweepRoute,
|
||||
SettingsRoute: SettingsRouteWithChildren,
|
||||
ConnectCallbackRoute: ConnectCallbackRoute,
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { createFileRoute, redirect } from "@tanstack/react-router";
|
||||
|
||||
import { ReviewSweepView } from "../components/reviewSweep/ReviewSweepView";
|
||||
|
||||
export const Route = createFileRoute("/review-sweep")({
|
||||
beforeLoad: async ({ context }) => {
|
||||
if (
|
||||
context.authGateState.status !== "authenticated" &&
|
||||
context.authGateState.status !== "hosted-static"
|
||||
) {
|
||||
throw redirect({ to: "/pair", replace: true });
|
||||
}
|
||||
},
|
||||
component: ReviewSweepView,
|
||||
});
|
||||
@@ -207,15 +207,6 @@ export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId):
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the environment's server understands thread.snooze/unsnooze.
|
||||
Same version-skew contract as settlement. */
|
||||
export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSnooze === true
|
||||
);
|
||||
}
|
||||
|
||||
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
|
||||
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ function getTimestampFormatter(
|
||||
return formatter;
|
||||
}
|
||||
|
||||
export function parseTimestampDate(isoDate: string): Date | null {
|
||||
function parseTimestampDate(isoDate: string): Date | null {
|
||||
const date = new Date(isoDate);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
+25
-74
@@ -7,27 +7,14 @@ import "vite-plus/test/config";
|
||||
import { defineConfig } from "vite-plus";
|
||||
import pkg from "./package.json" with { type: "json" };
|
||||
|
||||
import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
|
||||
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config";
|
||||
|
||||
const repoEnv = loadRepoEnv();
|
||||
Object.assign(process.env, repoEnv);
|
||||
|
||||
// Single-origin dev is signalled positively, because it cannot be inferred
|
||||
// from the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys
|
||||
// but `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so
|
||||
// a developer with either URL in their `.env` gets it back here. Baking it then
|
||||
// pins the client to localhost and breaks every non-localhost origin — the
|
||||
// exact failure single-origin mode exists to prevent, and an invisible one
|
||||
// since the page still loads.
|
||||
const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
|
||||
|
||||
const port = Number(process.env.PORT ?? 5733);
|
||||
const explicitHost = process.env.HOST?.trim();
|
||||
const host = explicitHost || "localhost";
|
||||
const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
|
||||
const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
|
||||
const host = process.env.HOST?.trim() || "localhost";
|
||||
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
|
||||
const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
|
||||
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
|
||||
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
|
||||
@@ -78,20 +65,7 @@ const unitTestProject = {
|
||||
},
|
||||
} satisfies TestProjectInlineConfiguration;
|
||||
|
||||
function resolveDevProxyTarget(
|
||||
backendPort: string | undefined,
|
||||
wsUrl: string | undefined,
|
||||
): string | undefined {
|
||||
// Browser dev is single-origin: the backend port is proxied through this
|
||||
// server so the app works from any origin (localhost, tailnet, LAN, phone).
|
||||
// T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
|
||||
const port = Number(backendPort?.trim());
|
||||
if (Number.isInteger(port) && port > 0) {
|
||||
return `http://localhost:${port}/`;
|
||||
}
|
||||
|
||||
// dev:desktop still points the renderer straight at the backend, so fall
|
||||
// back to deriving the target from the explicit websocket URL.
|
||||
function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
|
||||
if (!wsUrl) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -112,17 +86,7 @@ function resolveDevProxyTarget(
|
||||
}
|
||||
}
|
||||
|
||||
const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
|
||||
|
||||
// Vite rejects requests whose Host header isn't localhost, which blocks sharing
|
||||
// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
|
||||
// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
|
||||
// Anything else (ngrok, a LAN IP alias) goes through the env var.
|
||||
const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0);
|
||||
const allowedHosts = [".ts.net", ...configuredAllowedHosts];
|
||||
const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
|
||||
|
||||
export default defineConfig(() => {
|
||||
return {
|
||||
@@ -155,10 +119,6 @@ export default defineConfig(() => {
|
||||
define: {
|
||||
// In dev mode, tell the web app where the WebSocket server lives
|
||||
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
|
||||
// Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
|
||||
// under single-origin dev this must stay empty even when a `.env`
|
||||
// supplies it, so the client falls back to window.location.origin.
|
||||
"import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
|
||||
"import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
|
||||
"import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
|
||||
"import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
|
||||
@@ -185,41 +145,32 @@ export default defineConfig(() => {
|
||||
host,
|
||||
port,
|
||||
strictPort: true,
|
||||
allowedHosts,
|
||||
...(devProxyTarget
|
||||
? {
|
||||
// One entry per shared prefix; the server's dev catch-all 404s the
|
||||
// same list, so the two sides cannot drift. `/ws` is the app's own
|
||||
// socket — Vite's HMR socket is matched separately and exactly
|
||||
// (path "/" plus a vite-hmr subprotocol), so the two upgrade
|
||||
// handlers don't collide.
|
||||
proxy: Object.fromEntries(
|
||||
DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
|
||||
prefix,
|
||||
{
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
...(prefix === "/ws" ? { ws: true } : {}),
|
||||
},
|
||||
]),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
// Electron's BrowserWindow needs the HMR socket pinned to an explicit
|
||||
// host to connect reliably; dev:desktop is the only mode that sets HOST.
|
||||
// Everywhere else, leaving this unset lets the client derive it from the
|
||||
// page origin, which is what makes HMR work over Tailscale/LAN instead of
|
||||
// failing an attempt against the wrong machine's localhost first.
|
||||
// (Vite 8 logs connection state via console.debug — enable "Verbose".)
|
||||
...(explicitHost
|
||||
? {
|
||||
hmr: {
|
||||
protocol: "ws",
|
||||
host: explicitHost,
|
||||
clientPort: port,
|
||||
proxy: {
|
||||
"/.well-known": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/api": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/attachments": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
hmr: {
|
||||
// Explicit config so Vite's HMR WebSocket connects reliably
|
||||
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
|
||||
// connection logs — enable "Verbose" in DevTools to see them.
|
||||
protocol: "ws",
|
||||
host,
|
||||
clientPort: port,
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: "dist",
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
# Scripts
|
||||
|
||||
- `vp run dev` — Starts contracts, server, and web in watch mode.
|
||||
- `vp run dev --share` — Also publishes the web port over HTTPS on this machine's tailnet. The startup pairing URL is built against the shared origin, and the mapping is removed on exit.
|
||||
- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.
|
||||
- `vp run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands run from a linked **git worktree** default to that worktree's gitignored `.t3`, even when `T3CODE_HOME` is set, storing state in `<worktree>/.t3/userdata`. Pass `--home-dir <path>` to choose another isolated directory explicitly. Submodules are not worktrees and keep the normal precedence.
|
||||
- From the **main checkout**, dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
|
||||
- Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
|
||||
- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
|
||||
- Pass dev-runner flags directly after the root task name, for example:
|
||||
`vp run dev --home-dir /tmp/t3code-dev`
|
||||
@@ -25,7 +23,6 @@
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/prod/black-macos-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3code://app/index.html` (not a `127.0.0.1` document URL).
|
||||
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `vp run dist:desktop:dmg -- --keep-stage`
|
||||
@@ -39,12 +36,6 @@
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
## Browser development
|
||||
|
||||
`dev` and `dev:web` leave `VITE_HTTP_URL` and `VITE_WS_URL` unset so the browser resolves the backend from `window.location.origin`. Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the server, allowing the same bundle to work from localhost or a tailnet hostname.
|
||||
|
||||
Worktrees derive a preferred port offset from their path. The runner shifts both ports together when either is occupied or the web port is blocked by browsers, so treat the `[dev-runner]` output as authoritative.
|
||||
|
||||
## Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
"scripts": {
|
||||
"prepare": "effect-tsgo patch && vp config --no-agent",
|
||||
"dev": "node scripts/dev-runner.ts dev",
|
||||
"dev:share": "node scripts/dev-runner.ts dev --share",
|
||||
"dev:server": "node scripts/dev-runner.ts dev:server",
|
||||
"dev:web": "node scripts/dev-runner.ts dev:web",
|
||||
"dev:marketing": "vp run --filter @t3tools/marketing dev",
|
||||
|
||||
@@ -37,8 +37,6 @@ export type ArchiveThreadInput = CommandInput<"thread.archive">;
|
||||
export type UnarchiveThreadInput = CommandInput<"thread.unarchive">;
|
||||
export type SettleThreadInput = CommandInput<"thread.settle">;
|
||||
export type UnsettleThreadInput = CommandInput<"thread.unsettle">;
|
||||
export type SnoozeThreadInput = CommandInput<"thread.snooze">;
|
||||
export type UnsnoozeThreadInput = CommandInput<"thread.unsnooze">;
|
||||
export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;
|
||||
export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;
|
||||
export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;
|
||||
@@ -177,26 +175,6 @@ export const unsettleThread: (input: UnsettleThreadInput) => CommandEffect = Eff
|
||||
});
|
||||
});
|
||||
|
||||
export const snoozeThread: (input: SnoozeThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.snoozeThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.snooze",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const unsnoozeThread: (input: UnsnoozeThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.unsnoozeThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.unsnooze",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.updateThreadMetadata",
|
||||
)(function* (input) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
|
||||
import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
|
||||
export function createReviewEnvironmentAtoms<R, E>(
|
||||
@@ -13,13 +13,5 @@ export function createReviewEnvironmentAtoms<R, E>(
|
||||
tag: WS_METHODS.reviewGetDiffPreview,
|
||||
staleTimeMs: 5_000,
|
||||
}),
|
||||
summarizeThread: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:review:summarize-thread",
|
||||
tag: WS_METHODS.reviewSummarizeThread,
|
||||
}),
|
||||
mergePullRequest: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:review:merge-pull-request",
|
||||
tag: WS_METHODS.reviewMergePullRequest,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -13,12 +13,10 @@ import {
|
||||
type SetThreadInteractionModeInput,
|
||||
type SetThreadRuntimeModeInput,
|
||||
type SettleThreadInput,
|
||||
type SnoozeThreadInput,
|
||||
type StartThreadTurnInput,
|
||||
type StopThreadSessionInput,
|
||||
type UnarchiveThreadInput,
|
||||
type UnsettleThreadInput,
|
||||
type UnsnoozeThreadInput,
|
||||
type UpdateThreadMetadataInput,
|
||||
archiveThread,
|
||||
createThread,
|
||||
@@ -30,12 +28,10 @@ import {
|
||||
setThreadInteractionMode,
|
||||
setThreadRuntimeMode,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
startThreadTurn,
|
||||
stopThreadSession,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
updateThreadMetadata,
|
||||
} from "../operations/commands.ts";
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
@@ -51,12 +47,10 @@ export type {
|
||||
SetThreadInteractionModeInput,
|
||||
SetThreadRuntimeModeInput,
|
||||
SettleThreadInput,
|
||||
SnoozeThreadInput,
|
||||
StartThreadTurnInput,
|
||||
StopThreadSessionInput,
|
||||
UnarchiveThreadInput,
|
||||
UnsettleThreadInput,
|
||||
UnsnoozeThreadInput,
|
||||
UpdateThreadMetadataInput,
|
||||
} from "../operations/commands.ts";
|
||||
|
||||
@@ -106,18 +100,6 @@ export function createThreadEnvironmentAtoms<R, E>(
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
snooze: createEnvironmentCommand(runtime, {
|
||||
label: "environment-data:commands:thread:snooze",
|
||||
execute: (input: SnoozeThreadInput) => snoozeThread(input),
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
unsnooze: createEnvironmentCommand(runtime, {
|
||||
label: "environment-data:commands:thread:unsnooze",
|
||||
execute: (input: UnsnoozeThreadInput) => unsnoozeThread(input),
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
updateMetadata: createEnvironmentCommand(runtime, {
|
||||
label: "environment-data:commands:thread:update-metadata",
|
||||
execute: (input: UpdateThreadMetadataInput) => updateThreadMetadata(input),
|
||||
|
||||
@@ -59,8 +59,6 @@ export function mergeEnvironmentThread(
|
||||
archivedAt: shell.archivedAt,
|
||||
settledOverride: shell.settledOverride,
|
||||
settledAt: shell.settledAt,
|
||||
snoozedUntil: shell.snoozedUntil,
|
||||
snoozedAt: shell.snoozedAt,
|
||||
session: shell.session,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -74,8 +74,6 @@ export function applyThreadDetailEvent(
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
@@ -126,28 +124,6 @@ export function applyThreadDetailEvent(
|
||||
},
|
||||
};
|
||||
|
||||
case "thread.snoozed":
|
||||
return {
|
||||
kind: "updated",
|
||||
thread: {
|
||||
...thread,
|
||||
snoozedUntil: event.payload.snoozedUntil,
|
||||
snoozedAt: event.payload.snoozedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
},
|
||||
};
|
||||
|
||||
case "thread.unsnoozed":
|
||||
return {
|
||||
kind: "updated",
|
||||
thread: {
|
||||
...thread,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
},
|
||||
};
|
||||
|
||||
// ── Thread metadata ─────────────────────────────────────────────
|
||||
case "thread.meta-updated":
|
||||
return {
|
||||
|
||||
@@ -90,130 +90,6 @@ export function canSettle(
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The snooze lifecycle fields plus everything needed to detect a raised
|
||||
* hand. Snooze is an overlay on the active state: a snoozed thread stays
|
||||
* "active" in the data model and is only suppressed from the inbox until
|
||||
* its wake time passes or the thread demands attention.
|
||||
*/
|
||||
export type ThreadSnoozeShell = Pick<
|
||||
OrchestrationThreadShell,
|
||||
| "snoozedUntil"
|
||||
| "snoozedAt"
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingUserInput"
|
||||
| "session"
|
||||
| "latestTurn"
|
||||
>;
|
||||
|
||||
/**
|
||||
* A snoozed thread "raises its hand" when something happens that outranks
|
||||
* the user's snooze: the agent is blocked on them (approval / user input),
|
||||
* the session failed, or a run completed after the snooze was set — the
|
||||
* v1 taste of event-based snooze ("something happened" wakes early).
|
||||
* Raising a hand never clears the server-side snooze fields; it only stops
|
||||
* the thread from CLASSIFYING as snoozed, exactly like blocked work and
|
||||
* effectiveSettled.
|
||||
*/
|
||||
export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
|
||||
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
|
||||
// Only a FRESH failure raises the hand: a thread snoozed while already
|
||||
// failed stays snoozed — that snooze was the user saying "I saw it, not
|
||||
// now". session.updatedAt stamps the status edge, so an error newer than
|
||||
// the snooze is new information.
|
||||
if (
|
||||
shell.session?.status === "error" &&
|
||||
(shell.snoozedAt == null || Date.parse(shell.session.updatedAt) > Date.parse(shell.snoozedAt))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
shell.snoozedAt != null &&
|
||||
shell.latestTurn?.state === "completed" &&
|
||||
shell.latestTurn.completedAt != null &&
|
||||
Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A thread may be snoozed unless the agent is blocked on the user: hiding a
|
||||
* pending approval or user-input request defeats the request, and a queued
|
||||
* turn start (a message no turn has adopted yet) is invisible pending work
|
||||
* the same way it is for settle. A running session IS snoozable — snooze
|
||||
* only affects visibility, never the agent. Client-side twin of the server
|
||||
* invariants so the UI can reject before a round trip.
|
||||
*/
|
||||
export function canSnooze(
|
||||
shell: Pick<
|
||||
OrchestrationThreadShell,
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
|
||||
>,
|
||||
options: { readonly now: string },
|
||||
): boolean {
|
||||
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
|
||||
if (hasQueuedTurnStart(shell, options)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snoozed resolution: hidden from the inbox while the wake time is in the
|
||||
* future and the thread has not raised its hand. Timer wakes are derived —
|
||||
* no server event fires when snoozedUntil passes; the stale fields simply
|
||||
* stop classifying as snoozed (and feed the woke indicator until the user
|
||||
* visits or re-engages).
|
||||
*/
|
||||
export function effectiveSnoozed(
|
||||
shell: ThreadSnoozeShell,
|
||||
options: { readonly now: string },
|
||||
): boolean {
|
||||
if (shell.snoozedUntil == null) return false;
|
||||
const wakeAtMs = Date.parse(shell.snoozedUntil);
|
||||
// Malformed data never hides a thread.
|
||||
if (Number.isNaN(wakeAtMs)) return false;
|
||||
if (wakeAtMs <= Date.parse(options.now)) return false;
|
||||
return !threadRaisedHandWhileSnoozed(shell);
|
||||
}
|
||||
|
||||
/**
|
||||
* When a previously-snoozed thread woke, or null if it never snoozed / is
|
||||
* still snoozed. Used for the "Woke" indicator: the thread reappears in its
|
||||
* original sort position (the inbox sort is deliberately static), so the
|
||||
* wake signal has to carry the weight. Compare against the client's
|
||||
* lastVisitedAt — visiting clears the indicator like it clears unread.
|
||||
*
|
||||
* Timer wakes report the wake time itself; raised-hand wakes report the
|
||||
* triggering timestamp so a visit BEFORE the early wake doesn't suppress
|
||||
* the indicator.
|
||||
*/
|
||||
export function threadWokeAt(
|
||||
shell: ThreadSnoozeShell,
|
||||
options: { readonly now: string },
|
||||
): string | null {
|
||||
if (shell.snoozedUntil == null) return null;
|
||||
const wakeAtMs = Date.parse(shell.snoozedUntil);
|
||||
if (Number.isNaN(wakeAtMs)) return null;
|
||||
// An early hand-raise wake stays authoritative even after the scheduled
|
||||
// wake time passes: reporting snoozedUntil then would resurface a Woke
|
||||
// indicator the user already cleared by visiting (snoozedUntil is newer
|
||||
// than that visit's lastVisitedAt).
|
||||
if (threadRaisedHandWhileSnoozed(shell)) {
|
||||
if (
|
||||
shell.snoozedAt != null &&
|
||||
shell.latestTurn?.state === "completed" &&
|
||||
shell.latestTurn.completedAt != null &&
|
||||
Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
|
||||
) {
|
||||
return shell.latestTurn.completedAt;
|
||||
}
|
||||
return shell.session?.updatedAt ?? shell.snoozedAt ?? null;
|
||||
}
|
||||
// No raised hand: woke iff the timer elapsed (still-snoozed → null).
|
||||
return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A merged/closed change request settles its thread only once the thread has
|
||||
* been idle this long. Without the idle guard the merge signal is permanent:
|
||||
|
||||
@@ -1,237 +0,0 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
canSnooze,
|
||||
effectiveSnoozed,
|
||||
threadRaisedHandWhileSnoozed,
|
||||
threadWokeAt,
|
||||
type ThreadSnoozeShell,
|
||||
} from "./threadSettled.ts";
|
||||
|
||||
const NOW = "2026-04-10T12:00:00.000Z";
|
||||
const SNOOZED_AT = "2026-04-10T09:00:00.000Z";
|
||||
const FUTURE_WAKE = "2026-04-11T09:00:00.000Z";
|
||||
const PAST_WAKE = "2026-04-10T10:00:00.000Z";
|
||||
|
||||
function makeShell(input: {
|
||||
readonly snoozedUntil?: string | null;
|
||||
readonly snoozedAt?: string | null;
|
||||
readonly sessionStatus?: "starting" | "running" | "ready" | "error";
|
||||
readonly pending?: "approval" | "user-input";
|
||||
readonly turnCompletedAt?: string | null;
|
||||
}): ThreadSnoozeShell {
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
return {
|
||||
snoozedUntil: input.snoozedUntil ?? null,
|
||||
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
|
||||
hasPendingApprovals: input.pending === "approval",
|
||||
hasPendingUserInput: input.pending === "user-input",
|
||||
session:
|
||||
input.sessionStatus === undefined
|
||||
? null
|
||||
: {
|
||||
threadId,
|
||||
status: input.sessionStatus,
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: input.sessionStatus === "error" ? "boom" : null,
|
||||
updatedAt: "2026-04-10T11:00:00.000Z",
|
||||
},
|
||||
latestTurn:
|
||||
input.turnCompletedAt === undefined
|
||||
? null
|
||||
: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: SNOOZED_AT,
|
||||
startedAt: null,
|
||||
completedAt: input.turnCompletedAt,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("effectiveSnoozed", () => {
|
||||
it("hides a thread whose wake time is in the future", () => {
|
||||
expect(effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE }), { now: NOW })).toBe(true);
|
||||
});
|
||||
|
||||
it("stops classifying as snoozed once the wake time passes (timer wake, no event)", () => {
|
||||
expect(effectiveSnoozed(makeShell({ snoozedUntil: PAST_WAKE }), { now: NOW })).toBe(false);
|
||||
});
|
||||
|
||||
it("never snoozes a thread with no snooze state", () => {
|
||||
expect(effectiveSnoozed(makeShell({}), { now: NOW })).toBe(false);
|
||||
});
|
||||
|
||||
it("never hides on malformed wake data", () => {
|
||||
expect(effectiveSnoozed(makeShell({ snoozedUntil: "not-a-date" }), { now: NOW })).toBe(false);
|
||||
});
|
||||
|
||||
it("wakes early when the agent is blocked on the user", () => {
|
||||
expect(
|
||||
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "approval" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("wakes early on a failure that happened after the snooze", () => {
|
||||
// makeShell stamps session.updatedAt at 11:00, after SNOOZED_AT (9:00).
|
||||
expect(
|
||||
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("stays snoozed when the failure predates the snooze — the user saw it", () => {
|
||||
expect(
|
||||
effectiveSnoozed(
|
||||
makeShell({
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
sessionStatus: "error",
|
||||
// Snoozed AFTER the error's status edge.
|
||||
snoozedAt: "2026-04-10T11:30:00.000Z",
|
||||
}),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("stays snoozed while the session keeps working — snooze never pauses the agent", () => {
|
||||
expect(
|
||||
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "running" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("wakes early when a run completes after the snooze was set", () => {
|
||||
expect(
|
||||
effectiveSnoozed(
|
||||
makeShell({ snoozedUntil: FUTURE_WAKE, turnCompletedAt: "2026-04-10T10:30:00.000Z" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores runs that completed before the snooze — the user saw that result", () => {
|
||||
expect(
|
||||
effectiveSnoozed(
|
||||
makeShell({ snoozedUntil: FUTURE_WAKE, turnCompletedAt: "2026-04-10T08:00:00.000Z" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("threadRaisedHandWhileSnoozed", () => {
|
||||
it("is false for a quiet snoozed thread", () => {
|
||||
expect(threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE }))).toBe(false);
|
||||
});
|
||||
|
||||
it("is true for approvals, input, and failures", () => {
|
||||
expect(
|
||||
threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "approval" })),
|
||||
).toBe(true);
|
||||
expect(
|
||||
threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input" })),
|
||||
).toBe(true);
|
||||
expect(
|
||||
threadRaisedHandWhileSnoozed(
|
||||
makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canSnooze", () => {
|
||||
it("allows snoozing quiet and working threads alike", () => {
|
||||
expect(canSnooze({ ...makeShell({}), latestUserMessageAt: null }, { now: NOW })).toBe(true);
|
||||
expect(
|
||||
canSnooze(
|
||||
{ ...makeShell({ sessionStatus: "running" }), latestUserMessageAt: null },
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses blocked-on-you work", () => {
|
||||
expect(
|
||||
canSnooze({ ...makeShell({ pending: "approval" }), latestUserMessageAt: null }, { now: NOW }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
canSnooze(
|
||||
{ ...makeShell({ pending: "user-input" }), latestUserMessageAt: null },
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses a queued turn start — same invisible-pending-work rule as settle", () => {
|
||||
// Fresh user message, no turn has adopted it, within the grace window.
|
||||
expect(
|
||||
canSnooze(
|
||||
{ ...makeShell({}), latestUserMessageAt: "2026-04-10T11:59:30.000Z" },
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(false);
|
||||
// Outside the grace window the message is stale data, not queued work.
|
||||
expect(
|
||||
canSnooze(
|
||||
{ ...makeShell({}), latestUserMessageAt: "2026-04-10T11:00:00.000Z" },
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("threadWokeAt", () => {
|
||||
it("is null for never-snoozed and still-snoozed threads", () => {
|
||||
expect(threadWokeAt(makeShell({}), { now: NOW })).toBe(null);
|
||||
expect(threadWokeAt(makeShell({ snoozedUntil: FUTURE_WAKE }), { now: NOW })).toBe(null);
|
||||
});
|
||||
|
||||
it("reports the wake time for a timer wake", () => {
|
||||
expect(threadWokeAt(makeShell({ snoozedUntil: PAST_WAKE }), { now: NOW })).toBe(PAST_WAKE);
|
||||
});
|
||||
|
||||
it("reports the completion time for an early run-completed wake", () => {
|
||||
expect(
|
||||
threadWokeAt(
|
||||
makeShell({ snoozedUntil: FUTURE_WAKE, turnCompletedAt: "2026-04-10T10:30:00.000Z" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe("2026-04-10T10:30:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to session activity for blocked/failed early wakes", () => {
|
||||
expect(
|
||||
threadWokeAt(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }), {
|
||||
now: NOW,
|
||||
}),
|
||||
).toBe("2026-04-10T11:00:00.000Z");
|
||||
});
|
||||
|
||||
it("keeps the early wake authoritative after the scheduled time passes", () => {
|
||||
// Woke early at 10:30 via run-completed; the scheduled wake (PAST_WAKE
|
||||
// 10:00 relative to a later now) has ALSO passed. Reporting the
|
||||
// scheduled time would resurface a Woke pill the user already cleared
|
||||
// by visiting between the early wake and now.
|
||||
expect(
|
||||
threadWokeAt(
|
||||
makeShell({ snoozedUntil: PAST_WAKE, turnCompletedAt: "2026-04-10T09:30:00.000Z" }),
|
||||
{ now: NOW },
|
||||
),
|
||||
).toBe("2026-04-10T09:30:00.000Z");
|
||||
});
|
||||
});
|
||||
@@ -44,13 +44,6 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
|
||||
pre-settlement servers, so clients treat missing as unsupported and
|
||||
never send the commands under version skew. */
|
||||
threadSettlement: Schema.optionalKey(Schema.Boolean),
|
||||
/** Server understands thread.snooze / thread.unsnooze commands. Same
|
||||
version-skew contract as threadSettlement. */
|
||||
threadSnooze: Schema.optionalKey(Schema.Boolean),
|
||||
/** Server understands the review.summarizeThread RPC used by the sidebar
|
||||
work-review sweep. Absent on older servers, so clients skip their
|
||||
threads instead of sending an unknown method. */
|
||||
reviewSweep: Schema.optionalKey(Schema.Boolean),
|
||||
/** The update path clients should offer for this server. Absent on
|
||||
servers that must be relaunched manually (dev checkouts, Windows
|
||||
foreground runs, pre-update servers). */
|
||||
|
||||
@@ -176,10 +176,7 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<
|
||||
"gpt-5.3-spark": "gpt-5.3-codex-spark",
|
||||
},
|
||||
[CLAUDE_DRIVER_KIND]: {
|
||||
opus: "claude-opus-5",
|
||||
"opus-5": "claude-opus-5",
|
||||
"claude-opus-5.0": "claude-opus-5",
|
||||
"claude-opus-5-0": "claude-opus-5",
|
||||
opus: "claude-opus-4-8",
|
||||
"opus-4.8": "claude-opus-4-8",
|
||||
"claude-opus-4.8": "claude-opus-4-8",
|
||||
"opus-4.7": "claude-opus-4-7",
|
||||
|
||||
@@ -361,12 +361,6 @@ export const OrchestrationThread = Schema.Struct({
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
|
||||
// Snooze is an overlay on the active lifecycle, not a fourth destination:
|
||||
// a snoozed thread stays "active" in the model and is only suppressed from
|
||||
// the inbox until snoozedUntil passes (or the thread raises its hand).
|
||||
// Optional so payloads from pre-snooze servers still decode.
|
||||
snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
|
||||
snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
|
||||
deletedAt: Schema.NullOr(IsoDateTime),
|
||||
messages: Schema.Array(OrchestrationMessage),
|
||||
proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(
|
||||
@@ -417,8 +411,6 @@ export const OrchestrationThreadShell = Schema.Struct({
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
|
||||
snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
|
||||
snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
|
||||
session: Schema.NullOr(OrchestrationSession),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
hasPendingApprovals: Schema.Boolean,
|
||||
@@ -591,27 +583,6 @@ const ThreadUnsettleCommand = Schema.Struct({
|
||||
reason: Schema.Literal("user"),
|
||||
});
|
||||
|
||||
const ThreadSnoozeCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.snooze"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
// The wake time. Event-based wake conditions (PR merged, review posted)
|
||||
// will arrive as an optional condition field alongside this; time-based
|
||||
// snooze is just the first kind of condition.
|
||||
snoozedUntil: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadUnsnoozeCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.unsnooze"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
// Commands only carry "user": activity wakes are decided server-side (the
|
||||
// decider emits thread.unsnoozed(reason: "activity") directly), and timer
|
||||
// wakes need no event at all — clients derive visibility from snoozedUntil,
|
||||
// so a passed wake time simply stops classifying as snoozed.
|
||||
reason: Schema.Literal("user"),
|
||||
});
|
||||
|
||||
const ThreadMetaUpdateCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.meta.update"),
|
||||
commandId: CommandId,
|
||||
@@ -756,8 +727,6 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
|
||||
ThreadUnarchiveCommand,
|
||||
ThreadSettleCommand,
|
||||
ThreadUnsettleCommand,
|
||||
ThreadSnoozeCommand,
|
||||
ThreadUnsnoozeCommand,
|
||||
ThreadMetaUpdateCommand,
|
||||
ThreadRuntimeModeSetCommand,
|
||||
ThreadInteractionModeSetCommand,
|
||||
@@ -781,8 +750,6 @@ export const ClientOrchestrationCommand = Schema.Union([
|
||||
ThreadUnarchiveCommand,
|
||||
ThreadSettleCommand,
|
||||
ThreadUnsettleCommand,
|
||||
ThreadSnoozeCommand,
|
||||
ThreadUnsnoozeCommand,
|
||||
ThreadMetaUpdateCommand,
|
||||
ThreadRuntimeModeSetCommand,
|
||||
ThreadInteractionModeSetCommand,
|
||||
@@ -887,8 +854,6 @@ export const OrchestrationEventType = Schema.Literals([
|
||||
"thread.unarchived",
|
||||
"thread.settled",
|
||||
"thread.unsettled",
|
||||
"thread.snoozed",
|
||||
"thread.unsnoozed",
|
||||
"thread.meta-updated",
|
||||
"thread.runtime-mode-set",
|
||||
"thread.interaction-mode-set",
|
||||
@@ -980,23 +945,6 @@ export const ThreadUnsettledPayload = Schema.Struct({
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadSnoozedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
snoozedUntil: IsoDateTime,
|
||||
snoozedAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadUnsnoozedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
// user: explicit "wake now". activity: real work arrived (user message /
|
||||
// session coming alive) and the decider cleared the snooze — mirrors
|
||||
// thread.unsettled's activity resets. Timer wakes emit no event: clients
|
||||
// derive them from snoozedUntil passing.
|
||||
reason: Schema.Literals(["user", "activity"]),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadMetaUpdatedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -1174,16 +1122,6 @@ export const OrchestrationEvent = Schema.Union([
|
||||
type: Schema.Literal("thread.unsettled"),
|
||||
payload: ThreadUnsettledPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.snoozed"),
|
||||
payload: ThreadSnoozedPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.unsnoozed"),
|
||||
payload: ThreadUnsnoozedPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.meta-updated"),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { GitCommandError, TextGenerationError } from "./git.ts";
|
||||
import { ModelSelection } from "./orchestration.ts";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { GitCommandError } from "./git.ts";
|
||||
import { VcsError } from "./vcs.ts";
|
||||
|
||||
export const ReviewDiffPreviewInput = Schema.Struct({
|
||||
@@ -35,122 +34,3 @@ export type ReviewDiffPreviewResult = typeof ReviewDiffPreviewResult.Type;
|
||||
|
||||
export const ReviewDiffPreviewError = Schema.Union([VcsError, GitCommandError]);
|
||||
export type ReviewDiffPreviewError = typeof ReviewDiffPreviewError.Type;
|
||||
|
||||
export const ReviewThreadSummaryInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
/** Whether the thread is currently eligible to settle (no running session,
|
||||
pending approvals, or pending user input). The server never recommends
|
||||
settling when this is false, regardless of what the model says. */
|
||||
canSettleNow: Schema.Boolean,
|
||||
/** Model to run the review with. Defaults to the server's
|
||||
textGenerationModelSelection when omitted (older clients). */
|
||||
modelSelection: Schema.optionalKey(ModelSelection),
|
||||
});
|
||||
export type ReviewThreadSummaryInput = typeof ReviewThreadSummaryInput.Type;
|
||||
|
||||
/** Size of the thread's latest ready checkpoint diff — a cheap effort proxy
|
||||
for the review UI ("how big is this thread's change"). */
|
||||
export const ReviewThreadDiffStats = Schema.Struct({
|
||||
files: Schema.Int,
|
||||
additions: Schema.Int,
|
||||
deletions: Schema.Int,
|
||||
});
|
||||
export type ReviewThreadDiffStats = typeof ReviewThreadDiffStats.Type;
|
||||
|
||||
/** Live pull-request context gathered during the review: state, review
|
||||
verdict, CI, and whether the PR is mergeable as-is. */
|
||||
export const ReviewThreadPrStatus = Schema.Struct({
|
||||
number: Schema.Int,
|
||||
url: TrimmedNonEmptyString,
|
||||
state: Schema.Literals(["open", "closed", "merged"]),
|
||||
/** GitHub reviewDecision: APPROVED / CHANGES_REQUESTED / REVIEW_REQUIRED /
|
||||
empty (no required reviews). */
|
||||
reviewDecision: Schema.NullOr(TrimmedNonEmptyString),
|
||||
/** Rolled-up CI outcome for the head commit. */
|
||||
checksPassing: Schema.NullOr(Schema.Boolean),
|
||||
/** GitHub mergeable: whether the branch applies cleanly onto base. */
|
||||
mergeable: Schema.NullOr(Schema.Boolean),
|
||||
/** Open + clean merge + CI green + not blocked by requested changes. */
|
||||
mergeReady: Schema.Boolean,
|
||||
recentCommentCount: Schema.Int,
|
||||
});
|
||||
export type ReviewThreadPrStatus = typeof ReviewThreadPrStatus.Type;
|
||||
|
||||
/** What the review generation itself cost, reported by the provider CLI. */
|
||||
export const ReviewThreadGenerationUsage = Schema.Struct({
|
||||
inputTokens: Schema.Int,
|
||||
outputTokens: Schema.Int,
|
||||
/** Absent when the provider doesn't report a cost. */
|
||||
costUsd: Schema.optionalKey(Schema.Number),
|
||||
durationMs: Schema.Int,
|
||||
});
|
||||
export type ReviewThreadGenerationUsage = typeof ReviewThreadGenerationUsage.Type;
|
||||
|
||||
export const ReviewThreadSummaryResult = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
summary: TrimmedNonEmptyString,
|
||||
/** One imperative sentence: the user's single next action. Optional for
|
||||
pre-nextStep servers. */
|
||||
nextStep: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
/** Null when the current title is still accurate. */
|
||||
suggestedTitle: Schema.NullOr(TrimmedNonEmptyString),
|
||||
recommendSettle: Schema.Boolean,
|
||||
settleReason: Schema.NullOr(TrimmedNonEmptyString),
|
||||
/** Absent when the thread has no ready checkpoint (or pre-diff servers). */
|
||||
diffStats: Schema.optionalKey(ReviewThreadDiffStats),
|
||||
/** Absent when the thread has no PR, the lookup failed, or pre-PR servers. */
|
||||
prStatus: Schema.optionalKey(ReviewThreadPrStatus),
|
||||
/** Absent when the provider doesn't report usage. */
|
||||
usage: Schema.optionalKey(ReviewThreadGenerationUsage),
|
||||
});
|
||||
export type ReviewThreadSummaryResult = typeof ReviewThreadSummaryResult.Type;
|
||||
|
||||
export class ReviewThreadNotFoundError extends Schema.TaggedErrorClass<ReviewThreadNotFoundError>()(
|
||||
"ReviewThreadNotFoundError",
|
||||
{ threadId: ThreadId },
|
||||
) {}
|
||||
|
||||
export const ReviewThreadSummaryError = Schema.Union([
|
||||
TextGenerationError,
|
||||
ReviewThreadNotFoundError,
|
||||
]);
|
||||
export type ReviewThreadSummaryError = typeof ReviewThreadSummaryError.Type;
|
||||
|
||||
export const ReviewMergePullRequestInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
/** The PR number the client saw at review time; the server re-validates
|
||||
merge-readiness against live GitHub state before merging. */
|
||||
pullRequestNumber: Schema.Int,
|
||||
});
|
||||
export type ReviewMergePullRequestInput = typeof ReviewMergePullRequestInput.Type;
|
||||
|
||||
export const ReviewMergePullRequestResult = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
outcome: Schema.Literals([
|
||||
"merged",
|
||||
/** Branch no longer applies cleanly (e.g. an earlier queue merge landed
|
||||
first). The client hands the conflict to the thread's agent. */
|
||||
"conflict",
|
||||
/** PR already merged or closed since the review ran. */
|
||||
"already-closed",
|
||||
/** No longer merge-ready (CI regressed, review dismissed, ...). */
|
||||
"not-ready",
|
||||
]),
|
||||
detail: Schema.NullOr(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ReviewMergePullRequestResult = typeof ReviewMergePullRequestResult.Type;
|
||||
|
||||
export class ReviewMergeError extends Schema.TaggedErrorClass<ReviewMergeError>()(
|
||||
"ReviewMergeError",
|
||||
{
|
||||
threadId: ThreadId,
|
||||
detail: TrimmedNonEmptyString,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export const ReviewMergePullRequestError = Schema.Union([
|
||||
ReviewThreadNotFoundError,
|
||||
ReviewMergeError,
|
||||
]);
|
||||
export type ReviewMergePullRequestError = typeof ReviewMergePullRequestError.Type;
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user