Compare commits

..
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 ffd43b41ec fix(server): second round of review findings
- Restore the powershell/ps literal union on
  TerminalSubprocessCheckError.command; the widening to Schema.String
  was unnecessary once the capture path got its own error class.
- Decide session liveness before registerTerminalProcesses, so a
  terminal that exited or restarted mid-tick cannot get its old process
  tree re-registered with port discovery.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-09 14:51:48 -07:00
Theo BrowneandClaude Fable 5 04ae0412ef fix(server): address review findings on trace churn PR
- Dedicated TerminalProcessTableCaptureError for whole-table snapshot
  failures instead of a terminalPid: 0 sentinel on the per-terminal
  error (Macroscope conventions).
- Fail the snapshot when ps/powershell output is truncated instead of
  silently treating cut-off sessions as subprocess-free; cap raised to
  4 MiB (Macroscope).
- Poll entries carry the pid they were inspected under, so a terminal
  restart mid-tick can no longer register a stale inspection against
  the new process (Macroscope).
- makeLocalFileTracer forwards compressBackups to its default sink
  (Macroscope).
- Crash-safe gzip rotation: rename first, publish gz via tmp+rename,
  drop plain crash leftovers next to their gz copy in both the rotation
  chain and the diagnostics reader, prune orphaned .gz.tmp files
  (Cursor Bugbot).
- cli/config.test.ts expectations updated for traceMaxFiles=30 and
  traceKeepAllSpans (CI failure).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-09 14:46:08 -07:00
Theo BrowneandClaude Fable 5 3cc7cf3c83 perf(server): trace logs keep hours of history instead of minutes
The local trace file burned through its whole 100 MB rotation window in
10-36 minutes, which made incident audits impossible: by the time a
slow-PR-badge report came in, the relevant spans were already rotated
away. Two sources dominated: the terminal subprocess poller (~40% of
bytes: pgrep + up to three ps spawns per session per second, each a full
process-table enumeration) and sql.execute spans (~28%).

Write less:
- One shared ps/powershell process-table snapshot per poll tick serves
  every running terminal; per-session inspection is now pure lookup.
  This also removes 50-75 process spawns/sec on busy hosts.
- The poll tick runs untraced; an explicit
  terminal.subprocessActivityChanged span fires only on a real state
  flip.
- Tail policy in the local file tracer: failures, interruptions, spans
  with events, and slow spans always persist; fast successes are
  rate-limited per span name (50 per 30s). OTLP delegate still sees
  every span. T3CODE_TRACE_KEEP_ALL_SPANS=true restores full fidelity.
- Dropped constant db.name/service.name attributes from every
  sql.execute span.

Keep more:
- Rotated trace backups are gzipped (measured 10.6x on real span data)
  and T3CODE_TRACE_MAX_FILES now defaults to 30, so the same disk
  budget covers hours.
- TraceDiagnostics reads backups one file at a time (instead of
  slurping every rotation into memory) and transparently gunzips .gz
  backups; plain legacy backups still age along the chain.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-08 21:12:57 -07:00
Theo BrowneandClaude Fable 5 05eb051184 feat(web): keep unsent drafts one click away in the sidebar (#5777)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 20:29:21 -07:00
Theo BrowneandClaude Fable 5 ddaa6afef5 feat(server): vp run migrate-dev-db seeds worktree dev dbs with real data (#5773)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:51:18 -07:00
Theo BrowneandClaude Opus 5 6f69b4407f fix(web): sidebar rows show the branch again, not a truncated plan step (#5776)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 19:45:21 -07:00
Theo BrowneandClaude Fable 5 6dbffa022d feat: pick worktree or current checkout per project (#5766)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:44:58 -07:00
Theo BrowneandClaude Fable 5 5bb8c03664 fix(server): settle no longer leaves monitors and dev servers running (#5774)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:44:15 -07:00
Theo BrowneandClaude Fable 5 886195ec1e fix(web): usage totals no longer jump while devices report in (#5772)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:05:16 -07:00
Theo BrowneandClaude Fable 5 288d8e3457 feat(web): overhaul project settings into a real settings page (#5768)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 18:50:03 -07:00
Theo BrowneandClaude Fable 5 5208bdeb0d fix(web): pinned reorder no longer reshuffles while writes land (#5767)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 18:46:27 -07:00
Theo BrowneandClaude Fable 5 a6c9b41f90 feat(server): agents can now open the images you paste into chat (#5757)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 18:43:53 -07:00
Theo BrowneandClaude Fable 5 70c423a5e4 fix(web): usage page loses the cost quality panel, gains a back button (#5756)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 21:31:20 -04:00
Theo Browne 89c320df0b fix(server): stop Codex threads with queued follow-ups (#5762) 2026-08-08 17:52:06 -07:00
Theo Browne 7b2cf4374f chore: vouch saphid (#5763) 2026-08-08 20:44:28 -04:00
Theo Browne 49964e38c0 chore: vouch gfsaaser24 (#5761) 2026-08-09 00:32:10 +00:00
e70cdb478d fix(server): stop Claude resume handshakes from completing turns that never ran (#5710)
Co-authored-by: t3-turbo-simulation <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 17:24:42 -07:00
naMqe be01b287b9 fix(web): add missing cursor-pointer styling to dropdowns and interactive buttons (#5716) 2026-08-08 20:02:57 -04:00
Theo BrowneandClaude Fable 5 c2f8cb7ca1 feat(web): show how many subagents are running at a glance (#5745)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 16:20:06 -07:00
Leonel Rivas 89ee692bf0 fix(web): persist diff view mode (#5731) 2026-08-08 17:02:51 -04:00
Theo BrowneandClaude Opus 5 a20923ce46 fix(web): usage chart no longer makes Claude look like the bigger spender (#5697)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 05:43:03 -07:00
Theo BrowneandClaude Opus 5 8101cd0449 feat(usage): usage page reading provider transcripts across environments (#5684)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 03:59:04 -07:00
Theo BrowneandClaude Fable 5 30164cb1ba feat(mobile): one sheet for model and thread settings (#5625)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 03:51:20 -07:00
Theo BrowneandClaude Fable 5 0640410726 fix(desktop): zoom shortcuts no longer die when the preview browser has focus (#5691)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 02:24:38 -07:00
Theo BrowneandClaude Fable 5 2c7267ad43 fix(server): stop the reaper from silently killing live background subagents (#5677)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 21:42:14 -07:00
Chris Deeming daf8ee0b2f fix(web): inherit terminal size in simple typography (#5628) 2026-08-07 23:31:47 -04:00
t3-code[bot] ed886fe181 fix(web): delay transient reconnect warnings (#5670)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 23:17:18 -04:00
Theo BrowneandClaude Opus 5 4eaf5ef8bb fix(server): stop PR status lookups amplifying GitHub rate limits (#5673)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 18:09:46 -07:00
Theo BrowneandClaude Fable 5 0de9540739 feat: sidebar v2 is now the default sidebar (#5672)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 18:06:10 -07:00
Theo BrowneandClaude Fable 5 31891a1a0c feat(web): fold plan mode and token-by-token output into Legacy features (#5664)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 17:17:44 -07:00
Illia Panasenko 45d9aa90ba fix(web): show Stop button while input is pending (#5554) 2026-08-07 17:03:52 -04:00
Henry Zhang 7a84f6cf10 fix(web): reconnect the composer seam for remote non-Git projects (#5633) 2026-08-07 17:03:31 -04:00
maria f0fb406acf feat(web): make sidebar artwork theme-aware (#5636) 2026-08-07 15:41:59 -04:00
t3-code[bot] 82406bce99 chore: vouch chrisdeeming (#5641)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 15:01:39 -04:00
Chris Deeming 72d673a855 feat(desktop): remember recently used sites in the Browser panel (#5270) 2026-08-07 14:45:56 -04:00
t3-code[bot] e2cd2383ce chore(ci): vouch StiensWout (#5637)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 14:29:50 -04:00
Theo BrowneandClaude Fable 5 5661c6116c feat(web): drag pinned threads into your own order (#5581)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 06:57:22 -07:00
Theo BrowneandClaude Opus 5 6d70e6d778 fix(mobile): reconnects no longer shift the thread list (#5372)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 06:21:04 -07:00
t3-code[bot] be1a836745 chore(release): prepare v0.0.32 2026-08-07 11:50:54 +00:00
218 changed files with 20435 additions and 11022 deletions

No files matched your search

+4
View File
@@ -11,9 +11,11 @@
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chrisdeeming
github:chuks-qua
github:cursoragent
github:gbarros-dev
github:gfsaaser24
github:github-actions[bot]
github:hwanseoc
github:jamesx0416
@@ -25,7 +27,9 @@ github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:saphid
github:shiroyasha9
github:StiensWout
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.31",
"version": "0.0.32",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -78,6 +78,7 @@ describe("DesktopLifecycle", () => {
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.void,
zoomMain: () => Effect.void,
syncAppearance: Effect.void,
});
@@ -91,6 +91,7 @@ function makePoolLayer(
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
zoomMain: () => Effect.die("unexpected zoom"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
@@ -39,8 +39,7 @@ const clientSettings: ClientSettings = {
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
sidebarV2Enabled: false,
sidebarV2ConfiguredByUser: false,
legacySidebarEnabled: false,
timestampFormat: "24-hour",
wordWrap: true,
};
@@ -81,6 +81,8 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
zoomMain: (direction) =>
Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
@@ -94,6 +96,30 @@ const makeElectronMenuLayer = (
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
const configureMenu = (
selectedAction: Deferred.Deferred<string>,
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
) =>
Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
describe("DesktopApplicationMenu", () => {
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
Effect.gen(function* () {
@@ -101,25 +127,7 @@ describe("DesktopApplicationMenu", () => {
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
yield* configureMenu(selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
@@ -138,4 +146,38 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
// Zoom must route through DesktopWindow.zoomMain instead of the Electron
// zoom roles: the roles zoom whichever webContents has focus, which breaks
// app zoom while an embedded preview WebContentsView holds focus.
it.effect("routes View menu zoom to the main window instead of zoom roles", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu(selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const viewMenu = template.find((item) => item.label === "View");
assert.isDefined(viewMenu);
if (!Array.isArray(viewMenu.submenu)) {
throw new Error("Expected View menu submenu to be an array.");
}
assert.isUndefined(
viewMenu.submenu.find((item) => item.role?.toLowerCase().includes("zoom")),
);
const zoomIn = viewMenu.submenu.find((item) => item.label === "Zoom In");
assert.isDefined(zoomIn);
assert.equal(zoomIn.accelerator, "CmdOrCtrl+=");
if (typeof zoomIn.click !== "function") {
throw new Error("Expected Zoom In menu item to have a click handler.");
}
zoomIn.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.equal(yield* Deferred.await(selectedAction), "zoom-in");
}),
);
});
@@ -49,6 +49,13 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
yield* desktopWindow.dispatchMenuAction(action);
});
const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
direction: DesktopWindow.MainWindowZoomDirection,
): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.zoomMain(direction);
});
const checkForUpdatesFromMenu = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -127,6 +134,9 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -181,10 +191,21 @@ export const make = Effect.gen(function* () {
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
{ role: "zoomOut" },
/*
Not the zoom roles: those act on the focused webContents, so with
an embedded preview WebContentsView focused they zoom the guest
page and the app UI appears stuck. These always zoom the main
window (see DesktopWindow.zoomMain).
*/
{ label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
{ label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
{
label: "Zoom In",
accelerator: "CmdOrCtrl+Plus",
visible: false,
click: zoomClick("in"),
},
{ label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
{ type: "separator" },
{ role: "togglefullscreen" },
],
+20
View File
@@ -61,6 +61,8 @@ export type DesktopWindowError =
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
export type MainWindowZoomDirection = "in" | "out" | "reset";
export class DesktopWindow extends Context.Service<
DesktopWindow,
{
@@ -87,6 +89,12 @@ export class DesktopWindow extends Context.Service<
readonly handleBackendNotReady: Effect.Effect<void>;
readonly flushMainWindowBounds: Effect.Effect<void>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
// Zooms the main window's own webContents. The Electron `zoomIn`/`zoomOut`
// menu roles act on whichever webContents has keyboard focus, so with an
// embedded preview WebContentsView (or DevTools) focused they zoom the
// guest page instead of the app UI. The menu routes here to always target
// the main window.
readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect<void>;
readonly syncAppearance: Effect.Effect<void>;
}
>()("@t3tools/desktop/window/DesktopWindow") {}
@@ -836,6 +844,18 @@ export const make = Effect.gen(function* () {
send();
}),
zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
yield* Effect.annotateCurrentSpan({ direction });
const window = yield* focusedMainWindow;
if (Option.isNone(window) || window.value.isDestroyed()) {
return;
}
const webContents = window.value.webContents;
// Same step size as the Electron zoomIn/zoomOut menu roles.
webContents.setZoomLevel(
direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
);
}),
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
yield* electronWindow.syncAllAppearance((window) =>
@@ -16,6 +16,18 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
/**
* Horizontal correction applied to content rendered in the brand title slot,
* shared with the connection-status swap so both align identically.
*/
export function brandTitleOffset(nativeLeadingItem: boolean): number {
if (Platform.OS !== "ios") return 0;
if (nativeLeadingItem) {
return Platform.isPad ? IPAD_NATIVE_LEADING_TITLE_OFFSET : IOS_NATIVE_LEADING_TITLE_OFFSET;
}
return Platform.isPad ? IPAD_HOME_TITLE_OFFSET : 0;
}
/**
* Compact brand lockup sized for native navigation bars.
*/
@@ -28,16 +40,7 @@ export function CompactBrandTitle(
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
const titleOffset =
Platform.OS !== "ios"
? 0
: props.nativeLeadingItem
? Platform.isPad
? IPAD_NATIVE_LEADING_TITLE_OFFSET
: IOS_NATIVE_LEADING_TITLE_OFFSET
: Platform.isPad
? IPAD_HOME_TITLE_OFFSET
: 0;
const titleOffset = brandTitleOffset(props.nativeLeadingItem === true);
return (
<View
+23 -12
View File
@@ -21,6 +21,7 @@ import {
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
} from "../layout/native-mail-search-toolbar";
import type { HomeProjectSortOrder } from "./homeThreadList";
import { WorkspaceConnectionTitle } from "./WorkspaceConnectionTitle";
import {
buildHomeListFilterMenu,
type HomeListFilterMenuEnvironment,
@@ -47,6 +48,7 @@ export function HomeHeader(props: {
readonly onProjectChange: (projectKey: string | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onOpenEnvironments: () => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
}) {
@@ -207,18 +209,27 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
>
<View className="w-full max-w-[720px] self-center gap-3">
<View className="flex-row items-center gap-2.5">
<View className="flex-1 flex-row items-center gap-2">
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
<T3Wordmark color={iconColor} height={15} />
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
Code
</RNText>
<View className="rounded-full bg-subtle px-2 py-0.75">
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
{stageLabel}
</RNText>
</View>
</View>
{/* Brand slot doubles as the connection status surface: while an
environment reconnects, the lockup fades to a status label in
place (no layout shift in the list below). */}
<WorkspaceConnectionTitle
grow
onPress={props.onOpenEnvironments}
brand={
<View className="flex-row items-center gap-2">
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
<T3Wordmark color={iconColor} height={15} />
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
Code
</RNText>
<View className="rounded-full bg-subtle px-2 py-0.75">
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
{stageLabel}
</RNText>
</View>
</View>
}
/>
<ControlPillMenu
actions={menuActions}
@@ -3,7 +3,6 @@ import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useState } from "react";
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
@@ -20,6 +19,7 @@ import { useHomeListOptions } from "./home-list-options";
import { buildHomeProjectScopes } from "./homeThreadList";
import { usePendingTaskListActions } from "./usePendingTaskListActions";
import { useThreadListActions } from "./useThreadListActions";
import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle";
/* ─── Route screen ───────────────────────────────────────────────────── */
@@ -44,6 +44,7 @@ export function HomeRouteScreen() {
unsnoozeThread,
pinThread,
unpinThread,
movePinnedThread,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -126,8 +127,16 @@ export function HomeRouteScreen() {
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
>
<>
{/* Restore the compact title after the split branch blanks the detail header. */}
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
{/* Restore the compact title after the split branch blanks the detail
header. The brand slot doubles as the connection status surface:
while an environment reconnects, the lockup fades to a status label
in place (no layout shift in the list below). */}
<NativeStackScreenOptions
options={getConnectionAwareBrandHeaderOptions({
onOpenEnvironments: () =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
})}
/>
<HomeHeader
environments={environments}
projects={projectFilterOptions}
@@ -138,6 +147,9 @@ export function HomeRouteScreen() {
threadSortOrder={listOptions.threadSortOrder}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
@@ -159,11 +171,9 @@ export function HomeRouteScreen() {
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
+49 -41
View File
@@ -11,6 +11,7 @@ import {
threadSearchMatchKey,
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
@@ -71,8 +72,6 @@ import {
type HomeProjectSortOrder,
} from "./homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
/* ─── Types ──────────────────────────────────────────────────────────── */
@@ -97,7 +96,6 @@ interface HomeScreenProps {
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onAddConnection: () => void;
readonly onOpenEnvironments: () => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
@@ -113,6 +111,10 @@ interface HomeScreenProps {
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onMovePinnedThread: (
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -524,6 +526,12 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onPinThread],
);
const handleMovePinnedThread = useCallback(
(thread: EnvironmentThreadShell, direction: "up" | "down") => {
void props.onMovePinnedThread(thread, direction);
},
[props.onMovePinnedThread],
);
const handleUnpinThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onUnpinThread(thread);
@@ -598,6 +606,29 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const pinReorderEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinReorder === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order (reorder-capable threads only) for the
// Move up/down position flags. Computed from all shells, not the rendered
// list, so search/scope filtering never disables or misdirects a move.
const arrangedPinnedKeys = useMemo(() => {
const pinned = sortPinnedThreadsByOrderKey(
props.threads.filter(
(thread) =>
thread.pinnedAt != null &&
thread.archivedAt === null &&
pinReorderEnvironmentIds.has(thread.environmentId),
),
);
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
}, [pinReorderEnvironmentIds, props.threads]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -784,11 +815,18 @@ export function HomeScreen(props: HomeScreenProps) {
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
pinReorderSupported={pinReorderEnvironmentIds.has(thread.environmentId)}
canMovePinnedUp={arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`) > 0}
canMovePinnedDown={(() => {
const index = arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`);
return index !== -1 && index < arrangedPinnedKeys.length - 1;
})()}
onSnoozeThread={handleSnoozeThread}
onUnsnoozeThread={handleUnsnoozeThread}
onUnsettleThread={handleUnsettleThread}
onPinThread={handlePinThread}
onUnpinThread={handleUnpinThread}
onMovePinnedThread={handleMovePinnedThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
@@ -801,6 +839,8 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleChangeRequestState,
handleDeleteThread,
arrangedPinnedKeys,
handleMovePinnedThread,
handlePinThread,
handleSettleThread,
handleSnoozeThread,
@@ -810,6 +850,7 @@ export function HomeScreen(props: HomeScreenProps) {
handleSwipeableWillOpen,
handleUnsettleThread,
pinningEnvironmentIds,
pinReorderEnvironmentIds,
projectByKey,
projectCwdByKey,
props.onArchiveThread,
@@ -976,20 +1017,13 @@ export function HomeScreen(props: HomeScreenProps) {
? null
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
"this environment");
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
// Connection state surfaces in the header title slot
// (WorkspaceConnectionTitle) — nothing renders inside the list, so
// reconnects never shift the rows.
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
projectCount: props.projects.length,
});
const connectionStatus =
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
<View
className="absolute left-0 right-0 items-center"
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
>
<WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
</View>
) : null;
if (!hasAnyThreads) {
return (
@@ -1008,41 +1042,17 @@ export function HomeScreen(props: HomeScreenProps) {
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
variant="plain"
/>
{emptyState.loading && !shouldShowConnectionStatus ? (
{emptyState.loading ? (
<View className="mt-4 items-center">
<ActivityIndicator color={accentColor} />
</View>
) : null}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="mt-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</View>
{connectionStatus}
</View>
);
}
const listHeader = (
<>
{Platform.OS === "ios" ? null : <HomeTopContentSpacer />}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="pb-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</>
);
const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
// Project scoping lives in the header filter menu (no inline chip row on
// mobile — the menu is the one filter surface).
@@ -1123,7 +1133,6 @@ export function HomeScreen(props: HomeScreenProps) {
}}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</View>
);
}
@@ -1178,7 +1187,6 @@ export function HomeScreen(props: HomeScreenProps) {
}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</View>
);
}
@@ -1,56 +0,0 @@
import { SymbolView } from "../../components/AppSymbol";
import { ActivityIndicator, Pressable } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import type { WorkspaceState } from "../../state/workspaceModel";
import { workspaceConnectionStatusLabel } from "./workspace-connection-status";
export function WorkspaceConnectionStatus(props: {
readonly state: WorkspaceState;
readonly onPress: () => void;
readonly variant?: "floating" | "sidebar";
}) {
const iconColor = useThemeColor("--color-icon-muted");
const isSynchronizing =
props.state.networkStatus !== "offline" &&
props.state.connectionError === null &&
(props.state.connectingEnvironments.length > 0 || props.state.hasPendingShellSnapshot);
const variant = props.variant ?? "floating";
return (
<Pressable
accessibilityHint="Opens environment settings"
accessibilityLabel={workspaceConnectionStatusLabel(props.state)}
accessibilityRole="button"
onPress={props.onPress}
className={
variant === "sidebar"
? "mx-3 flex-row items-center gap-2 rounded-xl bg-subtle px-3 py-2.5"
: "flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
}
style={
variant === "floating"
? {
shadowColor: "#000",
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.12,
shadowRadius: 24,
}
: undefined
}
>
{isSynchronizing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
)}
<Text className="min-w-0 flex-1 text-sm font-t3-bold text-foreground" numberOfLines={1}>
{workspaceConnectionStatusLabel(props.state)}
</Text>
{variant === "sidebar" ? (
<SymbolView name="chevron.right" size={11} tintColor={iconColor} type="monochrome" />
) : null}
</Pressable>
);
}
@@ -0,0 +1,194 @@
import type {
NativeStackHeaderItem,
NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { ActivityIndicator, Animated, Platform, Pressable, View } from "react-native";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { brandTitleOffset, CompactBrandTitle } from "../../components/CompactBrandTitle";
import { useThemeColor } from "../../lib/useThemeColor";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { useWorkspaceState } from "../../state/workspace";
import {
workspaceConnectionStatusPresentation,
type WorkspaceConnectionStatusPresentation,
} from "./workspace-connection-status";
/**
* Delay before a connection interruption surfaces in the title slot. Sub-second
* blips (the common reconnect case) resolve without any UI at all.
*/
const STATUS_SHOW_DELAY_MS = 800;
const FADE_IN_MS = 250;
/**
* Connection status presentation, debounced for display: null until the
* workspace has been in a non-connected state for STATUS_SHOW_DELAY_MS,
* then live-updating until the workspace reconnects (null again immediately).
*/
function useDelayedConnectionStatus(): WorkspaceConnectionStatusPresentation | null {
const { state } = useWorkspaceState();
const presentation = workspaceConnectionStatusPresentation(state);
const hasStatus = presentation !== null;
const [visible, setVisible] = useState(false);
useEffect(() => {
if (!hasStatus) {
setVisible(false);
return;
}
const timer = setTimeout(() => setVisible(true), STATUS_SHOW_DELAY_MS);
return () => clearTimeout(timer);
}, [hasStatus]);
return visible ? presentation : null;
}
/**
* One-shot entrance fade for the status label. Deliberately JS-driven: this can
* mount inside a native header item (RNSScreenStackHeaderSubview), where
* native-driver animated nodes blank the re-hosted view entirely. The JS driver
* updates opacity through the ordinary style path, which those subviews handle.
*/
function StatusFadeIn(props: { readonly children: ReactNode; readonly grow?: boolean }) {
const opacity = useRef(new Animated.Value(0)).current;
useEffect(() => {
const animation = Animated.timing(opacity, {
duration: FADE_IN_MS,
toValue: 1,
useNativeDriver: false,
});
animation.start();
return () => animation.stop();
}, [opacity]);
return (
<Animated.View
style={[
{ alignItems: "center", flexDirection: "row", opacity },
props.grow ? { flex: 1, minWidth: 0 } : null,
]}
>
{props.children}
</Animated.View>
);
}
/**
* Renders the brand/title slot of a thread-list surface, swapping the brand
* for the workspace connection status while an environment is unavailable.
*
* Both states occupy the same slot, so connection changes never shift the
* layout below. While connected the brand renders untouched — no wrapper —
* keeping the native header item on the exact element tree that predates the
* status swap. Replaces the old WorkspaceConnectionStatus pill, which inserted
* a row above the thread list.
*/
export function WorkspaceConnectionTitle(props: {
/** Content shown while connected (brand lockup or a screen title). */
readonly brand: ReactNode;
/** Opens environment settings. Status is not pressable when omitted. */
readonly onPress?: () => void;
/** Fill the available row width (in-flow headers) instead of hugging content (native title slots). */
readonly grow?: boolean;
readonly size?: "navbar" | "pageTitle";
/** Horizontal correction so the status aligns with the brand in native title slots. */
readonly statusOffset?: number;
}) {
const iconColor = String(useThemeColor("--color-icon-muted"));
const status = useDelayedConnectionStatus();
const size = props.size ?? "navbar";
if (status === null) {
return props.grow ? (
<View style={{ alignItems: "center", flex: 1, flexDirection: "row", minWidth: 0 }}>
{props.brand}
</View>
) : (
<>{props.brand}</>
);
}
return (
<StatusFadeIn grow={props.grow}>
<Pressable
accessibilityHint="Opens environment settings"
accessibilityLabel={status.label}
accessibilityRole="button"
disabled={props.onPress === undefined}
hitSlop={8}
onPress={props.onPress}
className="flex-row items-center gap-2"
style={{ marginLeft: props.statusOffset ?? 0 }}
>
{status.showsProgress ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="wifi.slash"
size={size === "pageTitle" ? 17 : 15}
tintColor={iconColor}
type="monochrome"
/>
)}
<Text
className={
size === "pageTitle"
? "text-[20px] font-t3-bold text-foreground-muted"
: "text-[16px] font-t3-bold text-foreground-muted"
}
numberOfLines={1}
style={{ flexShrink: 1 }}
>
{status.label}
</Text>
</Pressable>
</StatusFadeIn>
);
}
/**
* getCompactBrandHeaderOptions with the brand slot upgraded to the
* connection-status swap. Screens with an environment-settings callback apply
* this over the static brand options at mount.
*/
export function getConnectionAwareBrandHeaderOptions(opts: {
readonly onOpenEnvironments: () => void;
readonly fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"];
}): NativeStackNavigationOptions {
if (Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED) {
return {
headerTitle: "Threads",
headerTitleStyle: { color: "transparent", fontSize: 18, fontWeight: "800" },
title: "Threads",
unstable_headerLeftItems: (): NativeStackHeaderItem[] => [
{
element: (
<WorkspaceConnectionTitle
brand={<CompactBrandTitle nativeLeadingItem />}
onPress={opts.onOpenEnvironments}
statusOffset={brandTitleOffset(true)}
/>
),
hidesSharedBackground: true,
type: "custom",
},
],
};
}
return {
headerTitle: () => (
<WorkspaceConnectionTitle
brand={<CompactBrandTitle />}
onPress={opts.onOpenEnvironments}
statusOffset={brandTitleOffset(false)}
/>
),
headerTitleStyle: opts.fallbackTitleStyle,
title: "Threads",
};
}
@@ -8,9 +8,14 @@ import { Alert } from "react-native";
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots";
import {
pinOrderKeyBetween,
planPinnedMove,
sortPinnedThreadsByOrderKey,
} from "@t3tools/client-runtime/state/thread-sort";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { threadEnvironment } from "../../state/threads";
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
/** Version skew: never send settle/unsettle to a server that predates them
@@ -36,6 +41,13 @@ function environmentSupportsPinning(environmentId: EnvironmentThreadShell["envir
);
}
function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["environmentId"]) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadPinReorder === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -211,6 +223,10 @@ export function useThreadListActions(): {
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly movePinnedThread: (
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
@@ -331,9 +347,21 @@ export function useThreadListActions(): {
return false;
}
selectionHaptic();
// Same placement as web: a fresh pin takes the top of the arranged
// run. Servers that predate reordering get the bare pin (keyless).
let orderKey: string | undefined;
if (environmentSupportsPinReorder(thread.environmentId)) {
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
let firstKey: string | null = null;
for (const shell of shells) {
if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
}
orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;
}
const result = await pinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
@@ -378,6 +406,85 @@ export function useThreadListActions(): {
[unpinMutation],
);
// Move up / Move down for the pinned block. Computed against the CANONICAL
// keyed pinned order (not the rendered list), so the move is valid even
// while search or a project scope filters rows: the same fractional-key
// scheme web dragging uses, one write to one thread per move (plus a
// one-time section materialization when legacy keyless pins are involved).
const reorderPinnedMutation = useAtomCommand(threadEnvironment.reorderPin, {
reportFailure: false,
});
// One move at a time: a second tap before the first write's event lands
// would plan from the same stale snapshot and silently collapse two moves
// into one — same double-dispatch guard as snoozeThread.
const movePinnedInFlightRef = useRef(false);
const movePinnedThread = useCallback(
async (thread: EnvironmentThreadShell, direction: "up" | "down") => {
if (movePinnedInFlightRef.current) return false;
if (!environmentSupportsPinReorder(thread.environmentId)) {
Alert.alert(
"Could not move thread",
"This environment's server does not support pinned reordering yet. Update the server to reorder pins.",
);
return false;
}
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
const pinned = sortPinnedThreadsByOrderKey(
shells.filter(
(shell) =>
shell.pinnedAt != null &&
shell.archivedAt === null &&
environmentSupportsPinReorder(shell.environmentId),
),
);
const orderedIds = pinned.map((shell) => scopedThreadKey(shell.environmentId, shell.id));
const assignments = planPinnedMove({
orderedIds,
keysById: new Map(
pinned.map((shell) => [
scopedThreadKey(shell.environmentId, shell.id),
shell.pinOrderKey ?? null,
]),
),
movedId: scopedThreadKey(thread.environmentId, thread.id),
direction,
});
if (assignments === null || assignments.length === 0) return false;
const shellByKey = new Map(
pinned.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
);
selectionHaptic();
movePinnedInFlightRef.current = true;
try {
for (const assignment of assignments) {
const target = shellByKey.get(assignment.id);
if (target === undefined) continue;
const result = await reorderPinnedMutation({
environmentId: target.environmentId,
input: { threadId: target.id, orderKey: assignment.orderKey },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not move thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The pinned thread could not be moved.",
);
// No rollback: keys already written are valid orderings on their
// own (each write is a complete, consistent placement), so a
// partial materialization leaves the list sensible, not corrupt.
return false;
}
}
return true;
} finally {
movePinnedInFlightRef.current = false;
}
},
[reorderPinnedMutation],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
return {
@@ -389,6 +496,7 @@ export function useThreadListActions(): {
unsettleThread,
pinThread,
unpinThread,
movePinnedThread,
};
}
@@ -4,6 +4,7 @@ import type { WorkspaceState } from "../../state/workspaceModel";
import {
shouldShowWorkspaceConnectionStatus,
workspaceConnectionStatusLabel,
workspaceConnectionStatusPresentation,
} from "./workspace-connection-status";
function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState {
@@ -84,4 +85,36 @@ describe("workspace connection status", () => {
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
expect(workspaceConnectionStatusLabel(state)).toBe("Loading threads...");
});
it("presents nothing while connected", () => {
expect(workspaceConnectionStatusPresentation(workspaceState())).toBeNull();
});
it("presents progress while reconnecting but not while offline", () => {
const reconnecting = workspaceState({
hasConnectingEnvironment: true,
hasReadyEnvironment: false,
connectingEnvironments: [
{
environmentId: "environment-1" as never,
environmentLabel: "Julius’s Mac mini",
displayUrl: "",
isRelayManaged: false,
connectionState: "reconnecting",
connectionError: null,
connectionErrorTraceId: null,
},
],
});
expect(workspaceConnectionStatusPresentation(reconnecting)).toEqual({
label: "Reconnecting to Julius’s Mac mini",
showsProgress: true,
});
const offline = workspaceState({ networkStatus: "offline", hasReadyEnvironment: false });
expect(workspaceConnectionStatusPresentation(offline)).toEqual({
label: "You are offline",
showsProgress: false,
});
});
});
@@ -1,5 +1,11 @@
import type { WorkspaceState } from "../../state/workspaceModel";
export interface WorkspaceConnectionStatusPresentation {
readonly label: string;
/** True while actively working (connecting/syncing) — render a spinner. False for offline/error/idle states — render a wifi-slash icon. */
readonly showsProgress: boolean;
}
export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): boolean {
return (
state.networkStatus === "offline" ||
@@ -24,3 +30,17 @@ export function workspaceConnectionStatusLabel(state: WorkspaceState): string {
}
return "Not connected";
}
/** Header-title presentation of the connection state, or null while connected. */
export function workspaceConnectionStatusPresentation(
state: WorkspaceState,
): WorkspaceConnectionStatusPresentation | null {
if (!shouldShowWorkspaceConnectionStatus(state)) return null;
return {
label: workspaceConnectionStatusLabel(state),
showsProgress:
state.networkStatus !== "offline" &&
state.connectionError === null &&
(state.connectingEnvironments.length > 0 || state.hasPendingShellSnapshot),
};
}
@@ -131,7 +131,7 @@ function LocalSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<BetaSettingsSection />
<LegacySettingsSection />
<ArchivedThreadsSettingsSection />
@@ -519,7 +519,7 @@ function ConfiguredSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<BetaSettingsSection />
<LegacySettingsSection />
<ArchivedThreadsSettingsSection />
@@ -538,26 +538,27 @@ function GeneralSettingsSection() {
}
/**
* Device-local beta toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → Beta backed by mobile preferences.
* Device-local legacy toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → General → Legacy features backed by
* mobile preferences.
*/
function BetaSettingsSection() {
function LegacySettingsSection() {
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const threadListV2Enabled = useThreadListV2Enabled();
return (
<View className="gap-3">
<SettingsSection title="Beta">
<SettingsSection title="Legacy">
<SettingsSwitchRow
icon="sidebar.left"
label="Thread List v2"
value={threadListV2Enabled}
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
label="Legacy Thread List"
value={!threadListV2Enabled}
onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
One flat thread list in creation order. Active work renders as cards; settled threads
collapse to compact rows. Switch back any time.
Brings back the original grouped thread list. The default list is flat, in creation order:
active work renders as cards; settled threads collapse to compact rows.
</Text>
</View>
);
@@ -25,15 +25,12 @@ import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStri
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import { ComposerSurface } from "./ThreadComposer";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import {
clearComposerDraftContent,
@@ -43,7 +40,7 @@ import {
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
@@ -103,6 +100,10 @@ export function NewTaskDraftScreen(props: {
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: promptInputRef,
isEditorFocused: isComposerFocused,
});
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
@@ -521,7 +522,15 @@ export function NewTaskDraftScreen(props: {
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
const interaction = InteractionManager.runAfterInteractions(() => {
focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
focusFrame = requestAnimationFrame(() => {
// The delayed focus can land after the settings sheet opened, which
// would pop the keyboard underneath its modal.
if (!settingsSheetPresentation.isActiveRef.current) {
promptInputRef.current?.focus();
} else {
settingsSheetPresentation.restoreFocusAfterSave();
}
});
});
return () => {
@@ -530,7 +539,11 @@ export function NewTaskDraftScreen(props: {
cancelAnimationFrame(focusFrame);
}
};
}, [selectedProject]);
}, [
selectedProject,
settingsSheetPresentation.isActiveRef,
settingsSheetPresentation.restoreFocusAfterSave,
]);
const environmentMenuActions = useMemo(
() =>
@@ -544,10 +557,6 @@ export function NewTaskDraftScreen(props: {
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
[flow.providerGroups, flow.selectedModel],
);
const providerOptionDescriptors = useMemo(
() =>
resolveProviderOptionDescriptors({
@@ -557,54 +566,6 @@ export function NewTaskDraftScreen(props: {
[flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
);
const optionsMenuActions = useMemo(
() => [
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
subtitle:
flow.runtimeMode === "approval-required"
? "Approve actions"
: flow.runtimeMode === "auto-accept-edits"
? "Auto-accept edits"
: flow.runtimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: flow.runtimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: flow.interactionMode === value ? ("on" as const) : undefined,
};
}),
},
],
[flow.interactionMode, flow.runtimeMode, providerOptionDescriptors],
);
const workspaceMenuActions = useMemo(() => {
const branchActions =
flow.availableBranches.length === 0
@@ -675,10 +636,12 @@ export function NewTaskDraftScreen(props: {
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const settingsSummaryLabel = threadSettingsSummaryLabel({
modelLabel: flow.selectedModelOption?.label ?? "Model",
optionDescriptors: providerOptionDescriptors,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
});
const workspaceLabel = useMemo(
() =>
formatWorkspaceLabel({
@@ -688,13 +651,6 @@ export function NewTaskDraftScreen(props: {
}),
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
);
function handleModelMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("model:")) {
return;
}
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
return;
@@ -702,28 +658,6 @@ export function NewTaskDraftScreen(props: {
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
}
function handleOptionsMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
}
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
flow.setSelectedModelOptions(providerOptions);
return;
}
if (event.startsWith("options:runtime:")) {
flow.setRuntimeMode(
event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],
);
return;
}
if (event.startsWith("options:interaction:")) {
flow.setInteractionMode(
event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],
);
}
}
function handleWorkspaceMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
@@ -930,7 +864,9 @@ export function NewTaskDraftScreen(props: {
const isDarkMode = colorScheme === "dark";
// Android expansion follows native editor focus so relayout cannot race
// the touch gesture that opens the keyboard.
const isExpanded = !isAndroid || isComposerFocused;
// The settings sheet dismisses the keyboard, so its flag keeps the Android
// draft composer expanded through the blur (mirrors ThreadComposer).
const isExpanded = !isAndroid || isComposerFocused || settingsSheetPresentation.isActive;
const canStart =
Boolean(flow.selectedProject) &&
Boolean(flow.selectedModel) &&
@@ -984,28 +920,14 @@ export function NewTaskDraftScreen(props: {
showChevron={false}
disabled={isIncomingShareTransferPending}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={flow.selectedModelOption?.label ?? "Model"}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
disabled={isIncomingShareTransferPending}
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
<ControlPillMenu
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
@@ -1031,6 +953,21 @@ export function NewTaskDraftScreen(props: {
</>
);
const settingsSheet = (
<ThreadSettingsSheet
visible={settingsSheetPresentation.isVisible}
onClose={settingsSheetPresentation.close}
onDismissed={settingsSheetPresentation.onDismissed}
providerGroups={flow.providerGroups}
selectedModel={flow.selectedModel}
onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}
optionDescriptors={providerOptionDescriptors}
onUpdateOptionSelections={flow.setSelectedModelOptions}
runtimeMode={flow.runtimeMode}
onUpdateRuntimeMode={flow.setRuntimeMode}
/>
);
const startButton = (
<ComposerToolbarButton
accessibilityLabel={
@@ -1120,6 +1057,7 @@ export function NewTaskDraftScreen(props: {
) : null}
</View>
</KeyboardAvoidingView>
{settingsSheet}
</View>
);
}
@@ -1153,6 +1091,7 @@ export function NewTaskDraftScreen(props: {
</ComposerToolbarRow>
</View>
</KeyboardAvoidingView>
{settingsSheet}
</View>
);
}
@@ -51,10 +51,10 @@ import {
ComposerToolbarScroller,
ComposerToolbarTrigger,
} from "../../components/ComposerToolbarTrigger";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ControlPill } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import {
@@ -62,14 +62,11 @@ import {
normalizeSearchQuery,
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
/**
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
@@ -273,15 +270,28 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const fallbackInputRef = useRef<ComposerEditorHandle>(null);
const inputRef = props.editorRef ?? fallbackInputRef;
const [isFocused, setIsFocused] = useState(false);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: inputRef,
isEditorFocused: isFocused,
});
const wasExpandedBeforePreviewRef = useRef(false);
const inFlightThreadIdsRef = useRef(new Set<string>());
const { onExpandedChange } = props;
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
const isExpanded = isFocused;
// Opening and closing count as active so the composer stays expanded while
// focus moves between its native editor and the settings modal.
const isExpanded = isFocused || settingsSheetPresentation.isActive;
const canSend = hasContent;
// Notify the parent from the derived value, not focus events: the parent
// sizes the feed inset from this, and blur-during-sheet would otherwise
// report collapsed while the composer still renders expanded.
useEffect(() => {
onExpandedChange?.(isExpanded);
}, [isExpanded, onExpandedChange]);
const onPressImage = useCallback(
(uri: string) => {
wasExpandedBeforePreviewRef.current = isFocused;
@@ -299,13 +309,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const handleFocus = useCallback(() => {
setIsFocused(true);
onExpandedChange?.(true);
}, [onExpandedChange]);
}, []);
const handleBlur = useCallback(() => {
setIsFocused(false);
onExpandedChange?.(false);
}, [onExpandedChange]);
}, []);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting";
@@ -588,6 +596,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
[props.serverConfig, currentModelSelection],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
// An existing thread is bound to its harness: sessions can't move between
// provider instances, so the picker only offers the thread's own group.
const threadProviderGroups = useMemo(
() => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
[providerGroups, currentModelSelection.instanceId],
);
const currentModelOption =
modelOptions.find(
(option) =>
@@ -602,95 +616,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}),
[currentModelOption?.capabilities, currentModelSelection.options],
);
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(providerGroups, currentModelSelection),
[providerGroups, currentModelSelection],
);
// ── Options menu ─────────────────────────────────────────
const optionsMenuActions = useMemo(
() => [
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
subtitle:
currentRuntimeMode === "approval-required"
? "Approve actions"
: currentRuntimeMode === "auto-accept-edits"
? "Auto-accept edits"
: currentRuntimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: currentRuntimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: currentInteractionMode === value ? ("on" as const) : undefined,
};
}),
},
],
[currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],
);
// ── Menu handlers ────────────────────────────────────────
function handleModelMenuAction(event: string) {
if (!event.startsWith("model:")) {
return;
}
const modelKey = event.slice("model:".length);
const option = modelOptions.find((o) => o.key === modelKey);
if (option) {
props.onUpdateModelSelection(option.selection);
}
}
function handleOptionsMenuAction(event: string) {
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
props.onUpdateModelSelection({
...currentModelSelection,
options: providerOptions,
});
return;
}
if (event.startsWith("options:runtime:")) {
const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
props.onUpdateRuntimeMode(runtimeMode);
return;
}
if (event.startsWith("options:interaction:")) {
const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
props.onUpdateInteractionMode(interactionMode);
}
}
const settingsSummaryLabel = threadSettingsSummaryLabel({
modelLabel: currentModelOption?.label ?? currentModelSelection.model,
optionDescriptors: providerOptionDescriptors,
runtimeMode: currentRuntimeMode,
interactionMode: currentInteractionMode,
});
return (
<Animated.View
@@ -861,28 +792,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={currentModelOption?.label ?? currentModelSelection.model}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
{showStopAction ? (
<ComposerToolbarButton
accessibilityLabel="Stop"
@@ -916,6 +834,21 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null}
</Animated.View>
<ThreadSettingsSheet
visible={settingsSheetPresentation.isVisible}
onClose={settingsSheetPresentation.close}
onDismissed={settingsSheetPresentation.onDismissed}
providerGroups={threadProviderGroups}
selectedModel={currentModelSelection}
onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}
optionDescriptors={providerOptionDescriptors}
onUpdateOptionSelections={(options) =>
props.onUpdateModelSelection({ ...currentModelSelection, options })
}
runtimeMode={currentRuntimeMode}
onUpdateRuntimeMode={props.onUpdateRuntimeMode}
/>
<ImageViewing
images={previewImageUri ? [{ uri: previewImageUri }] : []}
imageIndex={0}
@@ -11,6 +11,7 @@ import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
@@ -55,8 +56,10 @@ import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThrea
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
import { useThreadListActions } from "../home/useThreadListActions";
import { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status";
import {
getConnectionAwareBrandHeaderOptions,
WorkspaceConnectionTitle,
} from "../home/WorkspaceConnectionTitle";
import { SidebarHeaderActions } from "./sidebar-header-actions";
import { SidebarFilterButton } from "./sidebar-filter-button";
import { createSidebarHeaderItems } from "./sidebar-native-header-items";
@@ -207,6 +210,7 @@ function ThreadNavigationSidebarPane(
unsettleThread,
pinThread,
unpinThread,
movePinnedThread,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -492,6 +496,28 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const pinReorderEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinReorder === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order for Move up/down flags — computed from
// all shells so search/scope filtering never disables a valid move.
const arrangedPinnedKeys = useMemo(() => {
const pinned = sortPinnedThreadsByOrderKey(
threads.filter(
(thread) =>
thread.pinnedAt != null &&
thread.archivedAt === null &&
pinReorderEnvironmentIds.has(thread.environmentId),
),
);
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
}, [pinReorderEnvironmentIds, threads]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -600,7 +626,6 @@ function ThreadNavigationSidebarPane(
threadListV2Enabled,
threadListV2Layout,
]);
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
const listMenuActions = useMemo<MenuAction[]>(
() => [
{
@@ -929,11 +954,20 @@ function ThreadNavigationSidebarPane(
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
pinReorderSupported={pinReorderEnvironmentIds.has(thread.environmentId)}
canMovePinnedUp={
arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`) > 0
}
canMovePinnedDown={(() => {
const index = arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`);
return index !== -1 && index < arrangedPinnedKeys.length - 1;
})()}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
onSwipeableClose={handleSwipeableClose}
@@ -1054,13 +1088,16 @@ function ThreadNavigationSidebarPane(
},
[
archiveThread,
arrangedPinnedKeys,
confirmDeletePendingTask,
confirmDeleteThread,
handleChangeRequestState,
handleSelectThread,
handleSwipeableClose,
handleSwipeableWillOpen,
movePinnedThread,
openPendingTask,
pinReorderEnvironmentIds,
pinThread,
pinningEnvironmentIds,
projectByKey,
@@ -1153,6 +1190,13 @@ function ThreadNavigationSidebarPane(
<NativeStackScreenOptions
optionsVersion={nativeHeaderItems}
options={{
// Re-applies the shell's static brand slot with the
// connection-status swap so reconnects surface in the header
// instead of shifting the list.
...getConnectionAwareBrandHeaderOptions({
onOpenEnvironments: props.onOpenEnvironmentSettings,
fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
}),
headerSearchBarOptions: {
ref: searchBarRef,
autoCapitalize: "none",
@@ -1203,17 +1247,6 @@ function ThreadNavigationSidebarPane(
scrollEventThrottle={16}
showsVerticalScrollIndicator={false}
style={styles.threadList}
ListHeaderComponent={
showsConnectionStatus ? (
<View className="px-1.5 pt-0.5 pb-2">
<WorkspaceConnectionStatus
onPress={props.onOpenEnvironmentSettings}
state={catalogState}
variant="sidebar"
/>
</View>
) : null
}
ListEmptyComponent={listEmpty}
/>
</GestureDetector>
@@ -1304,9 +1337,19 @@ function ThreadNavigationSidebarPane(
</Svg>
</View>
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
Threads
</Text>
{/* Title slot doubles as the connection status surface: while an
environment reconnects, "Threads" fades to a status label in
place (no layout shift in the list below). */}
<WorkspaceConnectionTitle
grow
onPress={props.onOpenEnvironmentSettings}
size="pageTitle"
brand={
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
Threads
</Text>
}
/>
<SidebarHeaderButtonGroup colorScheme={colorScheme}>
<ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
<SidebarFilterButton
@@ -1335,16 +1378,6 @@ function ThreadNavigationSidebarPane(
value={props.searchQuery}
/>
</View>
{showsConnectionStatus ? (
<View className="px-3.5 pt-2.5">
<WorkspaceConnectionStatus
onPress={props.onOpenEnvironmentSettings}
state={catalogState}
variant="sidebar"
/>
</View>
) : null}
</View>
</View>
);
@@ -0,0 +1,678 @@
import type {
ModelSelection,
ProviderInteractionMode,
ProviderOptionDescriptor,
ProviderOptionSelection,
RuntimeMode,
} from "@t3tools/contracts";
import {
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import * as Haptics from "expo-haptics";
import { useCallback, useEffect, useRef, useState } from "react";
import {
Modal,
Platform,
Pressable,
ScrollView,
Switch,
useWindowDimensions,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { ProviderIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
import { useThemeColor } from "../../lib/useThemeColor";
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
/**
* The everyday harnesses stay expanded; every other provider (OpenRouter
* catalogs and friends) folds behind its header so a 300-model catalog can't
* bury the list.
*/
const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
/**
* Desktop-oriented effort keywords that don't belong in the phone picker.
* Prompt-injected values (ultrathink and friends) are filtered from the
* descriptor metadata; ultracode is a real option but a workflow trigger, not
* a reasoning level. A value set elsewhere still displays, it just isn't
* offered.
*/
const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
const RUNTIME_MODE_CHOICES: ReadonlyArray<{
readonly mode: RuntimeMode;
readonly label: string;
readonly shortLabel: string;
}> = [
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
];
/**
* Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
* covering model, provider options, runtime mode, and plan mode in one label.
*/
export function threadSettingsSummaryLabel(input: {
readonly modelLabel: string;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
}): string {
const runtime = RUNTIME_MODE_CHOICES.find((choice) => choice.mode === input.runtimeMode);
return [
input.modelLabel,
...providerOptionValueLabels(input.optionDescriptors),
...(runtime ? [runtime.shortLabel] : []),
...(input.interactionMode === "plan" ? ["Plan"] : []),
].join(" · ");
}
function selectableChoices(descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>) {
const injected = new Set(descriptor.promptInjectedValues ?? []);
return descriptor.options.filter(
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
);
}
function ModelRow(props: {
readonly option: ModelOption;
readonly selected: boolean;
readonly onPress: () => void;
}) {
const primaryFg = useThemeColor("--color-primary-foreground");
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.selected }}
onPress={props.onPress}
// Selected rows get the same primary treatment as the submenu rows.
// Subtle backgrounds (bg-subtle-strong) get overridden by the OS
// selection chrome on iOS 26, so use the explicit high-contrast style
// everywhere instead.
className={cn(
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3 py-3.5 active:opacity-70",
props.selected ? "bg-primary" : "bg-transparent",
)}
>
<Text
className={cn(
"shrink text-sm font-t3-medium",
props.selected ? "text-primary-foreground" : "text-foreground",
)}
numberOfLines={1}
>
{props.option.label}
</Text>
{props.option.isDefault ? (
<View className="rounded-md bg-subtle-strong px-1.5 py-0.5">
<Text className="text-3xs font-t3-bold text-foreground-muted">Default</Text>
</View>
) : null}
{props.option.isLegacy ? (
<View className="rounded-md bg-subtle px-1.5 py-0.5">
<Text className="text-3xs font-t3-bold text-foreground-muted">Legacy</Text>
</View>
) : null}
<View className="flex-1" />
{props.selected ? (
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
) : null}
</Pressable>
);
}
/**
* Provider section header with the harness logo. Secondary providers render
* as a tappable fold (count + chevron while collapsed); primary providers
* and the group holding the current selection are static headers.
*/
function ProviderHeader(props: {
readonly driver: string | undefined;
readonly label: string;
readonly collapsible: boolean;
readonly collapsed: boolean;
readonly modelCount: number;
readonly onToggle: () => void;
}) {
const iconSubtle = useThemeColor("--color-icon-subtle");
return (
<Pressable
accessibilityRole={props.collapsible ? "button" : "header"}
accessibilityState={props.collapsible ? { expanded: !props.collapsed } : undefined}
accessibilityLabel={
props.collapsible ? `${props.label}, ${props.modelCount} models` : props.label
}
disabled={!props.collapsible}
onPress={props.onToggle}
className={cn(
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3",
props.collapsible ? "py-3.5 active:opacity-70" : "pb-2 pt-4",
)}
>
<ProviderIcon provider={props.driver} size={15} />
<Text className="text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
{props.label}
</Text>
{props.collapsible ? (
<>
<View className="flex-1" />
{props.collapsed ? (
<Text className="text-2xs font-t3-medium text-foreground-muted">
{props.modelCount}
</Text>
) : null}
<SymbolView
name={props.collapsed ? "chevron.down" : "chevron.up"}
size={11}
tintColor={iconSubtle}
type="monochrome"
/>
</>
) : null}
</Pressable>
);
}
/** Compact row that opens a single-choice submenu panel. */
function DisclosureRow(props: {
readonly label: string;
readonly value: string | undefined;
readonly disabled?: boolean;
readonly onPress: () => void;
}) {
const iconSubtle = useThemeColor("--color-icon-subtle");
return (
<Pressable
accessibilityRole="button"
disabled={props.disabled}
onPress={props.onPress}
className={cn(
"flex-row items-center gap-2 px-5 py-3 active:opacity-70",
props.disabled && "opacity-40",
)}
>
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
<View className="flex-1" />
{props.value ? (
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
{props.value}
</Text>
) : null}
<SymbolView name="chevron.right" size={12} tintColor={iconSubtle} type="monochrome" />
</Pressable>
);
}
/** Single option inside a submenu panel. */
function ChoiceRow(props: {
readonly label: string;
readonly selected: boolean;
readonly onPress: () => void;
}) {
const primaryFg = useThemeColor("--color-primary-foreground");
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.selected }}
onPress={props.onPress}
className={cn(
"mx-2.5 flex-row items-center rounded-xl px-3 py-3.5 active:opacity-70",
props.selected ? "bg-primary" : "bg-transparent",
)}
>
<Text
className={cn(
"shrink text-sm font-t3-medium",
props.selected ? "text-primary-foreground" : "text-foreground",
)}
>
{props.label}
</Text>
<View className="flex-1" />
{props.selected ? (
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
) : null}
</Pressable>
);
}
function SwitchRow(props: {
readonly label: string;
readonly value: boolean;
readonly disabled?: boolean;
readonly onValueChange: (value: boolean) => void;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
return (
<View
className={cn(
"flex-row items-center justify-between px-5 py-2.5",
props.disabled && "opacity-40",
)}
>
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
type SubmenuPage =
| { readonly kind: "descriptor"; readonly id: string }
| { readonly kind: "runtime" };
/**
* Unified thread settings: the sheet is the provider-grouped model list
* (primary harnesses expanded, other providers folded, legacy behind the
* top-right pill) with a Save button, plus compact disclosure rows whose
* single-choice submenus stack in a small panel over the sheet so it never
* changes size. Model changes stage until Save — while staged, the settings
* rows edit the staged model's options and Save applies everything together.
*
* Callers control which harnesses are offered via providerGroups: an
* existing thread must pass only its own provider's group, since a session
* can't switch harness mid-thread.
*
* Rendered through an RN Modal (not the root OverlayPortal) so it also
* presents above natively-presented form sheets like the new-task draft.
* Callers must dismiss the keyboard when opening — the iOS keyboard window
* would otherwise cover the lower half of the sheet.
*/
export function ThreadSettingsSheet(props: {
readonly visible: boolean;
/**
* "save" = the Save/Done button (the user is finished configuring);
* "dismiss" = backdrop, grabber, or system back. Hosts only restore the
* keyboard for "save" so a stray tap outside a control never pops it.
*/
readonly onClose: (reason: ThreadSettingsSheetCloseReason) => void;
readonly onDismissed: () => void;
readonly providerGroups: ReadonlyArray<ProviderGroup>;
readonly selectedModel: ModelSelection | null;
readonly onSelectModel: (option: ModelOption) => void;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;
readonly runtimeMode: RuntimeMode;
readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
}) {
const insets = useSafeAreaInsets();
const { height: windowHeight } = useWindowDimensions();
const [showLegacyToggle, setShowLegacyToggle] = useState(false);
const [expandedProviders, setExpandedProviders] = useState<ReadonlySet<string>>(() => new Set());
const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);
const [submenu, setSubmenu] = useState<SubmenuPage | null>(null);
const wasPresentedRef = useRef(false);
const notifyDismissed = useCallback(() => {
if (!wasPresentedRef.current) {
return;
}
wasPresentedRef.current = false;
props.onDismissed();
}, [props.onDismissed]);
// Every open starts fresh: no staged model, no submenu, legacy hidden,
// secondary providers folded. The sheet stays mounted between opens, so
// state would otherwise stick around.
useEffect(() => {
if (props.visible) {
wasPresentedRef.current = true;
setShowLegacyToggle(false);
setExpandedProviders(new Set());
setPendingModel(null);
setSubmenu(null);
} else if (Platform.OS === "android" && wasPresentedRef.current) {
// React Native only emits Modal.onDismiss on iOS. Android uses no exit
// animation below, so the post-commit effect is its dismissal boundary.
notifyDismissed();
}
}, [notifyDismissed, props.visible]);
const isApplied = (option: ModelOption) =>
option.selection.instanceId === props.selectedModel?.instanceId &&
option.selection.model === props.selectedModel.model;
// The list highlights the staged pick; Save turns it into the applied one.
const isDisplayed = (option: ModelOption) =>
pendingModel ? option.key === pendingModel.key : isApplied(option);
// While a model is staged, the settings rows describe and edit the staged
// model's options (kept on its pending selection); Save applies model and
// options together. Otherwise they edit the applied selection directly.
const displayedDescriptors = pendingModel
? pendingModel.capabilities
? getProviderOptionDescriptors({
caps: pendingModel.capabilities,
selections: pendingModel.selection.options,
})
: []
: props.optionDescriptors;
const hasLegacyModels = props.providerGroups.some((group) =>
group.models.some((model) => model.isLegacy),
);
// Legacy stays hidden unless the pill is toggled this open; a highlighted
// legacy model is exempted from the filter instead of forcing the whole
// legacy list visible.
const showLegacy = showLegacyToggle;
// Stable settings rows: the union of descriptors across the primary
// harnesses' current models (plus whatever the displayed model advertises)
// always renders, with unsupported rows disabled instead of vanishing when
// the selection changes. Keyed by label, not id — Claude and Codex use
// different ids for the same "Reasoning" concept.
const descriptorTemplate = (() => {
const seen = new Map<string, { type: "select" | "boolean" }>();
for (const group of props.providerGroups) {
const driver = group.models[0]?.providerDriver;
if (driver === undefined || !PRIMARY_PROVIDER_DRIVERS.has(driver)) {
continue;
}
for (const model of group.models) {
if (model.isLegacy) {
continue;
}
for (const descriptor of model.capabilities?.optionDescriptors ?? []) {
if (!seen.has(descriptor.label)) {
seen.set(descriptor.label, { type: descriptor.type });
}
}
}
}
for (const descriptor of displayedDescriptors) {
if (!seen.has(descriptor.label)) {
seen.set(descriptor.label, { type: descriptor.type });
}
}
return [...seen.entries()].map(([label, entry]) => ({ label, ...entry }));
})();
const handleSave = () => {
if (pendingModel) {
void Haptics.selectionAsync();
props.onSelectModel(pendingModel);
}
props.onClose("save");
};
const handleOptionChange = (id: string, value: string | boolean) => {
const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
if (!next) {
return;
}
if (pendingModel) {
setPendingModel({
...pendingModel,
selection: { ...pendingModel.selection, options: next },
});
} else {
props.onUpdateOptionSelections(next);
}
};
const toggleProvider = (providerKey: string) => {
setExpandedProviders((current) => {
const next = new Set(current);
if (!next.delete(providerKey)) {
next.add(providerKey);
}
return next;
});
};
const activeDescriptor =
submenu?.kind === "descriptor"
? displayedDescriptors.find(
(descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,
)
: undefined;
const submenuContent =
submenu?.kind === "runtime"
? {
title: "Runtime",
rows: RUNTIME_MODE_CHOICES.map((choice) => ({
id: choice.mode,
label: choice.label,
selected: choice.mode === props.runtimeMode,
onPress: () => {
void Haptics.selectionAsync();
props.onUpdateRuntimeMode(choice.mode);
setSubmenu(null);
},
})),
}
: activeDescriptor?.type === "select"
? {
title: activeDescriptor.label,
rows: selectableChoices(activeDescriptor).map((choice) => ({
id: choice.id,
label: choice.label,
selected: choice.id === getProviderOptionCurrentValue(activeDescriptor),
onPress: () => {
void Haptics.selectionAsync();
handleOptionChange(activeDescriptor.id, choice.id);
setSubmenu(null);
},
})),
}
: null;
return (
<Modal
transparent
statusBarTranslucent
navigationBarTranslucent
animationType={Platform.OS === "ios" ? "fade" : "none"}
visible={props.visible}
onDismiss={notifyDismissed}
onRequestClose={submenuContent ? () => setSubmenu(null) : () => props.onClose("dismiss")}
>
<View className="flex-1 justify-end">
<Pressable
accessibilityLabel="Close thread settings"
className="absolute inset-0 bg-backdrop"
onPress={() => props.onClose("dismiss")}
/>
<View
className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet"
style={{ maxHeight: windowHeight * 0.85 }}
>
{/* The grabber doubles as the accessible close control: the dim
backdrop above a tall sheet is a sliver, and VoiceOver can't
reach it at all. */}
<Pressable
accessibilityLabel="Close thread settings"
accessibilityRole="button"
onPress={() => props.onClose("dismiss")}
className="items-center pb-1 pt-2.5"
>
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
</Pressable>
{hasLegacyModels ? (
<View className="flex-row justify-end px-4 pb-1.5">
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: showLegacy }}
hitSlop={8}
onPress={() => {
void Haptics.selectionAsync();
setShowLegacyToggle(!showLegacy);
}}
className="rounded-full border border-border bg-subtle px-3 py-1.5 active:opacity-70"
>
<Text className="text-2xs font-t3-medium text-foreground-muted">
{showLegacy ? "Hide legacy models" : "Show legacy models"}
</Text>
</Pressable>
</View>
) : null}
{/* Only the model list scrolls. Provider catalogs can run to
hundreds of models (OpenRouter), so the rows below stay pinned
and reachable instead of living at the end of that scroll. */}
<ScrollView
style={{ flexShrink: 1 }}
contentContainerStyle={{ paddingBottom: 8 }}
showsVerticalScrollIndicator={false}
>
{props.providerGroups.map((group) => {
const driver = group.models[0]?.providerDriver;
const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
const visibleModels = showLegacy
? group.models
: group.models.filter((model) => !model.isLegacy || isDisplayed(model));
if (visibleModels.length === 0) {
return null;
}
const containsSelection = group.models.some(isDisplayed);
const collapsible = !isPrimary && !containsSelection;
const collapsed = collapsible && !expandedProviders.has(group.providerKey);
return (
<View key={group.providerKey}>
<ProviderHeader
driver={driver}
label={group.providerLabel}
collapsible={collapsible}
collapsed={collapsed}
modelCount={visibleModels.length}
onToggle={() => toggleProvider(group.providerKey)}
/>
{collapsed
? null
: visibleModels.map((option) => (
<ModelRow
key={option.key}
option={option}
selected={isDisplayed(option)}
onPress={() => {
void Haptics.selectionAsync();
// Re-tapping the applied model cancels staging.
setPendingModel((current) =>
pendingModelAfterPress({
current,
pressed: option,
pressedIsApplied: isApplied(option),
}),
);
}}
/>
))}
</View>
);
})}
</ScrollView>
<View className="mx-5 h-px bg-border" />
<View style={{ paddingBottom: insets.bottom + 12 }}>
{descriptorTemplate.map((entry) => {
const live = displayedDescriptors.find(
(descriptor) => descriptor.label === entry.label,
);
if ((live?.type ?? entry.type) === "select") {
return (
<DisclosureRow
key={entry.label}
label={entry.label}
value={live ? getProviderOptionCurrentLabel(live) : undefined}
disabled={!live}
onPress={() => {
if (live) {
setSubmenu({ kind: "descriptor", id: live.id });
}
}}
/>
);
}
return (
<SwitchRow
key={entry.label}
label={entry.label}
value={live?.type === "boolean" ? (live.currentValue ?? false) : false}
disabled={!live}
onValueChange={(value) => {
if (live) {
handleOptionChange(live.id, value);
}
}}
/>
);
})}
<DisclosureRow
label="Runtime"
value={
RUNTIME_MODE_CHOICES.find((choice) => choice.mode === props.runtimeMode)?.label
}
onPress={() => setSubmenu({ kind: "runtime" })}
/>
<Pressable
accessibilityRole="button"
onPress={handleSave}
className="mx-4 mt-2 h-12 items-center justify-center rounded-full bg-primary active:opacity-80"
>
<Text className="text-sm font-t3-bold text-primary-foreground">
{pendingModel ? "Save" : "Done"}
</Text>
</Pressable>
</View>
</View>
{/* Submenus stack over the sheet instead of replacing its content,
so the main sheet keeps its size while drilling in and out. */}
{submenuContent ? (
<View className="absolute inset-0 justify-end">
<Pressable
accessibilityLabel={`Close ${submenuContent.title}`}
className="absolute inset-0 bg-backdrop"
onPress={() => setSubmenu(null)}
/>
<View className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet">
<Pressable
accessibilityLabel={`Close ${submenuContent.title}`}
accessibilityRole="button"
onPress={() => setSubmenu(null)}
className="items-center pb-1 pt-2.5"
>
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
</Pressable>
<Text className="px-5 pb-1.5 text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
{submenuContent.title}
</Text>
<ScrollView
style={{ maxHeight: windowHeight * 0.5 }}
contentContainerStyle={{ paddingBottom: insets.bottom + 12 }}
showsVerticalScrollIndicator={false}
bounces={false}
>
{submenuContent.rows.map((row) => (
<ChoiceRow
key={row.id}
label={row.label}
selected={row.selected}
onPress={row.onPress}
/>
))}
</ScrollView>
</View>
</View>
) : null}
</View>
</Modal>
);
}
@@ -3,6 +3,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import type {
EnvironmentId,
ModelSelection,
ProjectReadFileResult,
ProviderInteractionMode,
ProviderOptionSelection,
RuntimeMode,
@@ -13,8 +14,14 @@ import {
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
MessageId,
T3_PROJECT_FILE_NAME,
ThreadId,
} from "@t3tools/contracts";
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import {
isDefaultThreadEnvModeSettled,
resolveDefaultThreadEnvMode,
} from "@t3tools/shared/threadEnvMode";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
@@ -25,10 +32,13 @@ import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import {
buildModelOptions,
groupByProvider,
resolveDefaultableModelSelection,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
import { projectEnvironment } from "../../state/projects";
import { useEnvironmentQuery } from "../../state/query";
import {
appendComposerDraftAttachments,
clearComposerDraft,
@@ -147,7 +157,10 @@ type NewTaskFlowContextValue = {
readonly reset: () => void;
readonly setProject: (project: EnvironmentProject) => void;
readonly selectEnvironment: (environmentId: EnvironmentId) => void;
readonly setSelectedModelKey: (key: string | null) => void;
readonly setSelectedModelKey: (
key: string | null,
options?: ReadonlyArray<ProviderOptionSelection>,
) => void;
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
readonly selectBranch: (branch: VcsRef) => void;
readonly setStartFromOrigin: (value: boolean) => void;
@@ -341,10 +354,35 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
// The server's configured default decides the mode until the user picks one
// explicitly — same resolution web uses for new draft threads.
const defaultWorkspaceMode: WorkspaceMode =
selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local";
// Default mode until the user picks one explicitly — same resolution web
// uses for new draft threads: per-project setting, then the repo's
// checked-in t3.json, then the server's configured default.
const t3ProjectFileQuery = useEnvironmentQuery(
selectedProject !== null && selectedProject.workspaceRoot !== ""
? projectEnvironment.readFile({
environmentId: selectedProject.environmentId,
input: { cwd: selectedProject.workspaceRoot, relativePath: T3_PROJECT_FILE_NAME },
})
: null,
);
const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
const t3ProjectFileDefaultMode = useMemo(() => {
if (t3ProjectFileData === null || t3ProjectFileData.truncated) return null;
return parseT3ProjectFile(t3ProjectFileData.contents)?.defaultThreadEnvMode ?? null;
}, [t3ProjectFileData]);
const defaultWorkspaceMode: WorkspaceMode = resolveDefaultThreadEnvMode({
projectSetting: selectedProject?.defaultThreadEnvMode,
projectFile: t3ProjectFileDefaultMode,
globalDefault: selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local",
});
// While unsettled the resolved default is provisional. Nothing may write
// it into the draft during that window (the auto-branch effect does), or
// the frozen interim value beats the t3.json default once it loads.
const defaultWorkspaceModeSettled = isDefaultThreadEnvModeSettled({
explicitMode: selectedProjectDraft.workspaceSelection?.mode,
projectSetting: selectedProject?.defaultThreadEnvMode,
projectFilePending: t3ProjectFileQuery.isPending,
});
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
@@ -359,14 +397,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
// Stored selections (draft and project default) only count while their
// provider is usable on the server; otherwise the server's default model
// wins instead of silently targeting a disabled provider.
// Stored selections only count while their provider is usable on the
// server; otherwise the server's default model wins instead of silently
// targeting a disabled provider. The draft selection is an explicit pick
// and passes through as-is; the project default (last used, possibly from
// desktop) is implicit and additionally never resolves to a legacy model.
const draftModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProjectDraft.modelSelection ?? null,
);
const projectDefaultModelSelection = resolveSelectableModelSelection(
const projectDefaultModelSelection = resolveDefaultableModelSelection(
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
);
@@ -404,7 +444,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
);
const setSelectedModelKey = useCallback(
(key: string | null) => {
// Options ride along in the same write: a follow-up setSelectedModelOptions
// call would rebuild the selection from the stale pre-switch model.
(key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => {
if (!key || !selectedProjectDraftKey) {
return;
}
@@ -413,7 +455,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: option.selection,
modelSelection: options ? { ...option.selection, options } : option.selection,
});
},
[modelOptions, selectedProjectDraftKey],
@@ -610,7 +652,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}, [refreshBranches, selectedProject]);
useEffect(() => {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
if (
!defaultWorkspaceModeSettled ||
workspaceMode !== "worktree" ||
selectedBranchName !== null
) {
return;
}
// The default may only exist as origin/<default> (isRemote), which
@@ -622,7 +668,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
}, [
allBranchRefs,
availableBranches,
defaultWorkspaceModeSettled,
selectBranch,
selectedBranchName,
workspaceMode,
]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
@@ -354,6 +354,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly snoozeSupported: boolean;
/** False on servers that predate thread.pin/unpin. */
readonly pinningSupported: boolean;
/** False on servers that predate thread.pin.reorder. Gates the pinned
Move up / Move down menu items. */
readonly pinReorderSupported?: boolean;
readonly onMovePinnedThread?: (thread: EnvironmentThreadShell, direction: "up" | "down") => void;
/** Position flags for the pinned block so the menu disables the move that
would fall off the end of the list. */
readonly canMovePinnedUp?: boolean;
readonly canMovePinnedDown?: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
@@ -382,6 +390,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onArchiveThread,
onPinThread,
onUnpinThread,
onMovePinnedThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
@@ -416,6 +425,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
const handleMovePinnedUp = useCallback(
() => onMovePinnedThread?.(thread, "up"),
[onMovePinnedThread, thread],
);
const handleMovePinnedDown = useCallback(
() => onMovePinnedThread?.(thread, "down"),
[onMovePinnedThread, thread],
);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
// Swipe: the v2 primary action is the lifecycle transition. Every settled
@@ -459,12 +476,34 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
() =>
props.pinningSupported
? [
...(pinnedRow && props.pinReorderSupported === true
? [
{
id: "move-pin-up",
title: "Move up",
image: "arrow.up",
attributes: { disabled: props.canMovePinnedUp !== true },
} satisfies MenuAction,
{
id: "move-pin-down",
title: "Move down",
image: "arrow.down",
attributes: { disabled: props.canMovePinnedDown !== true },
} satisfies MenuAction,
]
: []),
pinnedRow
? { id: "unpin", title: "Unpin", image: "pin.slash" }
: { id: "pin", title: "Pin", image: "pin" },
]
: [],
[pinnedRow, props.pinningSupported],
[
pinnedRow,
props.canMovePinnedDown,
props.canMovePinnedUp,
props.pinReorderSupported,
props.pinningSupported,
],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
@@ -491,6 +530,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "unsnooze") handleUnsnooze();
if (nativeEvent.event === "pin") handlePin();
if (nativeEvent.event === "unpin") handleUnpin();
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
@@ -507,6 +548,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handleMovePinnedDown,
handleMovePinnedUp,
handlePin,
handleSettle,
handleSnooze,
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ProviderOptionSelection } from "@t3tools/contracts";
import type { ModelOption } from "../../lib/modelOptions";
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
function modelOption(
model: string,
options: ReadonlyArray<ProviderOptionSelection> = [],
): ModelOption {
return {
key: `codex:${model}`,
label: model,
subtitle: "Codex",
providerKey: "codex",
providerLabel: "Codex",
providerDriver: "codex",
isDefault: false,
isLegacy: false,
capabilities: null,
selection: {
instanceId: ProviderInstanceId.make("codex"),
model,
options,
},
};
}
describe("thread settings sheet state", () => {
it("clears staging when the applied model is pressed", () => {
expect(
pendingModelAfterPress({
current: modelOption("gpt-next"),
pressed: modelOption("gpt-current"),
pressedIsApplied: true,
}),
).toBeNull();
});
it("preserves staged options when the highlighted model is pressed again", () => {
const pending = modelOption("gpt-next", [{ id: "effort", value: "high" }]);
expect(
pendingModelAfterPress({
current: pending,
pressed: modelOption("gpt-next"),
pressedIsApplied: false,
}),
).toBe(pending);
});
it("stages a different model", () => {
const pressed = modelOption("gpt-other");
expect(
pendingModelAfterPress({
current: modelOption("gpt-next"),
pressed,
pressedIsApplied: false,
}),
).toBe(pressed);
});
});
@@ -0,0 +1,13 @@
import type { ModelOption } from "../../lib/modelOptions";
/** Preserve staged provider options when the highlighted model is tapped again. */
export function pendingModelAfterPress(input: {
readonly current: ModelOption | null;
readonly pressed: ModelOption;
readonly pressedIsApplied: boolean;
}): ModelOption | null {
if (input.pressedIsApplied) {
return null;
}
return input.current?.key === input.pressed.key ? input.current : input.pressed;
}
@@ -104,20 +104,24 @@ describe("resolveThreadListV2SnoozeMenuSelection", () => {
describe("resolveThreadListV2Enabled", () => {
it("defaults on when the device has never chosen", () => {
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
true,
);
expect(
resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: true }),
).toBe(true);
});
it("honors an explicit device opt-out", () => {
expect(resolveThreadListV2Enabled({ preference: false, preferencesLoaded: true })).toBe(false);
expect(resolveThreadListV2Enabled({ preference: true, preferencesLoaded: true })).toBe(true);
it("honors an explicit legacy opt-in", () => {
expect(resolveThreadListV2Enabled({ legacyPreference: true, preferencesLoaded: true })).toBe(
false,
);
expect(resolveThreadListV2Enabled({ legacyPreference: false, preferencesLoaded: true })).toBe(
true,
);
});
it("holds the default while preferences are still loading so the list does not remount", () => {
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: false })).toBe(
true,
);
expect(
resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: false }),
).toBe(true);
});
});
@@ -9,6 +9,7 @@ import {
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -102,23 +103,23 @@ export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
/**
* Thread List v2 is on by default on every app variant; the Settings → Beta
* toggle is an opt-out. Preferences persist as sparse patches, so `undefined`
* genuinely means "never chosen".
* The flat Thread List v2 is the default on every app variant; the Settings →
* Legacy toggle opts a device back into the grouped legacy list. Preferences
* persist as sparse patches, so `undefined` genuinely means "never chosen".
*
* `preferencesLoaded` guards the startup window: preferences load
* asynchronously, and rendering one list before the stored choice arrives would
* remount the whole thing a tick later. While loading, hold the default — that
* is where every device without an explicit opt-out lands anyway.
* is where every device without an explicit legacy opt-in lands anyway.
*/
export function resolveThreadListV2Enabled(input: {
readonly preference: boolean | undefined;
readonly legacyPreference: boolean | undefined;
readonly preferencesLoaded: boolean;
}): boolean {
if (!input.preferencesLoaded) {
return true;
}
return input.preference ?? true;
return input.legacyPreference !== true;
}
export function resolveThreadListV2Status(
@@ -383,8 +384,8 @@ export function buildThreadListV2Items(input: {
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: snooze outranks everything, including a
// pin — a snoozed thread leaves the list until it wakes (or raises its
// hand). The pin survives underneath, so a woken thread reappears at
// its original spot in the creation-ordered pinned block.
// hand). The pin (and its pinOrderKey) survives underneath, so a woken
// thread reappears at its exact spot in the pinned block.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozed.push(thread);
if (
@@ -444,7 +445,7 @@ export function buildThreadListV2Items(input: {
);
const items: ThreadListV2Item[] = [];
for (const thread of sortThreadsForListV2(pinned)) {
for (const thread of sortPinnedThreadsByOrderKey(pinned)) {
items.push({
thread,
variant: "card",
@@ -5,15 +5,15 @@ import { mobilePreferencesAtom } from "../../state/preferences";
import { resolveThreadListV2Enabled } from "./threadListV2";
/**
* Resolved Thread List v2 state: the device-local preference if the user has
* set one, otherwise the default (on). Every consumer must read through this
* Resolved Thread List v2 state: on unless the device opted into the legacy
* grouped list (Settings → Legacy). Every consumer must read through this
* rather than the raw preference, which is undefined until explicitly chosen.
*/
export function useThreadListV2Enabled(): boolean {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const loaded = AsyncResult.isSuccess(preferencesResult);
return resolveThreadListV2Enabled({
preference: loaded ? preferencesResult.value.threadListV2Enabled : undefined,
legacyPreference: loaded ? preferencesResult.value.legacyThreadListEnabled : undefined,
preferencesLoaded: loaded,
});
}
@@ -0,0 +1,98 @@
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import { KeyboardController } from "react-native-keyboard-controller";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
export type ThreadSettingsSheetCloseReason = "save" | "dismiss";
type PresentationPhase = "closed" | "opening" | "visible" | "closing";
/**
* Keeps the custom native composer and the settings modal from owning focus at
* the same time. Opening waits for the keyboard dismissal to finish, while
* focus restoration waits for the modal's dismissal callback.
*/
export function useThreadSettingsSheetPresentation(input: {
readonly editorRef: RefObject<ComposerEditorHandle | null>;
readonly isEditorFocused: boolean;
}) {
const [phase, setPhase] = useState<PresentationPhase>("closed");
const isActiveRef = useRef(false);
const isMountedRef = useRef(true);
const openingIdRef = useRef(0);
const restoreFocusOnSaveRef = useRef(false);
const shouldRestoreAfterDismissRef = useRef(false);
useEffect(
() => () => {
isMountedRef.current = false;
isActiveRef.current = false;
openingIdRef.current += 1;
},
[],
);
const open = useCallback(() => {
if (isActiveRef.current) {
return;
}
isActiveRef.current = true;
restoreFocusOnSaveRef.current = input.isEditorFocused || KeyboardController.isVisible();
shouldRestoreAfterDismissRef.current = false;
setPhase("opening");
const openingId = openingIdRef.current + 1;
openingIdRef.current = openingId;
// Keyboard.dismiss() only tracks React Native TextInputs. The composer is
// a custom native text view, so explicitly resign its first responder too.
input.editorRef.current?.blur();
void KeyboardController.dismiss().then(() => {
if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {
return;
}
setPhase("visible");
});
}, [input.editorRef, input.isEditorFocused]);
const close = useCallback((reason: ThreadSettingsSheetCloseReason) => {
if (!isActiveRef.current) {
return;
}
openingIdRef.current += 1;
shouldRestoreAfterDismissRef.current = reason === "save" && restoreFocusOnSaveRef.current;
setPhase("closing");
}, []);
const onDismissed = useCallback(() => {
const shouldRestoreFocus = shouldRestoreAfterDismissRef.current;
shouldRestoreAfterDismissRef.current = false;
restoreFocusOnSaveRef.current = false;
isActiveRef.current = false;
setPhase("closed");
if (shouldRestoreFocus) {
input.editorRef.current?.focus();
}
}, [input.editorRef]);
// The new-task screen can have an autofocus queued before the sheet opens.
// Preserve that intent for Save without allowing it to focus under the modal.
const restoreFocusAfterSave = useCallback(() => {
if (isActiveRef.current) {
restoreFocusOnSaveRef.current = true;
}
}, []);
return {
isActive: phase !== "closed",
isActiveRef,
isVisible: phase === "visible",
open,
close,
onDismissed,
restoreFocusAfterSave,
} as const;
}
+43 -46
View File
@@ -3,14 +3,14 @@ import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
import {
buildModelMenuActions,
buildModelOptions,
groupByProvider,
resolveDefaultableModelSelection,
resolveSelectableModelSelection,
} from "./modelOptions";
describe("mobile model options", () => {
it("folds legacy models into a provider-scoped menu", () => {
it("groups models by provider and flags legacy entries", () => {
const config = {
providers: [
{
@@ -39,51 +39,14 @@ describe("mobile model options", () => {
],
} as unknown as ServerConfig;
const actions = buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null);
expect(actions).toMatchObject([
expect(groupByProvider(buildModelOptions(config, null))).toMatchObject([
{
title: "Codex",
subactions: [{ id: "model:codex:gpt-5.6-sol", title: "GPT-5.6 Sol" }],
},
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4", title: "GPT-5.4" }],
},
]);
});
it("omits an empty provider menu when every model is legacy", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
expect(
buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null),
).toMatchObject([
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4" }],
providerKey: "codex",
providerLabel: "Codex",
models: [
{ key: "codex:gpt-5.6-sol", label: "GPT-5.6 Sol", isLegacy: false },
{ key: "codex:gpt-5.4", label: "GPT-5.4", isLegacy: true },
],
},
]);
});
@@ -174,4 +137,38 @@ describe("mobile model options", () => {
// No config (environment offline) — nothing to validate against.
expect(resolveSelectableModelSelection(null, disabled)).toBe(disabled);
});
it("keeps legacy models out of implicit defaults", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{ slug: "gpt-5.6-sol", name: "GPT-5.6 Sol", isCustom: false, capabilities: null },
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
const current = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" };
const legacy = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" };
expect(resolveDefaultableModelSelection(config, current)).toBe(current);
// A legacy last-used selection falls through to the provider default.
expect(resolveDefaultableModelSelection(config, legacy)).toBeNull();
// Offline: nothing to validate against, selection passes through.
expect(resolveDefaultableModelSelection(null, legacy)).toBe(legacy);
});
});
+20 -51
View File
@@ -3,7 +3,6 @@ import type {
ModelSelection,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
buildProviderOptionSelectionsFromDescriptors,
getProviderOptionDescriptors,
@@ -85,6 +84,26 @@ export function resolveSelectableModelSelection(
: null;
}
/**
* Like resolveSelectableModelSelection, but additionally rejects legacy
* models. Used for implicit defaults (stored draft, project last-used): a
* new thread should never quietly start on a legacy model, so those fall
* through to the provider's default instead. Explicit picks in the settings
* sheet are unaffected.
*/
export function resolveDefaultableModelSelection(
config: T3ServerConfig | null | undefined,
selection: ModelSelection | null,
): ModelSelection | null {
const usable = resolveSelectableModelSelection(config, selection);
if (!usable || !config) {
return usable;
}
const provider = config.providers.find((candidate) => candidate.instanceId === usable.instanceId);
const model = provider?.models.find((candidate) => candidate.slug === usable.model);
return model?.isLegacy === true ? null : usable;
}
export function buildModelOptions(
config: T3ServerConfig | null | undefined,
fallbackModelSelection: ModelSelection | null,
@@ -168,53 +187,3 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
models: group.models,
}));
}
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
return {
id: `model:${option.key}`,
title: option.label,
state:
option.selection.instanceId === selectedModel?.instanceId &&
option.selection.model === selectedModel.model
? "on"
: undefined,
};
}
export function buildModelMenuActions(
groups: ReadonlyArray<ProviderGroup>,
selectedModel: ModelSelection | null,
): MenuAction[] {
return groups.flatMap((group) => {
const currentModels = group.models.filter((model) => !model.isLegacy);
const legacyModels = group.models.filter((model) => model.isLegacy);
const selected = group.models.find(
(model) =>
model.selection.instanceId === selectedModel?.instanceId &&
model.selection.model === selectedModel.model,
);
return [
...(currentModels.length > 0
? [
{
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: selected && !selected.isLegacy ? selected.label : undefined,
subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
...(legacyModels.length > 0
? [
{
id: `legacy-models:${group.providerKey}`,
title: `${group.providerLabel} legacy models`,
subtitle: selected?.isLegacy ? selected.label : undefined,
subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
];
});
}
+15 -37
View File
@@ -3,9 +3,8 @@ import { describe, expect, it } from "vite-plus/test";
import type { ModelCapabilities } from "@t3tools/contracts";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
applyProviderOptionSelection,
providerOptionValueLabels,
resolveProviderOptionDescriptors,
} from "./providerOptions";
@@ -35,31 +34,13 @@ const CODEX_CAPABILITIES: ModelCapabilities = {
};
describe("mobile provider options", () => {
it("renders the option descriptors advertised by the selected model", () => {
it("summarizes the option values currently in effect", () => {
const descriptors = resolveProviderOptionDescriptors({
capabilities: CODEX_CAPABILITIES,
selections: undefined,
});
expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([
{
title: "Reasoning",
subtitle: "Medium",
subactions: [
{ title: "Medium (default)", state: "on" },
{ title: "High", state: undefined },
],
},
{
title: "Service Tier",
subtitle: "Standard",
subactions: [
{ title: "Standard (default)", state: "on" },
{ title: "Fast", state: undefined },
],
},
]);
expect(providerOptionsConfigurationLabel(descriptors)).toBe("Medium · Standard");
expect(providerOptionValueLabels(descriptors)).toEqual(["Medium", "Standard"]);
});
it("updates generic select options without knowing provider-specific ids", () => {
@@ -67,14 +48,18 @@ describe("mobile provider options", () => {
capabilities: CODEX_CAPABILITIES,
selections: undefined,
});
const actions = buildProviderOptionMenuActions(descriptors);
const fastEvent = actions[1]?.subactions?.[1]?.id;
expect(fastEvent).toBeDefined();
expect(applyProviderOptionMenuEvent(descriptors, fastEvent!)).toEqual([
expect(
applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "priority" }),
).toEqual([
{ id: "reasoningEffort", value: "medium" },
{ id: "serviceTier", value: "priority" },
]);
// Choices the model doesn't advertise are rejected, not stored.
expect(
applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "turbo" }),
).toBeNull();
expect(applyProviderOptionSelection(descriptors, { id: "unknown", value: "high" })).toBeNull();
});
it("treats an unspecified boolean capability as off", () => {
@@ -85,16 +70,9 @@ describe("mobile provider options", () => {
selections: undefined,
});
expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([
{
title: "Fast Mode",
subtitle: "Off",
subactions: [
{ title: "Off", state: "on" },
{ title: "On", state: undefined },
],
},
expect(providerOptionValueLabels(descriptors)).toEqual([]);
expect(applyProviderOptionSelection(descriptors, { id: "fastMode", value: true })).toEqual([
{ id: "fastMode", value: true },
]);
expect(providerOptionsConfigurationLabel(descriptors)).toBe("Configuration");
});
});
+20 -87
View File
@@ -3,48 +3,12 @@ import type {
ProviderOptionDescriptor,
ProviderOptionSelection,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
buildProviderOptionSelectionsFromDescriptors,
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
const PROVIDER_OPTION_EVENT_PREFIX = "provider-option:";
function providerOptionEvent(id: string, value: string | boolean): string {
return `${PROVIDER_OPTION_EVENT_PREFIX}${encodeURIComponent(JSON.stringify({ id, value }))}`;
}
function parseProviderOptionEvent(
event: string,
): { readonly id: string; readonly value: string | boolean } | null {
if (!event.startsWith(PROVIDER_OPTION_EVENT_PREFIX)) {
return null;
}
try {
const parsed: unknown = JSON.parse(
decodeURIComponent(event.slice(PROVIDER_OPTION_EVENT_PREFIX.length)),
);
if (
typeof parsed === "object" &&
parsed !== null &&
"id" in parsed &&
typeof parsed.id === "string" &&
"value" in parsed &&
(typeof parsed.value === "string" || typeof parsed.value === "boolean")
) {
return { id: parsed.id, value: parsed.value };
}
} catch {
return null;
}
return null;
}
export function resolveProviderOptionDescriptors(input: {
readonly capabilities: ModelCapabilities | null | undefined;
readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;
@@ -58,72 +22,41 @@ export function resolveProviderOptionDescriptors(input: {
});
}
export function buildProviderOptionMenuActions(
/**
* Labels for the option values currently in effect (select values plus
* enabled booleans), used to summarize the thread configuration in the
* composer trigger pill.
*/
export function providerOptionValueLabels(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
): ReadonlyArray<MenuAction> {
return descriptors.map((descriptor) => {
const currentValue =
descriptor.type === "boolean"
? (descriptor.currentValue ?? false)
: getProviderOptionCurrentValue(descriptor);
const choices =
descriptor.type === "select"
? descriptor.options.map((option) => ({
id: providerOptionEvent(descriptor.id, option.id),
title: `${option.label}${option.isDefault ? " (default)" : ""}`,
state: currentValue === option.id ? ("on" as const) : undefined,
}))
: ([false, true] as const).map((value) => ({
id: providerOptionEvent(descriptor.id, value),
title: value ? "On" : "Off",
state: currentValue === value ? ("on" as const) : undefined,
}));
return {
id: `provider-option-menu:${descriptor.id}`,
title: descriptor.label,
subtitle:
descriptor.type === "boolean"
? currentValue
? "On"
: "Off"
: getProviderOptionCurrentLabel(descriptor),
subactions: choices,
};
});
}
export function providerOptionsConfigurationLabel(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
): string {
const labels = descriptors.flatMap((descriptor) => {
): ReadonlyArray<string> {
return descriptors.flatMap((descriptor) => {
if (descriptor.type === "boolean") {
return descriptor.currentValue ? [descriptor.label] : [];
}
const label = getProviderOptionCurrentLabel(descriptor);
return label ? [label] : [];
});
return labels.length > 0 ? labels.join(" · ") : "Configuration";
}
export function applyProviderOptionMenuEvent(
/**
* Applies one option change (by descriptor id) and returns the full selection
* list to store on the model selection, or null when the change doesn't match
* an advertised descriptor / choice.
*/
export function applyProviderOptionSelection(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
event: string,
change: ProviderOptionSelection,
): ReadonlyArray<ProviderOptionSelection> | null {
const selection = parseProviderOptionEvent(event);
if (!selection) {
return null;
}
const descriptor = descriptors.find((candidate) => candidate.id === selection.id);
const descriptor = descriptors.find((candidate) => candidate.id === change.id);
if (!descriptor) {
return null;
}
if (
(descriptor.type === "boolean" && typeof selection.value !== "boolean") ||
(descriptor.type === "boolean" && typeof change.value !== "boolean") ||
(descriptor.type === "select" &&
(typeof selection.value !== "string" ||
!descriptor.options.some((option) => option.id === selection.value)))
(typeof change.value !== "string" ||
!descriptor.options.some((option) => option.id === change.value)))
) {
return null;
}
@@ -132,7 +65,7 @@ export function applyProviderOptionMenuEvent(
candidate.id === descriptor.id
? {
...candidate,
currentValue: selection.value,
currentValue: change.value,
}
: candidate,
) as ReadonlyArray<ProviderOptionDescriptor>;
@@ -27,12 +27,13 @@ export interface Preferences {
readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode;
/**
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
* client-settings sync, so the flat v2 thread list is opted out of per
* device. Undefined means the user has never chosen, which resolves to on —
* see `resolveThreadListV2Enabled`.
* Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
* no client-settings sync, so the legacy grouped thread list is opted into
* per device. Deliberately a fresh key (was `threadListV2Enabled`, an
* opt-out): sanitizing drops the old key, so every device resets to the
* default flat list — see `resolveThreadListV2Enabled`.
*/
readonly threadListV2Enabled?: boolean;
readonly legacyThreadListEnabled?: boolean;
}
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
@@ -84,7 +85,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
threadListV2Enabled?: boolean;
legacyThreadListEnabled?: boolean;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
@@ -121,8 +122,8 @@ function sanitizePreferences(parsed: Preferences): Preferences {
) {
preferences.projectGroupingMode = parsed.projectGroupingMode;
}
if (typeof parsed.threadListV2Enabled === "boolean") {
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
if (typeof parsed.legacyThreadListEnabled === "boolean") {
preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
}
return preferences;
}
@@ -23,6 +23,7 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import * as ServerConfig from "../src/config.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
@@ -93,6 +94,7 @@ const makeIntegrationFixture = (options?: { readonly analytics?: Layer.Layer<Ana
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerConfig.layerTest(cwd, cwd).pipe(Layer.provide(NodeServices.layer)),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
options?.analytics ?? AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.31",
"version": "0.0.32",
"license": "MIT",
"repository": {
"type": "git",
+195
View File
@@ -0,0 +1,195 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../src/persistence/Migrations.ts";
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
import { runMigrateDevDb } from "./migrate-dev-db.ts";
const withDatabase = <A, E>(
databasePath: string,
effect: Effect.Effect<A, E, SqlClient.SqlClient>,
) => effect.pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));
/** A migrated source db with one thread per lifecycle state. Only
* `stopped-thread` qualifies for the clone. */
const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(function* (
baseDir: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const stateDir = path.join(baseDir, "userdata");
const databasePath = path.join(stateDir, "state.sqlite");
yield* fs.makeDirectory(stateDir, { recursive: true });
yield* withDatabase(
databasePath,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations();
// The real shared db carries this column from a branch build without a
// matching migration; reproduce that drift so the filter is exercised.
yield* sql`ALTER TABLE projection_threads ADD COLUMN monitor_json TEXT`;
yield* sql`INSERT INTO projection_projects
(project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at)
VALUES
('project-kept', 'Kept', '/tmp/kept', '[]', '2026-08-01', '2026-08-01', NULL),
('project-deleted', 'Deleted', '/tmp/deleted', '[]', '2026-08-01', '2026-08-02', '2026-08-02')`;
const threads = [
["stopped-thread", "project-kept", "stopped", null, null],
["running-thread", "project-kept", "running", null, null],
["settled-thread", "project-kept", "stopped", "2026-08-01", null],
["monitored-thread", "project-kept", "stopped", null, '{"kind":"pr"}'],
["deleted-project-thread", "project-deleted", "stopped", null, null],
] as const;
for (const [threadId, projectId, status, settledAt, monitorJson] of threads) {
yield* sql`INSERT INTO projection_threads
(thread_id, project_id, title, created_at, updated_at, settled_at, monitor_json)
VALUES (${threadId}, ${projectId}, ${threadId}, '2026-08-01', '2026-08-01', ${settledAt}, ${monitorJson})`;
yield* sql`INSERT INTO projection_thread_sessions (thread_id, status, updated_at)
VALUES (${threadId}, ${status}, '2026-08-01')`;
yield* sql`INSERT INTO orchestration_events
(event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json)
VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}')`;
}
yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at)
VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`;
}),
);
return databasePath;
});
it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
it.effect("keeps only stopped threads from live projects and clears auth state", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-src-" });
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-dest-" });
const source = yield* createFixtureSource(sourceDir);
const result = yield* runMigrateDevDb(
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
{ sharedHome: sourceDir },
);
assert.equal(result.databasePath, path.join(destDir, "userdata", "state.sqlite"));
const kept = yield* withDatabase(
result.databasePath,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const threads = yield* sql<{ thread_id: string }>`
SELECT thread_id FROM projection_threads ORDER BY thread_id`;
const events = yield* sql<{ stream_id: string }>`
SELECT stream_id FROM orchestration_events`;
const [auth] = yield* sql<{ count: number }>`
SELECT COUNT(*) AS count FROM auth_sessions`;
return { threads, events, authCount: auth?.count ?? 0 };
}),
);
assert.deepStrictEqual(
kept.threads.map((row) => row.thread_id),
["stopped-thread"],
);
assert.deepStrictEqual(
kept.events.map((row) => row.stream_id),
["stopped-thread"],
);
assert.equal(kept.authCount, 0);
}),
);
it.effect("fails loudly on a migration slot collision", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slot-" });
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slot-dest-" });
const source = yield* createFixtureSource(sourceDir);
// Simulate another branch having claimed slot 1 first: the id is
// recorded, so this checkout's migration 1 silently never runs.
yield* withDatabase(
source,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`UPDATE effect_sql_migrations
SET name = 'SomebodyElsesMigration' WHERE migration_id = 1`;
}),
);
const error = yield* runMigrateDevDb(
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
{ sharedHome: sourceDir },
).pipe(Effect.flip);
assert.equal(error._tag, "MigrateDevDbSlotCollisionError");
if (error._tag === "MigrateDevDbSlotCollisionError") {
assert.equal(error.slot, 1);
assert.equal(error.appliedName, "SomebodyElsesMigration");
}
}),
);
it.effect("refuses while a dev server holds the destination", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-" });
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-dest-" });
const source = yield* createFixtureSource(sourceDir);
// This test process stands in for a live dev server.
const stateDir = path.join(destDir, "userdata");
yield* fs.makeDirectory(stateDir, { recursive: true });
yield* fs.writeFileString(
path.join(stateDir, "server-runtime.json"),
`{"version":1,"pid":${process.pid}}`,
);
const error = yield* runMigrateDevDb(
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
{ sharedHome: sourceDir },
).pipe(Effect.flip);
assert.equal(error._tag, "MigrateDevDbServerRunningError");
if (error._tag === "MigrateDevDbServerRunningError") {
assert.equal(error.pid, process.pid);
}
}),
);
it.effect("refuses a source that resolves to a destination path", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sharedDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-" });
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-dest-" });
// A leftover snapshot from a prior failed run, passed as --source: it
// must not be deleted before it is read.
const leftoverSnapshot = path.join(destDir, "userdata", "state.sqlite.migrate-dev-db-tmp");
yield* fs.makeDirectory(path.dirname(leftoverSnapshot), { recursive: true });
yield* fs.writeFileString(leftoverSnapshot, "not a real db");
const error = yield* runMigrateDevDb(
{ baseDir: destDir, source: leftoverSnapshot, projects: 5, threadsPerProject: 10 },
{ sharedHome: sharedDir },
).pipe(Effect.flip);
assert.equal(error._tag, "MigrateDevDbSourceIsDestinationError");
assert.equal(yield* fs.exists(leftoverSnapshot), true);
}),
);
it.effect("refuses to rebuild the shared home", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
const source = yield* createFixtureSource(sourceDir);
const error = yield* runMigrateDevDb(
{ baseDir: sourceDir, source, projects: 5, threadsPerProject: 10 },
{ sharedHome: sourceDir },
).pipe(Effect.flip);
assert.equal(error._tag, "MigrateDevDbSharedHomeError");
}),
);
});
+560
View File
@@ -0,0 +1,560 @@
#!/usr/bin/env node
/**
* Rebuild an isolated dev database from a pruned snapshot of the real
* ~/.t3 database, then run this checkout's migrations against it.
*
* `vp run migrate-dev-db` from a worktree:
* 1. Nukes `<worktree>/.t3/userdata/state.sqlite`.
* 2. Snapshots the real db (read-only VACUUM INTO) and prunes it to the
* most recently updated projects and, per project, the most recent
* threads that have fully stopped. Working, settled, and monitored
* threads are skipped so the dev server never adopts live work.
* Auth sessions, pairing links, command receipts, and provider
* runtime rows are dropped — pair a fresh browser against dev.
* 3. Runs migrations on the result. Because the clone carries the real
* `effect_sql_migrations` table, this proves a new migration applies
* on top of the real applied set, and the slot check below catches
* the silent failure where two branches claim the same
* `Migrations/NNN_` id (the second one's CREATE TABLE is skipped).
*
* The event log (`orchestration_events`) is pruned per stream while
* `sqlite_sequence` and `projection_state` carry over untouched, so new
* events keep appending after the old high-water mark and projection
* cursors never rewind.
*/
// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard.
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeOS from "node:os";
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { Command, Flag } from "effect/unstable/cli";
import { migrationManifest, runMigrations } from "../src/persistence/Migrations.ts";
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
export class MigrateDevDbNotInWorktreeError extends Schema.TaggedErrorClass<MigrateDevDbNotInWorktreeError>()(
"MigrateDevDbNotInWorktreeError",
{},
) {
override get message(): string {
return "Not inside a linked git worktree. Pass --base-dir to target an isolated .t3 directory.";
}
}
export class MigrateDevDbSharedHomeError extends Schema.TaggedErrorClass<MigrateDevDbSharedHomeError>()(
"MigrateDevDbSharedHomeError",
{},
) {
override get message(): string {
return "Refusing to rebuild the shared ~/.t3 database. Use an isolated --base-dir.";
}
}
export class MigrateDevDbSourceMissingError extends Schema.TaggedErrorClass<MigrateDevDbSourceMissingError>()(
"MigrateDevDbSourceMissingError",
{
sourcePath: Schema.String,
},
) {
override get message(): string {
return `Source database does not exist at '${this.sourcePath}'.`;
}
}
export class MigrateDevDbSourceIsDestinationError extends Schema.TaggedErrorClass<MigrateDevDbSourceIsDestinationError>()(
"MigrateDevDbSourceIsDestinationError",
{
sourcePath: Schema.String,
},
) {
override get message(): string {
return `Source database '${this.sourcePath}' resolves to a path this command rewrites. Pick a different --source or --base-dir.`;
}
}
export class MigrateDevDbServerRunningError extends Schema.TaggedErrorClass<MigrateDevDbServerRunningError>()(
"MigrateDevDbServerRunningError",
{
databasePath: Schema.String,
pid: Schema.Number,
},
) {
override get message(): string {
return `Dev database at '${this.databasePath}' is open by a running server (pid ${this.pid} per server-runtime.json). Stop that server first; if that pid is not actually a T3 server (stale descriptor, reused pid), delete the server-runtime.json next to the database and retry.`;
}
}
export class MigrateDevDbDestinationBusyError extends Schema.TaggedErrorClass<MigrateDevDbDestinationBusyError>()(
"MigrateDevDbDestinationBusyError",
{
databasePath: Schema.String,
reason: Schema.Literals(["write-locked", "wal-held"]),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
const detail =
this.reason === "write-locked"
? "the database is write-locked"
: "another connection is holding its WAL";
return `Dev database at '${this.databasePath}' looks in use (${detail}). Stop the dev server first; if none is running, delete the -wal/-shm files next to it.`;
}
}
/**
* Two branches claimed the same Migrations/NNN_ slot: the id was already
* recorded under a different name, so this checkout's migration was
* silently skipped and its schema changes never applied.
*/
export class MigrateDevDbSlotCollisionError extends Schema.TaggedErrorClass<MigrateDevDbSlotCollisionError>()(
"MigrateDevDbSlotCollisionError",
{
slot: Schema.Number,
codeName: Schema.String,
appliedName: Schema.String,
},
) {
override get message(): string {
return `Migration slot collision at ${this.slot}: this checkout registers '${this.codeName}' but the database already applied '${this.appliedName}' in that slot. Renumber the new migration to a free slot.`;
}
}
export class MigrateDevDbPhaseError extends Schema.TaggedErrorClass<MigrateDevDbPhaseError>()(
"MigrateDevDbPhaseError",
{
phase: Schema.Literals(["snapshot", "prune", "compact", "migrate", "verify"]),
databasePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `migrate-dev-db failed during ${this.phase} on '${this.databasePath}'.`;
}
}
export interface RunMigrateDevDbInput {
/** Isolated .t3 directory. Defaults to `<worktree>/.t3` of the cwd. */
readonly baseDir?: string | undefined;
/** Source database. Defaults to `~/.t3/userdata/state.sqlite`. */
readonly source?: string | undefined;
readonly projects: number;
readonly threadsPerProject: number;
}
export interface RunMigrateDevDbOptions {
/** Overridable for tests; the directory writes must never target. */
readonly sharedHome?: string | undefined;
}
interface KeptProject {
readonly title: string;
readonly threads: number;
}
const removeDatabaseFiles = Effect.fn("removeDatabaseFiles")(function* (databasePath: string) {
const fs = yield* FileSystem.FileSystem;
for (const suffix of ["", "-wal", "-shm"]) {
yield* fs.remove(`${databasePath}${suffix}`).pipe(Effect.orElseSucceed(() => undefined));
}
});
/** The slice of server-runtime.json this script cares about. */
const ServerRuntimeState = Schema.fromJsonString(Schema.Struct({ pid: Schema.Number }));
const decodeServerRuntimeState = Schema.decodeEffect(ServerRuntimeState);
const isProcessAlive = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch (error) {
// EPERM means the process exists but belongs to someone else.
return (error as NodeJS.ErrnoException).code === "EPERM";
}
};
/** Liveness probe for a running dev server. The server writes its pid to
* server-runtime.json next to the database, which also catches an idle
* server holding an open-but-inactive connection. The SQL probes below back
* that up: BEGIN IMMEDIATE fails while a writer is active, and
* wal_checkpoint(TRUNCATE) reports busy while another connection holds the
* WAL. A leftover -shm alone is not a signal — read-only connections cannot
* clean it up on close. */
const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runtimeStatePath = path.join(path.dirname(databasePath), "server-runtime.json");
const runtimeState = yield* fs.readFileString(runtimeStatePath).pipe(
Effect.flatMap(decodeServerRuntimeState),
// A missing or malformed descriptor is not a liveness signal.
Effect.option,
);
if (Option.isSome(runtimeState) && isProcessAlive(runtimeState.value.pid)) {
return yield* new MigrateDevDbServerRunningError({
databasePath,
pid: runtimeState.value.pid,
});
}
if (!(yield* fs.exists(databasePath))) {
return;
}
const checkpoint = yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql.unsafe("PRAGMA busy_timeout = 0").unprepared;
yield* sql.unsafe("BEGIN IMMEDIATE").unprepared;
yield* sql.unsafe("ROLLBACK").unprepared;
return yield* sql.unsafe<{ busy: number }>("PRAGMA wal_checkpoint(TRUNCATE)").unprepared;
}).pipe(
Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
Effect.mapError(
(cause) =>
new MigrateDevDbDestinationBusyError({
databasePath,
reason: "write-locked",
cause,
}),
),
);
if (checkpoint[0] !== undefined && Number(checkpoint[0].busy) !== 0) {
return yield* new MigrateDevDbDestinationBusyError({
databasePath,
reason: "wal-held",
});
}
});
const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
const sql = yield* SqlClient.SqlClient;
// The shared db can carry monitor_json from a branch build even though no
// migration in this checkout creates it, so filter it only when present.
const threadColumns = yield* sql<{ name: string }>`
SELECT name FROM pragma_table_info('projection_threads')`;
const monitorFilter = threadColumns.some((column) => column.name === "monitor_json")
? "AND t.monitor_json IS NULL"
: "";
// "Stopped" is the persisted subset of the UI's thread status: the session
// reached status 'stopped' and nothing marks the thread settled or
// monitored. The in-memory working/monitoring liveness never persists, so
// filtering the session status is sufficient.
yield* sql.unsafe(`CREATE TEMP TABLE stopped_threads AS
SELECT t.thread_id, t.project_id, t.updated_at
FROM projection_threads t
JOIN projection_thread_sessions s ON s.thread_id = t.thread_id
WHERE t.deleted_at IS NULL
AND t.archived_at IS NULL
AND t.settled_at IS NULL
AND (t.settled_override IS NULL OR t.settled_override <> 'settled')
${monitorFilter}
AND s.status = 'stopped'`).unprepared;
// Projects with clonable threads outrank empty-but-recent ones: the point
// of the exercise is thread data, not the project list.
yield* sql`CREATE TEMP TABLE kept_projects AS
SELECT p.project_id
FROM projection_projects p
LEFT JOIN (
SELECT project_id, MAX(updated_at) AS last_stopped_at
FROM stopped_threads
GROUP BY project_id
) q ON q.project_id = p.project_id
WHERE p.deleted_at IS NULL
ORDER BY (q.last_stopped_at IS NULL) ASC,
COALESCE(q.last_stopped_at, p.updated_at) DESC
LIMIT ${input.projects}`;
yield* sql`CREATE TEMP TABLE kept_threads AS
SELECT thread_id FROM (
SELECT
st.thread_id,
ROW_NUMBER() OVER (
PARTITION BY st.project_id
ORDER BY st.updated_at DESC
) AS recency_rank
FROM stopped_threads st
JOIN kept_projects kp ON kp.project_id = st.project_id
)
WHERE recency_rank <= ${input.threadsPerProject}`;
yield* sql.withTransaction(
Effect.gen(function* () {
yield* sql`DELETE FROM projection_projects
WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`;
yield* sql`DELETE FROM projection_threads
WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
for (const table of [
"projection_thread_messages",
"projection_thread_activities",
"projection_thread_sessions",
"projection_turns",
"projection_pending_approvals",
"projection_thread_proposed_plans",
"checkpoint_diff_blobs",
]) {
yield* sql.unsafe(
`DELETE FROM ${table} WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
).unprepared;
}
yield* sql`DELETE FROM orchestration_events
WHERE (aggregate_kind = 'thread'
AND stream_id NOT IN (SELECT thread_id FROM kept_threads))
OR (aggregate_kind = 'project'
AND stream_id NOT IN (SELECT project_id FROM kept_projects))`;
yield* sql`DELETE FROM orchestration_command_receipts`;
yield* sql`DELETE FROM provider_session_runtime`;
yield* sql`DELETE FROM auth_sessions`;
yield* sql`DELETE FROM auth_pairing_links`;
}),
);
const keptProjects = yield* sql<{ title: string; threads: number }>`
SELECT
p.title,
(SELECT COUNT(*) FROM projection_threads t WHERE t.project_id = p.project_id) AS threads
FROM projection_projects p
ORDER BY p.updated_at DESC`;
const [events] = yield* sql<{ count: number }>`
SELECT COUNT(*) AS count FROM orchestration_events`;
return {
projects: keptProjects as ReadonlyArray<KeptProject>,
eventCount: events?.count ?? 0,
};
});
/** Compare this checkout's migration registry against what the cloned
* database recorded: same slot under a different name means the migration
* was skipped, not applied. */
const verifyMigrationSlots = Effect.fn("verifyMigrationSlots")(function* () {
const sql = yield* SqlClient.SqlClient;
const applied = yield* sql<{ migration_id: number; name: string }>`
SELECT migration_id, name FROM effect_sql_migrations`;
const appliedById = new Map(applied.map((row) => [Number(row.migration_id), row.name]));
for (const [slot, codeName] of migrationManifest) {
const appliedName = appliedById.get(slot);
if (appliedName !== undefined && appliedName !== codeName) {
return yield* new MigrateDevDbSlotCollisionError({ slot, codeName, appliedName });
}
}
});
export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
input: RunMigrateDevDbInput,
options: RunMigrateDevDbOptions = {},
) {
// SQLite treats a negative LIMIT as "no limit", which would clone
// everything. The CLI flags validate this too; this covers direct callers.
if (input.projects < 1 || input.threadsPerProject < 0) {
return yield* Effect.die("projects must be >= 1 and threadsPerProject >= 0");
}
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
const sourcePath = path.resolve(
input.source ?? path.join(sharedHome, "userdata", "state.sqlite"),
);
const baseDir =
input.baseDir !== undefined
? path.resolve(input.baseDir)
: yield* resolveWorktreeT3Home(process.cwd());
if (baseDir === undefined) {
return yield* new MigrateDevDbNotInWorktreeError();
}
const stateDir = path.join(baseDir, "userdata");
const databasePath = path.join(stateDir, "state.sqlite");
const snapshotPath = `${databasePath}.migrate-dev-db-tmp`;
if (!(yield* fs.exists(sourcePath))) {
return yield* new MigrateDevDbSourceMissingError({ sourcePath });
}
const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
fs.realPath(baseDir).pipe(Effect.orElseSucceed(() => baseDir)),
fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
]);
if (canonicalBaseDir === canonicalSharedHome) {
return yield* new MigrateDevDbSharedHomeError();
}
// The destination db and snapshot both get deleted below; a --source that
// resolves to either (e.g. a leftover snapshot file) would be destroyed
// before it is ever read.
const canonicalSourcePath = yield* fs
.realPath(sourcePath)
.pipe(Effect.orElseSucceed(() => sourcePath));
for (const destination of [databasePath, snapshotPath]) {
const canonicalDestination = yield* fs
.realPath(destination)
.pipe(Effect.orElseSucceed(() => destination));
if (canonicalSourcePath === canonicalDestination) {
return yield* new MigrateDevDbSourceIsDestinationError({ sourcePath });
}
}
yield* fs.makeDirectory(stateDir, { recursive: true });
yield* ensureNotInUse(databasePath);
const wrapPhase =
(phase: MigrateDevDbPhaseError["phase"], phaseDatabasePath: string) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.mapError(
(cause) => new MigrateDevDbPhaseError({ phase, databasePath: phaseDatabasePath, cause }),
),
);
yield* removeDatabaseFiles(snapshotPath);
// The snapshot is a full-size copy of the source; make sure it is removed
// even when a phase fails partway through.
const { executedMigrations, pruned } = yield* Effect.gen(function* () {
yield* Console.log(`Snapshotting ${sourcePath} (read-only)...`);
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`VACUUM INTO ${snapshotPath}`;
}).pipe(
Effect.provide(NodeSqliteClient.layer({ filename: sourcePath, readonly: true })),
wrapPhase("snapshot", sourcePath),
);
// Migrate before pruning: a source older than this checkout would
// otherwise crash the prune queries on columns that don't exist yet.
// Running against the full snapshot also exercises new migrations on the
// same data volume the real database would face.
yield* Console.log("Running migrations on the snapshot...");
const executed = yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
// Mirror server boot (persistence/Layers/Sqlite.ts).
yield* sql.unsafe("PRAGMA foreign_keys = ON").unprepared;
return yield* runMigrations();
}).pipe(
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
wrapPhase("migrate", snapshotPath),
);
// Verify while the snapshot is still the only thing touched: a slot
// collision must abort before the old worktree db gets replaced with a
// schema whose colliding migration was silently skipped.
yield* verifyMigrationSlots().pipe(
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
Effect.catchTags({
SqlError: (cause) =>
Effect.fail(
new MigrateDevDbPhaseError({ phase: "verify", databasePath: snapshotPath, cause }),
),
}),
);
yield* Console.log(
`Pruning to ${input.projects} projects, ${input.threadsPerProject} stopped threads each...`,
);
const result = yield* pruneSnapshot(input).pipe(
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
wrapPhase("prune", snapshotPath),
);
yield* Console.log(`Compacting into ${databasePath}...`);
// Re-check right before the swap: a dev server started while the
// snapshot was migrating and pruning must not lose its database.
yield* ensureNotInUse(databasePath);
yield* removeDatabaseFiles(databasePath);
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`VACUUM INTO ${databasePath}`;
}).pipe(
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
wrapPhase("compact", databasePath),
);
return { executedMigrations: executed, pruned: result };
}).pipe(Effect.ensuring(removeDatabaseFiles(snapshotPath)));
yield* fs.chmod(databasePath, 0o600);
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
// WAL does not survive VACUUM INTO; set it so first `vp run dev` finds
// the database exactly as server boot would have left it.
yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared;
}).pipe(
Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
wrapPhase("compact", databasePath),
);
const size = (yield* fs.stat(databasePath)).size;
return {
databasePath,
sizeBytes: Number(size),
projects: pruned.projects,
eventCount: pruned.eventCount,
executedMigrations: executedMigrations.map(([id, name]) => `${id}_${name}`),
};
});
const formatSize = (bytes: number): string =>
bytes >= 1024 * 1024
? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
: `${(bytes / 1024).toFixed(0)} KB`;
export const migrateDevDbCommand = Command.make(
"migrate-dev-db",
{
projects: Flag.integer("projects").pipe(
Flag.withDefault(5),
Flag.withDescription("How many recently updated projects to keep."),
),
threadsPerProject: Flag.integer("threads-per-project").pipe(
Flag.withDefault(10),
Flag.withDescription("How many recent stopped threads to keep per project."),
),
baseDir: Flag.string("base-dir").pipe(
Flag.optional,
Flag.withDescription("Isolated .t3 directory. Defaults to the current worktree's .t3."),
),
source: Flag.string("source").pipe(
Flag.optional,
Flag.withDescription("Source database. Defaults to ~/.t3/userdata/state.sqlite."),
),
},
({ projects, threadsPerProject, baseDir, source }) =>
Effect.gen(function* () {
const result = yield* runMigrateDevDb({
projects,
threadsPerProject,
baseDir: Option.getOrUndefined(baseDir),
source: Option.getOrUndefined(source),
});
yield* Console.log("");
yield* Console.log(
`Dev database ready: ${result.databasePath} (${formatSize(result.sizeBytes)})`,
);
for (const project of result.projects) {
yield* Console.log(` ${project.title}: ${project.threads} threads`);
}
yield* Console.log(` ${result.eventCount} orchestration events kept`);
yield* Console.log(
result.executedMigrations.length === 0
? " Migrations: already current (no new migrations in this checkout)"
: ` Migrations applied: ${result.executedMigrations.join(", ")}`,
);
}),
).pipe(
Command.withDescription(
"Rebuild the worktree dev database from a pruned snapshot of the real ~/.t3 data, then run migrations.",
),
);
if (import.meta.main) {
Command.run(migrateDevDbCommand, { version: "0.0.0" }).pipe(
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
}
+1
View File
@@ -45,6 +45,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.serverGetProcessResourceHistory]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,
[WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,
[WS_METHODS.serverGetUsageSummary]: AuthOrchestrationReadScope,
[WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
+1
View File
@@ -72,6 +72,7 @@ const makeCliTestServerConfig = (baseDir: string) =>
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
traceKeepAllSpans: false,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
+2 -1
View File
@@ -45,7 +45,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
traceTimingEnabled: true,
traceBatchWindowMs: 1_000,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
traceMaxFiles: 30,
traceKeepAllSpans: false,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
+7 -1
View File
@@ -84,8 +84,13 @@ const EnvServerConfig = Config.all({
Config.map(Option.getOrUndefined),
),
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
// Rotated backups are gzip-compressed (~12x on span NDJSON), so a larger
// file count buys hours of incident history for tens of megabytes.
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(30)),
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
// Escape hatch: persist every sampled span (no tail filtering) when full
// fidelity matters more than the retention window.
traceKeepAllSpans: Config.boolean("T3CODE_TRACE_KEEP_ALL_SPANS").pipe(Config.withDefault(false)),
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
@@ -356,6 +361,7 @@ export const resolveServerConfig = (
traceBatchWindowMs: env.traceBatchWindowMs,
traceMaxBytes: env.traceMaxBytes,
traceMaxFiles: env.traceMaxFiles,
traceKeepAllSpans: env.traceKeepAllSpans,
otlpTracesUrl:
env.otlpTracesUrl ??
bootstrap?.otlpTracesUrl ??
+1
View File
@@ -328,6 +328,7 @@ const makePairServerConfig = Effect.fn(function* (input: {
traceBatchWindowMs: 1_000,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
traceKeepAllSpans: false,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
+2
View File
@@ -61,6 +61,7 @@ export class ServerConfig extends Context.Service<
readonly traceBatchWindowMs: number;
readonly traceMaxBytes: number;
readonly traceMaxFiles: number;
readonly traceKeepAllSpans: boolean;
readonly otlpTracesUrl: string | undefined;
readonly otlpMetricsUrl: string | undefined;
readonly otlpExportIntervalMs: number;
@@ -174,6 +175,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
traceKeepAllSpans: false,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeZlib from "node:zlib";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -237,7 +238,11 @@ describe("TraceDiagnostics", () => {
kind: "trace-file-read-failed",
message: `Failed to read local trace file '${traceFilePath}.1'.`,
});
assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
assert.deepStrictEqual(diagnostics.scannedFilePaths, [
`${traceFilePath}.1.gz`,
`${traceFilePath}.1`,
traceFilePath,
]);
const failureLog = logAnnotations.find(
(annotations) => annotations.traceFilePath === `${traceFilePath}.1`,
@@ -251,6 +256,65 @@ describe("TraceDiagnostics", () => {
}),
);
it.effect("reads gzip-compressed rotated backups", () =>
Effect.gen(function* () {
const traceFilePath = "/tmp/server.trace.ndjson";
const notFound = (method: string, path: string) =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method,
description: "missing",
pathOrDescriptor: path,
}),
);
const fileSystemLayer = FileSystem.layerNoop({
readFile: (path) =>
path === `${traceFilePath}.1.gz`
? Effect.succeed(
new Uint8Array(
NodeZlib.gzipSync(
record({
name: "backup.span",
traceId: "trace-gz",
spanId: "span-gz",
startMs: 1_000,
durationMs: 10,
}),
),
),
)
: notFound("readFile", path),
readFileString: (path) =>
path === traceFilePath
? Effect.succeed(
record({
name: "current.span",
traceId: "trace-live",
spanId: "span-live",
startMs: 2_000,
durationMs: 10,
}),
)
: notFound("readFileString", path),
});
const diagnostics = yield* TraceDiagnostics.readTraceDiagnostics({
traceFilePath,
maxFiles: 1,
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
}).pipe(Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer))));
assert.equal(diagnostics.recordCount, 2);
assert.equal(Option.isNone(diagnostics.error), true);
assert.deepStrictEqual(diagnostics.topSpansByCount.map((span) => span.name).toSorted(), [
"backup.span",
"current.span",
]);
}),
);
it.effect("keeps only the slowest span occurrences while aggregating large inputs", () =>
Effect.sync(() => {
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
+155 -103
View File
@@ -7,6 +7,7 @@ import type {
ServerTraceDiagnosticsSpanOccurrence,
ServerTraceDiagnosticsSpanSummary,
} from "@t3tools/contracts";
import * as NodeZlib from "node:zlib";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -81,11 +82,12 @@ interface TraceDiagnosticsErrorSummary {
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
const TOP_LIMIT = 10;
const RECENT_LIMIT = 20;
// Backups rotate as `.N.gz` since compressBackups, but plain `.N` files from
// before the change age along the chain untouched, so both are candidates.
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
const backupCount = Math.max(0, Math.floor(maxFiles));
const backups = Array.from(
{ length: backupCount },
(_, index) => `${traceFilePath}.${backupCount - index}`,
const backups = Array.from({ length: backupCount }, (_, index) => backupCount - index).flatMap(
(suffix) => [`${traceFilePath}.${suffix}.gz`, `${traceFilePath}.${suffix}`],
);
return [...backups, traceFilePath];
}
@@ -186,26 +188,10 @@ function insertBoundedSlowestSpan(
}
}
export function aggregateTraceDiagnostics(
input: TraceDiagnosticsInput,
): ServerTraceDiagnosticsResult {
const readAt = input.readAt;
const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path);
if (input.files.length === 0) {
return makeEmptyDiagnostics({
traceFilePath: input.traceFilePath,
scannedFilePaths,
readAt,
slowSpanThresholdMs,
error: input.error ?? {
kind: "trace-file-not-found",
message: "No local trace files were found.",
},
...(input.partialFailure ? { partialFailure: true } : {}),
});
}
// Incremental aggregation lets the reader feed one decoded file at a time and
// drop its text before touching the next, so peak memory stays one file wide
// no matter how many rotated backups exist.
export function createTraceDiagnosticsAggregator(slowSpanThresholdMs: number) {
let parseErrorCount = 0;
let recordCount = 0;
let failureCount = 0;
@@ -224,8 +210,8 @@ export function aggregateTraceDiagnostics(
const latestWarningAndErrorLogs: ServerTraceDiagnosticsLogEvent[] = [];
const logLevelCounts: Record<string, number> = {};
for (const file of input.files) {
const lines = file.text.split(/\r?\n/);
const addFileText = (text: string) => {
const lines = text.split(/\r?\n/);
for (const line of lines) {
if (line.trim().length === 0) continue;
@@ -334,56 +320,102 @@ export function aggregateTraceDiagnostics(
}
}
}
};
const finish = (input: {
readonly traceFilePath: string;
readonly scannedFilePaths: ReadonlyArray<string>;
readonly readAt: DateTime.Utc;
readonly error?: TraceDiagnosticsErrorSummary;
readonly partialFailure?: boolean;
}): ServerTraceDiagnosticsResult => {
const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]
.map(([name, span]) => ({
name,
count: span.count,
failureCount: span.failureCount,
totalDurationMs: span.totalDurationMs,
averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
maxDurationMs: span.maxDurationMs,
}))
.toSorted(
(left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs,
)
.slice(0, TOP_LIMIT);
return {
traceFilePath: input.traceFilePath,
scannedFilePaths: [...input.scannedFilePaths],
readAt: input.readAt,
recordCount,
parseErrorCount,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
failureCount,
interruptionCount,
slowSpanThresholdMs,
slowSpanCount,
logLevelCounts,
topSpansByCount,
slowestSpans,
commonFailures: [...failuresByKey.values()]
.toSorted(
(left, right) =>
right.count - left.count ||
DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),
)
.slice(0, TOP_LIMIT),
latestFailures: latestFailures
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt),
)
.slice(0, RECENT_LIMIT),
latestWarningAndErrorLogs: latestWarningAndErrorLogs
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt),
)
.slice(0, RECENT_LIMIT),
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
error: Option.fromNullishOr(input.error),
};
};
return { addFileText, finish };
}
export function aggregateTraceDiagnostics(
input: TraceDiagnosticsInput,
): ServerTraceDiagnosticsResult {
const readAt = input.readAt;
const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path);
if (input.files.length === 0) {
return makeEmptyDiagnostics({
traceFilePath: input.traceFilePath,
scannedFilePaths,
readAt,
slowSpanThresholdMs,
error: input.error ?? {
kind: "trace-file-not-found",
message: "No local trace files were found.",
},
...(input.partialFailure ? { partialFailure: true } : {}),
});
}
const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]
.map(([name, span]) => ({
name,
count: span.count,
failureCount: span.failureCount,
totalDurationMs: span.totalDurationMs,
averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
maxDurationMs: span.maxDurationMs,
}))
.toSorted((left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs)
.slice(0, TOP_LIMIT);
return {
const aggregator = createTraceDiagnosticsAggregator(slowSpanThresholdMs);
for (const file of input.files) {
aggregator.addFileText(file.text);
}
return aggregator.finish({
traceFilePath: input.traceFilePath,
scannedFilePaths,
readAt,
recordCount,
parseErrorCount,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
failureCount,
interruptionCount,
slowSpanThresholdMs,
slowSpanCount,
logLevelCounts,
topSpansByCount,
slowestSpans,
commonFailures: [...failuresByKey.values()]
.toSorted(
(left, right) =>
right.count - left.count ||
DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),
)
.slice(0, TOP_LIMIT),
latestFailures: latestFailures
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt),
)
.slice(0, RECENT_LIMIT),
latestWarningAndErrorLogs: latestWarningAndErrorLogs
.toSorted(
(left, right) => DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt),
)
.slice(0, RECENT_LIMIT),
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
error: Option.fromNullishOr(input.error),
};
...(input.error ? { error: input.error } : {}),
...(input.partialFailure ? { partialFailure: true } : {}),
});
}
type TraceFileReadResult =
@@ -394,7 +426,22 @@ function readTraceFile(
fileSystem: FileSystem.FileSystem,
path: string,
): Effect.Effect<TraceFileReadResult, TraceFileReadError> {
return fileSystem.readFileString(path).pipe(
const decoded = path.endsWith(".gz")
? fileSystem.readFile(path).pipe(
Effect.flatMap((bytes) =>
Effect.try({
try: () => NodeZlib.gunzipSync(bytes).toString("utf8"),
catch: (cause) =>
new TraceFileReadError({
traceFilePath: path,
causeTag: "GzipDecode",
cause,
}),
}),
),
)
: fileSystem.readFileString(path);
return decoded.pipe(
Effect.map((text): TraceFileReadResult => ({ _tag: "Loaded", path, text })),
Effect.catchTags({
PlatformError: (cause) =>
@@ -419,39 +466,46 @@ export const make = Effect.gen(function* () {
const readAt = options.readAt ?? (yield* DateTime.now);
const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);
const results = yield* Effect.all(
paths.map((path) =>
readTraceFile(fileSystem, path).pipe(
Effect.tapError((cause) =>
Effect.logWarning("Failed to read local trace file.").pipe(
Effect.annotateLogs({
traceFilePath: cause.traceFilePath,
errorTag: cause._tag,
causeTag: cause.causeTag,
}),
),
// One file at a time: each decoded text is aggregated and released
// before the next read, so a large maxFiles never loads the whole
// rotation window into memory at once.
const aggregator = createTraceDiagnosticsAggregator(slowSpanThresholdMs);
let loadedFileCount = 0;
let readFailureError: TraceDiagnosticsErrorSummary | undefined;
const loadedPaths = new Set<string>();
for (const path of paths) {
// A plain backup next to its own .gz copy is a crash leftover with
// identical content — counting both would double every span in it.
if (!path.endsWith(".gz") && loadedPaths.has(`${path}.gz`)) {
continue;
}
const result = yield* readTraceFile(fileSystem, path).pipe(
Effect.tapError((cause) =>
Effect.logWarning("Failed to read local trace file.").pipe(
Effect.annotateLogs({
traceFilePath: cause.traceFilePath,
errorTag: cause._tag,
causeTag: cause.causeTag,
}),
),
Effect.result,
),
),
{
concurrency: 1,
},
);
const files = results.flatMap((result) =>
Result.isSuccess(result) && result.success._tag === "Loaded"
? [{ path: result.success.path, text: result.success.text }]
: [],
);
const readFailure = results.find(Result.isFailure);
const readFailureError = readFailure
? ({
Effect.result,
);
if (Result.isFailure(result)) {
readFailureError ??= {
kind: "trace-file-read-failed",
message: readFailure.failure.message,
} satisfies TraceDiagnosticsErrorSummary)
: undefined;
message: result.failure.message,
} satisfies TraceDiagnosticsErrorSummary;
continue;
}
if (result.success._tag === "Loaded") {
loadedFileCount += 1;
loadedPaths.add(path);
aggregator.addFileText(result.success.text);
}
}
if (files.length === 0) {
if (loadedFileCount === 0) {
return makeEmptyDiagnostics({
traceFilePath: options.traceFilePath,
scannedFilePaths: paths,
@@ -466,12 +520,10 @@ export const make = Effect.gen(function* () {
});
}
return aggregateTraceDiagnostics({
return aggregator.finish({
traceFilePath: options.traceFilePath,
files,
scannedFilePaths: paths,
readAt,
slowSpanThresholdMs,
...(readFailureError ? { partialFailure: true, error: readFailureError } : {}),
});
},
@@ -27,6 +27,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
traceKeepAllSpans: false,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
@@ -146,6 +146,7 @@ export const make = Effect.gen(function* () {
threadSettlement: true,
threadSnooze: true,
threadPinning: true,
threadPinReorder: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
+68
View File
@@ -5,6 +5,7 @@ import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -948,6 +949,73 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status skips the provider lookup for a branch that was never pushed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/never-pushed"]);
const { manager, ghCalls } = yield* makeManager();
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("feature/never-pushed");
expect(status.pr).toBeNull();
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(0);
}),
);
it.effect("status still looks up PRs for a branch pushed without --set-upstream", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pushed-no-upstream"]);
// No `-u`, so the remote-tracking ref exists but branch.<name>.merge does
// not. Most terminal and agent pushes land this way, and they can still
// have a PR, so the skip must not trigger here.
yield* runGit(repoDir, ["push", "origin", "feature/pushed-no-upstream"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 214,
title: "Pushed without upstream",
url: "https://github.com/pingdotgg/t3code/pull/214",
baseRefName: "main",
headRefName: "feature/pushed-no-upstream",
state: "OPEN",
updatedAt: "2026-04-01T15:00:00Z",
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.pr?.number).toBe(214);
expect(ghCalls.filter((call) => call.startsWith("pr list ")).length).toBeGreaterThan(0);
}),
);
it("backs off repeated PR lookup failures past the healthy refresh cadence", () => {
expect(Duration.toMillis(GitManager.prLookupFailureTtl(1))).toBe(20_000);
expect(Duration.toMillis(GitManager.prLookupFailureTtl(2))).toBe(40_000);
// The point of the backoff: by the third retry a failing branch must not be
// asking more often than a healthy one, which refreshes every 2 minutes.
expect(Duration.toMillis(GitManager.prLookupFailureTtl(4))).toBeGreaterThan(120_000);
expect(Duration.toMillis(GitManager.prLookupFailureTtl(20))).toBe(900_000);
});
it.effect(
"status ignores unrelated fork PRs when the current branch tracks the same repository",
() =>
+89 -9
View File
@@ -110,8 +110,25 @@ const TOAST_DESCRIPTION_MAX = 72;
const STATUS_RESULT_CACHE_TTL = Duration.seconds(1);
const STATUS_RESULT_CACHE_CAPACITY = 2_048;
const PR_LOOKUP_CACHE_TTL = Duration.minutes(2);
const PR_LOOKUP_FAILURE_TTL = Duration.seconds(20);
const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20);
const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15);
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
/**
* How long a failed PR lookup is cached, given the number of consecutive
* failures for that branch.
*
* A hosting provider rejects a throttled request immediately, so caching every
* failure for a flat 20s made a rate-limited poller re-ask *faster* than a
* healthy one does (which waits PR_LOOKUP_CACHE_TTL), turning a transient 429
* into sustained pressure. Backing off per branch keeps the retry rate below
* the healthy rate once a branch has failed more than a couple of times.
*/
export function prLookupFailureTtl(consecutiveFailures: number): Duration.Duration {
const exponent = Math.max(0, consecutiveFailures - 1);
const backoffMs = Duration.toMillis(PR_LOOKUP_FAILURE_BASE_TTL) * Math.pow(2, exponent);
return Duration.min(Duration.millis(backoffMs), PR_LOOKUP_FAILURE_MAX_TTL);
}
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;
@@ -889,6 +906,23 @@ export const make = Effect.gen(function* () {
// back to a null upstreamRef.
const prLookupCacheKey = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
[cwd, details.branch, details.upstreamRef ?? "", String(prLookupEpoch(cwd))].join("\u0000");
// Consecutive failures per cache key, so a branch that keeps failing waits
// longer before the next attempt. Cleared as soon as a lookup succeeds.
const prLookupFailureStreakByKey = new Map<string, number>();
const nextPrLookupFailureTtl = (key: string) => {
if (
!prLookupFailureStreakByKey.has(key) &&
prLookupFailureStreakByKey.size >= PR_LOOKUP_CACHE_CAPACITY
) {
const oldestKey = prLookupFailureStreakByKey.keys().next().value;
if (oldestKey !== undefined) {
prLookupFailureStreakByKey.delete(oldestKey);
}
}
const streak = (prLookupFailureStreakByKey.get(key) ?? 0) + 1;
prLookupFailureStreakByKey.set(key, streak);
return prLookupFailureTtl(streak);
};
const prLookupCache = yield* Cache.makeWith(
(key: string) => {
const [cwd = "", branch = "", upstreamRef = ""] = key.split("\u0000");
@@ -896,17 +930,26 @@ export const make = Effect.gen(function* () {
branch,
upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,
};
return resolveBranchHeadContext(cwd, details).pipe(
Effect.flatMap((headContext) =>
findLatestPrForHeadContext(cwd, headContext).pipe(
Effect.map((latest) => ({ latest, headContext })),
),
),
);
return Effect.gen(function* () {
const headContext = yield* resolveBranchHeadContext(cwd, details);
// Only skip when the branch is untracked as well: anything carrying an
// upstream keeps the old behaviour.
if (details.upstreamRef === null && (yield* isUnpublishedBranch(cwd, headContext))) {
return { latest: null, headContext };
}
const latest = yield* findLatestPrForHeadContext(cwd, headContext);
return { latest, headContext };
});
},
{
capacity: PR_LOOKUP_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? PR_LOOKUP_CACHE_TTL : PR_LOOKUP_FAILURE_TTL),
timeToLive: (exit, key) => {
if (Exit.isSuccess(exit)) {
prLookupFailureStreakByKey.delete(key);
return PR_LOOKUP_CACHE_TTL;
}
return nextPrLookupFailureTtl(key);
},
},
);
// A transient lookup failure (rate limit, network blip) must not clear an
@@ -1169,6 +1212,43 @@ export const make = Effect.gen(function* () {
} satisfies BranchHeadContext;
});
/**
* Whether git has no record of this branch on any remote, so a change request
* cannot exist for it and asking the provider is a guaranteed-empty API call.
*
* `git push` writes the remote-tracking ref even without `-u` (how most
* terminal and agent pushes land), which makes this a safer "did it ever
* reach the host" test than looking for upstream config, and the glob spans
* every remote so a fork branch still counts. A repository that tracks no
* remotes at all cannot answer the question, because then every branch looks
* unpublished; it, and any failed probe, keeps the lookup.
*/
const isUnpublishedBranch = Effect.fn("isUnpublishedBranch")(function* (
cwd: string,
headContext: Pick<BranchHeadContext, "headBranch">,
) {
if (headContext.headBranch.length === 0) {
return false;
}
const matchesRef = (pattern: string) =>
gitCore
.execute({
operation: "GitManager.isUnpublishedBranch",
cwd,
args: ["for-each-ref", "--count=1", "--format=%(refname)", pattern],
timeoutMs: 5_000,
})
.pipe(Effect.map((result) => result.stdout.trim().length > 0));
return yield* Effect.all(
[matchesRef("refs/remotes"), matchesRef(`refs/remotes/*/${headContext.headBranch}`)],
{ concurrency: "unbounded" },
).pipe(
Effect.map(([tracksAnyRemote, tracksThisBranch]) => tracksAnyRemote && !tracksThisBranch),
Effect.orElseSucceed(() => false),
);
});
const findOpenPr = Effect.fn("findOpenPr")(function* (
cwd: string,
headContext: Pick<
@@ -34,6 +34,7 @@ export const ObservabilityLive = Layer.unwrap(
maxBytes: config.traceMaxBytes,
maxFiles: config.traceMaxFiles,
batchWindowMs: config.traceBatchWindowMs,
compressBackups: true,
onFlush: (stats) =>
attribution.record({
component: "server-trace",
@@ -65,6 +66,9 @@ export const ObservabilityLive = Layer.unwrap(
batchWindowMs: config.traceBatchWindowMs,
sink,
...(delegate ? { delegate } : {}),
// Tail policy applies to the local file only; the OTLP delegate
// still receives every sampled span.
...(config.traceKeepAllSpans ? {} : { tailPolicy: {} }),
});
return Layer.mergeAll(
@@ -495,6 +495,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
title: event.payload.title,
workspaceRoot: event.payload.workspaceRoot,
defaultModelSelection: event.payload.defaultModelSelection,
defaultThreadEnvMode: null,
scripts: event.payload.scripts,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
@@ -518,6 +519,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.defaultModelSelection !== undefined
? { defaultModelSelection: event.payload.defaultModelSelection }
: {}),
...(event.payload.defaultThreadEnvMode !== undefined
? { defaultThreadEnvMode: event.payload.defaultThreadEnvMode }
: {}),
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
updatedAt: event.payload.updatedAt,
});
@@ -612,6 +616,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
pinOrderKey: null,
titleRegenerationRequestId: null,
titleRegenerationStartedAt: null,
latestUserMessageAt: null,
@@ -728,6 +733,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: event.payload.pinnedAt,
...(event.payload.pinOrderKey !== undefined
? { pinOrderKey: event.payload.pinOrderKey }
: {}),
updatedAt: event.payload.updatedAt,
});
return;
@@ -743,6 +751,22 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: null,
pinOrderKey: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.pin-reordered": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinOrderKey: event.payload.orderKey,
updatedAt: event.payload.updatedAt,
});
return;
@@ -87,6 +87,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
pinned_at,
pin_order_key,
created_at,
updated_at,
deleted_at
@@ -105,6 +107,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
1,
0,
0,
'2026-02-24T00:00:01.000Z',
'gm',
'2026-02-24T00:00:02.000Z',
'2026-02-24T00:00:03.000Z',
NULL
@@ -280,6 +284,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
runOnWorktreeCreate: false,
},
],
defaultThreadEnvMode: null,
createdAt: "2026-02-24T00:00:00.000Z",
updatedAt: "2026-02-24T00:00:01.000Z",
deletedAt: null,
@@ -317,7 +322,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm",
titleRegeneration: null,
deletedAt: null,
messages: [
@@ -397,6 +403,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
runOnWorktreeCreate: false,
},
],
defaultThreadEnvMode: null,
createdAt: "2026-02-24T00:00:00.000Z",
updatedAt: "2026-02-24T00:00:01.000Z",
},
@@ -433,7 +440,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm",
titleRegeneration: null,
session: {
threadId: ThreadId.make("thread-1"),
@@ -316,6 +316,7 @@ function mapProjectShellRow(
workspaceRoot: row.workspaceRoot,
repositoryIdentity,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -391,6 +392,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -423,6 +425,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -458,6 +461,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -495,6 +499,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -841,6 +846,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -863,6 +869,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -932,6 +939,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -1538,6 +1546,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspaceRoot: row.workspaceRoot,
repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -1562,6 +1571,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
@@ -1666,6 +1676,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -1766,6 +1777,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: [],
@@ -1901,6 +1913,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
@@ -2045,6 +2058,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
@@ -2154,6 +2168,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspaceRoot: option.value.workspaceRoot,
repositoryIdentity,
defaultModelSelection: option.value.defaultModelSelection,
defaultThreadEnvMode: option.value.defaultThreadEnvMode,
scripts: option.value.scripts,
createdAt: option.value.createdAt,
updatedAt: option.value.updatedAt,
@@ -2321,6 +2336,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value),
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
@@ -2441,6 +2457,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value),
deletedAt: null,
messages: messageRows.map((row) => {
@@ -16,6 +16,7 @@ import {
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
type OrchestrationCommand,
ProjectId,
ProviderItemId,
type ServerSettings,
@@ -256,57 +257,52 @@ describe("ProviderRuntimeIngestion", () => {
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(ingestion.drain);
const dispatch = (command: OrchestrationCommand) => Effect.runPromise(engine.dispatch(command));
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-provider-project-create"),
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
}),
);
await Effect.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
await dispatch({
type: "project.create",
commandId: CommandId.make("cmd-provider-project-create"),
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
});
await dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
threadId: ThreadId.make("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
});
await dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
});
provider.setSession({
provider: ProviderDriverKind.make("codex"),
status: "ready",
@@ -318,6 +314,7 @@ describe("ProviderRuntimeIngestion", () => {
return {
engine,
dispatch,
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
emit: provider.emit,
setProviderSession: provider.setSession,
@@ -843,6 +840,82 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("rejects an untargeted turn.completed when no turn is active", async () => {
const harness = await createHarness();
const seededAt = "2026-01-01T00:00:00.000Z";
// A turn start is pending: the session reads "starting" with no active
// turn tracked yet. This is the window the Claude resume handshake's
// phantom (turn.completed with no turnId) used to slip through, stomping
// "starting" back to "ready" for a turn that never existed.
await harness.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed-untargeted-completion"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "starting",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
lastError: null,
},
createdAt: seededAt,
});
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-untargeted"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: seededAt,
threadId: asThreadId("thread-1"),
status: "completed",
});
await harness.drain();
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.status).toBe("starting");
expect(thread?.session?.activeTurnId).toBeNull();
});
it("accepts a targeted turn.completed when no turn is active", async () => {
const harness = await createHarness();
const seededAt = "2026-01-01T00:00:00.000Z";
// A completion that names its turn still lands even when no active turn
// is tracked (e.g. its turn.started was lost). Only untargeted
// completions are rejected.
await harness.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed-targeted-completion"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "starting",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
lastError: null,
},
createdAt: seededAt,
});
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-targeted-late"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: seededAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-late"),
status: "completed",
});
await waitForThread(harness.readModel, (thread) => thread.session?.status === "ready");
});
it("ignores non-active turn completion when runtime omits thread id", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2199,7 +2272,7 @@ describe("ProviderRuntimeIngestion", () => {
});
it("starts a new streaming assistant message segment after approval", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } });
const startedAt = "2026-03-28T07:00:00.000Z";
const pausedAt = "2026-03-28T07:00:01.000Z";
const resumedAt = "2026-03-28T07:00:02.000Z";
@@ -2306,7 +2379,7 @@ describe("ProviderRuntimeIngestion", () => {
});
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } });
const now = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
@@ -1532,8 +1532,14 @@ const make = Effect.gen(function* () {
if (activeTurnId !== null && eventTurnId !== undefined) {
return sameId(activeTurnId, eventTurnId);
}
// If no active turn is tracked, accept completion scoped to this thread.
return true;
// No active turn tracked: accept only completions that name their
// turn (covers a real completion whose turn.started was lost). An
// untargeted completion cannot prove it belongs to any turn this
// thread ran — the known emitter was the Claude resume handshake
// (system/init + result(num_turns: 0)), which is not a turn at
// all — and applying it here stomps the "starting" lifecycle
// state while a turn start is pending.
return eventTurnId !== undefined;
default:
return true;
}
@@ -1655,7 +1661,7 @@ const make = Effect.gen(function* () {
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
(settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"),
);
if (assistantDeliveryMode === "buffered") {
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
@@ -1691,7 +1697,7 @@ const make = Effect.gen(function* () {
const detailedThread = yield* getLoadedThreadDetail();
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
(settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"),
);
const flushedMessageIds =
assistantDeliveryMode === "buffered"
+2
View File
@@ -15,6 +15,7 @@ import {
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
ThreadPinReorderedPayload as ContractsThreadPinReorderedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -46,6 +47,7 @@ export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
export const ThreadPinReorderedPayload = ContractsThreadPinReorderedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -16,6 +16,7 @@ const PINNED_AT = "1969-12-30T00:00:00.000Z";
function makeReadModel(input: {
readonly pinnedAt?: string | null;
readonly pinOrderKey?: string | null;
readonly archivedAt?: string | null;
readonly settledOverride?: "settled" | "active" | null;
readonly settledAt?: string | null;
@@ -44,6 +45,7 @@ function makeReadModel(input: {
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? PINNED_AT : null),
pinnedAt: input.pinnedAt ?? null,
pinOrderKey: input.pinOrderKey ?? null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -223,4 +225,100 @@ it.layer(NodeServices.layer)("pinned thread decider", (it) => {
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("a fresh pin carries the client's order key", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-keyed"),
threadId: ThreadId.make("thread-1"),
orderKey: "g",
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinOrderKey).toBe("g");
}
}),
);
it.effect(
"re-pinning ignores the incoming order key so raced pins cannot move a placed thread",
() =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-keyed-again"),
threadId: ThreadId.make("thread-1"),
orderKey: "t",
},
readModel: makeReadModel({ pinnedAt: PINNED_AT, pinOrderKey: "g" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinOrderKey).toBeUndefined();
}
}),
);
it.effect("reorders a pinned thread, stamping the new key", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin.reorder",
commandId: CommandId.make("cmd-reorder"),
threadId: ThreadId.make("thread-1"),
orderKey: "m",
},
readModel: makeReadModel({ pinnedAt: PINNED_AT, pinOrderKey: "g" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pin-reordered");
if (events[0]?.type === "thread.pin-reordered") {
expect(events[0].payload.orderKey).toBe("m");
// A real move stamps the command time (the test clock), not the
// thread's previous updatedAt.
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
}),
);
it.effect("reordering onto the same key preserves updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin.reorder",
commandId: CommandId.make("cmd-reorder-noop"),
threadId: ThreadId.make("thread-1"),
orderKey: "g",
},
readModel: makeReadModel({ pinnedAt: PINNED_AT, pinOrderKey: "g" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pin-reordered");
if (events[0]?.type === "thread.pin-reordered") {
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("rejects reordering an unpinned thread", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pin.reorder",
commandId: CommandId.make("cmd-reorder-unpinned"),
threadId: ThreadId.make("thread-1"),
orderKey: "m",
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
@@ -0,0 +1,103 @@
import { CommandId, EventId, ProjectId, type OrchestrationEvent } from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const now = "2026-01-01T00:00:00.000Z";
const projectId = ProjectId.make("project-env-mode");
const seedProjectCreated = (sequence: number): OrchestrationEvent => ({
sequence,
eventId: EventId.make(`evt-project-env-mode-${sequence}`),
aggregateKind: "project",
aggregateId: projectId,
type: "project.created",
occurredAt: now,
commandId: CommandId.make(`cmd-project-env-mode-${sequence}`),
causationEventId: null,
correlationId: CommandId.make(`cmd-project-env-mode-${sequence}`),
metadata: {},
payload: {
projectId,
title: "Env mode",
workspaceRoot: "/tmp/env-mode",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
it.layer(NodeServices.layer)("decider project defaultThreadEnvMode", (it) => {
it.effect("propagates defaultThreadEnvMode through meta.update into the read model", () =>
Effect.gen(function* () {
const readModel = yield* projectEvent(createEmptyReadModel(now), seedProjectCreated(1));
expect(readModel.projects[0]?.defaultThreadEnvMode).toBeNull();
const result = yield* decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-env-mode-set"),
projectId,
defaultThreadEnvMode: "worktree",
},
readModel,
});
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.meta-updated");
expect((event.payload as { defaultThreadEnvMode?: unknown }).defaultThreadEnvMode).toBe(
"worktree",
);
const updated = yield* projectEvent(readModel, { ...event, sequence: 2 });
expect(updated.projects[0]?.defaultThreadEnvMode).toBe("worktree");
}),
);
it.effect("omits the field when unset and clears it on explicit null", () =>
Effect.gen(function* () {
const readModel = yield* projectEvent(createEmptyReadModel(now), seedProjectCreated(1));
const unrelated = yield* decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-env-mode-title"),
projectId,
title: "Renamed",
},
readModel,
});
const unrelatedEvent = Array.isArray(unrelated) ? unrelated[0] : unrelated;
expect("defaultThreadEnvMode" in (unrelatedEvent.payload as object)).toBe(false);
const set = yield* decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-env-mode-set"),
projectId,
defaultThreadEnvMode: "worktree",
},
readModel,
});
const setEvent = Array.isArray(set) ? set[0] : set;
const afterSet = yield* projectEvent(readModel, { ...setEvent, sequence: 2 });
const clear = yield* decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-env-mode-clear"),
projectId,
defaultThreadEnvMode: null,
},
readModel: afterSet,
});
const clearEvent = Array.isArray(clear) ? clear[0] : clear;
const afterClear = yield* projectEvent(afterSet, { ...clearEvent, sequence: 3 });
expect(afterClear.projects[0]?.defaultThreadEnvMode).toBeNull();
}),
);
});
@@ -518,4 +518,55 @@ it.layer(NodeServices.layer)("settled thread decider", (it) => {
expect(routineEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
}),
);
it.effect("drops an onlyIfSettled session stop when the thread was re-engaged", () =>
Effect.gen(function* () {
const stopCommand = (commandId: string) =>
({
type: "thread.session.stop",
commandId: CommandId.make(commandId),
threadId: ThreadId.make("thread-1"),
createdAt: NOW,
onlyIfSettled: true,
}) as const;
// Still settled with an idle session: the cleanup stop goes through.
const stopped = yield* decideOrchestrationCommand({
command: stopCommand("cmd-stop-settled-idle"),
readModel: makeReadModel("settled", null, makeSession("ready")),
});
const stoppedEvents = Array.isArray(stopped) ? stopped : [stopped];
expect(stoppedEvents.map((event) => event.type)).toEqual(["thread.session-stop-requested"]);
// Re-engaged before the stop was decided (a turn start unsettles the
// thread): the stale cleanup stop must not kill the new session.
const unsettledError = yield* decideOrchestrationCommand({
command: stopCommand("cmd-stop-unsettled"),
readModel: makeReadModel(null, null, makeSession("starting")),
}).pipe(Effect.flip);
expect(unsettledError._tag).toBe("OrchestrationCommandInvariantError");
// Still settled but the session is already coming alive: same drop.
const aliveError = yield* decideOrchestrationCommand({
command: stopCommand("cmd-stop-session-alive"),
readModel: makeReadModel("settled", null, makeSession("starting")),
}).pipe(Effect.flip);
expect(aliveError._tag).toBe("OrchestrationCommandInvariantError");
// Without the flag the stop stays unconditional (archive, stop button).
const unconditional = yield* decideOrchestrationCommand({
command: {
type: "thread.session.stop",
commandId: CommandId.make("cmd-stop-unconditional"),
threadId: ThreadId.make("thread-1"),
createdAt: NOW,
},
readModel: makeReadModel(null, null, makeSession("starting")),
});
const unconditionalEvents = Array.isArray(unconditional) ? unconditional : [unconditional];
expect(unconditionalEvents.map((event) => event.type)).toEqual([
"thread.session-stop-requested",
]);
}),
);
});
+68 -1
View File
@@ -287,6 +287,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.defaultModelSelection !== undefined
? { defaultModelSelection: command.defaultModelSelection }
: {}),
...(command.defaultThreadEnvMode !== undefined
? { defaultThreadEnvMode: command.defaultThreadEnvMode }
: {}),
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
updatedAt: occurredAt,
},
@@ -676,6 +679,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
pinnedAt: existingPinnedAt ?? occurredAt,
// A fresh pin takes the client's slot in the arranged order; on a
// re-pin the existing key wins so raced duplicates cannot move a
// thread the user already placed.
...(existingPinnedAt === null && command.orderKey !== undefined
? { pinOrderKey: command.orderKey }
: {}),
updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
},
};
@@ -745,6 +754,43 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.pin.reorder": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Only pinned threads have a slot in the arranged order. Rejecting
// (rather than silently pinning) keeps a raced reorder-after-unpin
// from resurrecting a pin the user just cleared.
if (thread.pinnedAt == null) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} is not pinned and cannot be reordered`,
}),
);
}
// Idempotent by re-emission (see thread.settle): a duplicate drop on
// the same slot keeps the existing updatedAt so it projects as a no-op.
const keyUnchanged = thread.pinOrderKey === command.orderKey;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.pin-reordered",
payload: {
threadId: command.threadId,
orderKey: command.orderKey,
updatedAt: keyUnchanged ? thread.updatedAt : occurredAt,
},
};
}
case "thread.meta.update": {
const thread = yield* requireThread({
readModel,
@@ -1073,11 +1119,32 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.session.stop": {
yield* requireThread({
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
// Settle-cleanup stops are conditional: between the settle landing and
// this command, another client may have re-engaged the thread (a turn
// start unsettles it and brings the session alive). Commands are
// decided serially against this read model, so checking here — not in
// the dispatcher's pre-settle snapshot — closes that race.
if (command.onlyIfSettled === true) {
const sessionComingAlive =
thread.session?.status === "starting" || thread.session?.status === "running";
if (
thread.settledOverride !== "settled" ||
sessionComingAlive ||
threadHasQueuedTurnStart(thread, command.createdAt)
) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} was re-engaged after settle; skipping session stop`,
}),
);
}
}
return {
...(yield* withEventBase({
aggregateKind: "thread",
@@ -75,3 +75,80 @@ it.effect("projects pin lifecycle events", () =>
expect(unpinned.threads[0]?.pinnedAt).toBeNull();
}),
);
it.effect("projects pin order key lifecycle", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const created = yield* projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "thread.created",
payload: {
threadId: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
expect(created.threads[0]?.pinOrderKey ?? null).toBeNull();
// Fresh pin carries the client's slot in the arranged order.
const pinned = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.pinned",
payload: {
threadId: ThreadId.make("thread-1"),
pinnedAt: now,
pinOrderKey: "g",
updatedAt: now,
},
}),
);
expect(pinned.threads[0]?.pinOrderKey).toBe("g");
// Re-pins and events from pre-reorder servers omit the field entirely;
// the existing key must survive rather than being nulled out.
const repinned = yield* projectEvent(
pinned,
makeEvent({
sequence: 3,
type: "thread.pinned",
payload: { threadId: ThreadId.make("thread-1"), pinnedAt: now, updatedAt: now },
}),
);
expect(repinned.threads[0]?.pinOrderKey).toBe("g");
// A drag persists the new slot.
const reordered = yield* projectEvent(
repinned,
makeEvent({
sequence: 4,
type: "thread.pin-reordered",
payload: { threadId: ThreadId.make("thread-1"), orderKey: "m", updatedAt: now },
}),
);
expect(reordered.threads[0]?.pinOrderKey).toBe("m");
// Unpin clears the slot: re-pinning is "pin again", not "restore an
// ancient position".
const unpinned = yield* projectEvent(
reordered,
makeEvent({
sequence: 5,
type: "thread.unpinned",
payload: { threadId: ThreadId.make("thread-1"), updatedAt: now },
}),
);
expect(unpinned.threads[0]?.pinOrderKey).toBeNull();
}),
);
@@ -24,6 +24,7 @@ import {
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
ThreadPinnedPayload,
ThreadPinReorderedPayload,
ThreadSnoozedPayload,
ThreadUnpinnedPayload,
ThreadUnarchivedPayload,
@@ -213,6 +214,7 @@ export function projectEvent(
title: payload.title,
workspaceRoot: payload.workspaceRoot,
defaultModelSelection: payload.defaultModelSelection,
defaultThreadEnvMode: null,
scripts: payload.scripts,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
@@ -245,6 +247,9 @@ export function projectEvent(
...(payload.defaultModelSelection !== undefined
? { defaultModelSelection: payload.defaultModelSelection }
: {}),
...(payload.defaultThreadEnvMode !== undefined
? { defaultThreadEnvMode: payload.defaultThreadEnvMode }
: {}),
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
updatedAt: payload.updatedAt,
}
@@ -402,6 +407,7 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: payload.pinnedAt,
...(payload.pinOrderKey !== undefined ? { pinOrderKey: payload.pinOrderKey } : {}),
updatedAt: payload.updatedAt,
}),
})),
@@ -413,6 +419,20 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: null,
// Unpin clears the slot: re-pinning is "pin again", not "restore
// an ancient position".
pinOrderKey: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.pin-reordered":
return decodeForEvent(ThreadPinReorderedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinOrderKey: payload.orderKey,
updatedAt: payload.updatedAt,
}),
})),
@@ -35,6 +35,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
title,
workspace_root,
default_model_selection_json,
default_thread_env_mode,
scripts_json,
created_at,
updated_at,
@@ -45,6 +46,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
${row.title},
${row.workspaceRoot},
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
${row.defaultThreadEnvMode},
${JSON.stringify(row.scripts)},
${row.createdAt},
${row.updatedAt},
@@ -55,6 +57,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
title = excluded.title,
workspace_root = excluded.workspace_root,
default_model_selection_json = excluded.default_model_selection_json,
default_thread_env_mode = excluded.default_thread_env_mode,
scripts_json = excluded.scripts_json,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
@@ -72,6 +75,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -91,6 +95,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -33,6 +33,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
defaultThreadEnvMode: null,
scripts: [],
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
@@ -48,6 +48,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until,
snoozed_at,
pinned_at,
pin_order_key,
title_regeneration_request_id,
title_regeneration_started_at,
latest_user_message_at,
@@ -74,6 +75,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.snoozedUntil},
${row.snoozedAt},
${row.pinnedAt},
${row.pinOrderKey ?? null},
${row.titleRegenerationRequestId ?? null},
${row.titleRegenerationStartedAt ?? null},
${row.latestUserMessageAt},
@@ -100,6 +102,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
pinned_at = excluded.pinned_at,
pin_order_key = excluded.pin_order_key,
title_regeneration_request_id = excluded.title_regeneration_request_id,
title_regeneration_started_at = excluded.title_regeneration_started_at,
latest_user_message_at = excluded.latest_user_message_at,
@@ -133,6 +136,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -168,6 +172,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
+3 -10
View File
@@ -46,16 +46,9 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
return Layer.provideMerge(
setup,
makeRuntimeSqliteLayer({
filename: dbPath,
spanAttributes: {
"db.name": path.basename(dbPath),
"service.name": "t3-server",
},
}),
);
// No per-span attributes: sql.execute fires ~76/s under load and constant
// attributes on every span were a measurable share of local trace volume.
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
}, Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
@@ -50,6 +50,8 @@ import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";
import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
/**
* Migration loader with all migrations defined inline.
@@ -99,6 +101,8 @@ export const migrationEntries = [
[35, "ProjectionThreadTitleRegeneration", Migration0035],
[36, "ProjectionThreadsPinned", Migration0036],
[37, "ProjectionTurnsKeysetIndex", Migration0037],
[38, "ProjectionThreadsPinOrderKey", Migration0038],
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,16 @@
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 === "pin_order_key")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN pin_order_key TEXT
`;
}
});
@@ -0,0 +1,16 @@
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_projects)
`;
if (!columns.some((column) => column.name === "default_thread_env_mode")) {
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN default_thread_env_mode TEXT
`;
}
});
@@ -6,7 +6,13 @@
*
* @module ProjectionProjectRepository
*/
import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts";
import {
IsoDateTime,
ModelSelection,
ProjectId,
ProjectScript,
ThreadEnvMode,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Context from "effect/Context";
@@ -19,6 +25,7 @@ export const ProjectionProject = Schema.Struct({
title: Schema.String,
workspaceRoot: Schema.String,
defaultModelSelection: Schema.NullOr(ModelSelection),
defaultThreadEnvMode: Schema.NullOr(ThreadEnvMode),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -42,6 +42,7 @@ export const ProjectionThread = Schema.Struct({
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
pinnedAt: Schema.NullOr(IsoDateTime),
pinOrderKey: Schema.optional(Schema.NullOr(Schema.String)),
titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),
titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
@@ -978,6 +978,75 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("does not emit turn.completed for a result with no active turn", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
// Collect through session.exited so the window after the second result
// is deterministically inside the collection: both results are queued
// after sendTurn returns and drain in order on the one stream consumer.
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
Stream.takeUntil((event) => event.type === "session.exited"),
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
num_turns: 1,
session_id: "sdk-session-1",
uuid: "result-real",
} as unknown as SDKMessage);
// Second result with no turn in flight — the shape the resume
// handshake (system/init + result(num_turns: 0)) delivers, and the
// same completeTurn branch every no-turnState result lands in. This
// used to emit an untargeted turn.completed; it must emit nothing.
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
num_turns: 0,
usage: { input_tokens: 0, output_tokens: 0 },
session_id: "sdk-session-1",
uuid: "result-handshake",
} as unknown as SDKMessage);
harness.query.finish();
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const completions = runtimeEvents.filter((event) => event.type === "turn.completed");
// Exactly one completion — the real turn's, targeted at its turn id.
// The buggy branch produced a second, untargeted one here.
assert.equal(completions.length, 1);
const completed = completions[0];
if (completed?.type === "turn.completed") {
assert.equal(String(completed.turnId), String(turn.turnId));
assert.equal(completed.payload.state, "completed");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -2248,24 +2248,24 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
rawPayload: result ?? { status },
});
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.completed",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
// A result with no local turn is never a turn this adapter started:
// real turns get turnState in sendTurn, and assistant messages that
// arrive outside a turn auto-start a synthetic one. What lands here is
// the resume handshake (system/init + result(num_turns: 0)), a late
// result for a turn already completed locally (steer auto-close,
// stream teardown), or a stream failure with no turn in flight. The
// untargeted turn.completed this branch used to emit carried no turnId,
// so ingestion could not attribute it — and whenever the projection had
// no active turn (a pending turn start included) it flipped the session
// lifecycle for a turn that never existed. Keep the usage emission,
// drop the lifecycle event, and leave a tripwire so the upstream
// trigger stays measurable in the field.
yield* Effect.logInfo("claude.turn.result-without-active-turn", {
threadId: context.session.threadId,
payload: {
state: status,
...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),
...(result?.usage ? { usage: result.usage } : {}),
...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),
...(typeof result?.total_cost_usd === "number"
? { totalCostUsd: result.total_cost_usd }
: {}),
...(errorMessage ? { errorMessage } : {}),
},
providerRefs: {},
status,
numTurns: result?.num_turns,
hasUsage: result?.usage !== undefined,
...(errorMessage ? { errorMessage } : {}),
});
return;
}
@@ -4090,6 +4090,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(ultracode ? { ultracode: true } : {}),
};
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
// The attachments dir grant lets the agent Read/copy pasted images at
// the paths ProviderService injects into the turn text, without an
// approval prompt. It is a leaf directory holding only attachment
// files; siblings like secrets/ and state.sqlite stay ungranted.
const additionalDirectories = [
...(input.cwd ? [input.cwd] : []),
serverConfig.attachmentsDir,
];
const queryOptions: ClaudeQueryOptions = {
...(input.cwd ? { cwd: input.cwd } : {}),
...(apiModelId ? { model: apiModelId } : {}),
@@ -4113,7 +4121,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
includePartialMessages: true,
canUseTool,
env: claudeEnvironment,
...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
additionalDirectories,
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
...(mcpSession
? {
@@ -4148,7 +4156,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
"claude.query.resume": existingResumeSessionId ?? "",
"claude.query.session_id": newSessionId ?? "",
"claude.query.include_partial_messages": true,
"claude.query.additional_directories": input.cwd ? [input.cwd] : [],
"claude.query.additional_directories": additionalDirectories,
"claude.query.setting_sources": [...CLAUDE_SETTING_SOURCES],
"claude.query.settings_json": encodeJsonStringForDiagnostics(settings) ?? "",
"claude.query.extra_args_json": encodeJsonStringForDiagnostics(extraArgs) ?? "",
@@ -245,4 +245,53 @@ describe("CodexSessionRuntime collab integration", () => {
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.live("Stop targets the active turn when Codex has accepted a queued follow-up", () =>
Effect.gen(function* () {
const activeTurnId = "019fe3e8-f908-7f31-8d51-283f4a47897a";
const queuedTurnId = "019fe3eb-8faf-7de3-a85b-ac64c7f9c8c3";
const script = {
rootThreadId: ROOT,
holdTurnOpen: true,
onlyFirstTurnStarts: true,
turnIds: [activeTurnId, queuedTurnId],
expectedActiveTurnId: activeTurnId,
notifications: [],
};
// @effect-diagnostics-next-line preferSchemaOverJson:off
NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
const interruptsPath = `${scriptPath}.interrupts`;
NodeFS.rmSync(interruptsPath, { force: true });
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
NodeFS.rmSync(scriptPath, { force: true });
NodeFS.rmSync(interruptsPath, { force: true });
}),
);
const runtime = yield* makeCodexSessionRuntime({
threadId: ThreadId.make("thread-codex-queued-stop"),
binaryPath: peerPath,
cwd: "/tmp",
runtimeMode: "full-access",
environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
});
yield* runtime.start();
yield* runtime.sendTurn({ input: "keep working" });
yield* runtime.sendTurn({ input: "queued follow-up" });
yield* runtime.interruptTurn();
const interrupts = NodeFS.readFileSync(interruptsPath, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as { threadId?: string; turnId?: string });
assert.deepEqual(interrupts.at(-1), {
threadId: ROOT,
turnId: activeTurnId,
});
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -814,13 +814,13 @@ function currentProviderThreadId(session: ProviderSession): string | undefined {
function updateSession(
sessionRef: Ref.Ref<ProviderSession>,
updates: Partial<ProviderSession>,
updates: Partial<ProviderSession> | ((session: ProviderSession) => Partial<ProviderSession>),
): Effect.Effect<void> {
return Effect.gen(function* () {
const updatedAt = DateTime.formatIso(yield* DateTime.now);
yield* Ref.update(sessionRef, (session) => ({
...session,
...updates,
...(typeof updates === "function" ? updates(session) : updates),
updatedAt,
}));
});
@@ -1782,11 +1782,14 @@ export const makeCodexSessionRuntime = (
),
);
const turnId = TurnId.make(response.turn.id);
yield* updateSession(sessionRef, {
yield* updateSession(sessionRef, (session) => ({
status: "running",
activeTurnId: turnId,
// Codex accepts follow-ups while the current turn is still
// running. The response contains the queued turn id, but
// turn/interrupt only accepts the id that is active now.
activeTurnId: session.activeTurnId ?? turnId,
...(normalizedModel ? { model: normalizedModel } : {}),
});
}));
const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
return {
threadId: options.threadId,
@@ -55,11 +55,15 @@ import {
makeSqlitePersistenceLive,
SqlitePersistenceMemory,
} from "../../persistence/Layers/Sqlite.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts";
const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
const serverConfigTestLayer = ServerConfig.layerTest(process.cwd(), process.cwd()).pipe(
Layer.provide(NodeServices.layer),
);
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
@@ -292,6 +296,7 @@ function makeProviderServiceLayer() {
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provideMerge(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -343,6 +348,7 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provideMerge(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -402,6 +408,7 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -486,6 +493,7 @@ it.effect(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(serverSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -556,6 +564,7 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -611,6 +620,7 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -671,6 +681,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -737,6 +748,7 @@ it.effect(
),
Layer.provide(firstDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -796,6 +808,7 @@ it.effect(
),
Layer.provide(secondDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -927,6 +940,54 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("appends attachment file paths to the turn input text", () =>
Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
const session = yield* provider.startSession(asThreadId("thread-attach"), {
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
threadId: asThreadId("thread-attach"),
cwd: "/tmp/project",
runtimeMode: "full-access",
});
const attachment = {
type: "image" as const,
id: "thread-attach-12345678-1234-1234-1234-123456789abc",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 123,
};
routing.codex.sendTurn.mockClear();
yield* provider.sendTurn({
threadId: session.threadId,
input: "use this screenshot",
attachments: [attachment],
});
const turnInput = routing.codex.sendTurn.mock.calls[0]?.[0] as ProviderSendTurnInput;
assert.equal(typeof turnInput.input, "string");
const turnText = turnInput.input ?? "";
assert.equal(turnText.startsWith("use this screenshot"), true);
assert.include(turnText, '[Attached image "screenshot.png" is saved at: ');
assert.equal(turnText.endsWith(`${attachment.id}.png]`), true);
// An attachment-only turn stays valid and the injected line becomes the
// whole input text, so the agent still learns the path.
routing.codex.sendTurn.mockClear();
yield* provider.sendTurn({
threadId: session.threadId,
attachments: [attachment],
});
const imageOnlyInput = routing.codex.sendTurn.mock.calls[0]?.[0] as ProviderSendTurnInput;
assert.equal(imageOnlyInput.input?.startsWith('[Attached image "screenshot.png"'), true);
yield* provider.stopSession({ threadId: session.threadId });
}),
);
it.effect("recovers stale persisted sessions for rollback by resuming thread identity", () =>
Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
@@ -1307,6 +1368,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
),
Layer.provide(firstDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -1345,6 +1407,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
),
Layer.provide(secondDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -1413,6 +1476,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
),
Layer.provide(firstDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -1446,6 +1510,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
),
Layer.provide(secondDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -35,6 +35,8 @@ import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as Stream from "effect/Stream";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import * as ServerConfig from "../../config.ts";
import {
increment,
providerMetricAttributes,
@@ -203,6 +205,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
options?: ProviderServiceLiveOptions,
) {
const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);
const serverConfig = yield* ServerConfig.ServerConfig;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
// Options-provided logger wins (test overrides); otherwise we take whatever
// the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical
@@ -665,16 +668,44 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
payload: rawInput,
});
const input = {
...parsed,
attachments: parsed.attachments ?? [],
};
if (!input.input && input.attachments.length === 0) {
const attachments = parsed.attachments ?? [];
if (!parsed.input && attachments.length === 0) {
return yield* toValidationError(
"ProviderService.sendTurn",
"Either input text or at least one attachment is required",
);
}
// Adapters inline attachment pixels into the model prompt, but the model's
// tools cannot dereference pixels. Appending the on-disk path is what lets
// a turn like "include this screenshot in the PR" copy the actual file.
// This runs after schema decode, so the appended lines are exempt from the
// PROVIDER_SEND_TURN_MAX_INPUT_CHARS check; attachment count is capped, so
// the overhead is bounded. Unresolvable ids are skipped here and surface
// as adapter errors when the file is read for inlining.
const attachmentPathLines = attachments.flatMap((attachment) => {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
return attachmentPath === null
? []
: [`[Attached ${attachment.type} "${attachment.name}" is saved at: ${attachmentPath}]`];
});
const inputTextWithAttachmentPaths =
attachmentPathLines.length === 0
? parsed.input
: [parsed.input, attachmentPathLines.join("\n")]
.filter((part): part is string => typeof part === "string" && part.length > 0)
.join("\n\n");
const input = {
...parsed,
...(inputTextWithAttachmentPaths !== undefined
? { input: inputTextWithAttachmentPaths }
: {}),
attachments,
};
yield* Effect.annotateCurrentSpan({
"provider.operation": "send-turn",
"provider.thread_id": input.threadId,
@@ -68,6 +68,7 @@ function makeReadModel(
readonly lastError: string | null;
readonly updatedAt: string;
} | null;
readonly backgroundLiveness?: "working" | "monitoring" | null;
}>,
) {
const now = "2026-01-01T00:00:00.000Z";
@@ -109,6 +110,7 @@ function makeReadModel(
latestTurn: null,
messages: [],
session: thread.session,
backgroundLiveness: thread.backgroundLiveness ?? null,
activities: [],
proposedPlans: [],
checkpoints: [],
@@ -135,6 +137,14 @@ describe("ProviderSessionReaper", () => {
runtime = null;
});
// Shared start sequence so each test adds no manual Effect runners
// (no-manual-effect-runtime-in-tests tracks this file's legacy count).
async function startReaper() {
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
}
async function createHarness(input: {
readonly readModel: ReturnType<typeof makeReadModel>;
readonly stopSessionImplementation?: (input: {
@@ -261,9 +271,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await startReaper();
await waitFor(() => harness.stopSession.mock.calls.length === 1);
@@ -311,9 +319,55 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await startReaper();
await Effect.runPromise(drainFibers);
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("skips stale sessions while background work is still live", async () => {
const threadId = ThreadId.make("thread-reaper-background-work");
const now = "2026-01-01T00:00:00.000Z";
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
backgroundLiveness: "working",
},
]),
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-background-work",
},
runtimePayload: null,
}),
);
await startReaper();
await Effect.runPromise(drainFibers);
expect(harness.stopSession).not.toHaveBeenCalled();
@@ -360,9 +414,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await startReaper();
await Effect.runPromise(drainFibers);
expect(harness.stopSession).not.toHaveBeenCalled();
@@ -409,9 +461,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await startReaper();
await Effect.runPromise(drainFibers);
expect(harness.stopSession).not.toHaveBeenCalled();
@@ -495,9 +545,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await startReaper();
await waitFor(() => harness.stopSession.mock.calls.length === 2);
@@ -578,9 +626,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await startReaper();
await waitFor(() => harness.stopSession.mock.calls.length === 2);
@@ -71,6 +71,19 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
continue;
}
// The turn can settle while background work runs on (subagent
// fleets, workflow runs, Monitor watch loops). Those live inside the
// provider process, so stopping the session would kill them silently,
// and nothing bumps lastSeenAt between turns.
if (thread?.backgroundLiveness != null) {
yield* Effect.logDebug("provider.session.reaper.skipped-background-work", {
threadId: binding.threadId,
backgroundLiveness: thread.backgroundLiveness,
idleDurationMs,
});
continue;
}
const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
Effect.tap(() =>
Effect.logInfo("provider.session.reaped", {
@@ -16,6 +16,7 @@ const fixture = JSON.parse(
const script = JSON.parse(NodeFS.readFileSync(process.env.T3_CODEX_COLLAB_SCRIPT, "utf8"));
const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
let turnStartCount = 0;
const rl = NodeReadline.createInterface({ input: process.stdin });
rl.on("line", (line) => {
@@ -43,14 +44,20 @@ rl.on("line", (line) => {
return;
}
if (method === "turn/start") {
write({ id, result: fixture.responses.turnStart });
const turnId = script.turnIds?.[turnStartCount];
const turn = turnId
? { ...fixture.responses.turnStart.turn, id: turnId }
: fixture.responses.turnStart.turn;
turnStartCount += 1;
write({ id, result: { ...fixture.responses.turnStart, turn } });
const rootThreadId = script.rootThreadId;
const turn = fixture.responses.turnStart.turn;
write({
jsonrpc: "2.0",
method: "turn/started",
params: { threadId: rootThreadId, turn },
});
if (script.onlyFirstTurnStarts !== true || turnStartCount === 1) {
write({
jsonrpc: "2.0",
method: "turn/started",
params: { threadId: rootThreadId, turn },
});
}
for (const notification of script.notifications) {
write({ jsonrpc: "2.0", method: notification.method, params: notification.params });
}
@@ -75,6 +82,20 @@ rl.on("line", (line) => {
`${process.env.T3_CODEX_COLLAB_SCRIPT}.interrupts`,
`${JSON.stringify({ threadId: target, turnId: message.params?.turnId })}\n`,
);
if (
script.expectedActiveTurnId &&
message.params?.threadId === script.rootThreadId &&
message.params?.turnId !== script.expectedActiveTurnId
) {
write({
id,
error: {
code: -32000,
message: `expected active turn id ${message.params?.turnId} but found ${script.expectedActiveTurnId}`,
},
});
return;
}
if (script.failInterruptFor && script.failInterruptFor === target) {
write({ id, error: { code: -32000, message: "thread already closed" } });
return;
+123
View File
@@ -149,6 +149,7 @@ import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryR
import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
import * as Data from "effect/Data";
import { makeOrchestrationIntegrationHarness } from "../integration/OrchestrationEngineHarness.integration.ts";
@@ -433,6 +434,7 @@ const buildAppUnderTest = (options?: {
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
traceKeepAllSpans: false,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
@@ -825,6 +827,7 @@ const buildAppUnderTest = (options?: {
const appLayer = servedRoutesLayer.pipe(
Layer.provide(resourceTelemetryLayer),
Layer.provide(UsageService.layerTest),
Layer.provide(
Layer.mock(BrowserTraceCollector.BrowserTraceCollector)({
record: () => Effect.void,
@@ -7018,6 +7021,126 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("stops the provider session after settle without closing terminals", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-settle");
const effects: string[] = [];
const dispatchedCommands: Array<OrchestrationCommand> = [];
const now = "2026-01-01T00:00:00.000Z";
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
effects.push(`terminal.close:${input.threadId}`);
}),
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
effects.push(`dispatch:${command.type}`);
return { sequence: dispatchedCommands.length };
}),
},
projectionSnapshotQuery: {
getThreadShellById: () =>
Effect.succeed(
Option.some(
makeDefaultOrchestrationThreadShell({
id: threadId,
updatedAt: now,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
}),
),
),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.settle",
commandId: CommandId.make("cmd-thread-settle"),
threadId,
}),
),
);
assert.equal(dispatchResult.sequence, 1);
assert.deepEqual(effects, ["dispatch:thread.settle", "dispatch:thread.session.stop"]);
const sessionStopCommand = dispatchedCommands[1];
assert.equal(sessionStopCommand?.type, "thread.session.stop");
if (sessionStopCommand?.type === "thread.session.stop") {
assert.equal(sessionStopCommand.threadId, threadId);
assert.equal(sessionStopCommand.commandId, "session-stop-for-settle:cmd-thread-settle");
assert.equal(sessionStopCommand.onlyIfSettled, true);
}
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("settles without dispatching session stop when the thread has no session", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-settle-no-session");
const effects: string[] = [];
const dispatchedCommands: Array<OrchestrationCommand> = [];
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
effects.push(`terminal.close:${input.threadId}`);
}),
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
effects.push(`dispatch:${command.type}`);
return { sequence: dispatchedCommands.length };
}),
},
projectionSnapshotQuery: {
getThreadShellById: () =>
Effect.succeed(
Option.some(makeDefaultOrchestrationThreadShell({ id: threadId, session: null })),
),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.settle",
commandId: CommandId.make("cmd-thread-settle-no-session"),
threadId,
}),
),
);
assert.equal(dispatchResult.sequence, 1);
assert.deepEqual(effects, ["dispatch:thread.settle"]);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
["thread.settle"],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("archives and still closes terminals when session stop fails", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-archive-stop-failure");
+4 -2
View File
@@ -20,7 +20,6 @@ import {
} from "./http.ts";
import { fixPath } from "./os-jank.ts";
import { websocketRpcRouteLayer } from "./ws.ts";
import { skillsHttpApiLayer } from "./skills/http.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
@@ -102,6 +101,7 @@ import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClien
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import {
clearPersistedServerRuntimeState,
@@ -159,6 +159,8 @@ const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
Layer.provideMerge(ServerSettingsLayerLive),
);
const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive));
const ResourceDiagnosticsLayerLive = Layer.mergeAll(
ResourceTelemetryLayerLive,
ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
@@ -411,6 +413,7 @@ const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
// Misc.
Layer.provideMerge(BackgroundLayerLive),
Layer.provideMerge(ResourceDiagnosticsLayerLive),
Layer.provideMerge(UsageLayerLive),
Layer.provideMerge(TraceDiagnostics.layer),
Layer.provideMerge(AnalyticsService.layer),
Layer.provideMerge(ExternalLauncher.layer),
@@ -432,7 +435,6 @@ export const makeRoutesLayer = Layer.mergeAll(
Layer.provide(authHttpApiLayer),
Layer.provide(connectHttpApiLayer),
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(skillsHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
),
@@ -1,213 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import {
ClaudeSettings,
CodexSettings,
ProviderDriverKind,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as ServerSettings from "../serverSettings.ts";
import { discoverGlobalSkillInventory, readSkillInstallations } from "./SkillInventory.ts";
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
const writeSkill = Effect.fn("SkillInventoryTest.writeSkill")(function* (
root: string,
directoryName: string,
description: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = path.join(root, "skills", directoryName);
yield* fileSystem.makeDirectory(directory, { recursive: true });
yield* fileSystem.writeFileString(
path.join(directory, "SKILL.md"),
`---\nname: ${directoryName}\ndescription: ${description}\n---\n`,
);
});
it.layer(NodeServices.layer)("discoverGlobalSkillInventory", (it) => {
it.effect("omits skills that become unreadable during inventory", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-skill-inventory-unreadable-",
});
const installations = yield* readSkillInstallations({
instanceId: "codex",
instance: {
driver: ProviderDriverKind.make("codex"),
config: decodeCodexSettings({}),
},
fallbackDisplayName: "Codex",
skills: [
{
name: "removed",
path: path.join(tempDirectory, "removed", "SKILL.md"),
enabled: true,
scope: "user",
},
],
});
assert.deepEqual(installations, []);
}),
);
it.effect("discovers global skills for configured Codex and Claude instances", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-skill-inventory-",
});
const codexHome = path.join(tempDirectory, "codex");
const claudeHome = path.join(tempDirectory, "claude");
yield* writeSkill(codexHome, "review", "Review with Codex.");
yield* writeSkill(claudeHome, "deploy", "Deploy with Claude.");
const inventory = yield* discoverGlobalSkillInventory().pipe(
Effect.provide(
ServerSettings.layerTest({
providers: {
codex: decodeCodexSettings({ homePath: path.join(tempDirectory, "empty-codex") }),
claudeAgent: decodeClaudeSettings({
homePath: path.join(tempDirectory, "empty-claude"),
}),
},
providerInstances: {
[ProviderInstanceId.make("codex_work")]: {
driver: ProviderDriverKind.make("codex"),
displayName: "Codex Work",
config: decodeCodexSettings({ homePath: codexHome }),
},
[ProviderInstanceId.make("claude_personal")]: {
driver: ProviderDriverKind.make("claudeAgent"),
displayName: "Claude Personal",
config: decodeClaudeSettings({ homePath: claudeHome }),
},
},
}),
),
);
assert.deepEqual(
inventory.installations.map((skill) => ({
harness: skill.harness,
harnessDisplayName: skill.harnessDisplayName,
name: skill.name,
directoryPath: skill.directoryPath,
hasContent: skill.content.includes(`#`) || skill.content.includes("description:"),
})),
[
{
harness: "claudeAgent",
harnessDisplayName: "Claude Personal",
name: "deploy",
directoryPath: path.join(claudeHome, "skills", "deploy"),
hasContent: true,
},
{
harness: "codex",
harnessDisplayName: "Codex Work",
name: "review",
directoryPath: path.join(codexHome, "skills", "review"),
hasContent: true,
},
],
);
}),
);
it.effect("respects provider enablement and instance environment", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-skill-inventory-environment-",
});
const codexHome = path.join(tempDirectory, "codex-env");
const claudeHome = path.join(tempDirectory, "claude-env");
const disabledCodexHome = path.join(tempDirectory, "codex-disabled");
const disabledClaudeHome = path.join(tempDirectory, "claude-disabled");
yield* writeSkill(codexHome, "codex-env-skill", "Loaded from CODEX_HOME.");
yield* writeSkill(claudeHome, "claude-env-skill", "Loaded from CLAUDE_CONFIG_DIR.");
yield* writeSkill(disabledCodexHome, "disabled-codex", "Must not appear.");
yield* writeSkill(disabledClaudeHome, "disabled-claude", "Must not appear.");
const inventory = yield* discoverGlobalSkillInventory().pipe(
Effect.provide(
ServerSettings.layerTest({
providers: {
codex: decodeCodexSettings({ homePath: path.join(tempDirectory, "legacy-codex") }),
claudeAgent: decodeClaudeSettings({
homePath: path.join(tempDirectory, "legacy-claude"),
}),
},
providerInstances: {
[ProviderInstanceId.make("codex_env")]: {
driver: ProviderDriverKind.make("codex"),
environment: [{ name: "CODEX_HOME", value: codexHome, sensitive: false }],
config: decodeCodexSettings({}),
},
[ProviderInstanceId.make("claude_env")]: {
driver: ProviderDriverKind.make("claudeAgent"),
environment: [{ name: "CLAUDE_CONFIG_DIR", value: claudeHome, sensitive: false }],
config: decodeClaudeSettings({}),
},
[ProviderInstanceId.make("codex_disabled")]: {
driver: ProviderDriverKind.make("codex"),
enabled: false,
config: decodeCodexSettings({ homePath: disabledCodexHome }),
},
[ProviderInstanceId.make("claude_disabled")]: {
driver: ProviderDriverKind.make("claudeAgent"),
config: decodeClaudeSettings({ enabled: false, homePath: disabledClaudeHome }),
},
},
}),
),
);
assert.deepEqual(inventory.installations.map((skill) => skill.name).sort(), [
"claude-env-skill",
"codex-env-skill",
]);
}),
);
it.effect("ignores unsupported provider instances", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-skill-inventory-empty-",
});
const inventory = yield* discoverGlobalSkillInventory().pipe(
Effect.provide(
ServerSettings.layerTest({
providers: {
codex: decodeCodexSettings({ homePath: path.join(tempDirectory, "codex") }),
claudeAgent: decodeClaudeSettings({
homePath: path.join(tempDirectory, "claude"),
}),
},
providerInstances: {
[ProviderInstanceId.make("opencode")]: {
driver: ProviderDriverKind.make("opencode"),
config: {},
},
},
}),
),
);
assert.deepEqual(inventory.installations, []);
}),
);
});
-136
View File
@@ -1,136 +0,0 @@
import type {
ProviderInstanceConfig,
ServerProviderSkill,
SkillInventory,
SkillInventoryInstallation,
} from "@t3tools/contracts";
import { ClaudeSettings, CodexSettings, ProviderInstanceId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { discoverClaudeSkills } from "../provider/Drivers/ClaudeSkills.ts";
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
import { deriveProviderInstanceConfigMap } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
import { mergeProviderInstanceEnvironment } from "../provider/ProviderInstanceEnvironment.ts";
import { ServerSettingsService } from "../serverSettings.ts";
const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
function harnessDisplayName(instance: ProviderInstanceConfig, fallback: string): string {
return instance.displayName?.trim() || fallback;
}
export const readSkillInstallations = Effect.fn("SkillInventory.readSkillInstallations")(
function* (input: {
readonly instanceId: string;
readonly instance: ProviderInstanceConfig;
readonly fallbackDisplayName: string;
readonly skills: ReadonlyArray<ServerProviderSkill>;
}): Effect.fn.Return<
ReadonlyArray<SkillInventoryInstallation>,
never,
FileSystem.FileSystem | Path.Path
> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const installations = yield* Effect.forEach(input.skills, (skill) =>
fileSystem.readFileString(skill.path).pipe(
Effect.map((content) => ({
providerInstanceId: ProviderInstanceId.make(input.instanceId),
harness: input.instance.driver,
harnessDisplayName: harnessDisplayName(input.instance, input.fallbackDisplayName),
name: skill.name,
...(skill.description ? { description: skill.description } : {}),
directoryPath: path.dirname(skill.path),
skillFilePath: skill.path,
content,
})),
Effect.option,
),
);
return Arr.getSomes(installations);
},
);
const discoverInstanceSkills = Effect.fn("SkillInventory.discoverInstanceSkills")(function* (
instanceId: string,
instance: ProviderInstanceConfig,
): Effect.fn.Return<
ReadonlyArray<SkillInventoryInstallation>,
never,
FileSystem.FileSystem | Path.Path
> {
const config = instance.config ?? {};
const processEnv = mergeProviderInstanceEnvironment(instance.environment);
if (instance.driver === "codex") {
const decoded = decodeCodexSettings(config);
if (decoded._tag === "None") return [];
if (!(instance.enabled ?? decoded.value.enabled)) return [];
const configuredHomePath = decoded.value.homePath || processEnv.CODEX_HOME?.trim() || "";
const layout = yield* resolveCodexHomeLayout({
...decoded.value,
homePath: configuredHomePath,
});
const skills = yield* discoverClaudeSkills(
{ homePath: layout.sharedHomePath },
undefined,
processEnv,
);
return yield* readSkillInstallations({
instanceId,
instance,
fallbackDisplayName: "Codex",
skills,
});
}
if (instance.driver === "claudeAgent") {
const decoded = decodeClaudeSettings(config);
if (decoded._tag === "None") return [];
if (!(instance.enabled ?? decoded.value.enabled)) return [];
const skills = yield* discoverClaudeSkills(decoded.value, undefined, processEnv);
return yield* readSkillInstallations({
instanceId,
instance,
fallbackDisplayName: "Claude",
skills,
});
}
// Cursor, Grok, and OpenCode do not expose compatible global skill directories.
return [];
});
export const discoverGlobalSkillInventory = Effect.fn(
"SkillInventory.discoverGlobalSkillInventory",
)(function* (): Effect.fn.Return<
SkillInventory,
never,
FileSystem.FileSystem | Path.Path | ServerSettingsService
> {
const settingsService = yield* ServerSettingsService;
const settings = yield* settingsService.getSettings.pipe(Effect.orDie);
const providerInstances = deriveProviderInstanceConfigMap(settings);
const installations = yield* Effect.forEach(
Object.entries(providerInstances),
([instanceId, instance]) => discoverInstanceSkills(instanceId, instance),
{ concurrency: "unbounded" },
);
return {
scannedAt: DateTime.formatIso(yield* DateTime.now),
installations: installations
.flat()
.sort(
(left, right) =>
left.harnessDisplayName.localeCompare(right.harnessDisplayName) ||
left.name.localeCompare(right.name),
),
};
});
-19
View File
@@ -1,19 +0,0 @@
import { AuthOrchestrationReadScope, EnvironmentHttpApi } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { annotateEnvironmentRequest, requireEnvironmentScope } from "../auth/http.ts";
import { discoverGlobalSkillInventory } from "./SkillInventory.ts";
export const skillsHttpApiLayer = HttpApiBuilder.group(EnvironmentHttpApi, "skills", (handlers) =>
Effect.succeed(
handlers.handle(
"inventory",
Effect.fn("environment.skills.inventory")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
return yield* discoverGlobalSkillInventory();
}),
),
),
);
+23
View File
@@ -1764,3 +1764,26 @@ it.layer(
}).pipe(Effect.provide(TestClock.layer())),
);
});
it("inspectSubprocessFromSnapshot resolves child command and descendants from one table", () => {
const snapshot = TerminalManager.processTableFromRows([
[100, 1, "zsh"],
[200, 100, "node"],
[201, 200, "esbuild"],
[202, 200, "tmux: server"],
[900, 1, "unrelated"],
]);
const inspected = TerminalManager.inspectSubprocessFromSnapshot(100, snapshot, "linux");
assert.equal(inspected.hasRunningSubprocess, true);
assert.equal(inspected.childCommand, "node");
assert.deepStrictEqual([...inspected.processIds].toSorted(), [100, 200, 201, 202]);
const idle = TerminalManager.inspectSubprocessFromSnapshot(900, snapshot, "linux");
assert.equal(idle.hasRunningSubprocess, false);
assert.equal(idle.childCommand, null);
assert.deepStrictEqual(idle.processIds, []);
const missing = TerminalManager.inspectSubprocessFromSnapshot(555, snapshot, "linux");
assert.equal(missing.hasRunningSubprocess, false);
});
+270 -268
View File
@@ -46,6 +46,7 @@ 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 References from "effect/References";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
@@ -90,7 +91,7 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubpr
{
cause: Schema.optional(Schema.Defect()),
terminalPid: Schema.Number,
command: Schema.Literals(["powershell", "pgrep", "ps"]),
command: Schema.Literals(["powershell", "ps"]),
},
) {
override get message(): string {
@@ -98,6 +99,22 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubpr
}
}
// The whole-table snapshot has no per-terminal identity, so its failure is a
// separate error rather than a TerminalSubprocessCheckError with a sentinel
// pid.
class TerminalProcessTableCaptureError extends Schema.TaggedErrorClass<TerminalProcessTableCaptureError>()(
"TerminalProcessTableCaptureError",
{
cause: Schema.optional(Schema.Defect()),
command: Schema.Literals(["powershell", "ps"]),
truncated: Schema.optional(Schema.Boolean),
},
) {
override get message(): string {
return `Failed to capture the process table with ${this.command}`;
}
}
class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcessSignalError>()(
"TerminalProcessSignalError",
{
@@ -188,7 +205,7 @@ export class TerminalManager extends Context.Service<
}
>()("t3/terminal/Manager/TerminalManager") {}
interface TerminalSubprocessInspectResult {
export interface TerminalSubprocessInspectResult {
readonly hasRunningSubprocess: boolean;
readonly childCommand: string | null;
readonly processIds: ReadonlyArray<number>;
@@ -610,246 +627,156 @@ function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean {
);
}
function parseFirstChildPidFromPgrep(stdout: string): number | null {
for (const line of stdout.split(/\r?\n/g)) {
const n = Number.parseInt(line.trim(), 10);
if (Number.isInteger(n) && n > 0) {
return n;
}
}
return null;
// One pid/ppid/name table read per poll tick serves every running terminal.
// The previous per-terminal inspection spawned pgrep plus up to three ps
// invocations per session per second (a full `ps -e` table each time), which
// dominated both process churn and trace volume on hosts with many terminals.
export interface ProcessTableSnapshot {
readonly commandByPid: ReadonlyMap<number, string>;
readonly childrenByParent: ReadonlyMap<number, ReadonlyArray<number>>;
}
function windowsInspectSubprocess(
terminalPid: number,
platform: NodeJS.Platform,
): Effect.Effect<
TerminalSubprocessInspectResult,
TerminalSubprocessCheckError,
export function processTableFromRows(
rows: Iterable<readonly [pid: number, parentPid: number, command: string]>,
): ProcessTableSnapshot {
const commandByPid = new Map<number, string>();
const childrenByParent = new Map<number, number[]>();
for (const [pid, parentPid, command] of rows) {
commandByPid.set(pid, command);
const children = childrenByParent.get(parentPid) ?? [];
children.push(pid);
childrenByParent.set(parentPid, children);
}
return { commandByPid, childrenByParent };
}
const PROCESS_TABLE_MAX_OUTPUT_BYTES = 4 * 1_048_576;
function captureWindowsProcessTable(): Effect.Effect<
ProcessTableSnapshot,
TerminalProcessTableCaptureError,
ProcessRunner.ProcessRunner
> {
const command =
'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }';
return Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
return yield* processRunner.run({
// powershell.exe is a real executable — never spawn it through cmd.exe
// shell mode, which would re-tokenize the `-Command` payload (pipes,
// semicolons) before PowerShell ever sees it.
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeout: "1500 millis",
maxOutputBytes: 32_768,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
});
}).pipe(
Effect.map((result) => {
if (result.code !== 0) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;
}
const processNameById = new Map<number, string>();
const childrenByParent = new Map<number, number[]>();
for (const line of result.stdout.split(/\r?\n/g)) {
const [pidRaw, parentPidRaw, nameRaw] = line.trim().split("|", 3);
const pid = Number(pidRaw);
const parentPid = Number(parentPidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;
processNameById.set(pid, nameRaw?.trim() ?? "");
const children = childrenByParent.get(parentPid) ?? [];
children.push(pid);
childrenByParent.set(parentPid, children);
}
const directChildren = childrenByParent.get(terminalPid) ?? [];
const childPid = directChildren[0];
if (childPid === undefined) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;
}
const processIds = new Set<number>([terminalPid]);
const pending = [terminalPid];
while (pending.length > 0) {
const parentPid = pending.pop();
if (parentPid === undefined) continue;
for (const pid of childrenByParent.get(parentPid) ?? []) {
if (processIds.has(pid)) continue;
processIds.add(pid);
pending.push(pid);
}
}
const normalized = normalizeChildCommandName(processNameById.get(childPid) ?? "", platform);
return {
hasRunningSubprocess: true,
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
processIds: [...processIds],
} as const;
}),
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
cause,
terminalPid,
command: "powershell",
}),
),
);
const result = yield* processRunner
.run({
// powershell.exe is a real executable — never spawn it through cmd.exe
// shell mode, which would re-tokenize the `-Command` payload (pipes,
// semicolons) before PowerShell ever sees it.
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeout: "1500 millis",
maxOutputBytes: PROCESS_TABLE_MAX_OUTPUT_BYTES,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) => new TerminalProcessTableCaptureError({ cause, command: "powershell" }),
),
);
if (result.code !== 0) {
return yield* new TerminalProcessTableCaptureError({ command: "powershell" });
}
// A truncated table silently loses the sessions past the cutoff — they
// would read as "no subprocesses" and drop out of resource registration.
if (result.stdoutTruncated) {
return yield* new TerminalProcessTableCaptureError({
command: "powershell",
truncated: true,
});
}
const rows: Array<readonly [number, number, string]> = [];
for (const line of result.stdout.split(/\r?\n/g)) {
const [pidRaw, parentPidRaw, nameRaw] = line.trim().split("|", 3);
const pid = Number(pidRaw);
const parentPid = Number(parentPidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;
rows.push([pid, parentPid, nameRaw?.trim() ?? ""]);
}
return processTableFromRows(rows);
});
}
const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(function* (
terminalPid: number,
platform: NodeJS.Platform,
): Effect.fn.Return<
TerminalSubprocessInspectResult,
TerminalSubprocessCheckError,
function capturePosixProcessTable(): Effect.Effect<
ProcessTableSnapshot,
TerminalProcessTableCaptureError,
ProcessRunner.ProcessRunner
> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const runPgrep = processRunner
.run({
command: "pgrep",
args: ["-P", String(terminalPid)],
timeout: "1 second",
maxOutputBytes: 32_768,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
cause,
terminalPid,
command: "pgrep",
}),
),
);
const runPs = processRunner
.run({
command: "ps",
args: ["-eo", "pid=,ppid="],
timeout: "1 second",
maxOutputBytes: 262_144,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
cause,
terminalPid,
command: "ps",
}),
),
);
let childPid: number | null = null;
const pgrepResult = yield* Effect.exit(runPgrep);
if (pgrepResult._tag === "Success") {
if (pgrepResult.value.code === 0) {
childPid = parseFirstChildPidFromPgrep(pgrepResult.value.stdout);
} else if (pgrepResult.value.code === 1) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
return Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
const result = yield* processRunner
.run({
command: "ps",
args: ["-eo", "pid=,ppid=,comm="],
timeout: "1 second",
maxOutputBytes: PROCESS_TABLE_MAX_OUTPUT_BYTES,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError((cause) => new TerminalProcessTableCaptureError({ cause, command: "ps" })),
);
if (result.code !== 0) {
return yield* new TerminalProcessTableCaptureError({ command: "ps" });
}
}
if (childPid === null) {
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Failure" || psResult.value.code !== 0) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
if (result.stdoutTruncated) {
return yield* new TerminalProcessTableCaptureError({ command: "ps", truncated: true });
}
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
if (ppid === terminalPid) {
childPid = pid;
break;
}
const rows: Array<readonly [number, number, string]> = [];
for (const line of result.stdout.split(/\r?\n/g)) {
// comm may contain spaces ("tmux: server"), so only the two leading
// numeric columns are positional.
const match = /^(\d+)\s+(\d+)\s*(.*)$/.exec(line.trim());
if (!match) continue;
rows.push([Number(match[1]), Number(match[2]), match[3] ?? ""]);
}
}
return processTableFromRows(rows);
});
}
if (childPid === null) {
function captureProcessTableSnapshot(
platform: NodeJS.Platform,
): Effect.Effect<
ProcessTableSnapshot,
TerminalProcessTableCaptureError,
ProcessRunner.ProcessRunner
> {
return platform === "win32" ? captureWindowsProcessTable() : capturePosixProcessTable();
}
export function inspectSubprocessFromSnapshot(
terminalPid: number,
snapshot: ProcessTableSnapshot,
platform: NodeJS.Platform,
): TerminalSubprocessInspectResult {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
const runComm = processRunner.run({
command: "ps",
args: ["-p", String(childPid), "-o", "comm="],
timeout: "1 second",
maxOutputBytes: 8_192,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
});
const commResult = yield* Effect.exit(runComm);
let rawComm: string | null = null;
if (commResult._tag === "Success" && commResult.value && commResult.value.code === 0) {
rawComm = commResult.value.stdout.trim();
const childPid = (snapshot.childrenByParent.get(terminalPid) ?? [])[0];
if (childPid === undefined) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
if (!rawComm || rawComm.length === 0) {
const runArgs = processRunner.run({
command: "ps",
args: ["-p", String(childPid), "-o", "args="],
timeout: "1 second",
maxOutputBytes: 16_384,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
});
const argsResult = yield* Effect.exit(runArgs);
if (argsResult._tag === "Success" && argsResult.value && argsResult.value.code === 0) {
const first = argsResult.value.stdout.trim().split(/\s+/)[0] ?? "";
rawComm = first.length > 0 ? first : null;
}
}
const normalized = rawComm ? normalizeChildCommandName(rawComm, platform) : null;
const processIds = new Set<number>([terminalPid]);
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Success" && psResult.value.code === 0) {
const childrenByParent = new Map<number, number[]>();
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
const children = childrenByParent.get(ppid) ?? [];
children.push(pid);
childrenByParent.set(ppid, children);
const pending = [terminalPid];
while (pending.length > 0) {
const parentPid = pending.pop();
if (parentPid === undefined) continue;
for (const pid of snapshot.childrenByParent.get(parentPid) ?? []) {
if (processIds.has(pid)) continue;
processIds.add(pid);
pending.push(pid);
}
const pending = [terminalPid];
while (pending.length > 0) {
const parentPid = pending.pop();
if (parentPid === undefined) continue;
for (const child of childrenByParent.get(parentPid) ?? []) {
if (processIds.has(child)) continue;
processIds.add(child);
pending.push(child);
}
}
} else {
processIds.add(childPid);
}
const normalized = normalizeChildCommandName(snapshot.commandByPid.get(childPid) ?? "", platform);
return {
hasRunningSubprocess: true,
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
processIds: [...processIds],
};
});
function defaultSubprocessInspectorForPlatform(platform: NodeJS.Platform) {
return Effect.fn("terminal.defaultSubprocessInspector")(function* (terminalPid: number) {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
if (platform === "win32") {
return yield* windowsInspectSubprocess(terminalPid, platform);
}
return yield* posixInspectSubprocess(terminalPid, platform);
});
}
function capHistory(history: string, maxLines: number): string {
@@ -1227,12 +1154,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const baseEnv = options.env ?? process.env;
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
const processRunner = yield* ProcessRunner.ProcessRunner;
const subprocessInspector =
options.subprocessInspector ??
((terminalPid) =>
defaultSubprocessInspectorForPlatform(platform)(terminalPid).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
));
// Injected per-terminal inspector is the test seam; the default path takes
// one process-table snapshot per tick instead (see pollSubprocessActivity).
const subprocessInspector = options.subprocessInspector ?? null;
const subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
@@ -2053,56 +1977,100 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
}
});
// The session objects are mutable and a restart can swap pid mid-tick, so
// every poll entry carries the pid it was inspected under; downstream guards
// compare against this captured pid, never a re-read of session.pid.
interface RunningSessionPoll {
readonly session: TerminalSessionState;
readonly pid: number;
}
const inspectRunningSubprocesses = Effect.fn("terminal.inspectRunningSubprocesses")(function* (
entries: ReadonlyArray<RunningSessionPoll>,
) {
const results = new Map<number, TerminalSubprocessInspectResult>();
if (subprocessInspector !== null) {
for (const { session, pid } of entries) {
const inspectResult = yield* subprocessInspector(pid).pipe(
Effect.map(Option.some),
Effect.catch((reason) =>
Effect.logWarning("failed to check terminal subprocess activity", {
threadId: session.threadId,
terminalId: session.terminalId,
terminalPid: pid,
reason,
}).pipe(Effect.as(Option.none<TerminalSubprocessInspectResult>())),
),
);
if (Option.isSome(inspectResult)) {
results.set(pid, inspectResult.value);
}
}
return results;
}
const snapshot = yield* captureProcessTableSnapshot(platform).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
Effect.map(Option.some),
// A failed snapshot skips the tick: sessions keep their previous state
// and the next tick retries.
Effect.catch((reason) =>
Effect.logWarning("failed to capture process table for subprocess activity", {
reason,
}).pipe(Effect.as(Option.none<ProcessTableSnapshot>())),
),
);
if (Option.isNone(snapshot)) {
return results;
}
for (const { pid } of entries) {
results.set(pid, inspectSubprocessFromSnapshot(pid, snapshot.value, platform));
}
return results;
});
const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () {
const state = yield* readManagerState;
const runningSessions = [...state.sessions.values()].filter(
(session): session is TerminalSessionState & { pid: number } =>
session.status === "running" && Number.isInteger(session.pid),
);
const runningSessions: Array<RunningSessionPoll> = [];
for (const session of state.sessions.values()) {
if (session.status === "running" && session.pid !== null && Number.isInteger(session.pid)) {
runningSessions.push({ session, pid: session.pid });
}
}
if (runningSessions.length === 0) {
return;
}
const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* (
session: TerminalSessionState & { pid: number },
const inspections = yield* inspectRunningSubprocesses(runningSessions);
const applySubprocessActivity = Effect.fn("terminal.applySubprocessActivity")(function* (
{ session, pid: terminalPid }: RunningSessionPoll,
next: TerminalSubprocessInspectResult,
) {
const terminalPid = session.pid;
const inspectResult = yield* subprocessInspector(terminalPid).pipe(
Effect.map(Option.some),
Effect.catch((reason) =>
Effect.logWarning("failed to check terminal subprocess activity", {
threadId: session.threadId,
terminalId: session.terminalId,
terminalPid,
reason,
}).pipe(Effect.as(Option.none<TerminalSubprocessInspectResult>())),
),
);
if (Option.isNone(inspectResult)) {
return;
}
const next = inspectResult.value;
yield* registerTerminalProcesses({
threadId: session.threadId,
terminalId: session.terminalId,
processIds: next.processIds,
});
const nextChildLabel = next.hasRunningSubprocess ? next.childCommand : null;
const event = yield* modifyManagerState((state) => {
const outcome = yield* modifyManagerState<{
readonly live: boolean;
readonly event: Option.Option<TerminalEvent>;
}>((state) => {
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
);
// Liveness is decided here, before process registration, so a
// terminal that exited or restarted mid-tick cannot get its old
// process tree re-registered with port discovery.
if (
Option.isNone(liveSession) ||
liveSession.value.status !== "running" ||
liveSession.value.pid !== terminalPid ||
(liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess &&
liveSession.value.childCommandLabel === nextChildLabel)
liveSession.value.pid !== terminalPid
) {
return [Option.none(), state] as const;
return [{ live: false, event: Option.none<TerminalEvent>() }, state] as const;
}
if (
liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess &&
liveSession.value.childCommandLabel === nextChildLabel
) {
return [{ live: true, event: Option.none<TerminalEvent>() }, state] as const;
}
liveSession.value.hasRunningSubprocess = next.hasRunningSubprocess;
@@ -2110,27 +2078,56 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const eventStamp = advanceEventSequence(liveSession.value);
return [
Option.some({
type: "activity" as const,
threadId: liveSession.value.threadId,
terminalId: liveSession.value.terminalId,
sequence: eventStamp.sequence,
hasRunningSubprocess: next.hasRunningSubprocess,
label: terminalWireLabel(liveSession.value),
}),
{
live: true,
event: Option.some({
type: "activity" as const,
threadId: liveSession.value.threadId,
terminalId: liveSession.value.terminalId,
sequence: eventStamp.sequence,
hasRunningSubprocess: next.hasRunningSubprocess,
label: terminalWireLabel(liveSession.value),
}),
},
state,
] as const;
});
if (!outcome.live) {
return;
}
yield* registerTerminalProcesses({
threadId: session.threadId,
terminalId: session.terminalId,
processIds: next.processIds,
});
const event = outcome.event;
if (Option.isSome(event)) {
yield* publishEvent(event.value);
// The poll tick runs with tracing suppressed; an actual state flip is
// the only part worth a span, so tracing is re-enabled just for it.
yield* publishEvent(event.value).pipe(
Effect.withSpan("terminal.subprocessActivityChanged", {
attributes: {
threadId: session.threadId,
terminalId: session.terminalId,
hasRunningSubprocess: next.hasRunningSubprocess,
...(nextChildLabel !== null ? { childCommand: nextChildLabel } : {}),
},
}),
Effect.provideService(References.TracerEnabled, true),
);
}
});
yield* Effect.forEach(runningSessions, checkSubprocessActivity, {
concurrency: "unbounded",
discard: true,
});
for (const entry of runningSessions) {
const next = inspections.get(entry.pid);
if (next === undefined) {
continue;
}
yield* applySubprocessActivity(entry, next);
}
});
const hasRunningSessions = readManagerState.pipe(
@@ -2144,6 +2141,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
Effect.flatMap((active) =>
active
? pollSubprocessActivity().pipe(
// Steady-state polling emitted several empty always-success
// spans per terminal per second. Suppress the whole tick; the
// explicit subprocessActivityChanged span above is the only
// trace output.
Effect.provideService(References.TracerEnabled, false),
Effect.flatMap(() => Effect.sleep(subprocessPollIntervalMs)),
)
: Effect.sleep(subprocessPollIntervalMs),
+420
View File
@@ -0,0 +1,420 @@
/**
* UsageService - scans provider transcripts and returns priced daily usage.
*
* The scan reads the provider CLIs' own session files rather than T3 Code's
* orchestration projections, so usage covers turns driven outside T3 Code too.
* This is the approach `ccusage` takes.
*
* Transcripts are append-only, so parsed records are memoised per file by
* `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm
* scans only reparse files that changed.
*
* @module UsageService
*/
import * as NodeOS from "node:os";
import {
USAGE_CONTRACT_VERSION,
type UsageProviderKind,
type UsageSource,
type UsageSummary,
type UsageSummaryInput,
UsageReadError,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
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 { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ServerConfig } from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import { resolveClaudeHomePath } from "../provider/Drivers/ClaudeHome.ts";
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
import { UsageAggregator } from "./usageAggregation.ts";
import { parseRateTable, type RateTable } from "./usagePricing.ts";
import {
listTranscriptFiles,
readDirectoryVolumeId,
readTranscriptRecords,
} from "./usageTranscriptReader.ts";
import {
decodeScanCache,
dedupeWithinFile,
encodeScanCache,
pruneScanCache,
type ScanCache,
} from "./usageScanCache.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
const LITELLM_RATES_URL =
"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
/** Rates move rarely; a day-old table keeps the page working offline. */
const RATES_TTL_MS = 24 * 60 * 60 * 1000;
/**
* Files are filtered by mtime before opening. The slack covers a session whose
* last write lands just before local midnight on the window's first day.
*/
const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
/** Longest window the UI offers, plus slack. Older entries are pruned. */
const CACHE_RETENTION_DAYS = 90;
/** On-disk shape of the rate snapshot. */
const RatesCacheFile = Schema.Struct({
fetchedAtMs: Schema.Number,
document: Schema.Unknown,
});
const decodeRatesCache = Schema.decodeUnknownEffect(
Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
);
const encodeRatesCache = Schema.encodeEffect(
Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
);
/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);
export class UsageService extends Context.Service<
UsageService,
{
readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
}
>()("t3/usage/UsageService") {}
/** Empty summary, for suites that only need the RPC surface to resolve. */
export const layerTest = Layer.succeed(
UsageService,
UsageService.of({
readSummary: (input) =>
Effect.succeed({
contractVersion: USAGE_CONTRACT_VERSION,
readAt: "1970-01-01T00:00:00.000Z",
timeZone: input.timeZone,
sinceDay: input.sinceDay,
untilDay: input.untilDay,
buckets: [],
sources: [],
pricing: {
status: "unavailable",
source: LITELLM_RATES_URL,
fetchedAt: null,
knownModels: 0,
},
scanDurationMs: 0,
}),
}),
);
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfig;
const settingsService = yield* ServerSettings.ServerSettingsService;
const httpClient = yield* HttpClient.HttpClient;
const fileCache: ScanCache = new Map();
let cacheDirty = false;
const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");
let rates: RateTable = new Map();
let ratesFetchedAtMs: number | null = null;
let ratesStatus: UsageSummary["pricing"]["status"] = "unavailable";
/**
* Loads the LiteLLM rate table, preferring a fresh copy and falling back to
* the on-disk snapshot. With neither, every model reports as unpriced rather
* than the page failing.
*/
const ensureRates = Effect.fn("UsageService.ensureRates")(function* () {
const now = yield* Clock.currentTimeMillis;
if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < RATES_TTL_MS) return;
if (ratesFetchedAtMs === null) {
const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
Effect.flatMap((raw) => decodeRatesCache(raw)),
Effect.catchCause(() => Effect.succeed(null)),
);
if (fromDisk !== null) {
const parsed = parseRateTable(fromDisk.document);
if (parsed.size > 0) {
rates = parsed;
ratesFetchedAtMs = fromDisk.fetchedAtMs;
ratesStatus = "cached";
if (now - fromDisk.fetchedAtMs < RATES_TTL_MS) return;
}
}
}
const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap((response) => response.json),
Effect.timeout(10_000),
Effect.catchCause(() => Effect.succeed(null)),
);
if (fetched === null) {
// The refresh failed; whatever we are serving is now past its TTL and
// must not keep claiming to be fresh.
if (rates.size > 0) ratesStatus = "cached";
return;
}
const parsed = parseRateTable(fetched);
if (parsed.size === 0) return;
rates = parsed;
ratesFetchedAtMs = now;
ratesStatus = "fresh";
yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)),
Effect.catchCause(() => Effect.void),
);
});
/**
* Claude's config dir is the home itself when overridden, but a default
* install nests transcripts under `~/.claude/projects`. Probe both.
*/
const resolveClaudeTranscriptDir = (homePath: string) =>
Effect.gen(function* () {
const nested = path.join(homePath, ".claude", "projects");
const nestedExists = yield* fileSystem
.exists(nested)
.pipe(Effect.catchCause(() => Effect.succeed(false)));
return nestedExists ? nested : path.join(homePath, "projects");
});
/** Resolves the transcript directory for each provider. */
const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* () {
// A settings failure must surface as an error: swallowing it here would
// present "zero usage from every provider" as a valid answer.
const settings = yield* settingsService.getSettings.pipe(
Effect.catchCause(
(cause) =>
new UsageReadError({
reason: "scanFailed",
// Bounded description; the squashed failure travels as the cause.
// Squashed, not the Cause tree: a full tree in a Defect field is
// the unbounded wire payload the bounded detail exists to avoid.
detail: "Server settings could not be read.",
cause: Cause.squash(cause),
}),
),
);
const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);
const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);
const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);
return [
{ provider: "claude" as const, dir: claudeDir },
{ provider: "codex" as const, dir: path.join(codexLayout.sharedHomePath, "sessions") },
];
});
/**
* Loads the persisted scan cache exactly once per process.
*
* `Effect.cached` makes concurrent first readers await the same load rather
* than each seeing a "loaded" flag set before the read finished and cold
* scanning against an empty cache.
*/
const ensureScanCacheLoaded = yield* Effect.cached(
Effect.gen(function* () {
const document = yield* fileSystem.readFileString(scanCachePath).pipe(
Effect.flatMap((raw) => decodeScanCacheFile(raw)),
Effect.catchCause(() => Effect.succeed(null)),
);
if (document === null) return;
for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
}),
);
const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
if (!cacheDirty) return;
// Cleared only after the write lands, so a failed persist is retried on
// the next scan instead of leaving disk permanently stale.
yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(
Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
Effect.map(() => {
cacheDirty = false;
}),
// A cache we cannot write is a slower next start, not a failed read.
Effect.catchCause(() => Effect.void),
);
});
/** Parses one transcript, reusing the cached result when it is unchanged. */
const readFileRecords = (
filePath: string,
size: number,
mtimeMs: number,
provider: UsageProviderKind,
): Effect.Effect<readonly UsageRecord[]> =>
Effect.gen(function* () {
const cached = fileCache.get(filePath);
// Provider is part of the identity: if both providers were ever pointed
// at one directory, a hit parsed by the other parser must not be reused.
if (
cached &&
cached.size === size &&
cached.mtimeMs === mtimeMs &&
cached.provider === provider
) {
return cached.records;
}
const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, provider));
// A read failure is not an empty transcript: caching it under this
// (size, mtime) would silently drop the file's usage until it changes.
if (parsed === null) return [];
// Stored already de-duplicated within the file, which is 99% of all
// duplicates. The aggregator still runs the cross-file dedupe pass.
const records = dedupeWithinFile(parsed);
fileCache.set(filePath, { size, mtimeMs, provider, records });
cacheDirty = true;
return records;
});
const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
if (input.sinceDay > input.untilDay) {
return yield* new UsageReadError({
reason: "invalidWindow",
detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
});
}
const startedAtMs = yield* Clock.currentTimeMillis;
yield* ensureRates();
yield* ensureScanCacheLoaded;
const hostId = NodeOS.hostname();
// The home resolvers ask for `Path` themselves; satisfy them from the
// instance we already hold so `readSummary` stays context-free.
const dirs = yield* resolveTranscriptDirs().pipe(Effect.provideService(Path.Path, path));
const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
if (Option.isNone(windowStart)) {
return yield* new UsageReadError({
reason: "invalidWindow",
detail: `sinceDay '${input.sinceDay}' is not a valid date`,
});
}
const windowStartMs = DateTime.toEpochMillis(windowStart.value) - MTIME_SLACK_MS;
const aggregator = new UsageAggregator({
timeZone: input.timeZone,
sinceDay: input.sinceDay,
untilDay: input.untilDay,
rates,
});
const sources: UsageSource[] = [];
const livePaths = new Set<string>();
const walkedRoots: string[] = [];
for (const { provider, dir } of dirs) {
const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
const exists = yield* fileSystem
.exists(dir)
.pipe(Effect.catchCause(() => Effect.succeed(false)));
if (!exists) {
sources.push({
fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
status: "missing",
scannedFiles: 0,
skippedFiles: 0,
malformedRecords: 0,
distinctSessions: 0,
message: "No transcript directory on this environment.",
});
continue;
}
walkedRoots.push(dir);
const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs));
let scannedFiles = 0;
let skippedFiles = 0;
// Distinct per directory. Buckets carry per-cell session counts, but a
// session spans days and models, so clients total this figure instead.
const sessionIds = new Set<string>();
for (const file of files) {
livePaths.add(file.path);
const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
if (records.length === 0) {
skippedFiles += 1;
continue;
}
scannedFiles += 1;
for (const record of records) {
// Only sessions that contributed in-window count: the mtime slack
// admits boundary files whose records fall outside the range.
if (aggregator.add(record) && record.sessionId.length > 0) {
sessionIds.add(record.sessionId);
}
}
}
sources.push({
fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
status: "ok",
scannedFiles,
skippedFiles,
malformedRecords: 0,
distinctSessions: sessionIds.size,
message: null,
});
}
const pruned = pruneScanCache(fileCache, {
livePaths,
walkedRoots,
windowStartMs,
retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,
});
if (pruned > 0) cacheDirty = true;
yield* persistScanCache();
const aggregated = aggregator.finish();
const readAt = yield* DateTime.now;
const finishedAtMs = yield* Clock.currentTimeMillis;
return {
contractVersion: USAGE_CONTRACT_VERSION,
readAt: DateTime.formatIso(readAt),
timeZone: input.timeZone,
sinceDay: input.sinceDay,
untilDay: input.untilDay,
buckets: aggregated.buckets,
sources,
pricing: {
status: ratesStatus,
source: LITELLM_RATES_URL,
fetchedAt:
ratesFetchedAtMs === null
? null
: DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
knownModels: rates.size,
},
scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
} satisfies UsageSummary;
});
return { readSummary } as const;
});
export const layer = Layer.effect(UsageService, make);
@@ -0,0 +1,132 @@
import { describe, expect, it } from "@effect/vitest";
import { UsageAggregator } from "./usageAggregation.ts";
import type { RateTable } from "./usagePricing.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
const rates: RateTable = new Map([
[
"claude-fable-5",
{
inputCostPerToken: 1e-5,
outputCostPerToken: 5e-5,
cacheReadCostPerToken: 1e-6,
cacheCreationCostPerToken: 1.25e-5,
},
],
]);
function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
return {
provider: "claude",
// 2026-08-07T04:05Z is still Aug 6 in Los Angeles.
timestampMs: Date.parse("2026-08-07T04:05:13.944Z"),
model: "claude-fable-5",
sessionId: "session-a",
totals: {
uncachedInputTokens: 100,
cachedInputTokens: 1000,
cacheCreationTokens: 10,
outputTokens: 50,
reasoningTokens: 0,
},
reportedCostUsd: null,
dedupeKey: null,
...overrides,
};
}
function aggregate(records: readonly UsageRecord[], timeZone = "UTC") {
const aggregator = new UsageAggregator({
timeZone,
sinceDay: "2026-08-01",
untilDay: "2026-08-31",
rates,
});
for (const item of records) aggregator.add(item);
return aggregator.finish();
}
describe("UsageAggregator", () => {
it("keeps only the first record for a repeated dedupe key", () => {
const result = aggregate([
record({ dedupeKey: "msg_1:" }),
record({ dedupeKey: "msg_1:" }),
record({ dedupeKey: "msg_1:" }),
]);
expect(result.duplicatesDropped).toBe(2);
expect(result.buckets).toHaveLength(1);
expect(result.buckets[0]?.records).toBe(1);
expect(result.buckets[0]?.totals.outputTokens).toBe(50);
});
it("still sums records that carry no dedupe key", () => {
const result = aggregate([record(), record()]);
expect(result.duplicatesDropped).toBe(0);
expect(result.buckets[0]?.totals.outputTokens).toBe(100);
});
it("buckets by the day in the requested time zone", () => {
const utc = aggregate([record()], "UTC");
const losAngeles = aggregate([record()], "America/Los_Angeles");
expect(utc.buckets[0]?.day).toBe("2026-08-07");
expect(losAngeles.buckets[0]?.day).toBe("2026-08-06");
});
it("prices against the rate table", () => {
const result = aggregate([record()]);
// 100*1e-5 + 1000*1e-6 + 10*1.25e-5 + 50*5e-5
expect(result.buckets[0]?.costUsd).toBeCloseTo(0.004625, 9);
expect(result.buckets[0]?.costSource).toBe("modelPriced");
});
it("counts tokens but not cost for a model with no rate", () => {
const result = aggregate([record({ model: "kimi-k3" })]);
expect(result.buckets[0]?.costUsd).toBe(0);
expect(result.buckets[0]?.costSource).toBe("unpriced");
expect(result.buckets[0]?.unpricedRecords).toBe(1);
expect(result.buckets[0]?.totals.outputTokens).toBe(50);
});
it("prefers a reported cost over the rate table", () => {
const result = aggregate([record({ reportedCostUsd: 1.25 })]);
expect(result.buckets[0]?.costUsd).toBe(1.25);
expect(result.buckets[0]?.costSource).toBe("providerReported");
});
it("drops records outside the window", () => {
const result = aggregate([record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") })]);
expect(result.outOfWindow).toBe(1);
expect(result.buckets).toHaveLength(0);
});
it("reports whether a record contributed", () => {
const aggregator = new UsageAggregator({
timeZone: "UTC",
sinceDay: "2026-08-01",
untilDay: "2026-08-31",
rates,
});
expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(true);
expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(false);
expect(aggregator.add(record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") }))).toBe(false);
});
it("separates providers and models into their own buckets", () => {
const result = aggregate([
record(),
record({ provider: "codex", model: "gpt-5.6-sol" }),
record({ model: "claude-opus-5" }),
]);
expect(result.buckets).toHaveLength(3);
});
});
Binary file not shown.
+148
View File
@@ -0,0 +1,148 @@
/**
* Model rate lookup and cost arithmetic.
*
* Rates come from LiteLLM's `model_prices_and_context_window.json`, the same
* table `ccusage` prices against. Everything here is pure: fetching and caching
* the table lives in `UsageService`.
*
* @module usagePricing
*/
import type { UsageCostSource, UsageTokenTotals } from "@t3tools/contracts";
/**
* The subset of a LiteLLM entry we price against. All values are USD per token.
*
* LiteLLM also publishes tiered variants (`*_above_272k_tokens`, `*_flex`,
* `*_priority`, `*_batches`). We deliberately price at the base tier: the
* transcripts don't record which tier served a request, so anything else would
* be a guess dressed up as precision.
*/
export interface ModelRate {
readonly inputCostPerToken: number;
readonly outputCostPerToken: number;
readonly cacheReadCostPerToken: number;
readonly cacheCreationCostPerToken: number;
}
export type RateTable = ReadonlyMap<string, ModelRate>;
/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */
interface LiteLlmEntry {
readonly input_cost_per_token?: unknown;
readonly output_cost_per_token?: unknown;
readonly cache_read_input_token_cost?: unknown;
readonly cache_creation_input_token_cost?: unknown;
}
function finiteNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
/**
* Projects the LiteLLM document into a rate table.
*
* Entries without both an input and an output rate are dropped: a half-priced
* model would silently under-report cost, which is worse than reporting the
* model as unpriced.
*/
export function parseRateTable(document: unknown): RateTable {
const table = new Map<string, ModelRate>();
if (typeof document !== "object" || document === null) return table;
for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
if (typeof raw !== "object" || raw === null) continue;
const entry = raw as LiteLlmEntry;
const input = finiteNumber(entry.input_cost_per_token);
const output = finiteNumber(entry.output_cost_per_token);
if (input === null || output === null) continue;
table.set(normalizeModelName(name), {
inputCostPerToken: input,
outputCostPerToken: output,
// Anthropic bills cache reads at a discount and cache writes at a
// premium. When a model omits them, cached input is priced as plain
// input rather than as free.
cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input,
cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input,
});
}
return table;
}
/**
* Canonicalises a model name for lookup.
*
* Strips a `provider/` prefix (LiteLLM publishes both `claude-opus-5` and
* `anthropic/claude-opus-5`) and lowercases, since transcripts are inconsistent
* about casing.
*/
export function normalizeModelName(model: string): string {
const trimmed = model.trim().toLowerCase();
const slash = trimmed.lastIndexOf("/");
return slash === -1 ? trimmed : trimmed.slice(slash + 1);
}
/**
* Models we never price, regardless of the table.
*
* `<synthetic>` marks locally generated messages that were never billed. Bare
* family names ("opus", "sonnet") are genuinely ambiguous across generations,
* so we report them as unpriced instead of guessing a generation.
*/
const UNPRICEABLE_MODELS = new Set([
"<synthetic>",
"synthetic",
"opus",
"sonnet",
"haiku",
"fable",
]);
export function lookupRate(table: RateTable, model: string): ModelRate | null {
const normalized = normalizeModelName(model);
if (normalized.length === 0 || UNPRICEABLE_MODELS.has(normalized)) return null;
return table.get(normalized) ?? null;
}
export interface PricedUsage {
readonly costUsd: number;
readonly costSource: UsageCostSource;
}
/**
* Prices a bucket's tokens.
*
* `reasoningTokens` is intentionally not charged separately: it is already
* counted inside `outputTokens`.
*/
export function priceUsage(
table: RateTable,
model: string,
totals: UsageTokenTotals,
reportedCostUsd: number | null,
): PricedUsage {
if (reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {
return { costUsd: reportedCostUsd, costSource: "providerReported" };
}
const rate = lookupRate(table, model);
if (rate === null) return { costUsd: 0, costSource: "unpriced" };
const costUsd =
totals.uncachedInputTokens * rate.inputCostPerToken +
totals.cachedInputTokens * rate.cacheReadCostPerToken +
totals.cacheCreationTokens * rate.cacheCreationCostPerToken +
totals.outputTokens * rate.outputCostPerToken;
return { costUsd, costSource: "modelPriced" };
}
/**
* What the cached input would have cost at full input rates, minus what it
* actually cost. Drives the "cache savings" figure.
*/
export function cacheSavingsUsd(table: RateTable, model: string, totals: UsageTokenTotals): number {
const rate = lookupRate(table, model);
if (rate === null) return 0;
return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken);
}
@@ -0,0 +1,206 @@
import { describe, expect, it } from "@effect/vitest";
import {
decodeScanCache,
dedupeWithinFile,
encodeScanCache,
pruneScanCache,
type ScanCache,
} from "./usageScanCache.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
return {
provider: "claude",
timestampMs: 1_786_000_000_000,
model: "claude-fable-5",
sessionId: "session-a",
totals: {
uncachedInputTokens: 2,
cachedInputTokens: 1000,
cacheCreationTokens: 10,
outputTokens: 50,
reasoningTokens: 0,
},
reportedCostUsd: null,
dedupeKey: "msg_1:",
...overrides,
};
}
function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]): ScanCache {
const cache: ScanCache = new Map();
for (const [path, mtimeMs, records] of entries) {
cache.set(path, { size: records.length * 10, mtimeMs, provider: "claude", records });
}
return cache;
}
describe("scan cache round trip", () => {
it("restores records unchanged", () => {
const original = cacheWith([
["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5" })]],
["/b.jsonl", 200, [record({ sessionId: "session-b", reportedCostUsd: 1.5 })]],
]);
const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original))));
expect(restored.size).toBe(2);
expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl"));
expect(restored.get("/b.jsonl")).toEqual(original.get("/b.jsonl"));
});
it("interns repeated model and session strings", () => {
const encoded = encodeScanCache(
cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]),
);
expect(encoded.models).toEqual(["claude-fable-5"]);
expect(encoded.sessions).toEqual(["session-a"]);
});
it("treats a corrupt or foreign document as an empty cache", () => {
// A bad cache should cost one cold scan, never a broken page.
expect(decodeScanCache(null).size).toBe(0);
expect(decodeScanCache("nonsense").size).toBe(0);
expect(decodeScanCache({ version: 999, models: [], sessions: [], files: {} }).size).toBe(0);
});
it("skips malformed file entries but keeps good ones", () => {
const encoded = encodeScanCache(cacheWith([["/good.jsonl", 100, [record()]]]));
const withJunk = {
...encoded,
files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } },
};
const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)));
expect([...restored.keys()]).toEqual(["/good.jsonl"]);
});
it("rejects the whole cache when an intern table holds a non-string", () => {
// models: [1] would pass the undefined guard, put a number in a record's
// model, and crash normalizeModelName at aggregate time.
const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
const poisoned = { ...encoded, models: [1] };
expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).size).toBe(0);
});
it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
// Keeping the surviving rows under the original (size, mtime) would read
// as a valid warm hit and the file would never be re-parsed.
const encoded = encodeScanCache(
cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]),
);
const rows = encoded.files["/a.jsonl"]!.r;
const poisoned = {
...encoded,
files: {
"/a.jsonl": {
...encoded.files["/a.jsonl"]!,
r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]],
},
},
};
const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
expect(restored.has("/a.jsonl")).toBe(false);
});
});
describe("pruneScanCache", () => {
const retentionCutoffMs = 1000;
it("drops entries older than retention", () => {
const cache = cacheWith([["/old.jsonl", 500, [record()]]]);
const removed = pruneScanCache(cache, {
livePaths: new Set(),
walkedRoots: ["/"],
windowStartMs: 400,
retentionCutoffMs,
});
expect(removed).toBe(1);
expect(cache.size).toBe(0);
});
it("drops in-window entries whose file has disappeared", () => {
const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]);
pruneScanCache(cache, {
livePaths: new Set(),
walkedRoots: ["/"],
windowStartMs: 4000,
retentionCutoffMs,
});
expect(cache.size).toBe(0);
});
it("keeps entries outside the walked window that are still within retention", () => {
// Viewing 7 days must not evict the 30-day entries, which that walk never
// looked for and so cannot prove are gone.
const cache = cacheWith([["/older-but-valid.jsonl", 2000, [record()]]]);
const removed = pruneScanCache(cache, {
livePaths: new Set(),
walkedRoots: ["/"],
windowStartMs: 4000,
retentionCutoffMs,
});
expect(removed).toBe(0);
expect(cache.size).toBe(1);
});
it("keeps entries the walk saw", () => {
const cache = cacheWith([["/live.jsonl", 5000, [record()]]]);
pruneScanCache(cache, {
livePaths: new Set(["/live.jsonl"]),
walkedRoots: ["/"],
windowStartMs: 4000,
retentionCutoffMs,
});
expect(cache.size).toBe(1);
});
});
describe("pruneScanCache with an unwalked root", () => {
it("keeps in-window entries for a provider whose directory was not walked", () => {
// A missing provider root or failed settings read leaves livePaths without
// that provider's files. Its warm entries must survive the pass.
const cache = cacheWith([["/codex/sessions/a.jsonl", 5000, [record()]]]);
const removed = pruneScanCache(cache, {
livePaths: new Set(),
walkedRoots: ["/claude/projects"],
windowStartMs: 4000,
retentionCutoffMs: 1000,
});
expect(removed).toBe(0);
expect(cache.size).toBe(1);
});
});
describe("dedupeWithinFile", () => {
it("keeps the first record per dedupe key", () => {
const kept = dedupeWithinFile([
record({ totals: { ...record().totals, outputTokens: 1 } }),
record({ totals: { ...record().totals, outputTokens: 999 } }),
record({ dedupeKey: "msg_2:" }),
]);
expect(kept).toHaveLength(2);
expect(kept[0]?.totals.outputTokens).toBe(1);
});
it("keeps every record that has no dedupe key", () => {
expect(
dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]),
).toHaveLength(2);
});
});
+253
View File
@@ -0,0 +1,253 @@
/**
* Durable per-file scan cache.
*
* Transcripts are append-only and a file that has not changed can never yield
* different usage, so parsed records are keyed by `(size, mtime)` and reused.
* Without this every server restart re-parses the whole window: roughly 3.5s
* for a 30-day scan here, against ~11ms to reload this cache.
*
* Caching *per file* rather than per day is deliberate. It is timezone
* independent, so changing the reporting zone does not invalidate anything, and
* it keeps cross-file de-duplication exact: cached entries are de-duplicated
* within their own file only, and the aggregator still applies the global
* dedupe pass over the small surviving key set.
*
* @module usageScanCache
*/
import type { UsageProviderKind } from "@t3tools/contracts";
import type { UsageRecord } from "./usageTranscripts.ts";
export const USAGE_SCAN_CACHE_VERSION = 1 as const;
export interface CachedFile {
readonly size: number;
readonly mtimeMs: number;
readonly provider: UsageProviderKind;
readonly records: readonly UsageRecord[];
}
export type ScanCache = Map<string, CachedFile>;
/**
* Row layout for the serialised form. Positional and interned rather than
* object-per-record: on a 30-day window that is the difference between a file
* measured in tens of megabytes and one under six.
*/
type SerializedRecord = readonly [
timestampMs: number,
modelIndex: number,
sessionIndex: number,
uncachedInputTokens: number,
cachedInputTokens: number,
cacheCreationTokens: number,
outputTokens: number,
reasoningTokens: number,
dedupeKey: string | null,
reportedCostUsd: number | null,
];
interface SerializedFile {
readonly s: number;
readonly m: number;
readonly p: UsageProviderKind;
readonly r: readonly SerializedRecord[];
}
interface SerializedCache {
readonly version: number;
readonly models: readonly string[];
readonly sessions: readonly string[];
readonly files: Readonly<Record<string, SerializedFile>>;
}
/** Serialises the cache, interning the repeated model and session strings. */
export function encodeScanCache(cache: ScanCache): SerializedCache {
const models: string[] = [];
const sessions: string[] = [];
const modelIndex = new Map<string, number>();
const sessionIndex = new Map<string, number>();
const intern = (table: string[], index: Map<string, number>, value: string): number => {
const existing = index.get(value);
if (existing !== undefined) return existing;
const next = table.length;
table.push(value);
index.set(value, next);
return next;
};
const files: Record<string, SerializedFile> = {};
for (const [path, entry] of cache) {
files[path] = {
s: entry.size,
m: entry.mtimeMs,
p: entry.provider,
r: entry.records.map((record) => [
record.timestampMs,
intern(models, modelIndex, record.model),
intern(sessions, sessionIndex, record.sessionId),
record.totals.uncachedInputTokens,
record.totals.cachedInputTokens,
record.totals.cacheCreationTokens,
record.totals.outputTokens,
record.totals.reasoningTokens,
record.dedupeKey,
record.reportedCostUsd,
]),
};
}
return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files };
}
function isRecordArray(value: unknown): value is readonly unknown[] {
return Array.isArray(value);
}
/**
* Rebuilds the cache from a parsed document.
*
* Anything malformed yields an empty cache rather than an error: a corrupt
* cache should cost one cold scan, never a broken page.
*/
export function decodeScanCache(document: unknown): ScanCache {
const cache: ScanCache = new Map();
if (typeof document !== "object" || document === null) return cache;
const root = document as Partial<SerializedCache>;
if (root.version !== USAGE_SCAN_CACHE_VERSION) return cache;
if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
if (typeof root.files !== "object" || root.files === null) return cache;
// The intern tables must be all strings: a numeric entry would pass the
// undefined guard below, land in a record's model, and crash the aggregate
// at normalizeModelName. A corrupt table rejects the whole cache.
if (!root.models.every((value) => typeof value === "string")) return cache;
if (!root.sessions.every((value) => typeof value === "string")) return cache;
const models = root.models as readonly string[];
const sessions = root.sessions as readonly string[];
for (const [path, raw] of Object.entries(root.files)) {
if (typeof raw !== "object" || raw === null) continue;
const entry = raw as Partial<SerializedFile>;
if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
if (entry.p !== "claude" && entry.p !== "codex") continue;
if (!isRecordArray(entry.r)) continue;
const provider: UsageProviderKind = entry.p;
const records: UsageRecord[] = [];
// Any corrupt row disqualifies the whole entry. Keeping the survivors
// under the original (size, mtime) would read as a valid warm hit and the
// file would never be re-parsed, silently losing the dropped rows' usage.
let corrupt = false;
for (const row of entry.r) {
if (!isRecordArray(row) || row.length < 10) {
corrupt = true;
break;
}
const [
timestampMs,
modelIndex,
sessionIndex,
uncached,
cached,
cacheCreation,
output,
reasoning,
dedupeKey,
reportedCostUsd,
] = row as SerializedRecord;
const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
if (
typeof timestampMs !== "number" ||
!Number.isFinite(timestampMs) ||
model === undefined ||
!Number.isFinite(uncached) ||
!Number.isFinite(cached) ||
!Number.isFinite(cacheCreation) ||
!Number.isFinite(output) ||
!Number.isFinite(reasoning)
) {
corrupt = true;
break;
}
records.push({
provider,
timestampMs,
model,
sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
totals: {
uncachedInputTokens: uncached,
cachedInputTokens: cached,
cacheCreationTokens: cacheCreation,
outputTokens: output,
reasoningTokens: reasoning,
},
reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
});
}
if (corrupt) continue;
cache.set(path, { size: entry.s, mtimeMs: entry.m, provider, records });
}
return cache;
}
export interface PruneOptions {
/** Files the walk just saw. Only meaningful inside the walked window. */
readonly livePaths: ReadonlySet<string>;
/**
* Roots the walk actually completed. Absence from `livePaths` only proves a
* file is gone when its root was walked: a provider whose directory failed to
* resolve this pass must not have its warm entries purged.
*/
readonly walkedRoots: readonly string[];
/** Start of the walked window; entries older than this were not looked for. */
readonly windowStartMs: number;
/** Entries older than this are dropped regardless. */
readonly retentionCutoffMs: number;
}
/**
* Drops aged-out entries, and entries for files that have disappeared.
*
* The walk only covers the requested window, so absence from `livePaths` only
* proves deletion for entries *inside* that window. Pruning everything the walk
* missed would evict the 30-day entries every time someone looked at 7 days.
*
* Replaces an earlier record cap that cleared the whole cache once exceeded,
* which meant a large enough window never warmed up at all.
*/
export function pruneScanCache(cache: ScanCache, options: PruneOptions): number {
let removed = 0;
for (const [path, entry] of cache) {
const agedOut = entry.mtimeMs < options.retentionCutoffMs;
const underWalkedRoot = options.walkedRoots.some((root) => path.startsWith(root));
const deleted =
underWalkedRoot && entry.mtimeMs >= options.windowStartMs && !options.livePaths.has(path);
if (agedOut || deleted) {
cache.delete(path);
removed += 1;
}
}
return removed;
}
/** Within-file de-duplication, applied before an entry is cached. */
export function dedupeWithinFile(records: readonly UsageRecord[]): readonly UsageRecord[] {
const seen = new Set<string>();
const kept: UsageRecord[] = [];
for (const record of records) {
if (record.dedupeKey !== null) {
if (seen.has(record.dedupeKey)) continue;
seen.add(record.dedupeKey);
}
kept.push(record);
}
return kept;
}
@@ -0,0 +1,141 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Raw filesystem access for transcript scanning.
*
* Isolated here so the rest of the usage code stays on Effect's `FileSystem`.
* The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB
* across ~1,500 files, and `readline` over a read stream is roughly an order of
* magnitude cheaper than materialising each file. The equivalent Effect stream
* pipeline is idiomatic but not fast enough to sit behind a page load.
*
* @module usageTranscriptReader
*/
import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import * as NodeReadline from "node:readline";
import type { UsageProviderKind } from "@t3tools/contracts";
import {
initialCodexScanState,
mightCarryUsage,
parseClaudeLine,
parseCodexLine,
type UsageRecord,
} from "./usageTranscripts.ts";
export interface TranscriptFile {
readonly path: string;
readonly size: number;
readonly mtimeMs: number;
}
/**
* Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
*
* Errors on individual entries are swallowed: session files rotate and get
* removed while the walk is in flight, and a partial listing is far better than
* failing the page.
*/
export async function listTranscriptFiles(
root: string,
sinceMs: number,
): Promise<readonly TranscriptFile[]> {
const found: TranscriptFile[] = [];
const walk = async (dir: string): Promise<void> => {
let entries;
try {
entries = await NodeFSP.readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const child = NodePath.join(dir, entry.name);
if (entry.isDirectory()) {
await walk(child);
continue;
}
if (!entry.name.endsWith(".jsonl")) continue;
try {
const stats = await NodeFSP.stat(child);
if (stats.mtimeMs >= sinceMs) {
found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });
}
} catch {
// Vanished between readdir and stat.
}
}
};
await walk(root);
return found;
}
/**
* Filesystem identity of a directory, as `device:inode`.
*
* Used to tell "two servers reading the same transcript directory" apart from
* "two machines whose hostname and home path happen to match". Returns an empty
* string when the directory cannot be stat'd.
*/
export async function readDirectoryVolumeId(path: string): Promise<string> {
try {
const stats = await NodeFSP.stat(path);
return `${stats.dev}:${stats.ino}`;
} catch {
return "";
}
}
/**
* Streams one transcript and returns the usage records it contains, or `null`
* when the file could not be read.
*
* The distinction matters to the caller's cache: a genuinely empty transcript
* is a stable fact worth memoising, while a transient read failure memoised
* under the same `(size, mtime)` key would silently drop that file's usage
* until the file next changes.
*
* Codex carries the active model on `turn_context` lines that hold no usage of
* their own, so those still have to pass through the reducer to keep model
* attribution correct.
*/
export async function readTranscriptRecords(
filePath: string,
provider: UsageProviderKind,
): Promise<readonly UsageRecord[] | null> {
const records: UsageRecord[] = [];
const codexState = initialCodexScanState();
try {
const lines = NodeReadline.createInterface({
input: NodeFS.createReadStream(filePath, { encoding: "utf8" }),
crlfDelay: Infinity,
});
for await (const line of lines) {
if (provider === "codex") {
if (
!mightCarryUsage(line, provider) &&
!line.includes('"turn_context"') &&
!line.includes('"session_meta"')
) {
continue;
}
const record = parseCodexLine(line, codexState);
if (record !== null) records.push(record);
continue;
}
if (!mightCarryUsage(line, provider)) continue;
const record = parseClaudeLine(line);
if (record !== null) records.push(record);
}
} catch {
return null;
}
return records;
}
@@ -0,0 +1,151 @@
import { describe, expect, it } from "@effect/vitest";
import {
initialCodexScanState,
parseClaudeLine,
parseCodexLine,
totalTokens,
} from "./usageTranscripts.ts";
/** Shaped after a real Claude Code assistant record. */
function claudeLine(overrides: {
messageId: string;
contentType: string;
model?: string;
outputTokens?: number;
}): string {
return JSON.stringify({
type: "assistant",
timestamp: "2026-08-07T04:05:13.944Z",
sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0",
cwd: "/home/theo/project",
message: {
id: overrides.messageId,
role: "assistant",
model: overrides.model ?? "claude-fable-5",
content: [{ type: overrides.contentType }],
usage: {
input_tokens: 2,
cache_creation_input_tokens: 66818,
cache_read_input_tokens: 1000,
output_tokens: overrides.outputTokens ?? 286,
},
},
});
}
describe("parseClaudeLine", () => {
it("extracts token totals and a dedupe key", () => {
const record = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" }));
expect(record).not.toBeNull();
expect(record?.provider).toBe("claude");
expect(record?.model).toBe("claude-fable-5");
expect(record?.totals).toEqual({
uncachedInputTokens: 2,
cachedInputTokens: 1000,
cacheCreationTokens: 66818,
outputTokens: 286,
reasoningTokens: 0,
});
expect(record?.dedupeKey).toBe("msg_1:");
});
it("gives every content block of one message the same dedupe key", () => {
// T3 Code writes one record per content block, each repeating the parent
// message's full usage. Summing them would overcount ~2.4x on real data.
const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" }));
const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" }));
expect(text?.dedupeKey).toBe(toolUse?.dedupeKey);
expect(text?.totals).toEqual(toolUse?.totals);
});
it("ignores records that are not assistant messages", () => {
expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull();
expect(parseClaudeLine("not json")).toBeNull();
});
});
describe("parseCodexLine", () => {
const sessionMeta = JSON.stringify({
type: "session_meta",
timestamp: "2026-08-01T05:17:41.289Z",
payload: { type: "session_meta", id: "019fbbc1-b12c-7360-a685-28c181f0025f" },
});
const turnContext = JSON.stringify({
type: "turn_context",
timestamp: "2026-08-01T05:17:42.694Z",
payload: { type: "turn_context", model: "gpt-5.6-sol" },
});
const tokenCount = (inputTokens: number, cached: number, output: number, reasoning: number) =>
JSON.stringify({
type: "event_msg",
timestamp: "2026-08-01T05:17:49.919Z",
payload: {
type: "token_count",
info: {
last_token_usage: {
input_tokens: inputTokens,
cached_input_tokens: cached,
cache_write_input_tokens: 0,
output_tokens: output,
reasoning_output_tokens: reasoning,
},
},
},
});
it("attributes usage to the model from the preceding turn context", () => {
const state = initialCodexScanState();
parseCodexLine(sessionMeta, state);
parseCodexLine(turnContext, state);
const record = parseCodexLine(tokenCount(19239, 11008, 299, 116), state);
expect(record?.provider).toBe("codex");
expect(record?.model).toBe("gpt-5.6-sol");
expect(record?.sessionId).toBe("019fbbc1-b12c-7360-a685-28c181f0025f");
// Codex reports input_tokens inclusive of the cached portion.
expect(record?.totals.uncachedInputTokens).toBe(19239 - 11008);
expect(record?.totals.cachedInputTokens).toBe(11008);
expect(record?.totals.reasoningTokens).toBe(116);
});
it("skips a repeated token_count so deltas are not double counted", () => {
const state = initialCodexScanState();
parseCodexLine(turnContext, state);
const first = parseCodexLine(tokenCount(100, 0, 10, 0), state);
const repeat = parseCodexLine(tokenCount(100, 0, 10, 0), state);
expect(first).not.toBeNull();
expect(repeat).toBeNull();
});
it("drops usage that arrives before any model is known", () => {
const state = initialCodexScanState();
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
});
it("does not let a pre-model event poison the duplicate signature", () => {
// A token_count before its turn_context is dropped; the identical event
// re-emitted once the model is known must still be counted.
const state = initialCodexScanState();
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
parseCodexLine(turnContext, state);
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
});
});
describe("totalTokens", () => {
it("does not add reasoning on top of output", () => {
expect(
totalTokens({
uncachedInputTokens: 10,
cachedInputTokens: 20,
cacheCreationTokens: 30,
outputTokens: 40,
reasoningTokens: 25,
}),
).toBe(100);
});
});
+246
View File
@@ -0,0 +1,246 @@
/**
* Pure parsers for the provider CLIs' on-disk session transcripts.
*
* Both parsers are line-at-a-time reducers so callers can stream large files
* without materialising them. Neither touches the filesystem.
*
* @module usageTranscripts
*/
import type { UsageProviderKind, UsageTokenTotals } from "@t3tools/contracts";
export interface UsageRecord {
readonly provider: UsageProviderKind;
readonly timestampMs: number;
readonly model: string;
readonly sessionId: string;
readonly totals: UsageTokenTotals;
readonly reportedCostUsd: number | null;
/**
* Key for cross-file de-duplication, or `null` when the record is inherently
* unique and needs no dedup.
*/
readonly dedupeKey: string | null;
}
const EMPTY_TOTALS: UsageTokenTotals = {
uncachedInputTokens: 0,
cachedInputTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
reasoningTokens: 0,
};
function int(value: unknown): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
}
function parseTimestampMs(value: unknown): number | null {
if (typeof value !== "string") return null;
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? null : parsed;
}
export function addTotals(a: UsageTokenTotals, b: UsageTokenTotals): UsageTokenTotals {
return {
uncachedInputTokens: a.uncachedInputTokens + b.uncachedInputTokens,
cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,
cacheCreationTokens: a.cacheCreationTokens + b.cacheCreationTokens,
outputTokens: a.outputTokens + b.outputTokens,
reasoningTokens: a.reasoningTokens + b.reasoningTokens,
};
}
export function totalTokens(totals: UsageTokenTotals): number {
// reasoningTokens is a subset of outputTokens and must not be added again.
return (
totals.uncachedInputTokens +
totals.cachedInputTokens +
totals.cacheCreationTokens +
totals.outputTokens
);
}
/**
* Cheap substring gate applied before `JSON.parse`.
*
* Transcripts are mostly tool output; only a minority of lines carry usage. On
* a 30-day window this skips roughly half the lines outright and is worth about
* an order of magnitude.
*/
export function mightCarryUsage(line: string, provider: UsageProviderKind): boolean {
return provider === "claude" ? line.includes('"usage"') : line.includes('"token_count"');
}
/* -------------------------------------------------------------------------- */
/* Claude Code */
/* -------------------------------------------------------------------------- */
/**
* Parses one line of a Claude Code transcript.
*
* T3 Code writes one record per assistant *content block*, and every one of
* those records repeats the same complete `usage` object for the parent
* message. Summing them overcounts by roughly 2.4x on a real workload, so the
* caller must drop repeats by `dedupeKey` and keep the first.
*/
export function parseClaudeLine(line: string): UsageRecord | null {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
return null;
}
if (typeof parsed !== "object" || parsed === null) return null;
const record = parsed as Record<string, unknown>;
if (record["type"] !== "assistant") return null;
const message = record["message"];
if (typeof message !== "object" || message === null) return null;
const messageRecord = message as Record<string, unknown>;
const usage = messageRecord["usage"];
if (typeof usage !== "object" || usage === null) return null;
const usageRecord = usage as Record<string, unknown>;
const timestampMs = parseTimestampMs(record["timestamp"]);
if (timestampMs === null) return null;
const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : "";
if (model.length === 0) return null;
const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null;
const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null;
// Matches ccusage: prefer the message/request pair, fall back to whichever
// half exists. Records with neither cannot be de-duplicated.
const dedupeKey =
messageId === null && requestId === null ? null : `${messageId ?? ""}:${requestId ?? ""}`;
const cost = record["costUSD"];
return {
provider: "claude",
timestampMs,
model,
sessionId: typeof record["sessionId"] === "string" ? record["sessionId"] : "",
totals: {
uncachedInputTokens: int(usageRecord["input_tokens"]),
cachedInputTokens: int(usageRecord["cache_read_input_tokens"]),
cacheCreationTokens: int(usageRecord["cache_creation_input_tokens"]),
outputTokens: int(usageRecord["output_tokens"]),
// Anthropic folds thinking tokens into output and does not break them out.
reasoningTokens: 0,
},
reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null,
dedupeKey,
};
}
/* -------------------------------------------------------------------------- */
/* Codex */
/* -------------------------------------------------------------------------- */
/**
* Rolling state for a single Codex rollout file.
*
* Codex `token_count` events carry no model, so the model is carried forward
* from the most recent `turn_context`. Sessions that switch models mid-run
* attribute correctly from the switch onward.
*/
export interface CodexScanState {
model: string;
sessionId: string;
lastUsageSignature: string | null;
}
export function initialCodexScanState(): CodexScanState {
return { model: "", sessionId: "", lastUsageSignature: null };
}
/**
* Feeds one line of a Codex rollout into `state`, returning a record when the
* line was a usage event.
*
* Deltas come from `last_token_usage`. Summing those across a session
* reconciles with the session's final `total_token_usage`, provided
* consecutive duplicate events are dropped, which this does.
*/
export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
return null;
}
if (typeof parsed !== "object" || parsed === null) return null;
const record = parsed as Record<string, unknown>;
const payload = record["payload"];
if (typeof payload !== "object" || payload === null) return null;
const payloadRecord = payload as Record<string, unknown>;
const payloadType = payloadRecord["type"];
if (record["type"] === "session_meta") {
const id = payloadRecord["id"] ?? payloadRecord["session_id"];
if (typeof id === "string") state.sessionId = id;
return null;
}
if (record["type"] === "turn_context") {
if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
return null;
}
if (payloadType !== "token_count") return null;
const info = payloadRecord["info"];
if (typeof info !== "object" || info === null) return null;
const last = (info as Record<string, unknown>)["last_token_usage"];
if (typeof last !== "object" || last === null) return null;
const lastRecord = last as Record<string, unknown>;
// Only an event that is otherwise eligible may consume the duplicate
// signature. A token_count arriving before its turn_context (no model yet)
// must not poison it, or the re-emitted copy after the model is known would
// be skipped as a duplicate and those tokens never counted.
const timestampMs = parseTimestampMs(record["timestamp"]);
if (timestampMs === null) return null;
if (state.model.length === 0) return null;
// Codex re-emits an unchanged token_count on some stream boundaries. Summing
// those would double count, so identical consecutive payloads are skipped.
const signature = JSON.stringify(lastRecord);
if (signature === state.lastUsageSignature) return null;
state.lastUsageSignature = signature;
const inputTokens = int(lastRecord["input_tokens"]);
const cachedInputTokens = int(lastRecord["cached_input_tokens"]);
const cacheCreationTokens = int(lastRecord["cache_write_input_tokens"]);
const outputTokens = int(lastRecord["output_tokens"]);
const totals: UsageTokenTotals = {
// Codex reports `input_tokens` inclusive of the cached portion.
uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
cachedInputTokens,
cacheCreationTokens,
outputTokens,
// Reported inside output_tokens, surfaced separately for the token mix.
reasoningTokens: Math.min(outputTokens, int(lastRecord["reasoning_output_tokens"])),
};
if (totalTokens(totals) === 0) return null;
return {
provider: "codex",
timestampMs,
model: state.model,
sessionId: state.sessionId,
totals,
// Codex does not report cost in the rollout.
reportedCostUsd: null,
// Rollout files are unique per session, so events need no global dedup.
dedupeKey: null,
};
}
export { EMPTY_TOTALS };
+65 -29
View File
@@ -105,6 +105,7 @@ import { requiredScopeForRpcMethod } from "./auth/RpcAuthorization.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
@@ -412,6 +413,7 @@ const makeWsRpcLayer = (
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;
const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry;
const usage = yield* UsageService.UsageService;
const relayClient = yield* RelayClient.RelayClient;
const authorizationError = (requiredScope: AuthEnvironmentScope) =>
new EnvironmentAuthorizationError({
@@ -1034,53 +1036,83 @@ const makeWsRpcLayer = (
ORCHESTRATION_WS_METHODS.dispatchCommand,
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
const shouldStopSessionAfterArchive =
normalizedCommand.type === "thread.archive"
? yield* projectionSnapshotQuery
.getThreadShellById(normalizedCommand.threadId)
.pipe(
Effect.map(
Option.match({
onNone: () => false,
onSome: (thread) =>
thread.session !== null && thread.session.status !== "stopped",
}),
),
Effect.orElseSucceed(() => false),
)
: false;
// Archive and settle both mean "done with this thread", so a
// live provider session must not keep running background work
// (PR monitors, dev servers, subagent fleets) after either
// lands. The decider rejects settling a starting/running
// session, so for settle this only ever stops an idle one; a
// stopped session-set does not count as activity, so the stop
// cannot un-settle the thread it follows.
const parkingCommand =
normalizedCommand.type === "thread.archive" ||
normalizedCommand.type === "thread.settle"
? normalizedCommand
: undefined;
// Best-effort on purpose: the user's archive/settle must not
// fail because this cleanup read blipped, so a failed read
// logs and skips the stop instead of propagating.
const shouldStopSessionAfterCommand = parkingCommand
? yield* projectionSnapshotQuery.getThreadShellById(parkingCommand.threadId).pipe(
Effect.map(
Option.match({
onNone: () => false,
onSome: (thread) =>
thread.session !== null && thread.session.status !== "stopped",
}),
),
Effect.catchCause((cause) =>
Effect.logWarning(
"failed to read thread session state before session-stop check",
{ threadId: parkingCommand.threadId, cause },
).pipe(Effect.as(false)),
),
)
: false;
const result = yield* dispatchNormalizedCommand(normalizedCommand);
if (normalizedCommand.type === "thread.archive") {
if (shouldStopSessionAfterArchive) {
if (parkingCommand) {
const parkingKind = parkingCommand.type === "thread.archive" ? "archive" : "settle";
if (shouldStopSessionAfterCommand) {
yield* Effect.gen(function* () {
const stopCommand = yield* normalizeDispatchCommand({
type: "thread.session.stop",
commandId: CommandId.make(
`session-stop-for-archive:${normalizedCommand.commandId}`,
`session-stop-for-${parkingKind}:${parkingCommand.commandId}`,
),
threadId: normalizedCommand.threadId,
threadId: parkingCommand.threadId,
createdAt: yield* nowIso,
// A settled thread can be re-engaged before this stop is
// decided; the decider then drops the stop instead of
// killing the new session. Archive stops stay
// unconditional: turn starts on archived threads are
// rejected, so there is no new session to protect.
...(parkingKind === "settle" ? { onlyIfSettled: true } : {}),
});
yield* dispatchNormalizedCommand(stopCommand);
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("failed to stop provider session during archive", {
threadId: normalizedCommand.threadId,
Effect.logWarning(`failed to stop provider session during ${parkingKind}`, {
threadId: parkingCommand.threadId,
cause,
}),
),
);
}
yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close thread terminals after archive", {
threadId: normalizedCommand.threadId,
error: error.message,
}),
),
);
// Terminals are user-opened panes, not thread background
// work: archive removes the thread from view so they close
// with it, but a settled thread stays reachable and may be
// un-settled, so its terminals stay up.
if (parkingCommand.type === "thread.archive") {
yield* terminalManager.close({ threadId: parkingCommand.threadId }).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close thread terminals after archive", {
threadId: parkingCommand.threadId,
error: error.message,
}),
),
);
}
}
return result;
}).pipe(
@@ -1529,6 +1561,10 @@ const makeWsRpcLayer = (
"rpc.aggregate": "server",
},
),
[WS_METHODS.serverGetUsageSummary]: (input) =>
observeRpcEffect(WS_METHODS.serverGetUsageSummary, usage.readSummary(input), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverRetryResourceTelemetry]: (_input) =>
observeRpcEffect(WS_METHODS.serverRetryResourceTelemetry, resourceTelemetry.retry, {
"rpc.aggregate": "server",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.31",
"version": "0.0.32",
"private": true,
"type": "module",
"scripts": {
Loaded 100 of 218 files, more files were not shown because too many files have changed in this diff. Show more