Compare commits

...
Author SHA1 Message Date
Theo Browne 83b003fa98 Merge branch 'main' into t3bot/streaming-projection-performance 2026-08-08 08:53: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
t3-code[bot] f483b694c0 fix(server): let forked reactors subscribe before dispatch 2026-08-07 20:57:49 +00:00
t3-code[bot] dbd8189dca chore(server): address effect review feedback 2026-08-07 20:35:33 +00:00
t3-code[bot] b56272397e perf(server): reduce streaming projection overhead 2026-08-07 20:24:33 +00: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
114 changed files with 14468 additions and 8140 deletions

No files matched your search

+2
View File
@@ -11,6 +11,7 @@
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chrisdeeming
github:chuks-qua
github:cursoragent
github:gbarros-dev
@@ -26,6 +27,7 @@ github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:StiensWout
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
@@ -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) =>
@@ -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}
@@ -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>
);
}
@@ -25,6 +25,7 @@ import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import {
buildModelOptions,
groupByProvider,
resolveDefaultableModelSelection,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { scopedProjectKey } from "../../lib/scopedEntities";
@@ -147,7 +148,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;
@@ -359,14 +363,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 +410,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 +421,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: option.selection,
modelSelection: options ? { ...option.selection, options } : option.selection,
});
},
[modelOptions, selectedProjectDraftKey],
@@ -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);
});
});
@@ -103,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(
@@ -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;
}
+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,
+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<
@@ -1177,6 +1177,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const streamingAt = "2026-01-01T00:00:01.000Z";
yield* eventStore.append({
type: "project.created",
@@ -1254,7 +1255,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
eventId: EventId.make("evt-a4"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-a"),
occurredAt: now,
occurredAt: streamingAt,
commandId: CommandId.make("cmd-a4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-a4"),
@@ -1266,8 +1267,8 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
text: " world",
turnId: null,
streaming: true,
createdAt: now,
updatedAt: now,
createdAt: streamingAt,
updatedAt: streamingAt,
},
});
@@ -1279,6 +1280,13 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
`;
assert.deepEqual(messageRows, [{ text: "hello world" }]);
const threadRows = yield* sql<{ readonly updatedAt: string }>`
SELECT updated_at AS "updatedAt"
FROM projection_threads
WHERE thread_id = 'thread-a'
`;
assert.deepEqual(threadRows, [{ updatedAt: streamingAt }]);
const stateRows = yield* sql<{
readonly projector: string;
readonly lastAppliedSequence: number;
@@ -842,7 +842,30 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.message-sent":
case "thread.message-sent": {
// The thread websocket already carries the incremental message event.
// Keep activity ordering current without rebuilding the list-view shell.
if (event.payload.role === "assistant" && event.payload.streaming) {
yield* projectionThreadRepository.touchUpdatedAt({
threadId: event.payload.threadId,
updatedAt: event.occurredAt,
});
return;
}
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
updatedAt: event.occurredAt,
});
yield* refreshThreadShellSummary(event.payload.threadId);
return;
}
case "thread.proposed-plan-upserted":
case "thread.activity-appended":
case "thread.approval-response-requested":
@@ -942,22 +965,31 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.message-sent": {
if (event.payload.streaming) {
const attachments =
event.payload.attachments !== undefined
? yield* materializeAttachmentsForProjection({
attachments: event.payload.attachments,
})
: undefined;
yield* projectionThreadMessageRepository.appendStreaming({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
turnId: event.payload.turnId,
role: event.payload.role,
text: event.payload.text,
...(attachments !== undefined ? { attachments: [...attachments] } : {}),
isStreaming: true,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
return;
}
const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({
messageId: event.payload.messageId,
});
const previousMessage = Option.getOrUndefined(existingMessage);
const nextText = Option.match(existingMessage, {
onNone: () => event.payload.text,
onSome: (message) => {
if (event.payload.streaming) {
return `${message.text}${event.payload.text}`;
}
if (event.payload.text.length === 0) {
return message.text;
}
return event.payload.text;
},
});
const nextAttachments =
event.payload.attachments !== undefined
? yield* materializeAttachmentsForProjection({
@@ -969,9 +1001,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
threadId: event.payload.threadId,
turnId: event.payload.turnId,
role: event.payload.role,
text: nextText,
text:
event.payload.text.length === 0 ? (previousMessage?.text ?? "") : event.payload.text,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
isStreaming: event.payload.streaming,
isStreaming: false,
createdAt: previousMessage?.createdAt ?? event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
@@ -1293,8 +1326,21 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
if (event.payload.turnId === null || event.payload.role !== "assistant") {
return;
}
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
});
// The first chunk attaches the assistant message to the turn. Later
// chunks do not change turn state, so avoid rewriting it per token.
if (
event.payload.streaming &&
Option.isSome(existingTurn) &&
existingTurn.value.assistantMessageId === event.payload.messageId
) {
return;
}
// A completed assistant message only settles the turn once the
// session is no longer running it — providers may emit several
// session is no longer running it. Providers may emit several
// assistant messages per turn (commentary between tool calls), and
// the turn must stay unsettled until the provider reports turn end
// (projected as thread.session-set leaving the "running" status).
@@ -1306,10 +1352,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
session.value.status === "running" &&
session.value.activeTurnId === event.payload.turnId;
const settlesTurn = !event.payload.streaming && !turnStillRunning;
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
});
if (Option.isSome(existingTurn)) {
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
@@ -1686,18 +1728,51 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
),
);
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
concurrency: 1,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ServerConfig, serverConfig),
Effect.asVoid,
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
),
);
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) => {
const attachmentSideEffects: AttachmentSideEffects = {
deletedThreadIds: new Set<string>(),
prunedThreadRelativePaths: new Map<string, Set<string>>(),
};
return sql
.withTransaction(
Effect.forEach(
projectors,
(projector) =>
projector.apply(event, attachmentSideEffects).pipe(
Effect.flatMap(() =>
projectionStateRepository.upsert({
projector: projector.name,
lastAppliedSequence: event.sequence,
updatedAt: event.occurredAt,
}),
),
),
{ concurrency: 1 },
),
)
.pipe(
Effect.flatMap(() =>
runAttachmentSideEffects(attachmentSideEffects).pipe(
Effect.catch((cause) =>
Effect.logWarning("failed to apply projected attachment side-effects", {
sequence: event.sequence,
eventType: event.type,
cause,
}),
),
),
),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ServerConfig, serverConfig),
Effect.asVoid,
Effect.catchTags({
SqlError: (sqlError) =>
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
}),
);
};
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
projectors,
@@ -2199,7 +2199,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 +2306,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(
@@ -1655,7 +1655,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 +1691,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"
@@ -66,6 +66,45 @@ layer("ProjectionThreadMessageRepository", (it) => {
}),
);
it.effect("atomically appends streaming text and preserves the original creation time", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.make("thread-streaming-append");
const messageId = MessageId.make("message-streaming-append");
const createdAt = "2026-02-28T19:05:00.000Z";
yield* repository.appendStreaming({
messageId,
threadId,
turnId: null,
role: "assistant",
text: "hello",
isStreaming: true,
createdAt,
updatedAt: createdAt,
});
yield* repository.appendStreaming({
messageId,
threadId,
turnId: null,
role: "assistant",
text: " world",
isStreaming: true,
createdAt: "2026-02-28T19:05:01.000Z",
updatedAt: "2026-02-28T19:05:01.000Z",
});
const row = yield* repository.getByMessageId({ messageId });
assert.equal(row._tag, "Some");
if (row._tag === "Some") {
assert.equal(row.value.text, "hello world");
assert.equal(row.value.createdAt, createdAt);
assert.equal(row.value.updatedAt, "2026-02-28T19:05:01.000Z");
assert.isTrue(row.value.isStreaming);
}
}),
);
it.effect("allows explicit attachment clearing with an empty array", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
@@ -95,6 +95,50 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
},
});
const appendStreamingProjectionThreadMessageRow = SqlSchema.void({
Request: ProjectionThreadMessage,
execute: (row) => {
const nextAttachmentsJson =
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
return sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
attachments_json,
is_streaming,
created_at,
updated_at
)
VALUES (
${row.messageId},
${row.threadId},
${row.turnId},
${row.role},
${row.text},
${nextAttachmentsJson},
1,
${row.createdAt},
${row.updatedAt}
)
ON CONFLICT (message_id)
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
role = excluded.role,
text = projection_thread_messages.text || excluded.text,
attachments_json = COALESCE(
excluded.attachments_json,
projection_thread_messages.attachments_json
),
is_streaming = 1,
updated_at = excluded.updated_at
`;
},
});
const getProjectionThreadMessageRow = SqlSchema.findOneOption({
Request: GetProjectionThreadMessageInput,
Result: ProjectionThreadMessageDbRowSchema,
@@ -151,6 +195,13 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")),
);
const appendStreaming: ProjectionThreadMessageRepositoryShape["appendStreaming"] = (row) =>
appendStreamingProjectionThreadMessageRow(row).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.appendStreaming:query"),
),
);
const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
getProjectionThreadMessageRow(input).pipe(
Effect.mapError(
@@ -176,6 +227,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
return {
upsert,
appendStreaming,
getByMessageId,
listByThreadId,
deleteByThreadId,
@@ -12,6 +12,7 @@ import {
ListProjectionThreadsByProjectInput,
ProjectionThread,
ProjectionThreadRepository,
TouchProjectionThreadInput,
type ProjectionThreadRepositoryShape,
} from "../Services/ProjectionThreads.ts";
import { ModelSelection } from "@t3tools/contracts";
@@ -149,6 +150,16 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
`,
});
const touchProjectionThreadRow = SqlSchema.void({
Request: TouchProjectionThreadInput,
execute: ({ threadId, updatedAt }) =>
sql`
UPDATE projection_threads
SET updated_at = ${updatedAt}
WHERE thread_id = ${threadId}
`,
});
const listProjectionThreadRows = SqlSchema.findAll({
Request: ListProjectionThreadsByProjectInput,
Result: ProjectionThreadDbRow,
@@ -205,6 +216,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.getById:query")),
);
const touchUpdatedAt: ProjectionThreadRepositoryShape["touchUpdatedAt"] = (input) =>
touchProjectionThreadRow(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.touchUpdatedAt:query")),
);
const listByProjectId: ProjectionThreadRepositoryShape["listByProjectId"] = (input) =>
listProjectionThreadRows(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.listByProjectId:query")),
@@ -218,6 +234,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
return {
upsert,
getById,
touchUpdatedAt,
listByProjectId,
deleteById,
} satisfies ProjectionThreadRepositoryShape;
@@ -62,6 +62,13 @@ export interface ProjectionThreadMessageRepositoryShape {
message: ProjectionThreadMessage,
) => Effect.Effect<void, ProjectionRepositoryError>;
/**
* Insert a streaming message or atomically append text to its existing row.
*/
readonly appendStreaming: (
message: ProjectionThreadMessage,
) => Effect.Effect<void, ProjectionRepositoryError>;
/**
* Read a projected thread message by id.
*/
@@ -63,6 +63,12 @@ export const DeleteProjectionThreadInput = Schema.Struct({
});
export type DeleteProjectionThreadInput = typeof DeleteProjectionThreadInput.Type;
export const TouchProjectionThreadInput = Schema.Struct({
threadId: ThreadId,
updatedAt: IsoDateTime,
});
export type TouchProjectionThreadInput = typeof TouchProjectionThreadInput.Type;
export const ListProjectionThreadsByProjectInput = Schema.Struct({
projectId: ProjectId,
});
@@ -86,6 +92,11 @@ export interface ProjectionThreadRepositoryShape {
input: GetProjectionThreadInput,
) => Effect.Effect<Option.Option<ProjectionThread>, ProjectionRepositoryError>;
/** Update only the activity timestamp without rewriting the thread shell. */
readonly touchUpdatedAt: (
input: TouchProjectionThreadInput,
) => Effect.Effect<void, ProjectionRepositoryError>;
/**
* List projected threads for a project.
*
@@ -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", {
+2
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";
@@ -825,6 +826,7 @@ const buildAppUnderTest = (options?: {
const appLayer = servedRoutesLayer.pipe(
Layer.provide(resourceTelemetryLayer),
Layer.provide(UsageService.layerTest),
Layer.provide(
Layer.mock(BrowserTraceCollector.BrowserTraceCollector)({
record: () => Effect.void,
+4
View File
@@ -101,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,
@@ -158,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)),
@@ -410,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),
+12
View File
@@ -21,3 +21,15 @@ it.effect("proves a root is parked before returning and releases it with one gat
}),
),
);
it.effect("lets an unparked child start before returning", () =>
Effect.scoped(
Effect.gen(function* () {
const started = yield* Deferred.make<void>();
yield* forkParked(Deferred.succeed(started, undefined));
expect(yield* Deferred.isDone(started)).toBe(true);
}),
),
);
+3
View File
@@ -16,6 +16,9 @@ export const forkParked = <A, E, R>(
const activation = yield* ServerActivation;
if (activation === undefined) {
yield* Effect.forkScoped(effect);
// Let the child reach its first suspension point before startup continues.
// Hot-stream consumers use this turn to establish their subscription.
yield* Effect.yieldNow;
return;
}
const parked = yield* Deferred.make<void>();
+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 };
+6
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({
@@ -1529,6 +1531,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",
+11
View File
@@ -11,6 +11,7 @@ import {
cssFontFamilies,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
resolveTerminalFontSizePreference,
} from "./appearanceFonts";
describe("areFontAdvancesMonospace", () => {
@@ -97,6 +98,16 @@ describe("resolveTerminalFontPreference", () => {
});
});
describe("resolveTerminalFontSizePreference", () => {
it("inherits the code font size in simple mode", () => {
expect(resolveTerminalFontSizePreference({ advanced: false, code: 15, terminal: 12 })).toBe(15);
});
it("keeps code and terminal font sizes independent in advanced mode", () => {
expect(resolveTerminalFontSizePreference({ advanced: true, code: 15, terminal: 12 })).toBe(12);
});
});
describe("font size clamping", () => {
it("keeps sizes inside the ranges the UI can absorb", () => {
expect(clampInterfaceFontSize(16)).toBe(16);
+9
View File
@@ -41,6 +41,15 @@ export function resolveTerminalFontPreference(input: {
return input.code;
}
export function resolveTerminalFontSizePreference(input: {
readonly advanced: boolean;
readonly code: number;
readonly terminal: number;
}): number {
if (input.advanced) return input.terminal;
return input.code;
}
function quoteFontFamilyName(name: string): string {
const bare = name.trim();
if (bare.length === 0) return "";
-45
View File
@@ -11,51 +11,6 @@ export function formatAppDisplayName(input: {
return `${input.baseName} (${input.stageLabel})`;
}
/**
* Whether the sidebar v2 beta is on by default for a build stage.
*
* Nightly and local dev opt in; Alpha and Latest stay on v1. This is resolved
* from the client's own stage label rather than the connected server's version:
* v2 only exists in the client, so a stable client on a nightly server has
* nothing to turn on.
*/
export function resolveSidebarV2Default(stageLabel: string): boolean {
const stage = stageLabel.trim().toLowerCase();
return stage === "nightly" || stage === "dev";
}
/**
* Resolved sidebar v2 state: an explicit choice if the user has made one,
* otherwise the default for this build stage.
*
* A stored `enabled: true` counts as an explicit choice even without the
* companion flag. `true` was never the schema default, so it can only have come
* from the Settings → Beta toggle — settings written before that flag existed
* would otherwise lose the opt-in and drop such users back to v1 on production.
* Mirrors how `normalizeDesktopSettingsDocument` treats a legacy stored
* `updateChannel: "nightly"` as user-configured.
*
* `settingsHydrated` guards the startup window: client settings load
* asynchronously and the pre-hydration snapshot is just the schema defaults, so
* resolving against it would mount one sidebar and swap it out a tick later,
* remounting the tree. While hydrating, hold v1 — where both paths already
* start.
*/
export function resolveSidebarV2Enabled(input: {
readonly enabled: boolean;
readonly configuredByUser: boolean;
readonly settingsHydrated: boolean;
readonly stageLabel: string;
}): boolean {
if (!input.settingsHydrated) {
return false;
}
return input.configuredByUser || input.enabled
? input.enabled
: resolveSidebarV2Default(input.stageLabel);
}
export function resolveServerBackedAppStageLabel(input: {
readonly primaryServerVersion: string | null | undefined;
readonly fallbackStageLabel: string;
-73
View File
@@ -2,8 +2,6 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
resolveServerBackedAppDisplayName,
resolveServerBackedAppStageLabel,
resolveSidebarV2Default,
resolveSidebarV2Enabled,
} from "./branding.logic";
const originalWindow = globalThis.window;
@@ -116,74 +114,3 @@ describe("branding logic", () => {
).toBe("T3 Code (Alpha)");
});
});
describe("resolveSidebarV2Default", () => {
it.each(["Nightly", "Dev", "nightly", " dev "])("enables the beta for %s builds", (stage) => {
expect(resolveSidebarV2Default(stage)).toBe(true);
});
it.each(["Alpha", "Latest", ""])("leaves the beta off for %s builds", (stage) => {
expect(resolveSidebarV2Default(stage)).toBe(false);
});
});
describe("resolveSidebarV2Enabled", () => {
const hydrated = { settingsHydrated: true } as const;
it.each(["Alpha", "Latest"])(
"keeps a legacy opt-in on %s builds even without the companion flag",
(stageLabel) => {
// `true` was never the schema default, so it can only be an explicit
// opt-in from settings written before `sidebarV2ConfiguredByUser` existed.
expect(
resolveSidebarV2Enabled({
...hydrated,
enabled: true,
configuredByUser: false,
stageLabel,
}),
).toBe(true);
},
);
it("applies the stage default when the beta was never enabled or configured", () => {
expect(
resolveSidebarV2Enabled({
...hydrated,
enabled: false,
configuredByUser: false,
stageLabel: "Nightly",
}),
).toBe(true);
expect(
resolveSidebarV2Enabled({
...hydrated,
enabled: false,
configuredByUser: false,
stageLabel: "Latest",
}),
).toBe(false);
});
it("honors an explicit opt-out over the stage default", () => {
expect(
resolveSidebarV2Enabled({
...hydrated,
enabled: false,
configuredByUser: true,
stageLabel: "Nightly",
}),
).toBe(false);
});
it("holds v1 until settings hydrate so the sidebar does not remount", () => {
expect(
resolveSidebarV2Enabled({
enabled: true,
configuredByUser: true,
settingsHydrated: false,
stageLabel: "Nightly",
}),
).toBe(false);
});
});
@@ -7,7 +7,8 @@ import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
import { readPreparedConnection } from "~/state/session";
const normalizeHostname = (host: string): string => host.toLowerCase().replace(/^\[|\]$/g, "");
export const normalizeHostname = (host: string): string =>
host.toLowerCase().replace(/^\[|\]$/g, "");
const parseIpv4Address = (host: string): readonly number[] | null => {
const parts = normalizeHostname(host).split(".").map(Number);
@@ -17,7 +18,7 @@ const parseIpv4Address = (host: string): readonly number[] | null => {
: null;
};
const isLocalLoopbackHost = (host: string): boolean => {
export const isLocalLoopbackHost = (host: string): boolean => {
const normalized = normalizeHostname(host);
if (normalized === "localhost" || normalized === "::1") return true;
return parseIpv4Address(normalized)?.[0] === 127;
+444
View File
@@ -0,0 +1,444 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
const { readPreparedConnection } = vi.hoisted(() => ({
readPreparedConnection: vi.fn<() => { httpBaseUrl: string } | null>(() => null),
}));
vi.mock("~/state/session", () => ({ readPreparedConnection }));
import {
BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
BROWSER_HISTORY_MAX_PROJECTS,
BROWSER_HISTORY_MAX_TITLE_LENGTH,
type BrowserHistoryEntry,
evictExcessProjects,
mergeBrowserHistoryState,
migratePersistedBrowserHistoryState,
normalizeHistoryUrl,
recordVisitForThread,
removeUrlForThread,
resetBrowserHistoryForTests,
setTitleForThreadUrl,
upsertHistoryEntry,
useBrowserHistoryStore,
} from "./browserHistoryStore";
function entry(overrides: Partial<BrowserHistoryEntry> = {}): BrowserHistoryEntry {
return { url: "http://localhost:3000/", lastVisitedAt: 1000, ...overrides };
}
beforeEach(() => readPreparedConnection.mockReturnValue(null));
afterEach(() => vi.restoreAllMocks());
function spyOnPersistWrites() {
const storage = useBrowserHistoryStore.persist.getOptions().storage;
if (!storage) throw new Error("Browser history persistence storage is unavailable.");
return vi.spyOn(storage, "setItem");
}
describe("normalizeHistoryUrl", () => {
it("normalizes bare loopback hosts to http and keeps path/query", () => {
expect(normalizeHistoryUrl("localhost:3000/admin?tab=1")).toBe(
"http://localhost:3000/admin?tab=1",
);
});
it("normalizes bare public hosts to https", () => {
expect(normalizeHistoryUrl("myapp.test")).toBe("https://myapp.test/");
});
it("preserves hash routes and strips credentials", () => {
expect(normalizeHistoryUrl("http://localhost:3000/app#/route")).toBe(
"http://localhost:3000/app#/route",
);
expect(normalizeHistoryUrl("https://user:[email protected]/")).toBe("https://example.com/");
});
it("rejects non-http(s), unparseable, and oversized urls", () => {
expect(normalizeHistoryUrl("ftp://example.com")).toBeNull();
expect(normalizeHistoryUrl("")).toBeNull();
expect(normalizeHistoryUrl(`http://localhost/${"a".repeat(2048)}`)).toBeNull();
});
});
describe("upsertHistoryEntry", () => {
it("prepends new urls", () => {
const next = upsertHistoryEntry([entry()], "http://localhost:5173/", 2000);
expect(next.map((e) => e.url)).toEqual(["http://localhost:5173/", "http://localhost:3000/"]);
expect(next[0]).toEqual({ url: "http://localhost:5173/", lastVisitedAt: 2000 });
});
it("moves revisits to front, updates the timestamp, and keeps the title", () => {
const existing = [
entry({ url: "http://a.test/", lastVisitedAt: 500, title: "A" }),
entry({ url: "http://b.test/", lastVisitedAt: 400 }),
];
const next = upsertHistoryEntry(existing, "http://b.test/", 3000);
expect(next.map((e) => e.url)).toEqual(["http://b.test/", "http://a.test/"]);
expect(next[0]?.lastVisitedAt).toBe(3000);
expect(next[1]?.title).toBe("A");
});
it("caps the list at the per-project limit", () => {
const full = Array.from({ length: BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT }, (_, i) =>
entry({ url: `http://localhost:${3000 + i}/`, lastVisitedAt: i }),
);
const next = upsertHistoryEntry(full, "http://new.test/", 9999);
expect(next).toHaveLength(BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
expect(next[0]?.url).toBe("http://new.test/");
const lastPort = 3000 + BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT - 1;
expect(next.some((e) => e.url === `http://localhost:${lastPort}/`)).toBe(false);
expect(next.some((e) => e.url === "http://localhost:3000/")).toBe(true);
});
it("with insertOrdered, slots an older entry below a newer one instead of prepending", () => {
const existing = [entry({ url: "http://newer.test/", lastVisitedAt: 2000 })];
const next = upsertHistoryEntry(existing, "http://older.test/", 1000, {
insertOrdered: true,
});
expect(next.map((e) => e.url)).toEqual(["http://newer.test/", "http://older.test/"]);
});
it("with insertOrdered, replaying an older visit for an existing entry keeps its newer timestamp", () => {
const existing = [entry({ url: "http://a.test/", lastVisitedAt: 2000 })];
const next = upsertHistoryEntry(existing, "http://a.test/", 1000, { insertOrdered: true });
expect(next).toEqual([{ url: "http://a.test/", lastVisitedAt: 2000 }]);
});
});
describe("evictExcessProjects", () => {
it("keeps the most recently visited projects when over the cap", () => {
const byProjectKey = Object.fromEntries(
Array.from({ length: BROWSER_HISTORY_MAX_PROJECTS + 2 }, (_, i) => [
`project-${i}`,
[entry({ lastVisitedAt: i })],
]),
);
const next = evictExcessProjects(byProjectKey);
expect(Object.keys(next)).toHaveLength(BROWSER_HISTORY_MAX_PROJECTS);
expect(next["project-0"]).toBeUndefined();
expect(next["project-1"]).toBeUndefined();
expect(next[`project-${BROWSER_HISTORY_MAX_PROJECTS + 1}`]).toBeDefined();
});
});
describe("migratePersistedBrowserHistoryState", () => {
it("drops malformed state and invalid entries", () => {
expect(migratePersistedBrowserHistoryState(null)).toEqual({ byProjectKey: {} });
expect(migratePersistedBrowserHistoryState({ byProjectKey: 42 })).toEqual({ byProjectKey: {} });
const migrated = migratePersistedBrowserHistoryState({
byProjectKey: {
good: [
{ url: "http://a.test/", lastVisitedAt: 100, title: "A" },
{ url: "", lastVisitedAt: 100 },
{ url: "ftp://ghost.test/", lastVisitedAt: 100 },
{ url: "http://b.test/", lastVisitedAt: Number.NaN },
"junk",
],
bad: "junk",
},
});
expect(migrated.byProjectKey["good"]).toEqual([
{ url: "http://a.test/", lastVisitedAt: 100, title: "A" },
]);
expect(migrated.byProjectKey["bad"]).toBeUndefined();
});
it("normalizes persisted urls with the same rules as live writes", () => {
const migrated = migratePersistedBrowserHistoryState({
byProjectKey: {
good: [{ url: "a.test/path#section", lastVisitedAt: 100 }],
},
});
expect(migrated.byProjectKey["good"]).toEqual([
{ url: "https://a.test/path#section", lastVisitedAt: 100 },
]);
});
it("restores MRU ordering, deduplicates normalized urls, and enforces project bounds", () => {
const byProjectKey = Object.fromEntries(
Array.from({ length: BROWSER_HISTORY_MAX_PROJECTS + 1 }, (_, index) => [
`project-${index}`,
[{ url: `http://project-${index}.test/`, lastVisitedAt: index }],
]),
);
byProjectKey["project-1"] = [
{ url: "a.test/", lastVisitedAt: 1 },
{ url: "http://newer.test/", lastVisitedAt: 3 },
{ url: "https://a.test/", lastVisitedAt: 2 },
];
const migrated = migratePersistedBrowserHistoryState({ byProjectKey });
expect(Object.keys(migrated.byProjectKey)).toHaveLength(BROWSER_HISTORY_MAX_PROJECTS);
expect(migrated.byProjectKey["project-0"]).toBeUndefined();
expect(migrated.byProjectKey["project-1"]).toEqual([
{ url: "http://newer.test/", lastVisitedAt: 3 },
{ url: "https://a.test/", lastVisitedAt: 2 },
]);
});
it("rejects a lastVisitedAt outside Date's valid range", () => {
const migrated = migratePersistedBrowserHistoryState({
byProjectKey: {
good: [
{ url: "http://a.test/", lastVisitedAt: 100 },
{ url: "http://b.test/", lastVisitedAt: 1e20 },
],
},
});
expect(migrated.byProjectKey["good"]).toEqual([{ url: "http://a.test/", lastVisitedAt: 100 }]);
});
it("truncates oversized persisted titles to the contract bound", () => {
const oversized = "x".repeat(BROWSER_HISTORY_MAX_TITLE_LENGTH + 100);
const migrated = migratePersistedBrowserHistoryState({
byProjectKey: {
good: [{ url: "http://a.test/", lastVisitedAt: 100, title: oversized }],
},
});
expect(migrated.byProjectKey["good"]?.[0]?.title).toHaveLength(
BROWSER_HISTORY_MAX_TITLE_LENGTH,
);
expect(migrated.byProjectKey["good"]?.[0]?.title).toBe(
oversized.slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH),
);
});
});
const threadRef = {
environmentId: EnvironmentId.make("env-1"),
threadId: ThreadId.make("thread-1"),
};
describe("useBrowserHistoryStore", () => {
beforeEach(() => {
resetBrowserHistoryForTests();
});
it("records visits for registered threads under the project key", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "myapp.test/admin#section", 1234);
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
{ url: "https://myapp.test/admin#section", lastVisitedAt: 1234 },
]);
});
it("does not persist when a thread is already registered to the same project", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
const persist = spyOnPersistWrites();
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
expect(persist).not.toHaveBeenCalled();
});
it("ignores invalid urls whether queued pending or recorded post-registration", () => {
recordVisitForThread(threadRef, "ftp://a.test/", 1);
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "ftp://a.test/", 2);
expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
});
it("sets titles update-only via the thread helper", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
setTitleForThreadUrl(threadRef, "http://a.test/", "Should not create");
expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
recordVisitForThread(threadRef, "http://a.test/#/settings", 1);
setTitleForThreadUrl(threadRef, "http://a.test/#/settings", "My App");
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("My App");
});
it("does not persist when the title is already set", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "http://a.test/", 1);
setTitleForThreadUrl(threadRef, "http://a.test/", "My App");
const persist = spyOnPersistWrites();
const byProjectKey = useBrowserHistoryStore.getState().byProjectKey;
setTitleForThreadUrl(threadRef, "http://a.test/", "My App");
expect(useBrowserHistoryStore.getState().byProjectKey).toBe(byProjectKey);
expect(persist).not.toHaveBeenCalled();
});
it("sets a title against a settled url that differs from the stored one only by a trailing slash", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "http://a.test/community", 1);
setTitleForThreadUrl(threadRef, "http://a.test/community/", "Community");
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]).toMatchObject({
url: "http://a.test/community",
title: "Community",
});
useBrowserHistoryStore.setState({ byProjectKey: {} });
recordVisitForThread(threadRef, "http://a.test/community/", 1);
setTitleForThreadUrl(threadRef, "http://a.test/community", "Community");
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]).toMatchObject({
url: "http://a.test/community/",
title: "Community",
});
});
it("matches a requested localhost URL to the resolved environment host", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
setTitleForThreadUrl(threadRef, "http://192.168.64.2:5173/app", "Local App", "192.168.64.2");
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("Local App");
});
it("deduplicates loopback aliases and the resolved environment host", () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.64.2:3773" });
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
recordVisitForThread(threadRef, "http://127.0.0.1:5173/app", 2);
recordVisitForThread(threadRef, "http://192.168.64.2:5173/app", 3);
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
{ url: "http://localhost:5173/app", lastVisitedAt: 3 },
]);
useBrowserHistoryStore.setState({ byProjectKey: {} });
recordVisitForThread(threadRef, "http://192.168.64.2:5173/app", 4);
recordVisitForThread(threadRef, "http://localhost:5173/app", 5);
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
{ url: "http://localhost:5173/app", lastVisitedAt: 5 },
]);
});
it("does not match a genuinely different path via the trailing-slash comparison", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "http://a.test/community", 1);
setTitleForThreadUrl(threadRef, "http://a.test/community/foo", "Foo");
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBeUndefined();
});
it("updates only the most recent entry when several share a trailing-slash comparison key", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "http://a.test/community/", 1);
recordVisitForThread(threadRef, "http://a.test/community", 2);
setTitleForThreadUrl(threadRef, "http://a.test/community/", "Community");
const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
expect(entries?.[0]).toMatchObject({ url: "http://a.test/community", title: "Community" });
expect(entries?.[1]).toMatchObject({ url: "http://a.test/community/" });
expect(entries?.[1]?.title).toBeUndefined();
});
it("truncates oversized titles to the contract bound", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "http://a.test/", 1);
const oversized = "y".repeat(BROWSER_HISTORY_MAX_TITLE_LENGTH + 50);
setTitleForThreadUrl(threadRef, "http://a.test/", oversized);
const title = useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title;
expect(title).toHaveLength(BROWSER_HISTORY_MAX_TITLE_LENGTH);
expect(title).toBe(oversized.slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH));
});
it("removes entries", () => {
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
recordVisitForThread(threadRef, "http://a.test/", 1);
recordVisitForThread(threadRef, "http://b.test/", 2);
removeUrlForThread(threadRef, "http://a.test/");
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.map((e) => e.url)).toEqual([
"http://b.test/",
]);
});
});
describe("pendingVisitsByThreadKey", () => {
beforeEach(() => {
resetBrowserHistoryForTests();
});
it("queues a visit recorded before registration and drains it in order on registration", () => {
recordVisitForThread(threadRef, "http://a.test/", 1);
recordVisitForThread(threadRef, "http://b.test/", 2);
expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.map((e) => e.url)).toEqual([
"http://b.test/",
"http://a.test/",
]);
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.lastVisitedAt).toBe(2);
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[1]?.lastVisitedAt).toBe(1);
expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
});
it("caps the per-thread pending list at 10, dropping the oldest", () => {
for (let i = 0; i < 12; i++) {
recordVisitForThread(threadRef, `http://a.test/${i}`, i);
}
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
const urls = useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.map((e) => e.url);
expect(urls).toHaveLength(10);
expect(urls).not.toContain("http://a.test/0");
expect(urls).not.toContain("http://a.test/1");
expect(urls?.[0]).toBe("http://a.test/11");
});
it("slots a replayed visit by timestamp instead of hoisting it above a newer live visit", () => {
const otherThreadRef = {
environmentId: EnvironmentId.make("env-1"),
threadId: ThreadId.make("thread-2"),
};
useBrowserHistoryStore.getState().registerThreadProject(otherThreadRef, "proj-a");
recordVisitForThread(otherThreadRef, "http://newer.test/", 2000);
recordVisitForThread(threadRef, "http://older.test/", 1000);
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
expect(entries?.map((e) => e.url)).toEqual(["http://newer.test/", "http://older.test/"]);
// `entries[0]` being the most recent is the invariant `evictExcessProjects` relies on.
expect(entries?.[0]?.lastVisitedAt).toBe(2000);
});
});
describe("pendingTitlesByThreadKey", () => {
beforeEach(() => {
resetBrowserHistoryForTests();
});
it("buffers a title set before registration and applies it once the matching visit drains", () => {
recordVisitForThread(threadRef, "http://a.test/", 1);
setTitleForThreadUrl(threadRef, "http://a.test/", "My App");
expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
expect(entries?.[0]).toMatchObject({ url: "http://a.test/", title: "My App" });
expect(useBrowserHistoryStore.getState().pendingTitlesByThreadKey).toEqual({});
});
it("preserves environment host matching while a title is pending", () => {
recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
setTitleForThreadUrl(threadRef, "http://192.168.64.2:5173/app", "Local App", "192.168.64.2");
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("Local App");
});
});
describe("mergeBrowserHistoryState", () => {
it("sanitizes same-version corrupt persisted data and preserves actions", () => {
// `migrate` only runs when versions differ; `merge` runs on every rehydrate.
const current = useBrowserHistoryStore.getState();
const merged = mergeBrowserHistoryState(
{
byProjectKey: {
a: [{ url: "ftp://bad.test/", lastVisitedAt: 1 }],
b: [{ url: "http://ok.test/", lastVisitedAt: 5 }],
},
projectKeyByThreadKey: { good: "b", stale: "a", malformed: 42 },
},
current,
);
expect(merged.byProjectKey).toEqual({
b: [{ url: "http://ok.test/", lastVisitedAt: 5 }],
});
expect(typeof merged.recordVisit).toBe("function");
expect(merged.projectKeyByThreadKey).toEqual({ good: "b" });
expect(merged.pendingVisitsByThreadKey).toEqual({});
expect(merged.pendingTitlesByThreadKey).toEqual({});
});
});
+398
View File
@@ -0,0 +1,398 @@
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { useShallow } from "zustand/react/shallow";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import { readPreparedConnection } from "~/state/session";
import { isLocalLoopbackHost, normalizeHostname } from "./browser/browserTargetResolver";
import { resolveStorage } from "./lib/storage";
export type BrowserHistoryEntry = { url: string; lastVisitedAt: number; title?: string };
export const BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT = 50;
export const BROWSER_HISTORY_MAX_PROJECTS = 20;
export const BROWSER_HISTORY_MAX_URL_LENGTH = 2048;
export const BROWSER_HISTORY_MAX_TITLE_LENGTH = 512;
const MAX_VALID_DATE_MS = 8_640_000_000_000_000;
export function isValidHistoryTimestamp(value: unknown): value is number {
return (
typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= MAX_VALID_DATE_MS
);
}
export function normalizeHistoryUrl(raw: string): string | null {
let parsed: URL;
try {
parsed = new URL(normalizePreviewUrl(raw));
} catch {
return null;
}
parsed.username = parsed.password = "";
return parsed.href.length > BROWSER_HISTORY_MAX_URL_LENGTH ? null : parsed.href;
}
export function titleLookupKey(normalized: string, environmentHostname?: string | null): string {
const parsed = new URL(visitLookupKey(normalized, environmentHostname));
if (parsed.pathname !== "/" && parsed.pathname.endsWith("/"))
parsed.pathname = parsed.pathname.slice(0, -1);
return parsed.href;
}
function visitLookupKey(normalized: string, environmentHostname?: string | null): string {
const parsed = new URL(normalized);
const host = normalizeHostname(parsed.hostname);
const environmentHost = environmentHostname && normalizeHostname(environmentHostname);
if (isLocalLoopbackHost(host) || host === "0.0.0.0" || host === environmentHost)
parsed.hostname = "local";
return parsed.href;
}
function isStableLocalUrl(normalized: string): boolean {
const host = normalizeHostname(new URL(normalized).hostname);
return isLocalLoopbackHost(host) || host === "0.0.0.0";
}
export function upsertHistoryEntry(
entries: ReadonlyArray<BrowserHistoryEntry>,
url: string,
at: number,
options?: { insertOrdered?: boolean; environmentHostname?: string | null },
): BrowserHistoryEntry[] {
const key = visitLookupKey(url, options?.environmentHostname);
const existing = entries.find(
(candidate) => visitLookupKey(candidate.url, options?.environmentHostname) === key,
);
const rest = entries.filter(
(candidate) => visitLookupKey(candidate.url, options?.environmentHostname) !== key,
);
const visitedAt =
options?.insertOrdered && existing && existing.lastVisitedAt > at ? existing.lastVisitedAt : at;
const storedUrl =
existing && (isStableLocalUrl(existing.url) || !isStableLocalUrl(url)) ? existing.url : url;
const entry: BrowserHistoryEntry = existing
? { ...existing, url: storedUrl, lastVisitedAt: visitedAt }
: { url, lastVisitedAt: visitedAt };
if (!options?.insertOrdered)
return [entry, ...rest].slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
const index = rest.findIndex((candidate) => candidate.lastVisitedAt < entry.lastVisitedAt);
const next = index === -1 ? [...rest, entry] : rest.toSpliced(index, 0, entry);
return next.slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
}
export function evictExcessProjects(
byProjectKey: Record<string, BrowserHistoryEntry[]>,
): Record<string, BrowserHistoryEntry[]> {
const keys = Object.keys(byProjectKey);
if (keys.length <= BROWSER_HISTORY_MAX_PROJECTS) return byProjectKey;
const kept = keys
.toSorted(
(a, b) =>
(byProjectKey[b]?.[0]?.lastVisitedAt ?? 0) - (byProjectKey[a]?.[0]?.lastVisitedAt ?? 0),
)
.slice(0, BROWSER_HISTORY_MAX_PROJECTS);
return Object.fromEntries(kept.map((key) => [key, byProjectKey[key] ?? []]));
}
export function migratePersistedBrowserHistoryState(persistedState: unknown): {
byProjectKey: Record<string, BrowserHistoryEntry[]>;
} {
if (!persistedState || typeof persistedState !== "object") return { byProjectKey: {} };
const raw = (persistedState as { byProjectKey?: unknown }).byProjectKey;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { byProjectKey: {} };
const byProjectKey: Record<string, BrowserHistoryEntry[]> = {};
for (const [projectKey, value] of Object.entries(raw as Record<string, unknown>)) {
if (!Array.isArray(value)) continue;
const seenUrls = new Set<string>();
const entries = value
.flatMap<BrowserHistoryEntry>((candidate) => {
if (!candidate || typeof candidate !== "object") return [];
const { url, lastVisitedAt, title } = candidate as Record<string, unknown>;
if (typeof url !== "string") return [];
const normalizedUrl = normalizeHistoryUrl(url);
if (!normalizedUrl) return [];
if (!isValidHistoryTimestamp(lastVisitedAt)) return [];
return [
{
url: normalizedUrl,
lastVisitedAt,
...(typeof title === "string" && title.length > 0
? { title: title.slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH) }
: {}),
},
];
})
.toSorted((a, b) => b.lastVisitedAt - a.lastVisitedAt)
.filter((entry) => {
const key = visitLookupKey(entry.url);
if (seenUrls.has(key)) return false;
seenUrls.add(key);
return true;
})
.slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
if (entries.length > 0) byProjectKey[projectKey] = entries;
}
return { byProjectKey: evictExcessProjects(byProjectKey) };
}
const BROWSER_HISTORY_STORAGE_KEY = "t3code:browser-history:v1";
const PENDING_MAX_PER_THREAD = 10;
const PENDING_MAX_THREADS = 20;
type PendingVisit = { url: string; at: number; environmentHostname: string | null };
type PendingTitle = { url: string; title: string; environmentHostname: string | null | undefined };
interface BrowserHistoryStoreState {
byProjectKey: Record<string, BrowserHistoryEntry[]>;
projectKeyByThreadKey: Record<string, string>;
pendingVisitsByThreadKey: Record<string, PendingVisit[]>;
pendingTitlesByThreadKey: Record<string, PendingTitle[]>;
recordVisit: (
projectKey: string,
url: string,
at: number,
options?: { insertOrdered?: boolean; environmentHostname?: string | null },
) => void;
setTitleForUrl: (
projectKey: string,
url: string,
title: string,
environmentHostname?: string | null,
) => void;
removeUrl: (projectKey: string, url: string) => void;
registerThreadProject: (ref: ScopedThreadRef, projectKey: string) => void;
}
function addPendingByThread<T>(
pendingByThreadKey: Record<string, T[]>,
threadKey: string,
item: T,
): Record<string, T[]> {
const existing = pendingByThreadKey[threadKey] ?? [];
const next = { ...pendingByThreadKey };
next[threadKey] = [...existing, item].slice(-PENDING_MAX_PER_THREAD);
const keys = Object.keys(next);
if (keys.length > PENDING_MAX_THREADS) {
const oldestKey = keys[0];
if (oldestKey !== undefined && oldestKey !== threadKey) delete next[oldestKey];
}
return next;
}
export const useBrowserHistoryStore = create<BrowserHistoryStoreState>()(
persist(
(set, get) => ({
byProjectKey: {},
projectKeyByThreadKey: {},
pendingVisitsByThreadKey: {},
pendingTitlesByThreadKey: {},
recordVisit: (projectKey, url, at, options) => {
const normalized = normalizeHistoryUrl(url);
if (!normalized) return;
set((state) => {
return {
byProjectKey: evictExcessProjects({
...state.byProjectKey,
[projectKey]: upsertHistoryEntry(
state.byProjectKey[projectKey] ?? [],
normalized,
at,
options,
),
}),
};
});
},
setTitleForUrl: (projectKey, url, title, environmentHostname) => {
const normalized = normalizeHistoryUrl(url);
const state = get();
const entries = state.byProjectKey[projectKey];
const trimmed = title.trim().slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH);
if (!normalized || !entries || trimmed.length === 0) return;
const key = titleLookupKey(normalized, environmentHostname);
const index = entries.findIndex(
(candidate) => titleLookupKey(candidate.url, environmentHostname) === key,
);
if (index === -1 || entries[index]?.title === trimmed) return;
set({
byProjectKey: {
...state.byProjectKey,
[projectKey]: entries.map((candidate, candidateIndex) =>
candidateIndex === index ? { ...candidate, title: trimmed } : candidate,
),
},
});
},
removeUrl: (projectKey, url) => {
const normalized = normalizeHistoryUrl(url);
const state = get();
const entries = state.byProjectKey[projectKey];
if (!normalized || !entries) return;
const next = entries.filter((candidate) => candidate.url !== normalized);
if (next.length === entries.length) return;
if (next.length === 0) {
const { [projectKey]: _removed, ...rest } = state.byProjectKey;
set({ byProjectKey: rest });
return;
}
set({ byProjectKey: { ...state.byProjectKey, [projectKey]: next } });
},
registerThreadProject: (ref, projectKey) => {
const threadKey = scopedThreadKey(ref);
const state = get();
const pendingVisits = state.pendingVisitsByThreadKey[threadKey];
const pendingTitles = state.pendingTitlesByThreadKey[threadKey];
if (
state.projectKeyByThreadKey[threadKey] === projectKey &&
!pendingVisits &&
!pendingTitles
) {
return;
}
const nextPendingVisits = { ...state.pendingVisitsByThreadKey };
const nextPendingTitles = { ...state.pendingTitlesByThreadKey };
delete nextPendingVisits[threadKey];
delete nextPendingTitles[threadKey];
set({
projectKeyByThreadKey: { ...state.projectKeyByThreadKey, [threadKey]: projectKey },
pendingVisitsByThreadKey: nextPendingVisits,
pendingTitlesByThreadKey: nextPendingTitles,
});
for (const visit of pendingVisits ?? [])
get().recordVisit(projectKey, visit.url, visit.at, {
insertOrdered: true,
environmentHostname: visit.environmentHostname,
});
for (const pendingTitle of pendingTitles ?? [])
get().setTitleForUrl(
projectKey,
pendingTitle.url,
pendingTitle.title,
pendingTitle.environmentHostname,
);
},
}),
{
name: BROWSER_HISTORY_STORAGE_KEY,
version: 1,
storage: createJSONStorage(() =>
resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
),
partialize: (state) => ({
byProjectKey: state.byProjectKey,
projectKeyByThreadKey: state.projectKeyByThreadKey,
}),
migrate: migratePersistedBrowserHistoryState,
merge: mergeBrowserHistoryState,
},
),
);
export function mergeBrowserHistoryState(
persistedState: unknown,
currentState: BrowserHistoryStoreState,
): BrowserHistoryStoreState {
const migrated = migratePersistedBrowserHistoryState(persistedState);
return {
...currentState,
...migrated,
projectKeyByThreadKey: migratePersistedThreadProjectKeys(persistedState, migrated.byProjectKey),
pendingVisitsByThreadKey: {},
pendingTitlesByThreadKey: {},
};
}
function migratePersistedThreadProjectKeys(
persistedState: unknown,
byProjectKey: Record<string, BrowserHistoryEntry[]>,
): Record<string, string> {
if (!persistedState || typeof persistedState !== "object") return {};
const raw = (persistedState as { projectKeyByThreadKey?: unknown }).projectKeyByThreadKey;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
return Object.fromEntries(
Object.entries(raw as Record<string, unknown>)
.filter(
(entry): entry is [string, string] =>
typeof entry[1] === "string" && entry[1] in byProjectKey,
)
.slice(-100),
);
}
export function recordVisitForThread(ref: ScopedThreadRef, url: string, at?: number): void {
const threadKey = scopedThreadKey(ref);
const state = useBrowserHistoryStore.getState();
const projectKey = state.projectKeyByThreadKey[threadKey];
const visitAt = at ?? Date.now();
const connection = readPreparedConnection(ref.environmentId);
const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : null;
if (!projectKey) {
useBrowserHistoryStore.setState({
pendingVisitsByThreadKey: addPendingByThread(state.pendingVisitsByThreadKey, threadKey, {
url,
at: visitAt,
environmentHostname,
}),
});
return;
}
state.recordVisit(projectKey, url, visitAt, { environmentHostname });
}
export function setTitleForThreadUrl(
ref: ScopedThreadRef,
url: string,
title: string,
environmentHostname?: string | null,
): void {
const threadKey = scopedThreadKey(ref);
const state = useBrowserHistoryStore.getState();
const projectKey = state.projectKeyByThreadKey[threadKey];
if (!projectKey) {
useBrowserHistoryStore.setState({
pendingTitlesByThreadKey: addPendingByThread(state.pendingTitlesByThreadKey, threadKey, {
url,
title,
environmentHostname,
}),
});
return;
}
state.setTitleForUrl(projectKey, url, title, environmentHostname);
}
export function removeUrlForThread(ref: ScopedThreadRef, url: string): void {
const state = useBrowserHistoryStore.getState();
const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)];
if (!projectKey) return;
state.removeUrl(projectKey, url);
}
const EMPTY_HISTORY: ReadonlyArray<BrowserHistoryEntry> = [];
export function useThreadRecentHistory(
ref: ScopedThreadRef,
limit: number,
): ReadonlyArray<BrowserHistoryEntry> {
return useBrowserHistoryStore(
useShallow((state) => {
const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)];
const entries = projectKey ? state.byProjectKey[projectKey] : undefined;
return entries && entries.length > 0 ? entries.slice(0, limit) : EMPTY_HISTORY;
}),
);
}
export function resetBrowserHistoryForTests(): void {
useBrowserHistoryStore.setState({
byProjectKey: {},
projectKeyByThreadKey: {},
pendingVisitsByThreadKey: {},
pendingTitlesByThreadKey: {},
});
useBrowserHistoryStore.persist.clearStorage();
}
+17 -9
View File
@@ -14,9 +14,11 @@ import { getLocalStorageItem } from "../hooks/useLocalStorage";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
import { useEnvironmentIdentificationMode, useSidebarV2Enabled } from "../hooks/useSettings";
import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
import LegacyThreadSidebar from "./LegacySidebar";
import ThreadSidebar from "./Sidebar";
import ThreadSidebarV2 from "./SidebarV2";
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
import {
resolveInitialThreadSidebarWidth,
@@ -118,13 +120,11 @@ function SidebarControl() {
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
const sidebarV2Enabled = useSidebarV2Enabled();
// Settings routes render the settings nav, which lives in the v1 component
// and is identical for both sidebars — so v1 stays mounted there.
const legacySidebarEnabled = useLegacySidebarEnabled();
// Settings routes show the settings nav in place of whichever thread
// sidebar is active.
const pathname = useLocation({ select: (location) => location.pathname });
const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
const useSidebarV2 = sidebarV2Enabled && !isOnSettings;
const useSidebarV2Theme = useSidebarV2 || isOnSettings;
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
// Subscribed rather than read once: the clamp must track live window size,
@@ -188,7 +188,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
side="left"
collapsible="offcanvas"
data-app-sidebar=""
data-sidebar-version={useSidebarV2Theme ? "v2" : "v1"}
className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
resizable={{
maxWidth: sidebarMaximumWidth,
@@ -200,7 +199,16 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
onResize: setSidebarWidth,
}}
>
{useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
{isOnSettings ? (
<>
<SidebarChromeHeader isElectron={isElectron} />
<SettingsSidebarNav pathname={pathname} />
</>
) : legacySidebarEnabled ? (
<LegacyThreadSidebar />
) : (
<ThreadSidebar />
)}
<SidebarRail />
</Sidebar>
{children}
+1 -1
View File
@@ -126,7 +126,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
if (isLocked) {
return (
<span className="inline-flex min-w-0 max-w-[48%] flex-1 items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 md:hidden">
<span className="inline-flex h-7 min-w-0 max-w-[48%] flex-1 items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 md:hidden">
{triggerContent}
</span>
);
@@ -50,7 +50,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
if (envLocked) {
return (
<span className="inline-flex shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
<span className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
{activeWorktreePath ? (
<>
<FolderGitIcon className="size-3" />
@@ -41,9 +41,14 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
[availableEnvironments],
);
// The static label carries the xs control's height (h-7 sm:h-6) as well as
// its padding: the composer context strip has no min-height of its own, and
// the glass seam joining it to the composer assumes a fixed strip height, so
// a shorter label would drag the seam out of line whenever this label is the
// only thing in the strip.
if (envLocked || onEnvironmentChange === undefined) {
return (
<span className="inline-flex min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
<span className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
{activeEnvironment?.isPrimary ? (
<MonitorIcon className="size-3 shrink-0" />
) : (
+5 -1
View File
@@ -52,6 +52,7 @@ import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "./ui/collapsi
import { ScrollArea } from "./ui/scroll-area";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { recordVisitForThread } from "../browserHistoryStore";
import { useOpenInPreferredEditor } from "../editorPreferences";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
@@ -1336,7 +1337,10 @@ function ChatMarkdown({
),
);
}
return openUrlInPreview({ threadRef, url, openPreview });
return openUrlInPreview({ threadRef, url, openPreview }).then((result) => {
if (result._tag === "Success") recordVisitForThread(threadRef, url);
return result;
});
},
[openPreview, threadRef],
);
+40 -1
View File
@@ -6,7 +6,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import type { Thread, ThreadShell } from "../types";
import {
@@ -19,13 +19,16 @@ import {
createLocalDispatchSnapshot,
deriveComposerSendState,
dismissBranchMismatchForSession,
ENVIRONMENT_RECONNECT_WARNING_GRACE_MS,
getStartedThreadModelChangeBlockReason,
hasEnvironmentReconnectWarningGraceElapsed,
hasServerAcknowledgedLocalDispatch,
isBranchMismatchDismissedForSession,
reconcileMountedTerminalThreadIds,
reconcileRetainedMountedThreadIds,
resolveThreadMetadataUpdateForNextTurn,
resolveSendEnvMode,
scheduleEnvironmentReconnectWarning,
startNewThreadForProject,
shouldShowBranchMismatchBanner,
shouldWriteThreadErrorToCurrentServerThread,
@@ -36,6 +39,42 @@ const projectId = ProjectId.make("project-1");
const threadId = ThreadId.make("thread-1");
const now = "2026-03-29T00:00:00.000Z";
describe("environment reconnect warning grace", () => {
afterEach(() => vi.useRealTimers());
it("shows a persistent reconnect after the grace period", () => {
vi.useFakeTimers();
const showWarning = vi.fn();
scheduleEnvironmentReconnectWarning(showWarning);
vi.advanceTimersByTime(ENVIRONMENT_RECONNECT_WARNING_GRACE_MS - 1);
expect(showWarning).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(showWarning).toHaveBeenCalledOnce();
});
it("cancels the warning when the connection recovers during the grace period", () => {
vi.useFakeTimers();
const showWarning = vi.fn();
const cancel = scheduleEnvironmentReconnectWarning(showWarning);
cancel();
vi.advanceTimersByTime(ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
expect(showWarning).not.toHaveBeenCalled();
});
it("does not reuse elapsed grace from another environment", () => {
const anotherEnvironmentId = EnvironmentId.make("environment-remote");
expect(hasEnvironmentReconnectWarningGraceElapsed(environmentId, environmentId)).toBe(true);
expect(hasEnvironmentReconnectWarningGraceElapsed(anotherEnvironmentId, environmentId)).toBe(
false,
);
});
});
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: threadId,
+13
View File
@@ -25,9 +25,22 @@ import type { DraftThreadEnvMode } from "../composerDraftStore";
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
return () => globalThis.clearTimeout(timeoutId);
}
export function hasEnvironmentReconnectWarningGraceElapsed(
activeEnvironmentId: EnvironmentId | null,
elapsedEnvironmentId: EnvironmentId | null,
): boolean {
return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId;
}
export function startNewThreadForProject(
projectRef: ScopedProjectRef | null,
handleNewThread: (projectRef: ScopedProjectRef) => Promise<void>,
+65 -5
View File
@@ -172,9 +172,14 @@ import {
projectScriptIdFromCommand,
} from "~/projectScripts";
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
import { useBrowserHistoryStore } from "~/browserHistoryStore";
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
import {
useClientSettings,
useClientSettingsHydrated,
useEnvironmentSettings,
} from "../hooks/useSettings";
import { useNowMinute } from "../hooks/useNowMinute";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
@@ -182,9 +187,11 @@ import { getTerminalFocusOwner } from "../lib/terminalFocus";
import { preventRepeatedTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
derivePhysicalProjectKey,
deriveLogicalProjectKeyFromSettings,
selectProjectGroupingSettings,
} from "../logicalProject";
import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";
import { buildDraftThreadRouteParams } from "../threadRoutes";
import {
type ComposerImageAttachment,
@@ -276,6 +283,8 @@ import {
createLocalDispatchSnapshot,
deriveComposerSendState,
dismissBranchMismatchForSession,
hasEnvironmentReconnectWarningGraceElapsed,
scheduleEnvironmentReconnectWarning,
hasServerAcknowledgedLocalDispatch,
isBranchMismatchDismissedForSession,
shouldShowBranchMismatchBanner,
@@ -1491,6 +1500,7 @@ function ChatViewContent(props: ChatViewProps) {
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
const canCheckoutPullRequestIntoThread = isLocalDraftThread;
const activeThreadId = activeThread?.id ?? null;
const activeThreadEnvironmentId = activeThread?.environmentId ?? null;
const runningTerminalIds = useThreadRunningTerminalIds({
environmentId: activeThread?.environmentId ?? null,
threadId: activeThreadId,
@@ -1526,8 +1536,11 @@ function ChatViewContent(props: ChatViewProps) {
return labels;
}, [activeThreadKnownSessions]);
const activeThreadRef = useMemo(
() => (activeThread ? scopeThreadRef(activeThread.environmentId, activeThread.id) : null),
[activeThread],
() =>
activeThreadEnvironmentId && activeThreadId
? scopeThreadRef(activeThreadEnvironmentId, activeThreadId)
: null,
[activeThreadEnvironmentId, activeThreadId],
);
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
const [timelineAnchor, setTimelineAnchor] = useState<{
@@ -1652,6 +1665,8 @@ function ChatViewContent(props: ChatViewProps) {
const activeProjectKey = activeProject
? `${activeProject.environmentId}:${activeProject.workspaceRoot}`
: null;
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const clientSettingsHydrated = useClientSettingsHydrated();
const [pendingFileSurfaceIdsByProject, setPendingFileSurfaceIdsByProject] = useState<
ReadonlyMap<string, ReadonlySet<string>>
>(() => new Map());
@@ -1690,11 +1705,54 @@ function ChatViewContent(props: ChatViewProps) {
// drive the environment picker in BranchToolbar.
const allProjects = useProjects();
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
useEffect(() => {
if (!clientSettingsHydrated || !activeThreadRef || !activeProject) return;
// Reuse the sidebar's grouping so history follows the project rows the user
// sees. Deriving the key from the active project alone would miss the
// identity a duplicate row borrows from its siblings.
const logicalKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({
projects: allProjects,
settings: projectGroupingSettings,
primaryEnvironmentId,
});
useBrowserHistoryStore
.getState()
.registerThreadProject(
activeThreadRef,
logicalKeyByPhysicalKey.get(derivePhysicalProjectKey(activeProject)) ??
deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings),
);
}, [
activeProject,
activeThreadRef,
allProjects,
clientSettingsHydrated,
primaryEnvironmentId,
projectGroupingSettings,
]);
const activeEnvironment =
activeThread == null ? null : (environmentById.get(activeThread.environmentId) ?? null);
const activeEnvironmentConnectionPhase = activeEnvironment?.connection.phase ?? "available";
const activeEnvironmentUnavailable =
activeEnvironment !== null && activeEnvironmentConnectionPhase !== "connected";
const activeReconnectingEnvironmentId =
activeEnvironmentConnectionPhase === "connecting" ||
activeEnvironmentConnectionPhase === "reconnecting"
? (activeEnvironment?.environmentId ?? null)
: null;
const [reconnectWarningGraceElapsedEnvironmentId, setReconnectWarningGraceElapsedEnvironmentId] =
useState<EnvironmentId | null>(null);
const reconnectWarningGraceElapsed = hasEnvironmentReconnectWarningGraceElapsed(
activeReconnectingEnvironmentId,
reconnectWarningGraceElapsedEnvironmentId,
);
useEffect(() => {
setReconnectWarningGraceElapsedEnvironmentId(null);
if (activeReconnectingEnvironmentId === null) return;
return scheduleEnvironmentReconnectWarning(() =>
setReconnectWarningGraceElapsedEnvironmentId(activeReconnectingEnvironmentId),
);
}, [activeReconnectingEnvironmentId]);
const activeEnvironmentUnavailableLabel = activeEnvironment?.label ?? null;
const activeEnvironmentUnavailableState = useMemo<EnvironmentUnavailableState | null>(() => {
if (!activeEnvironmentUnavailable || !activeEnvironmentUnavailableLabel || !activeEnvironment) {
@@ -1723,7 +1781,6 @@ function ChatViewContent(props: ChatViewProps) {
},
[retryEnvironment],
);
const projectGroupingSettings = selectProjectGroupingSettings(settings);
const logicalProjectEnvironments = useMemo(() => {
if (!activeProject) return [];
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
@@ -1928,7 +1985,9 @@ function ChatViewContent(props: ChatViewProps) {
// While an update runs, transient connect blips are expected (the server
// restarts) and the update banner already shows progress. Hard failure
// phases still surface so the Reconnect action stays reachable.
const suppressUnavailableBanner = updateRunning && environmentReconnecting;
const suppressUnavailableBanner =
environmentReconnecting &&
(updateRunning || (!reconnectingThroughVersionSkew && !reconnectWarningGraceElapsed));
if (activeEnvironmentUnavailableState && unavailableConnection && !suppressUnavailableBanner) {
if (reconnectingThroughVersionSkew) {
items.push({
@@ -2056,6 +2115,7 @@ function ChatViewContent(props: ChatViewProps) {
return items;
}, [
activeEnvironmentUnavailableState,
reconnectWarningGraceElapsed,
handleReconnectActiveEnvironment,
navigate,
setDismissedVersionMismatchKey,
File diff suppressed because it is too large. Load diff
+27 -25
View File
@@ -17,7 +17,7 @@ import {
resolveProjectStatusIndicator,
resolveSidebarStageBadgeLabel,
resolveThreadRowClassName,
resolveSidebarV2Status,
resolveSidebarThreadStatus,
resolveThreadStatusPill,
resolveWorkingStartedAt,
searchSidebarThreadsByTitle,
@@ -25,11 +25,11 @@ import {
shouldNavigateAfterProjectRemoval,
shouldClearThreadSelectionOnMouseDown,
sortLogicalProjectsForSidebar,
sortSettledThreadsForSidebarV2,
sortSettledThreadsForSidebar,
pinOrderKeyBetween,
planPinnedReorder,
sortPinnedThreadsForSidebarV2,
sortThreadsForSidebarV2,
sortPinnedThreadsForSidebar,
sortThreadsForSidebar,
sortProjectsForSidebar,
sortScopedProjectsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
@@ -627,7 +627,7 @@ describe("isContextMenuPointerDown", () => {
});
});
describe("resolveSidebarV2Status", () => {
describe("resolveSidebarThreadStatus", () => {
const session = {
threadId: ThreadId.make("thread-1"),
status: "running" as const,
@@ -642,15 +642,17 @@ describe("resolveSidebarV2Status", () => {
const idle = { hasPendingApprovals: false, hasPendingUserInput: false };
it("prioritizes approval over a running session", () => {
expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, session })).toBe(
expect(resolveSidebarThreadStatus({ ...idle, hasPendingApprovals: true, session })).toBe(
"approval",
);
});
it("prioritizes awaiting input over a running session, below approval", () => {
expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, session })).toBe("input");
expect(resolveSidebarThreadStatus({ ...idle, hasPendingUserInput: true, session })).toBe(
"input",
);
expect(
resolveSidebarV2Status({
resolveSidebarThreadStatus({
...idle,
hasPendingApprovals: true,
hasPendingUserInput: true,
@@ -660,9 +662,9 @@ describe("resolveSidebarV2Status", () => {
});
it("reports working for running and starting sessions", () => {
expect(resolveSidebarV2Status({ ...idle, session })).toBe("working");
expect(resolveSidebarThreadStatus({ ...idle, session })).toBe("working");
expect(
resolveSidebarV2Status({
resolveSidebarThreadStatus({
...idle,
session: { ...session, status: "starting" as const },
}),
@@ -671,19 +673,19 @@ describe("resolveSidebarV2Status", () => {
it("reports failed only while the session status is error", () => {
expect(
resolveSidebarV2Status({
resolveSidebarThreadStatus({
...idle,
session: { ...session, status: "error" as const, lastError: "boom" },
}),
).toBe("failed");
expect(
resolveSidebarV2Status({
resolveSidebarThreadStatus({
...idle,
session: { ...session, status: "stopped" as const, lastError: "persisted" },
}),
).toBe("ready");
expect(
resolveSidebarV2Status({
resolveSidebarThreadStatus({
...idle,
session: { ...session, status: "ready" as const, lastError: "persisted" },
}),
@@ -691,7 +693,7 @@ describe("resolveSidebarV2Status", () => {
});
it("defaults to ready with no session", () => {
expect(resolveSidebarV2Status({ ...idle, session: null })).toBe("ready");
expect(resolveSidebarThreadStatus({ ...idle, session: null })).toBe("ready");
});
});
@@ -715,14 +717,14 @@ describe("searchSidebarThreadsByTitle", () => {
});
});
describe("sortThreadsForSidebarV2", () => {
describe("sortThreadsForSidebar", () => {
const sortable = (input: { id: string; createdAt: string }) => ({
id: input.id,
createdAt: input.createdAt,
});
it("orders by creation time, newest first, ignoring activity", () => {
const sorted = sortThreadsForSidebarV2([
const sorted = sortThreadsForSidebar([
sortable({ id: "oldest", createdAt: "2026-03-09T08:00:00.000Z" }),
sortable({ id: "newest", createdAt: "2026-03-09T12:00:00.000Z" }),
sortable({ id: "middle", createdAt: "2026-03-09T10:00:00.000Z" }),
@@ -732,7 +734,7 @@ describe("sortThreadsForSidebarV2", () => {
});
it("breaks creation-time ties by id so the order is stable", () => {
const sorted = sortThreadsForSidebarV2([
const sorted = sortThreadsForSidebar([
sortable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z" }),
sortable({ id: "a", createdAt: "2026-03-09T10:00:00.000Z" }),
]);
@@ -838,7 +840,7 @@ describe("planPinnedReorder", () => {
});
});
describe("sortPinnedThreadsForSidebarV2", () => {
describe("sortPinnedThreadsForSidebar", () => {
const pinnable = (input: { id: string; createdAt: string; pinOrderKey?: string | null }) => ({
id: input.id,
createdAt: input.createdAt,
@@ -846,7 +848,7 @@ describe("sortPinnedThreadsForSidebarV2", () => {
});
it("sorts keyed threads by key ahead of keyless threads in creation order", () => {
const sorted = sortPinnedThreadsForSidebarV2([
const sorted = sortPinnedThreadsForSidebar([
pinnable({ id: "keyless-old", createdAt: "2026-03-09T08:00:00.000Z" }),
pinnable({ id: "second", createdAt: "2026-03-09T09:00:00.000Z", pinOrderKey: "t" }),
pinnable({ id: "keyless-new", createdAt: "2026-03-09T12:00:00.000Z" }),
@@ -862,7 +864,7 @@ describe("sortPinnedThreadsForSidebarV2", () => {
});
it("breaks equal keys by id so raced writes render identically everywhere", () => {
const sorted = sortPinnedThreadsForSidebarV2([
const sorted = sortPinnedThreadsForSidebar([
pinnable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z", pinOrderKey: "m" }),
pinnable({ id: "a", createdAt: "2026-03-09T11:00:00.000Z", pinOrderKey: "m" }),
]);
@@ -871,7 +873,7 @@ describe("sortPinnedThreadsForSidebarV2", () => {
});
});
describe("sortSettledThreadsForSidebarV2", () => {
describe("sortSettledThreadsForSidebar", () => {
const settled = (input: {
id: string;
settledAt?: string | null;
@@ -887,7 +889,7 @@ describe("sortSettledThreadsForSidebarV2", () => {
});
it("orders by settle time, most recently settled first", () => {
const sorted = sortSettledThreadsForSidebarV2([
const sorted = sortSettledThreadsForSidebar([
settled({
id: "settled-first",
settledAt: "2026-03-09T10:00:00.000Z",
@@ -905,7 +907,7 @@ describe("sortSettledThreadsForSidebarV2", () => {
});
it("falls back to last activity for auto-settled threads without a settledAt stamp", () => {
const sorted = sortSettledThreadsForSidebarV2([
const sorted = sortSettledThreadsForSidebar([
settled({ id: "auto-old", latestUserMessageAt: "2026-03-09T08:00:00.000Z" }),
settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }),
settled({ id: "auto-recent", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }),
@@ -917,7 +919,7 @@ describe("sortSettledThreadsForSidebarV2", () => {
it("counts a turn completion as activity for auto-settled threads", () => {
// The message came in before the other thread's, but its turn finished
// after: completion time is the real "work ended" moment.
const sorted = sortSettledThreadsForSidebarV2([
const sorted = sortSettledThreadsForSidebar([
settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }),
settled({
id: "completed-later",
@@ -930,7 +932,7 @@ describe("sortSettledThreadsForSidebarV2", () => {
});
it("breaks timestamp ties by id so the order is stable", () => {
const sorted = sortSettledThreadsForSidebarV2([
const sorted = sortSettledThreadsForSidebar([
settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }),
settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }),
]);
+14 -8
View File
@@ -423,21 +423,27 @@ export function resolveThreadRowClassName(input: {
);
}
// ── Sidebar v2 status model ─────────────────────────────────────────
// ── Sidebar thread status model ─────────────────────────────────────
// Five visual states, three colors: color is reserved for "act now"
// (approval), "in motion" (working), and "broken" (failed). Ready is the
// unlabeled resting state — the agent stopped and is waiting on the user,
// whether it finished, asked a question, or proposed a plan.
// Unread completion is tracked separately: it describes whether a ready
// thread needs attention, not what the thread is currently doing.
export type SidebarV2Status = "approval" | "input" | "working" | "monitoring" | "failed" | "ready";
export type SidebarThreadStatus =
| "approval"
| "input"
| "working"
| "monitoring"
| "failed"
| "ready";
type SidebarV2StatusInput = Pick<
type SidebarThreadStatusInput = Pick<
SidebarThreadSummary,
"hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
>;
export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status {
export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
if (thread.hasPendingApprovals) {
return "approval";
}
@@ -496,11 +502,11 @@ export function firstValidTimestamp(
return null;
}
// v2 sort: static creation order, newest thread on top. Activity NEVER
// Sidebar sort: static creation order, newest thread on top. Activity NEVER
// reorders the list — a row holds its position from open until settled, so
// the screen only moves at lifecycle transitions. Status (including pending
// approval) is carried by each card's edge strip, not by position.
export function sortThreadsForSidebarV2<
export function sortThreadsForSidebar<
T extends { readonly id: string; readonly createdAt: string },
>(threads: readonly T[]): T[] {
return [...threads].toSorted(
@@ -517,7 +523,7 @@ export {
pinOrderKeyBetween,
planPinnedReorder,
} from "@t3tools/client-runtime/state/thread-sort";
export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebarV2 } from "@t3tools/client-runtime/state/thread-sort";
export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
/**
* Search the already-ordered sidebar thread collection by title only.
@@ -566,7 +572,7 @@ export function resolveSettledTimestamp(thread: SettledTimestampInput): string |
// Settled rows are history, so they order by when the work ENDED, not when
// the thread was created or last touched.
export function sortSettledThreadsForSidebarV2<
export function sortSettledThreadsForSidebar<
T extends SettledTimestampInput & { readonly id: string },
>(threads: readonly T[]): T[] {
const timestampMs = (thread: T) => {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -66,7 +66,11 @@ import { terminalEnvironment } from "../state/terminal";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useAtomCommand } from "../state/use-atom-command";
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
import { resolveTerminalFontPreference, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../appearanceFonts";
import {
resolveTerminalFontPreference,
resolveTerminalFontSizePreference,
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
} from "../appearanceFonts";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -341,7 +345,13 @@ export function TerminalViewport({
terminal: settings.fontFamilyTerminal,
}),
);
const terminalFontSize = useClientSettings((settings) => settings.fontSizeTerminal);
const terminalFontSize = useClientSettings((settings) =>
resolveTerminalFontSizePreference({
advanced: advancedTypography,
code: settings.fontSizeCode,
terminal: settings.fontSizeTerminal,
}),
);
const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize });
const terminalSession = useAttachedTerminalSession({
environmentId,
@@ -1,6 +1,64 @@
import { describe, expect, it } from "vite-plus/test";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions";
vi.mock("~/hooks/useSettings", () => ({
useEnvironmentIdentificationMode: () => "none",
}));
vi.mock("../SidebarStageBackdrop", () => ({
StageBackdropButtonArt: () => null,
useSidebarStageBackdropVariant: () => null,
}));
import { ComposerPrimaryActions, formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions";
function renderPendingActions(isRunning: boolean) {
return renderToStaticMarkup(
createElement(ComposerPrimaryActions, {
compact: true,
pendingAction: {
questionIndex: 0,
isLastQuestion: true,
canAdvance: true,
isResponding: false,
isComplete: true,
},
isRunning,
showPlanFollowUpPrompt: false,
promptHasText: false,
isSendBusy: false,
sendDisabledReason: null,
isConnecting: false,
isEnvironmentUnavailable: false,
isPreparingWorktree: false,
hasSendableContent: false,
onPreviousPendingQuestion: () => {},
onInterrupt: () => {},
onImplementPlanInNewThread: () => {},
}),
);
}
function renderStandaloneStop() {
return renderToStaticMarkup(
createElement(ComposerPrimaryActions, {
compact: true,
pendingAction: null,
isRunning: true,
showPlanFollowUpPrompt: false,
promptHasText: false,
isSendBusy: false,
sendDisabledReason: null,
isConnecting: false,
isEnvironmentUnavailable: false,
isPreparingWorktree: false,
hasSendableContent: false,
onPreviousPendingQuestion: () => {},
onInterrupt: () => {},
onImplementPlanInNewThread: () => {},
}),
);
}
describe("formatPendingPrimaryActionLabel", () => {
it("returns 'Submitting...' while responding", () => {
@@ -91,3 +149,19 @@ describe("formatPendingPrimaryActionLabel", () => {
).toBe("Submit answers");
});
});
describe("ComposerPrimaryActions", () => {
it("offers Stop generation while a running turn is waiting for user input", () => {
expect(renderPendingActions(true)).toContain('aria-label="Stop generation"');
});
it("does not offer Stop generation for a pending request without a running turn", () => {
expect(renderPendingActions(false)).not.toContain('aria-label="Stop generation"');
});
it("matches the small pending action size without changing the standalone size", () => {
expect(renderPendingActions(true)).toContain("size-8 sm:size-7");
expect(renderStandaloneStop()).toContain("size-8 sm:h-8 sm:w-8");
expect(renderStandaloneStop()).not.toContain("sm:size-7");
});
});
@@ -75,9 +75,27 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
: undefined;
const isSendDisabled = sendDisabledReason !== null;
const renderStopGenerationButton = (insidePendingAction: boolean) => (
<button
type="button"
className={cn(
"flex cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none",
insidePendingAction ? "size-8 sm:size-7" : "size-8 sm:h-8 sm:w-8",
)}
{...pointerFocusProps}
onClick={onInterrupt}
aria-label="Stop generation"
>
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
<rect x="2" y="2" width="8" height="8" rx="1.5" />
</svg>
</button>
);
if (pendingAction) {
return (
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
{isRunning ? renderStopGenerationButton(true) : null}
{pendingAction.questionIndex > 0 ? (
compact ? (
<Button
@@ -130,19 +148,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
}
if (isRunning) {
return (
<button
type="button"
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none sm:h-8 sm:w-8"
{...pointerFocusProps}
onClick={onInterrupt}
aria-label="Stop generation"
>
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
<rect x="2" y="2" width="8" height="8" rx="1.5" />
</svg>
</button>
);
return renderStopGenerationButton(false);
}
if (showPlanFollowUpPrompt) {
@@ -1,6 +1,6 @@
import { cn } from "~/lib/utils";
/** Browser-window thumbnail glyph for the "Local" recommendation cards. */
/** Browser-window thumbnail glyph for preview recommendation cards. */
export function BrowserMockup({ className }: { className?: string }) {
return (
<div
@@ -0,0 +1,89 @@
import { EnvironmentId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => ({
servers: [] as Array<{
host: string;
port: number;
url: string;
requestedUrl: string;
processName: string | null;
pid: number | null;
terminal: null;
source: "scanner";
listening: boolean;
}>,
}));
vi.mock("./useDiscoveredLocalServers", () => ({
useDiscoveredLocalServers: () => mocks.servers,
}));
import { PreviewEmptyState } from "./PreviewEmptyState";
const environmentId = EnvironmentId.make("env-1");
function server(port: number) {
return {
host: "localhost",
port,
url: `http://localhost:${port}`,
requestedUrl: `http://localhost:${port}`,
processName: "node",
pid: 1,
terminal: null,
source: "scanner" as const,
listening: true,
};
}
function render(recentEntries: Array<{ url: string; lastVisitedAt: number; title?: string }>) {
return renderToStaticMarkup(
<PreviewEmptyState
environmentId={environmentId}
recentEntries={recentEntries}
onRemoveRecent={() => undefined}
onOpenUrl={() => undefined}
/>,
);
}
describe("PreviewEmptyState", () => {
it("renders a history entry in both groups when its host:port matches a live server", () => {
mocks.servers = [server(5173)];
const html = render([
{ url: "https://myapp.test/admin#users", lastVisitedAt: Date.now(), title: "Admin" },
{ url: "http://localhost:5173/", lastVisitedAt: Date.now(), title: "Recent Local" },
]);
expect(html).toContain("Recently used");
expect(html).toContain("Local servers");
expect(html).toContain("myapp.test/admin#users");
expect(html).toContain("Admin");
expect(html).toContain("Recent Local");
expect(html).toContain("node");
});
it("renders only the recents group when no servers are found", () => {
mocks.servers = [];
const html = render([{ url: "https://myapp.test/", lastVisitedAt: 0 }]);
expect(html).toContain("Recently used");
expect(html).not.toContain("Local servers");
});
it("keeps the original empty state when both groups are empty", () => {
mocks.servers = [];
const html = render([]);
expect(html).toContain("No preview yet");
});
it("renders an out-of-range lastVisitedAt entry without throwing", () => {
mocks.servers = [];
let html = "";
expect(() => {
html = render([{ url: "https://myapp.test/", lastVisitedAt: 1e20 }]);
}).not.toThrow();
expect(html).toContain("myapp.test");
expect(html).toContain("Remove");
});
});
@@ -1,15 +1,19 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { Globe, RadioTower } from "lucide-react";
import { Globe, History, RadioTower } from "lucide-react";
import type { BrowserHistoryEntry } from "~/browserHistoryStore";
import { Empty, EmptyDescription, EmptyMedia, EmptyTitle } from "~/components/ui/empty";
import { PreviewLocalServerCard } from "./PreviewLocalServerCard";
import { PreviewRecentUrlCard } from "./PreviewRecentUrlCard";
import { useDiscoveredLocalServers } from "./useDiscoveredLocalServers";
interface Props {
environmentId: EnvironmentId;
configuredUrls?: ReadonlyArray<string> | undefined;
recentlySeenUrls?: ReadonlyArray<string> | undefined;
recentEntries: ReadonlyArray<BrowserHistoryEntry>;
onRemoveRecent: (url: string) => void;
onOpenUrl: (url: string) => void;
}
@@ -17,6 +21,8 @@ export function PreviewEmptyState({
environmentId,
configuredUrls,
recentlySeenUrls,
recentEntries,
onRemoveRecent,
onOpenUrl,
}: Props) {
const servers = useDiscoveredLocalServers({
@@ -24,8 +30,9 @@ export function PreviewEmptyState({
configuredUrls,
recentlySeenUrls,
});
const recents = recentEntries.filter((entry) => URL.canParse(entry.url)).slice(0, 8);
if (servers.length === 0) {
if (servers.length === 0 && recents.length === 0) {
return (
<Empty>
<EmptyMedia variant="icon">
@@ -42,23 +49,45 @@ export function PreviewEmptyState({
return (
<div className="flex h-full min-h-0 overflow-y-auto px-5 py-8">
<div className="m-auto flex w-full max-w-xl flex-col gap-3">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<RadioTower className="size-4 shrink-0" />
<h2 className="font-medium">Local servers</h2>
</div>
<div className="flex flex-col divide-y divide-border/60 overflow-hidden rounded-xl border border-border/70 bg-background">
{servers.map((server) => (
<PreviewLocalServerCard
key={`${server.host}:${server.port}`}
server={server}
onOpen={() => onOpenUrl(server.url)}
/>
))}
</div>
<p className="px-1 text-xs text-muted-foreground">
Select a listening port to open it in this browser tab.
</p>
<div className="m-auto flex w-full max-w-xl flex-col gap-6">
{recents.length > 0 ? (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<History className="size-4 shrink-0" />
<h2 className="font-medium">Recently used</h2>
</div>
<div className="flex flex-col divide-y divide-border/60 overflow-hidden rounded-xl border border-border/70 bg-background">
{recents.map((entry) => (
<PreviewRecentUrlCard
key={entry.url}
entry={entry}
onOpen={() => onOpenUrl(entry.url)}
onRemove={() => onRemoveRecent(entry.url)}
/>
))}
</div>
</div>
) : null}
{servers.length > 0 ? (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<RadioTower className="size-4 shrink-0" />
<h2 className="font-medium">Local servers</h2>
</div>
<div className="flex flex-col divide-y divide-border/60 overflow-hidden rounded-xl border border-border/70 bg-background">
{servers.map((server) => (
<PreviewLocalServerCard
key={`${server.host}:${server.port}`}
server={server}
onOpen={() => onOpenUrl(server.requestedUrl)}
/>
))}
</div>
<p className="px-1 text-xs text-muted-foreground">
Select a listening port to open it in this browser tab.
</p>
</div>
) : null}
</div>
</div>
);
@@ -0,0 +1,51 @@
import { X } from "lucide-react";
import { isValidHistoryTimestamp, type BrowserHistoryEntry } from "~/browserHistoryStore";
import { useNowMinute } from "~/hooks/useNowMinute";
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { BrowserMockup } from "./BrowserMockup";
interface Props {
entry: BrowserHistoryEntry;
onOpen: () => void;
onRemove: () => void;
}
export function PreviewRecentUrlCard({ entry, onOpen, onRemove }: Props) {
const parsed = new URL(entry.url);
const path = parsed.pathname === "/" ? "" : parsed.pathname;
const label = `${parsed.host}${path}${parsed.search}${parsed.hash}`;
const visitedAt = isValidHistoryTimestamp(entry.lastVisitedAt)
? formatRelativeTimeLabel(new Date(entry.lastVisitedAt).toISOString())
: "";
useNowMinute();
return (
<div className="group relative flex w-full items-center">
<button
type="button"
onClick={onOpen}
className="flex w-full items-center gap-3 px-3 py-3 pr-10 text-left hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
>
<BrowserMockup className="size-7 shrink-0" />
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-sm font-medium text-foreground">
{entry.title ?? label}
</span>
<span className="truncate text-xs text-muted-foreground">
{entry.title ? `${label} · ` : ""}
{visitedAt}
</span>
</div>
</button>
<button
type="button"
aria-label={`Remove ${label} from history`}
onClick={onRemove}
className="absolute right-3 rounded p-1 text-muted-foreground opacity-0 hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover:opacity-100"
>
<X className="size-3.5" />
</button>
</div>
);
}
@@ -24,6 +24,17 @@ const mocks = vi.hoisted(() => ({
toggleAnnotation: null as (() => void) | null,
pictureInPicture: false,
showEmptyState: false,
recordVisitForThread: vi.fn(),
}));
const EMPTY_HISTORY: never[] = [];
vi.mock("~/browserHistoryStore", () => ({
recordVisitForThread: mocks.recordVisitForThread,
setTitleForThreadUrl: vi.fn(),
removeUrlForThread: vi.fn(),
BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT: 50,
useThreadRecentHistory: () => EMPTY_HISTORY,
}));
vi.mock("~/state/session", () => ({
@@ -232,6 +243,7 @@ describe("PreviewView navigation", () => {
mocks.toggleAnnotation = null;
mocks.pictureInPicture = false;
mocks.showEmptyState = false;
mocks.recordVisitForThread.mockClear();
});
it.each([
@@ -267,6 +279,27 @@ describe("PreviewView navigation", () => {
);
});
it("records a history visit with the normalized requested url on submit", async () => {
renderToStaticMarkup(
<PreviewView
threadRef={{
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
}}
tabId="tab-1"
visible
/>,
);
mocks.submittedUrl?.("localhost:3000/admin");
await vi.waitFor(() => {
expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
expect.objectContaining({ threadId: expect.anything() }),
"http://localhost:3000/admin",
);
});
});
it("maps an empty-state localhost server onto the WSL host", async () => {
mocks.showEmptyState = true;
renderToStaticMarkup(
@@ -296,6 +329,12 @@ describe("PreviewView navigation", () => {
},
"http://172.25.85.75:5173/app?mode=test#top",
);
await vi.waitFor(() =>
expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
expect.objectContaining({ threadId: expect.anything() }),
"http://localhost:5173/app?mode=test#top",
),
);
});
it("opens and closes a thread-scoped floating preview for the active tab", async () => {
+47 -12
View File
@@ -11,6 +11,13 @@ import {
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import { useCallback, useEffect, useRef, useState } from "react";
import {
BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
recordVisitForThread,
removeUrlForThread,
setTitleForThreadUrl,
useThreadRecentHistory,
} from "~/browserHistoryStore";
import { type ComposerImageAttachment, useComposerDraftStore } from "~/composerDraftStore";
import { previewAnnotationScreenshotFile } from "~/lib/previewAnnotation";
import { ensureLocalApi } from "~/localApi";
@@ -20,6 +27,7 @@ import {
useThreadPreviewState,
} from "~/previewStateStore";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import { useEnvironmentHttpBaseUrl } from "~/state/environments";
import { previewEnvironment } from "~/state/preview";
import { useAtomCommand } from "~/state/use-atom-command";
import { selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
@@ -83,12 +91,24 @@ export function PreviewView({
const activeRecordingTabIds = useActiveBrowserRecordingTabIds();
const pickActiveRef = useRef(false);
const isMountedRef = useRef(true);
// Kept in sync so the title effect can depend on the stable thread key
// instead of the thread object, which is recreated on every update.
const threadRefRef = useRef(threadRef);
threadRefRef.current = threadRef;
const previewState = useThreadPreviewState(threadRef);
const recentHistoryEntries = useThreadRecentHistory(
threadRef,
BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
);
const miniPlayer = usePreviewMiniPlayerStore((state) =>
selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef),
);
const addPreviewAnnotation = useComposerDraftStore((store) => store.addPreviewAnnotation);
const addImage = useComposerDraftStore((store) => store.addImage);
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);
const environmentHostname = environmentHttpBaseUrl
? new URL(environmentHttpBaseUrl).hostname
: null;
const open = useAtomCommand(previewEnvironment.open);
const resize = useAtomCommand(previewEnvironment.resize, "preview viewport resize");
@@ -128,20 +148,27 @@ export function PreviewView({
runtimeTabId ? (state.byTabId[runtimeTabId]?.rect ?? null) : null,
);
const navUrl = navStatus._tag === "Success" ? navStatus.url : null;
const navTitle = navStatus._tag === "Success" ? navStatus.title : null;
const latestHistoryUrl = recentHistoryEntries[0]?.url;
const threadKey = scopedThreadKey(threadRef);
useEffect(() => {
if (!navUrl || !navTitle || !latestHistoryUrl) return;
// Agent-driven pages only enrich an existing requested URL.
setTitleForThreadUrl(threadRefRef.current, navUrl, navTitle, environmentHostname);
// threadKey stands in for threadRef, whose identity churns on every thread update.
}, [environmentHostname, latestHistoryUrl, navTitle, navUrl, threadKey]);
const navigateToResolvedUrl = useCallback(
async (resolvedUrl: string) => {
if (runtimeTabId && previewBridge) {
// Drive the webview imperatively; `usePreviewBridge` mirrors the
// resolved URL back to the server so other clients stay in sync.
// The bridge mirrors the resolved URL back to the server.
await previewBridge.navigate(runtimeTabId, resolvedUrl);
rememberPreviewUrl(threadRef, resolvedUrl);
} else {
await openPreviewSession({
openPreview: open,
threadRef,
url: resolvedUrl,
});
return true;
}
const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });
return result._tag === "Success";
},
[open, runtimeTabId, threadRef],
);
@@ -149,23 +176,29 @@ export function PreviewView({
const handleSubmitUrl = useCallback(
async (next: string) => {
try {
await navigateToResolvedUrl(normalizePreviewUrl(next));
const normalized = normalizePreviewUrl(next);
if (await navigateToResolvedUrl(normalized)) {
recordVisitForThread(threadRef, normalized);
}
} catch {
// Server-side `failed` event renders the unreachable view.
}
},
[navigateToResolvedUrl],
[navigateToResolvedUrl, threadRef],
);
const handleOpenServerUrl = useCallback(
async (next: string) => {
try {
await navigateToResolvedUrl(resolveDiscoveredServerUrl(threadRef.environmentId, next));
const resolved = resolveDiscoveredServerUrl(threadRef.environmentId, next);
if (await navigateToResolvedUrl(resolved)) {
recordVisitForThread(threadRef, next);
}
} catch {
// Server-side `failed` event renders the unreachable view.
}
},
[navigateToResolvedUrl, threadRef.environmentId],
[navigateToResolvedUrl, threadRef],
);
const handleRefresh = useCallback(() => {
@@ -680,6 +713,8 @@ export function PreviewView({
environmentId={threadRef.environmentId}
configuredUrls={configuredUrls}
recentlySeenUrls={previewState.recentlySeenUrls}
recentEntries={recentHistoryEntries}
onRemoveRecent={(url) => removeUrlForThread(threadRef, url)}
onOpenUrl={(next) => void handleOpenServerUrl(next)}
/>
) : null}
@@ -6,6 +6,7 @@ import {
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
import { recordVisitForThread } from "~/browserHistoryStore";
import { useRightPanelStore } from "~/rightPanelStore";
import { openPreviewSession } from "./openPreviewSession";
@@ -21,6 +22,7 @@ export async function openDiscoveredPort<E>(input: {
url: resolvedUrl,
});
return mapAtomCommandResult(result, (snapshot) => {
recordVisitForThread(input.threadRef, input.port.url);
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
});
}
@@ -4,6 +4,7 @@ import { isPreviewableUrl } from "@t3tools/shared/preview";
import * as Schema from "effect/Schema";
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
import { recordVisitForThread } from "~/browserHistoryStore";
import { applyPreviewServerSnapshot, isPreviewSupportedInRuntime } from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
@@ -98,6 +99,7 @@ export async function openTerminalLinkInPreview<E>(
input.fallbackToBrowser();
return;
}
recordVisitForThread(input.threadRef, input.url);
applyPreviewServerSnapshot(input.threadRef, result.value);
useRightPanelStore.getState().openBrowser(input.threadRef, result.value.tabId);
return;
@@ -3,10 +3,13 @@ import { describe, expect, it } from "vite-plus/test";
import { mergeServers, type PreviewableServer } from "./useDiscoveredLocalServers";
const scannerServer = (overrides: Partial<DiscoveredLocalServer>): DiscoveredLocalServer => ({
const scannerServer = (
overrides: Partial<DiscoveredLocalServer & { requestedUrl: string }>,
): DiscoveredLocalServer & { requestedUrl: string } => ({
host: "localhost",
port: 5173,
url: "http://localhost:5173",
requestedUrl: overrides.url ?? "http://localhost:5173",
processName: "vite",
pid: 1234,
terminal: null,
@@ -24,6 +27,7 @@ describe("mergeServers", () => {
expect(result[0]).toMatchObject({
host: "localhost",
port: 5173,
requestedUrl: "http://localhost:5173",
source: "scanner",
listening: true,
processName: "vite",
@@ -56,6 +60,7 @@ describe("mergeServers", () => {
expect(result[0]).toMatchObject({
source: "configured",
listening: false,
requestedUrl: "http://localhost:5173/",
});
});
@@ -68,6 +73,7 @@ describe("mergeServers", () => {
expect(result.map((s) => s.port)).toEqual([5173, 8080]);
expect(result.find((s) => s.port === 5173)?.source).toBe("scanner");
expect(result.find((s) => s.port === 8080)?.source).toBe("recent");
expect(result.find((s) => s.port === 8080)?.requestedUrl).toBe("http://localhost:8080/");
});
it("ignores non-loopback URLs in configured/recent inputs", () => {
@@ -102,6 +108,22 @@ describe("mergeServers", () => {
});
expect(result).toHaveLength(1);
});
it("keeps a scanner entry's pre-resolution requestedUrl distinct from a resolved url", () => {
const result = mergeServers({
scanner: [
scannerServer({
port: 5173,
url: "https://env-42.example.dev:5173/",
requestedUrl: "http://localhost:5173/",
}),
],
configuredUrls: [],
recentlySeenUrls: [],
});
expect(result[0]?.url).toBe("https://env-42.example.dev:5173/");
expect(result[0]?.requestedUrl).toBe("http://localhost:5173/");
});
});
describe("PreviewableServer interface", () => {
@@ -13,6 +13,11 @@ export interface PreviewableServer extends DiscoveredLocalServer {
* `configured` entry can also be `listening` when the scan enriched it.
*/
listening: boolean;
/**
* Pre-resolution loopback url. `url` is the resolved navigation target
* (volatile on a remote environment); history must key off this instead.
*/
requestedUrl: string;
}
interface UseDiscoveredLocalServersInput {
@@ -36,6 +41,7 @@ export function useDiscoveredLocalServers(
scanner: scannerSnapshot.map((server) => ({
...server,
url: resolveDiscoveredServerUrl(input.environmentId, server.url),
requestedUrl: server.url,
})),
configuredUrls: input.configuredUrls ?? [],
recentlySeenUrls: input.recentlySeenUrls ?? [],
@@ -45,7 +51,7 @@ export function useDiscoveredLocalServers(
}
export function mergeServers(input: {
scanner: ReadonlyArray<DiscoveredLocalServer>;
scanner: ReadonlyArray<DiscoveredLocalServer & { requestedUrl: string }>;
configuredUrls: ReadonlyArray<string>;
recentlySeenUrls: ReadonlyArray<string>;
}): ReadonlyArray<PreviewableServer> {
@@ -60,6 +66,7 @@ export function mergeServers(input: {
host: parsed.host,
port: parsed.port,
url: parsed.url,
requestedUrl: parsed.url,
processName: null,
pid: null,
terminal: null,
@@ -95,6 +102,7 @@ export function mergeServers(input: {
host: parsed.host,
port: parsed.port,
url: parsed.url,
requestedUrl: parsed.url,
processName: null,
pid: null,
terminal: null,
@@ -1,132 +0,0 @@
import { useEffect, useState } from "react";
import {
useClientSettings,
useSidebarV2Enabled,
useUpdateClientSettings,
} from "../../hooks/useSettings";
import { Input } from "../ui/input";
import { Switch } from "../ui/switch";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
const AUTO_SETTLE_MIN_DAYS = 1;
const AUTO_SETTLE_MAX_DAYS = 90;
const AUTO_SETTLE_DEFAULT_DAYS = 3;
function AutoSettleDaysInput({
value,
onCommit,
}: {
value: number;
onCommit: (days: number) => void;
}) {
// Local draft so the field can be emptied mid-edit; the setting only moves
// on valid input and snaps back to the persisted value on blur.
const [draft, setDraft] = useState(String(value));
useEffect(() => {
setDraft(String(value));
}, [value]);
return (
<Input
type="number"
min={AUTO_SETTLE_MIN_DAYS}
max={AUTO_SETTLE_MAX_DAYS}
className="w-full sm:w-24"
value={draft}
onChange={(event) => {
setDraft(event.target.value);
// Number(), not parseInt: "3.5" must be rejected (not truncated to a
// committed 3 while the field shows 3.5) — commit only when the
// persisted value matches the displayed one.
const parsed = Number(event.target.value);
if (
Number.isInteger(parsed) &&
parsed >= AUTO_SETTLE_MIN_DAYS &&
parsed <= AUTO_SETTLE_MAX_DAYS
) {
onCommit(parsed);
}
}}
onBlur={() => setDraft(String(value))}
aria-label="Days of inactivity before auto-settle"
/>
);
}
export function BetaSettingsPanel() {
const sidebarV2Enabled = useSidebarV2Enabled();
const sidebarAutoSettleAfterDays = useClientSettings(
(settings) => settings.sidebarAutoSettleAfterDays,
);
const planModeEnabled = useClientSettings((settings) => settings.planModeEnabled);
const updateSettings = useUpdateClientSettings();
return (
<SettingsPageContainer>
<SettingsSection title="Beta features">
<SettingsRow
{...searchableSetting("sidebar-v2")}
description="One flat thread list in creation order. Active work renders as rich cards; settled threads collapse to compact rows. Settling requires an up-to-date server — on older servers threads simply stay active. Switch back any time."
control={
<Switch
checked={sidebarV2Enabled}
// Touching the switch pins the choice, so a nightly build that
// defaults v2 on does not flip it back after the user opts out.
onCheckedChange={(checked) =>
updateSettings({
sidebarV2Enabled: Boolean(checked),
sidebarV2ConfiguredByUser: true,
})
}
aria-label="Enable the sidebar v2 beta"
/>
}
/>
{sidebarV2Enabled ? (
<>
<SettingsRow
title={searchableSetting("auto-settle-inactive-threads").title}
description="Threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle."
control={
<Switch
checked={sidebarAutoSettleAfterDays !== null}
onCheckedChange={(checked) =>
updateSettings({
sidebarAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null,
})
}
aria-label="Auto-settle inactive threads"
/>
}
/>
{sidebarAutoSettleAfterDays !== null ? (
<SettingsRow
title="Days of inactivity before auto-settle"
description="Any new activity un-settles a thread automatically."
control={
<AutoSettleDaysInput
value={sidebarAutoSettleAfterDays}
onCommit={(days) => updateSettings({ sidebarAutoSettleAfterDays: days })}
/>
}
/>
) : null}
</>
) : null}
<SettingsRow
{...searchableSetting("restore-plan-mode")}
description="Legacy feature. Brings back the Build/Plan toggle in the composer along with the /plan and /default commands and the Shift+Tab shortcut. While off, every thread runs in build mode."
control={
<Switch
checked={planModeEnabled}
onCheckedChange={(checked) => updateSettings({ planModeEnabled: Boolean(checked) })}
aria-label="Restore plan mode (legacy)"
/>
}
/>
</SettingsSection>
</SettingsPageContainer>
);
}
@@ -1,4 +1,4 @@
import { ArchiveIcon, ArchiveX, LoaderIcon, SettingsIcon } from "lucide-react";
import { ArchiveIcon, ArchiveX, ChevronRightIcon, LoaderIcon, SettingsIcon } from "lucide-react";
import { Link } from "@tanstack/react-router";
import type { CSSProperties, ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -24,11 +24,13 @@ import {
MAX_GLASS_OPACITY,
MAX_INTERFACE_FONT_SIZE,
MAX_PROMPT_FONT_SIZE,
MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
MAX_TERMINAL_FONT_SIZE,
MIN_CODE_FONT_SIZE,
MIN_GLASS_OPACITY,
MIN_INTERFACE_FONT_SIZE,
MIN_PROMPT_FONT_SIZE,
MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
MIN_TERMINAL_FONT_SIZE,
} from "@t3tools/contracts/settings";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
@@ -79,6 +81,7 @@ import { useProjects } from "../../state/entities";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import { formatRelativeTimeLabel } from "../../timestampFormat";
import { Button } from "../ui/button";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
import {
Dialog,
DialogDescription,
@@ -97,6 +100,7 @@ import {
isMonospaceFamily,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
resolveTerminalFontSizePreference,
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
} from "../../appearanceFonts";
import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews";
@@ -462,6 +466,10 @@ export function useSettingsRestore(onRestored?: () => void) {
DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode
? ["Project Grouping"]
: []),
...(settings.sidebarAutoSettleAfterDays !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays
? ["Auto-settle inactive threads"]
: []),
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
...(settings.fontFamilySans !== DEFAULT_UNIFIED_SETTINGS.fontFamilySans
? ["Interface font"]
@@ -476,8 +484,9 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
? ["Diff whitespace changes"]
: []),
...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
? ["Assistant output"]
...(settings.enableLegacyTokenStreaming !==
DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming
? ["Stream token by token"]
: []),
...(settings.enableProviderUpdateChecks !==
DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks
@@ -521,8 +530,9 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.fontSizePrompt,
settings.fontSizeTerminal,
settings.glassOpacity,
settings.enableAssistantStreaming,
settings.enableLegacyTokenStreaming,
settings.enableProviderUpdateChecks,
settings.sidebarAutoSettleAfterDays,
settings.sidebarProjectGroupingMode,
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
@@ -601,7 +611,8 @@ export function useSettingsRestore(onRestored?: () => void) {
glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity,
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays,
enableLegacyTokenStreaming: DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming,
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile,
@@ -1262,7 +1273,11 @@ function SimpleFontRows() {
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
})}
size={settings.fontSizeTerminal}
size={resolveTerminalFontSizePreference({
advanced: false,
code: settings.fontSizeCode,
terminal: settings.fontSizeTerminal,
})}
/>
</>
}
@@ -1504,6 +1519,153 @@ function FontFamilySettingsRow({
);
}
const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ?? 3;
function AutoSettleDaysInput({
value,
onCommit,
}: {
value: number;
onCommit: (days: number) => void;
}) {
// Local draft so the field can be emptied mid-edit; the setting only moves
// on valid input and snaps back to the persisted value on blur.
const [draft, setDraft] = useState(String(value));
useEffect(() => {
setDraft(String(value));
}, [value]);
return (
<Input
type="number"
min={MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}
max={MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}
className="w-full sm:w-24"
value={draft}
onChange={(event) => {
setDraft(event.target.value);
// Number(), not parseInt: "3.5" must be rejected (not truncated to a
// committed 3 while the field shows 3.5) — commit only when the
// persisted value matches the displayed one.
const parsed = Number(event.target.value);
if (
Number.isInteger(parsed) &&
parsed >= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS &&
parsed <= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS
) {
onCommit(parsed);
}
}}
onBlur={() => setDraft(String(value))}
aria-label="Days of inactivity before auto-settle"
/>
);
}
// The legacy rows sit behind the fold, so a settings-search jump has to
// expand the section before its target can mount and scroll.
const LEGACY_FEATURE_TARGET_IDS: ReadonlySet<string> = new Set([
"legacy-plan-mode",
"legacy-token-streaming",
"legacy-sidebar",
]);
/**
* Retired features kept only for users who still depend on them. Collapsed by
* default so they stay out of the everyday settings path; a settings-search
* jump to one of the rows unfolds the section.
*/
function LegacyFeaturesSection() {
const settings = usePrimarySettings();
const updateSettings = useUpdatePrimarySettings();
const [open, setOpen] = useState(false);
const searchTargetId = useSettingsSearchTargetId();
// Unfold once per search jump; tracking the handled id lets the user fold
// the section back up without the still-set target immediately reopening it.
const lastExpandedTargetRef = useRef<string | null>(null);
useEffect(() => {
if (searchTargetId === null) {
// A handled jump clears the target; forgetting it here lets a later
// jump to the same row expand the section again.
lastExpandedTargetRef.current = null;
return;
}
if (!LEGACY_FEATURE_TARGET_IDS.has(searchTargetId)) return;
if (lastExpandedTargetRef.current === searchTargetId) return;
lastExpandedTargetRef.current = searchTargetId;
setOpen(true);
}, [searchTargetId]);
return (
<section className="space-y-3">
<Collapsible open={open} onOpenChange={setOpen}>
<CollapsibleTrigger className="group flex min-h-8 w-full items-center gap-2 px-3 sm:px-4">
<h2 className="text-lg font-semibold tracking-[-0.025em] text-muted-foreground transition-colors group-hover:text-foreground">
Legacy features
</h2>
<ChevronRightIcon className="size-4 text-muted-foreground transition-transform duration-200 group-data-panel-open:rotate-90" />
</CollapsibleTrigger>
<CollapsiblePanel>
<div className="relative space-y-1 overflow-visible pt-3 text-foreground">
<SettingsRow
{...searchableSetting("legacy-plan-mode")}
description="Brings back the Build/Plan toggle in the composer along with the /plan and /default commands and the Shift+Tab shortcut. While off, every thread runs in build mode."
control={
<Switch
checked={settings.planModeEnabled}
onCheckedChange={(checked) =>
updateSettings({ planModeEnabled: Boolean(checked) })
}
aria-label="Plan mode (legacy)"
/>
}
/>
<SettingsRow
{...searchableSetting("legacy-token-streaming")}
description="Paints assistant output token by token instead of in complete chunks. Not recommended: it is significantly slower, and long responses become harder to follow. Kept only for compatibility with the old behavior."
control={
<Switch
checked={settings.enableLegacyTokenStreaming}
onCheckedChange={(checked) => {
if (!checked) {
updateSettings({ enableLegacyTokenStreaming: false });
return;
}
void (async () => {
const api = readLocalApi();
const confirmed = await (api ?? ensureLocalApi()).dialogs.confirm(
[
"Turn on token-by-token output?",
"It is significantly slower than the default buffered output and hurts the reading experience. This switch exists only for backwards compatibility.",
].join("\n"),
);
if (confirmed) updateSettings({ enableLegacyTokenStreaming: true });
})();
}}
aria-label="Stream token by token (legacy)"
/>
}
/>
<SettingsRow
{...searchableSetting("legacy-sidebar")}
description="Brings back the original sidebar with per-project thread trees. The default sidebar shows one flat list: active work as rich cards, settled threads as compact rows."
control={
<Switch
checked={settings.legacySidebarEnabled}
onCheckedChange={(checked) =>
updateSettings({ legacySidebarEnabled: Boolean(checked) })
}
aria-label="Sidebar (legacy)"
/>
}
/>
</div>
</CollapsiblePanel>
</Collapsible>
</section>
);
}
export function GeneralSettingsPanel() {
const settings = usePrimarySettings();
const updateSettings = useUpdatePrimarySettings();
@@ -1596,6 +1758,47 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
{...searchableSetting("auto-settle-inactive-threads")}
description="Sidebar threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle."
resetAction={
settings.sidebarAutoSettleAfterDays !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ? (
<SettingResetButton
label="auto-settle"
onClick={() =>
updateSettings({
sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays,
})
}
/>
) : null
}
control={
<Switch
checked={settings.sidebarAutoSettleAfterDays !== null}
onCheckedChange={(checked) =>
updateSettings({
sidebarAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null,
})
}
aria-label="Auto-settle inactive threads"
/>
}
/>
{settings.sidebarAutoSettleAfterDays !== null ? (
<SettingsRow
title="Days of inactivity before auto-settle"
description="Any new activity un-settles a thread automatically."
control={
<AutoSettleDaysInput
value={settings.sidebarAutoSettleAfterDays}
onCommit={(days) => updateSettings({ sidebarAutoSettleAfterDays: days })}
/>
}
/>
) : null}
<SettingsRow
{...searchableSetting("time-format")}
description="System default follows your browser or OS clock preference."
@@ -1664,33 +1867,6 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
{...searchableSetting("assistant-output")}
description="Show token-by-token output while a response is in progress."
resetAction={
settings.enableAssistantStreaming !==
DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (
<SettingResetButton
label="assistant output"
onClick={() =>
updateSettings({
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
})
}
/>
) : null
}
control={
<Switch
checked={settings.enableAssistantStreaming}
onCheckedChange={(checked) =>
updateSettings({ enableAssistantStreaming: Boolean(checked) })
}
aria-label="Stream assistant messages"
/>
}
/>
<SettingsRow
{...searchableSetting("provider-update-checks")}
description="Check installed provider CLIs for newer available versions."
@@ -2050,6 +2226,8 @@ export function GeneralSettingsPanel() {
}
/>
</SettingsSection>
<LegacyFeaturesSection />
</SettingsPageContainer>
);
}
@@ -11,7 +11,6 @@ import {
ArchiveIcon,
ArrowLeftIcon,
BotIcon,
FlaskConicalIcon,
GitBranchIcon,
KeyboardIcon,
Link2Icon,
@@ -52,7 +51,6 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/providers": BotIcon,
"/settings/source-control": GitBranchIcon,
"/settings/connections": Link2Icon,
"/settings/beta": FlaskConicalIcon,
"/settings/archived": ArchiveIcon,
};
@@ -165,6 +165,7 @@ export function ThemeEditorPanel({
const isEditing = editingTheme !== null;
const [name, setName] = useState("");
const [activeAppearance, setActiveAppearance] = useState<ThemeAppearance>(initialAppearance);
const [sidebarArtwork, setSidebarArtwork] = useState(false);
const [isAdvanced, setIsAdvanced] = useState(false);
const [colorsByAppearance, setColorsByAppearance] = useState<ThemeEditorColorsByAppearance>(() =>
getThemeEditorColorsByAppearance(),
@@ -178,6 +179,7 @@ export function ThemeEditorPanel({
const [isInspecting, setIsInspecting] = useState(false);
const [selectedRole, setSelectedRole] = useState<ThemeColorRole | null>(null);
const [usageCount, setUsageCount] = useState<number | null>(null);
const previousMergeTargetIdRef = useRef<string | null>(null);
// Null parks the panel at its default corner; a value is a dragged spot,
// kept clamped so the header can always be grabbed again.
const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
@@ -259,6 +261,9 @@ export function ThemeEditorPanel({
setName(editingTheme?.label ?? seedName ?? "");
setActiveAppearance(nextAppearance);
// Artwork is opt-in for new themes, including duplicates. Editing keeps
// the theme's existing choice.
setSidebarArtwork(editingTheme?.sidebarArtwork === true);
// Themes saved by the guided editor carry the managed flag; anything
// else (imports, hand-edited files, older saves) opens in advanced mode
// so guided regeneration cannot silently discard hand-tuned colors. A
@@ -315,6 +320,18 @@ export function ThemeEditorPanel({
// an explanation instead.
const mergeTargetId = mergeTarget?.id ?? null;
const takenAppearancesKey = takenAppearances.join(",");
useEffect(() => {
if (previousMergeTargetIdRef.current === mergeTargetId) return;
previousMergeTargetIdRef.current = mergeTargetId;
// A matching name makes that existing theme the surviving merge target.
// Seed theme-level options from it so adding a palette or renaming onto it
// does not silently reset them. Leaving the merge restores the edited
// theme's option (or the off-by-default choice for a new theme).
setSidebarArtwork(
mergeTarget ? mergeTarget.sidebarArtwork === true : editingTheme?.sidebarArtwork === true,
);
}, [editingTheme, mergeTarget, mergeTargetId]);
useEffect(() => {
if (isEditing || mergeTargetId === null) return;
const taken = takenAppearancesKey.split(",").filter(Boolean) as ThemeAppearance[];
@@ -330,8 +347,8 @@ export function ThemeEditorPanel({
// comes back when the editor closes, including on cancel.
useEffect(() => {
if (!open || !isDraftSeeded) return;
applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance);
}, [activeAppearance, colorsByAppearance, isDraftSeeded, open]);
applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance, sidebarArtwork);
}, [activeAppearance, colorsByAppearance, isDraftSeeded, open, sidebarArtwork]);
useEffect(() => {
if (!open) return;
@@ -657,6 +674,7 @@ export function ThemeEditorPanel({
...mergeTarget.variants,
...Object.fromEntries(editedModes.map((mode) => [mode, colorsForSave[mode]])),
},
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
}),
);
@@ -687,6 +705,7 @@ export function ThemeEditorPanel({
...(getThemeModes(editingTheme).length > 1
? { variants: { [variantAppearance]: colorsForSave[variantAppearance] } }
: {}),
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(isAdvanced ? {} : { managed: true }),
}),
);
@@ -713,6 +732,7 @@ export function ThemeEditorPanel({
...mergeTarget.variants,
[activeAppearance]: colorsForSave[activeAppearance],
},
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
}),
);
@@ -723,6 +743,7 @@ export function ThemeEditorPanel({
name,
appearance: activeAppearance,
colors: colorsForSave[activeAppearance],
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(isAdvanced ? {} : { managed: true }),
}),
);
@@ -773,6 +794,7 @@ export function ThemeEditorPanel({
name,
onOpenChange,
onSaved,
sidebarArtwork,
simpleColorsDirtyByAppearance,
takenAppearances,
]);
@@ -832,6 +854,20 @@ export function ThemeEditorPanel({
</div>
);
const renderSidebarArtworkToggle = () => (
<label className="grid cursor-pointer grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
<span className="text-sm font-medium">Sidebar artwork</span>
<span className="flex items-center justify-between gap-3 text-xs text-muted-foreground">
<span>Show T3 Code environment artwork</span>
<Switch
aria-label="Allow sidebar artwork with this theme"
checked={sidebarArtwork}
onCheckedChange={(checked) => setSidebarArtwork(Boolean(checked))}
/>
</span>
</label>
);
const renderColorsHeader = () => (
<div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-start gap-3">
<div>
@@ -1088,6 +1124,7 @@ export function ThemeEditorPanel({
</p>
) : null}
{renderAppearanceButtons()}
{renderSidebarArtworkToggle()}
<div className="space-y-3">
{renderColorsHeader()}
{renderColorFields()}
@@ -5,7 +5,6 @@ export type SettingsPath =
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/beta"
| "/settings/archived";
export interface SettingsSearchItem {
@@ -26,7 +25,6 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
"/settings/providers": "Providers",
"/settings/source-control": "Source Control",
"/settings/connections": "Connections",
"/settings/beta": "Beta",
"/settings/archived": "Archive",
};
@@ -100,6 +98,11 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Project grouping",
to: "/settings/general",
},
{
id: "auto-settle-inactive-threads",
title: "Auto-settle inactive threads",
to: "/settings/general",
},
{
id: "time-format",
title: "Time format",
@@ -110,11 +113,6 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Hide whitespace changes",
to: "/settings/general",
},
{
id: "assistant-output",
title: "Assistant output",
to: "/settings/general",
},
{
id: "provider-update-checks",
title: "Provider update checks",
@@ -156,6 +154,21 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Diagnostics",
to: "/settings/general",
},
{
id: "legacy-plan-mode",
title: "Plan mode (legacy)",
to: "/settings/general",
},
{
id: "legacy-token-streaming",
title: "Stream token by token (legacy)",
to: "/settings/general",
},
{
id: "legacy-sidebar",
title: "Sidebar (legacy)",
to: "/settings/general",
},
{
id: "keybindings",
title: "Keybindings",
@@ -176,22 +189,6 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Remote environments",
to: "/settings/connections",
},
{
id: "sidebar-v2",
title: "Sidebar v2",
to: "/settings/beta",
},
{
id: "auto-settle-inactive-threads",
title: "Auto-settle inactive threads",
to: "/settings/beta",
targetId: "sidebar-v2",
},
{
id: "restore-plan-mode",
title: "Restore plan mode (legacy)",
to: "/settings/beta",
},
{
id: "archive",
title: "Archived threads",
@@ -1,4 +1,4 @@
import { SettingsIcon } from "lucide-react";
import { ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react";
import { memo, useCallback } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
@@ -118,11 +118,24 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
void navigate({ to: "/settings" });
}, [isMobile, navigate, setOpenMobile]);
const handleUsageClick = useCallback(() => {
if (isMobile) {
setOpenMobile(false);
}
void navigate({ to: "/usage" });
}, [isMobile, navigate, setOpenMobile]);
return (
<SidebarFooter className="p-[var(--sidebar-content-inset)]">
<SidebarProviderUpdatePill />
<SidebarUpdatePill />
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton onClick={handleUsageClick}>
<ChartNoAxesColumnIcon />
<span>Usage</span>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton onClick={handleSettingsClick}>
<SettingsIcon />
+454
View File
@@ -0,0 +1,454 @@
import type { UsageProviderKind } from "@t3tools/contracts";
import { RefreshCwIcon } from "lucide-react";
import { useMemo, useState } from "react";
import { cn } from "../../lib/utils";
import { useUsage } from "../../state/usage";
import {
enumerateDays,
formatCount,
formatDayShort,
formatPercent,
formatTokens,
formatUsd,
makeWindow,
} from "../../usage/usageFormat";
import { ScrollArea } from "../ui/scroll-area";
import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
const WINDOW_OPTIONS = [
{ days: 7, label: "7 days" },
{ days: 30, label: "30 days" },
{ days: 90, label: "90 days" },
] as const;
export function UsagePage() {
const [windowDays, setWindowDays] = useState<number>(30);
const [metric, setMetric] = useState<UsageChartMetric>("cost");
const [breakdown, setBreakdown] = useState<"model" | "day">("model");
// Recomputed only when the window length changes, so a re-render does not
// shift the range and refetch every environment.
const window = useMemo(() => makeWindow(windowDays), [windowDays]);
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
const days = useMemo(
() => enumerateDays(window.sinceDay, window.untilDay),
[window.sinceDay, window.untilDay],
);
const recentDays = useMemo(() => merged.daily.toReversed().slice(0, 8), [merged.daily]);
// Ranked by whatever the toggle is showing, so the bars always descend.
const orderedProviders = useMemo(
() =>
merged.providers.toSorted((a, b) =>
metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
),
[merged.providers, metric],
);
const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;
const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;
const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
return (
<ScrollArea className="h-full">
<div className="mx-auto flex w-full max-w-6xl flex-col gap-8 px-6 py-6">
<header className="flex flex-wrap items-start justify-between gap-4">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-semibold text-foreground">Usage</h1>
<p className="text-sm text-muted-foreground">
{formatDayShort(window.sinceDay)} to {formatDayShort(window.untilDay)}
</p>
</div>
<div className="flex items-center gap-2">
<div className="flex overflow-hidden rounded-md border border-border">
{WINDOW_OPTIONS.map((option) => (
<button
key={option.days}
type="button"
onClick={() => setWindowDays(option.days)}
className={cn(
"px-3 py-1.5 text-xs",
option.days === windowDays
? "bg-muted text-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
{option.label}
</button>
))}
</div>
<button
type="button"
onClick={refresh}
aria-label="Refresh usage"
className="rounded-md border border-border p-2 text-muted-foreground hover:text-foreground"
>
<RefreshCwIcon className="size-3.5" />
</button>
</div>
</header>
<UsageCoverageNotice
environments={environments}
duplicateSources={merged.duplicateSources}
staleEnvironments={merged.staleEnvironments}
isPartial={isPartial}
/>
{isPending ? (
<p className="py-16 text-center text-sm text-muted-foreground">
Scanning provider transcripts…
</p>
) : (
<>
{/* Cost first: the financial answer, then the provider split. */}
<section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
{/* The summary follows the chart toggle, so the headline and the
series are always reading the same units. */}
<div className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<span className="text-xs tracking-wide text-muted-foreground uppercase">
{metric === "cost" ? "Raw token cost" : "Processed tokens"}
</span>
<span className="text-4xl font-semibold text-foreground tabular-nums">
{metric === "cost"
? `${formatUsd(merged.costUsd)}*`
: formatTokens(merged.totalTokens)}
</span>
<span className="text-xs text-muted-foreground">
{metric === "cost"
? "* if billed at full API rate"
: `Input, cache reads and output across ${formatCount(merged.sessions)} sessions.`}
</span>
</div>
{orderedProviders.map((provider) => {
const share = metric === "cost" ? provider.costShare : provider.tokenShare;
return (
<div key={provider.provider} className="flex flex-col gap-1.5">
<div className="flex items-baseline justify-between">
<span className="flex items-center gap-2 text-sm text-foreground">
<ProviderMark provider={provider.provider} className="size-4" />
{PROVIDER_LABEL[provider.provider]}
</span>
<span className="text-sm text-foreground tabular-nums">
{metric === "cost"
? formatUsd(provider.costUsd)
: formatTokens(provider.totalTokens)}
</span>
</div>
<div className="h-1 w-full overflow-hidden rounded-full bg-muted">
<div
className="h-full"
style={{
width: `${(share * 100).toFixed(1)}%`,
backgroundColor: PROVIDER_COLOR[provider.provider],
}}
/>
</div>
<span className="text-xs text-muted-foreground">
{metric === "cost"
? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
: `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
</span>
</div>
);
})}
</div>
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 className="text-sm font-medium text-foreground">
Daily {metric === "tokens" ? "processed tokens" : "cost"}
</h2>
<div className="flex items-center gap-4">
<div className="flex overflow-hidden rounded-md border border-border">
{(["cost", "tokens"] as const).map((option) => (
<button
key={option}
type="button"
onClick={() => setMetric(option)}
className={cn(
"px-2.5 py-1 text-[10px] tracking-wide uppercase",
option === metric
? "bg-muted text-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
{option}
</button>
))}
</div>
<UsageChartLegend />
</div>
</div>
<UsageProviderChart days={days} daily={merged.daily} metric={metric} />
</div>
</section>
<section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5">
<Metric
label="Processed tokens"
value={formatTokens(merged.totalTokens)}
detail={`${formatTokens(dailyAverage)} per active day`}
/>
<Metric
label="Cached input"
value={formatTokens(merged.cachedInputTokens)}
detail={`${formatPercent(cachedShare)} of observed input`}
/>
<Metric
label="Uncached input"
value={formatTokens(merged.uncachedInputTokens)}
detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
/>
<Metric
label="Output"
value={formatTokens(merged.outputTokens)}
detail={`includes ${formatTokens(merged.reasoningTokens)} reasoning`}
/>
<Metric
label="Cache savings"
value={formatUsd(merged.costQuality.cacheSavingsUsd)}
detail={
merged.costUsd > 0
? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw token cost`
: "vs full input rates"
}
/>
</section>
<section className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,18rem)]">
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-3">
<h2 className="text-sm font-medium text-foreground">Breakdown</h2>
<div className="flex overflow-hidden rounded-md border border-border">
{(["model", "day"] as const).map((option) => (
<button
key={option}
type="button"
onClick={() => setBreakdown(option)}
className={cn(
"px-2.5 py-1 text-[10px] tracking-wide uppercase",
option === breakdown
? "bg-muted text-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
{option}
</button>
))}
</div>
</div>
{breakdown === "model" ? (
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border text-left text-xs text-muted-foreground">
<th className="py-2 font-normal">Model</th>
<th className="py-2 text-right font-normal">Cost</th>
<th className="py-2 text-right font-normal">Share</th>
<th className="py-2 text-right font-normal">Tokens</th>
</tr>
</thead>
<tbody>
{merged.models.length === 0 ? (
<tr>
<td colSpan={4} className="py-6 text-center text-muted-foreground">
No activity in this window.
</td>
</tr>
) : (
merged.models.map((model) => (
<tr
key={`${model.provider}:${model.model}`}
className="border-b border-border/50"
>
<td className="py-2 text-foreground">
<span className="flex items-center gap-2">
<ProviderMark provider={model.provider} className="size-3.5" />
{model.model}
</span>
</td>
<td className="py-2 text-right text-foreground tabular-nums">
{formatUsd(model.costUsd)}
</td>
<td className="py-2 text-right text-muted-foreground tabular-nums">
{formatPercent(model.costShare)}
</td>
<td className="py-2 text-right text-muted-foreground tabular-nums">
{formatTokens(model.totalTokens)}
</td>
</tr>
))
)}
</tbody>
</table>
) : (
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border text-left text-xs text-muted-foreground">
<th className="py-2 font-normal">Day</th>
{PROVIDER_ORDER.map((provider) => (
<th key={provider} className="py-2 text-right font-normal">
{PROVIDER_LABEL[provider]}
</th>
))}
<th className="py-2 text-right font-normal">Total</th>
<th className="py-2 text-right font-normal">Tokens</th>
</tr>
</thead>
<tbody>
{recentDays.length === 0 ? (
<tr>
<td colSpan={5} className="py-6 text-center text-muted-foreground">
No activity in this window.
</td>
</tr>
) : (
recentDays.map((day) => (
<tr key={day.day} className="border-b border-border/50">
<td className="py-2 text-foreground">{formatDayShort(day.day)}</td>
{PROVIDER_ORDER.map((provider) => (
<td
key={provider}
className="py-2 text-right text-muted-foreground tabular-nums"
>
{formatUsd(day.byProvider.get(provider)?.costUsd ?? 0)}
</td>
))}
<td className="py-2 text-right text-foreground tabular-nums">
{formatUsd(day.costUsd)}
</td>
<td className="py-2 text-right text-muted-foreground tabular-nums">
{formatTokens(day.totalTokens)}
</td>
</tr>
))
)}
</tbody>
</table>
)}
</div>
<div className="flex flex-col gap-3">
<h2 className="text-sm font-medium text-foreground">Cost quality</h2>
<dl className="flex flex-col">
<QualityRow
label="Provider reported"
value={formatPercent(merged.costQuality.providerReportedShare)}
/>
<QualityRow
label="Model priced"
value={formatPercent(merged.costQuality.modelPricedShare)}
/>
<QualityRow
label="Unpriced"
value={formatPercent(merged.costQuality.unpricedShare)}
/>
<QualityRow
label="Cache savings"
value={formatUsd(merged.costQuality.cacheSavingsUsd)}
/>
</dl>
</div>
</section>
</>
)}
</div>
</ScrollArea>
);
}
/** Brand mark for the harness a row belongs to. */
function ProviderMark({
provider,
className,
}: {
readonly provider: UsageProviderKind;
readonly className: string;
}) {
const Mark = PROVIDER_MARK[provider];
return <Mark className={cn("shrink-0", className)} aria-hidden />;
}
function Metric({
label,
value,
detail,
}: {
readonly label: string;
readonly value: string;
readonly detail: string;
}) {
return (
<div className="flex flex-col gap-0.5 bg-background px-4 py-3">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-lg text-foreground tabular-nums">{value}</span>
<span className="text-xs text-muted-foreground">{detail}</span>
</div>
);
}
function QualityRow({ label, value }: { readonly label: string; readonly value: string }) {
return (
<div className="flex items-center justify-between border-b border-border/50 py-2 text-sm">
<dt className="text-muted-foreground">{label}</dt>
<dd className="text-foreground tabular-nums">{value}</dd>
</div>
);
}
/**
* Says plainly when the totals are incomplete: an environment still answering,
* one that failed, or one whose transcripts another environment already
* reported.
*/
function UsageCoverageNotice({
environments,
duplicateSources,
staleEnvironments,
isPartial,
}: {
readonly environments: readonly {
environmentId: string;
label: string;
error: string | null;
isPending: boolean;
}[];
readonly duplicateSources: readonly string[];
readonly staleEnvironments: readonly string[];
readonly isPartial: boolean;
}) {
const failed = environments.filter((environment) => environment.error !== null);
const stale = environments.filter((environment) =>
staleEnvironments.includes(environment.environmentId),
);
if (failed.length === 0 && stale.length === 0 && duplicateSources.length === 0 && !isPartial) {
return null;
}
return (
<div className="flex flex-col gap-1 border border-border px-3 py-2 text-xs text-muted-foreground">
{isPartial ? <span>Some environments are still reporting. Totals are partial.</span> : null}
{failed.map((environment) => (
<span key={environment.label}>{environment.label} could not report usage.</span>
))}
{stale.map((environment) => (
<span key={environment.label}>
{environment.label} runs an older server version and is excluded from totals.
</span>
))}
{duplicateSources.length > 0 ? (
<span>
Counted once across environments sharing a transcript directory:{" "}
{duplicateSources.join(", ")}
</span>
) : null}
</div>
);
}
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vite-plus/test";
import { buildDayColumns, niceScale } from "./UsageProviderChart";
describe("niceScale", () => {
it("never puts the peak above the top of the scale", () => {
// Regression: an earlier version stopped at the last step below the peak,
// so the tallest day was drawn past the plot and clipped.
for (const peak of [1122.71, 999, 1, 0.04, 1_400_000_000, 37.5, 5000, 100.001]) {
const { max } = niceScale(peak, 4);
expect(max, `peak ${peak}`).toBeGreaterThanOrEqual(peak);
}
});
it("starts at zero and ends at the maximum", () => {
const { max, ticks } = niceScale(1122.71, 4);
expect(ticks[0]).toBe(0);
expect(ticks[ticks.length - 1]).toBeCloseTo(max, 6);
});
it("uses evenly spaced 1/2/5 steps", () => {
const { ticks } = niceScale(1122.71, 4);
const steps = ticks.slice(1).map((tick, index) => tick - (ticks[index] ?? 0));
for (const step of steps) expect(step).toBeCloseTo(steps[0] ?? 0, 6);
const [first = 0] = steps;
const normalized = first / 10 ** Math.floor(Math.log10(first));
expect([1, 2, 5, 10]).toContain(Math.round(normalized));
});
it("keeps the tick count near the requested resolution", () => {
const { ticks } = niceScale(1122.71, 4);
expect(ticks.length).toBeGreaterThanOrEqual(3);
expect(ticks.length).toBeLessThanOrEqual(7);
});
it("degrades to a single zero tick with no data", () => {
expect(niceScale(0, 4)).toEqual({ max: 0, ticks: [0] });
});
});
describe("buildDayColumns", () => {
const days = ["2026-08-01", "2026-08-02", "2026-08-03"];
const byDay = new Map([
[
"2026-08-01",
{
day: "2026-08-01",
costUsd: 30,
totalTokens: 300,
byProvider: new Map([
["codex" as const, { costUsd: 10, totalTokens: 100 }],
["claude" as const, { costUsd: 20, totalTokens: 200 }],
]),
},
],
// 2026-08-02 is deliberately absent: a day with no activity.
[
"2026-08-03",
{
day: "2026-08-03",
costUsd: 5,
totalTokens: 50,
byProvider: new Map([["claude" as const, { costUsd: 5, totalTokens: 50 }]]),
},
],
]);
it("plots each day on its own", () => {
expect(buildDayColumns(days, byDay, "cost").map((column) => column.total)).toEqual([30, 0, 5]);
});
it("reads the requested metric", () => {
expect(buildDayColumns(days, byDay, "tokens").map((column) => column.total)).toEqual([
300, 0, 50,
]);
});
it("keeps band values absolute rather than cumulative", () => {
// Regression: the bands were once stack offsets, which drew Claude Code
// permanently above Codex regardless of which provider spent more.
const [first] = buildDayColumns(days, byDay, "cost");
expect(first?.bands).toEqual([
{ provider: "codex", value: 10 },
{ provider: "claude", value: 20 },
]);
});
it("reports the total as the sum of its bands", () => {
for (const column of buildDayColumns(days, byDay, "cost")) {
const sum = column.bands.reduce((running, band) => running + band.value, 0);
expect(column.total).toBeCloseTo(sum, 9);
}
});
});
@@ -0,0 +1,395 @@
import type { UsageProviderKind } from "@t3tools/contracts";
import { useCallback, useMemo, useRef, useState } from "react";
import type { DailyTotals } from "../../usage/usageMerge";
import { formatDayShort, formatTokens, formatUsd } from "../../usage/usageFormat";
import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
const VIEW_WIDTH = 960;
const VIEW_HEIGHT = 260;
const TICK_COUNT = 4;
const PLOT_TOP = 8;
export type UsageChartMetric = "tokens" | "cost";
interface UsageProviderChartProps {
readonly days: readonly string[];
readonly daily: readonly DailyTotals[];
readonly metric: UsageChartMetric;
}
/** One day's per-provider values, shared by the paths and the hover readout. */
export interface DayColumn {
readonly bands: readonly {
readonly provider: UsageProviderKind;
readonly value: number;
}[];
readonly total: number;
}
interface Point {
readonly x: number;
readonly y: number;
}
function valueFor(
daily: DailyTotals | undefined,
provider: UsageProviderKind,
metric: UsageChartMetric,
): number {
const entry = daily?.byProvider.get(provider);
if (entry === undefined) return 0;
return metric === "tokens" ? entry.totalTokens : entry.costUsd;
}
/**
* Monotone cubic tangents (Fritsch-Carlson).
*
* Plain cubic smoothing overshoots on spiky daily data and would dip the area
* below zero between points, which reads as negative spend. This variant is
* shape-preserving, so a smoothed series never leaves the range of its samples.
*/
function monotoneTangents(points: readonly Point[]): readonly number[] {
const count = points.length;
if (count < 2) return [0];
const slopes: number[] = [];
for (let index = 0; index < count - 1; index += 1) {
const dx = (points[index + 1]?.x ?? 0) - (points[index]?.x ?? 0);
const dy = (points[index + 1]?.y ?? 0) - (points[index]?.y ?? 0);
slopes.push(dx === 0 ? 0 : dy / dx);
}
const tangents: number[] = Array.from({ length: count }, () => 0);
tangents[0] = slopes[0] ?? 0;
tangents[count - 1] = slopes[count - 2] ?? 0;
for (let index = 1; index < count - 1; index += 1) {
const previous = slopes[index - 1] ?? 0;
const next = slopes[index] ?? 0;
tangents[index] = previous * next <= 0 ? 0 : (previous + next) / 2;
}
for (let index = 0; index < count - 1; index += 1) {
const slope = slopes[index] ?? 0;
if (slope === 0) {
tangents[index] = 0;
tangents[index + 1] = 0;
continue;
}
const a = (tangents[index] ?? 0) / slope;
const b = (tangents[index + 1] ?? 0) / slope;
const magnitude = a * a + b * b;
if (magnitude > 9) {
const scale = 3 / Math.sqrt(magnitude);
tangents[index] = scale * a * slope;
tangents[index + 1] = scale * b * slope;
}
}
return tangents;
}
/** One cubic segment of a smoothed boundary. */
interface CurveSegment {
readonly from: Point;
readonly c1: Point;
readonly c2: Point;
readonly to: Point;
}
/** Smoothed polyline through `points`, as explicit cubic control points. */
function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
if (points.length < 2) return [];
const tangents = monotoneTangents(points);
const segments: CurveSegment[] = [];
for (let index = 0; index < points.length - 1; index += 1) {
const from = points[index];
const to = points[index + 1];
if (from === undefined || to === undefined) continue;
const dx = to.x - from.x;
segments.push({
from,
c1: { x: from.x + dx / 3, y: from.y + ((tangents[index] ?? 0) * dx) / 3 },
c2: { x: to.x - dx / 3, y: to.y - ((tangents[index + 1] ?? 0) * dx) / 3 },
to,
});
}
return segments;
}
function curvePath(segments: readonly CurveSegment[], startCommand: "M" | "L"): string {
const first = segments[0];
if (first === undefined) return "";
let path = `${startCommand}${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
for (const segment of segments) {
path += ` C${segment.c1.x.toFixed(2)},${segment.c1.y.toFixed(2)} ${segment.c2.x.toFixed(2)},${segment.c2.y.toFixed(2)} ${segment.to.x.toFixed(2)},${segment.to.y.toFixed(2)}`;
}
return path;
}
/**
* Builds a scale whose maximum is a readable 1/2/5 x 10^n step at or above the
* peak.
*
* Rounding the maximum *up* is the point: stopping at the last step below the
* peak leaves the tallest day drawn past the top of the plot, where it is
* clipped.
*/
export function niceScale(peak: number, count: number): { max: number; ticks: readonly number[] } {
if (peak <= 0) return { max: 0, ticks: [0] };
const rawStep = peak / count;
const magnitude = 10 ** Math.floor(Math.log10(rawStep));
const normalized = rawStep / magnitude;
const step = (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude;
const max = Math.ceil(peak / step) * step;
const ticks: number[] = [];
for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value);
return { max, ticks };
}
/**
* Turns the merged daily totals into one column per day.
*
* Values are absolute, not cumulative: the series are layered from a shared
* zero baseline rather than stacked. A stacked chart puts whichever provider is
* drawn last permanently above the other, which reads as "that one is bigger"
* even on days where it is not.
*
* The chart paths and the hover readout both consume this, so the number under
* the cursor is by construction the number that was plotted rather than a
* second derivation that can drift from it.
*/
export function buildDayColumns(
days: readonly string[],
byDay: ReadonlyMap<string, DailyTotals>,
metric: UsageChartMetric,
): readonly DayColumn[] {
return days.map((day) => {
const entry = byDay.get(day);
const bands = PROVIDER_ORDER.map((provider) => ({
provider,
value: valueFor(entry, provider, metric),
}));
return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) };
});
}
export function UsageProviderChart({ days, daily, metric }: UsageProviderChartProps) {
const byDay = useMemo(() => new Map(daily.map((entry) => [entry.day, entry])), [daily]);
const [hoverIndex, setHoverIndex] = useState<number | null>(null);
const plotRef = useRef<HTMLDivElement | null>(null);
const { paths, ticks, stepX, toY, series } = useMemo(() => {
if (days.length === 0) {
return {
paths: [],
ticks: [0] as readonly number[],
stepX: 0,
toY: () => VIEW_HEIGHT,
series: [] as readonly DayColumn[],
};
}
const columns = buildDayColumns(days, byDay, metric);
// The scale tops out at the largest single provider-day, not the largest
// sum: layered series each measure from zero, so a combined peak would
// leave the plot permanently half empty.
const peak = columns.reduce(
(max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
0,
);
const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT);
const step = days.length === 1 ? 0 : VIEW_WIDTH / (days.length - 1);
// Reserve a sliver above the top gridline so the series stroke, which is
// drawn at constant screen width, is not shaved off at a peak.
const toY = (value: number) =>
max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
const built = PROVIDER_ORDER.map((provider, providerIndex) => {
const curve = smoothCurve(
columns.map((column, dayIndex) => ({
x: dayIndex * step,
y: toY(column.bands[providerIndex]?.value ?? 0),
})),
);
const line = curvePath(curve, "M");
return {
provider,
total: columns.reduce((sum, column) => sum + (column.bands[providerIndex]?.value ?? 0), 0),
area: line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`,
line,
};
});
// Paint the heavier series first so the lighter one is never buried under
// it. The fills are faint enough that the order barely shows, but the
// strokes are drawn in a second pass regardless, so neither can be hidden.
const ordered = [...built].sort((a, b) => b.total - a.total);
return { paths: ordered, ticks: tickValues, stepX: step, toY, series: columns };
}, [byDay, days, metric]);
const format = metric === "tokens" ? formatTokens : formatUsd;
const handleMove = useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
const bounds = plotRef.current?.getBoundingClientRect();
if (bounds === undefined || bounds.width === 0 || days.length === 0) return;
const fraction = (event.clientX - bounds.left) / bounds.width;
const index = Math.round(fraction * (days.length - 1));
setHoverIndex(Math.min(days.length - 1, Math.max(0, index)));
},
[days.length],
);
const hoveredDay = hoverIndex === null ? undefined : days[hoverIndex];
const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex];
const hoverLeft = days.length <= 1 ? 0 : ((hoverIndex ?? 0) / (days.length - 1)) * 100;
return (
<div className="flex flex-col gap-1">
<div className="flex gap-2">
{/* Axis labels sit outside the plot so they stay aligned to gridlines. */}
<div className="relative h-56 w-14 shrink-0">
{ticks.map((tick) => (
<span
key={tick}
className="absolute right-0 -translate-y-1/2 text-[10px] text-muted-foreground tabular-nums"
style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}
>
{tick === 0 ? "0" : format(tick)}
</span>
))}
</div>
<div
ref={plotRef}
className="relative h-56 flex-1"
onMouseMove={handleMove}
onMouseLeave={() => setHoverIndex(null)}
>
<svg
className="h-full w-full"
viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}
preserveAspectRatio="none"
role="img"
aria-label={`Daily ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}
>
{ticks.map((tick) => {
const y = toY(tick);
return (
<line
key={tick}
x1={0}
x2={VIEW_WIDTH}
y1={y}
y2={y}
stroke="currentColor"
strokeWidth={1}
className="text-border"
vectorEffect="non-scaling-stroke"
/>
);
})}
{/* Fills first, then every stroke, so no series covers another's line. */}
{paths.map(({ provider, area }) => (
<path key={provider} d={area} fill={PROVIDER_COLOR[provider]} fillOpacity={0.12} />
))}
{paths.map(({ provider, line }) => (
<path
key={provider}
d={line}
fill="none"
stroke={PROVIDER_COLOR[provider]}
strokeWidth={2}
vectorEffect="non-scaling-stroke"
/>
))}
{hoverIndex === null ? null : (
<line
x1={hoverIndex * stepX}
x2={hoverIndex * stepX}
y1={PLOT_TOP}
y2={VIEW_HEIGHT}
stroke="currentColor"
strokeWidth={1}
className="text-muted-foreground"
vectorEffect="non-scaling-stroke"
/>
)}
</svg>
{hoveredDay === undefined ? null : (
<div
className="pointer-events-none absolute top-0 z-10 min-w-36 border border-border bg-background/95 px-2 py-1.5 text-xs"
style={{
left: `${hoverLeft}%`,
transform: hoverLeft > 60 ? "translateX(-100%)" : "translateX(0)",
}}
>
<div className="mb-1 text-muted-foreground">{formatDayShort(hoveredDay)}</div>
{PROVIDER_ORDER.map((provider) => {
const Mark = PROVIDER_MARK[provider];
return (
<div key={provider} className="flex items-center justify-between gap-3">
<span className="flex items-center gap-1.5 text-muted-foreground">
<Mark className="size-3 shrink-0" aria-hidden />
{PROVIDER_LABEL[provider]}
</span>
<span className="text-foreground tabular-nums">
{format(
hoveredColumn?.bands.find((band) => band.provider === provider)?.value ?? 0,
)}
</span>
</div>
);
})}
<div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">
<span className="text-muted-foreground">Total</span>
<span className="text-foreground tabular-nums">
{format(hoveredColumn?.total ?? 0)}
</span>
</div>
</div>
)}
</div>
</div>
<div className="flex justify-between pl-16 text-[10px] text-muted-foreground uppercase">
<span>{days[0] === undefined ? "" : formatDayShort(days[0])}</span>
<span>
{days[Math.floor(days.length / 2)] === undefined
? ""
: formatDayShort(days[Math.floor(days.length / 2)] ?? "")}
</span>
<span>
{days[days.length - 1] === undefined ? "" : formatDayShort(days[days.length - 1] ?? "")}
</span>
</div>
</div>
);
}
export function UsageChartLegend() {
return (
<div className="flex items-center gap-4">
{PROVIDER_ORDER.map((provider) => {
// The marks carry the same fills as the bands, so they key the chart
// just as a colour swatch would.
const Mark = PROVIDER_MARK[provider];
return (
<span key={provider} className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Mark className="size-3.5 shrink-0" aria-hidden />
{PROVIDER_LABEL[provider]}
</span>
);
})}
</div>
);
}
@@ -0,0 +1,33 @@
import type { UsageProviderKind } from "@t3tools/contracts";
import { ClaudeAI, type Icon, OpenAI } from "../Icons";
/**
* Series and table order. The chart layers both providers from a shared zero
* baseline, so this only fixes the reading order of legends, tables and hover
* rows; it does not decide which series sits above the other.
*/
export const PROVIDER_ORDER: readonly UsageProviderKind[] = ["codex", "claude"];
export const PROVIDER_LABEL: Record<UsageProviderKind, string> = {
claude: "Claude Code",
codex: "Codex",
};
/** Claude's brand orange against a neutral white for Codex. */
export const PROVIDER_COLOR: Record<UsageProviderKind, string> = {
claude: "#d97757",
codex: "#e6e6e6",
};
/**
* Brand marks, reused from the provider picker.
*
* These ship their own fills (`#d97757` for Claude, white on dark for OpenAI),
* which are the same colours as the chart bands, so swapping a colour dot for a
* mark keeps the series association intact rather than trading it away.
*/
export const PROVIDER_MARK: Record<UsageProviderKind, Icon> = {
claude: ClaudeAI,
codex: OpenAI,
};
+5
View File
@@ -279,6 +279,11 @@ describe("environment grouping", () => {
expect(physicalToLogicalKey.get(derivePhysicalProjectKey(staleWithoutRepositoryIdentity))).toBe(
repositoryIdentity.canonicalKey,
);
// Deriving from the stale project alone misses the identity its sibling
// carries, so consumers must go through the map to match the sidebar.
expect(
deriveLogicalProjectKeyFromSettings(staleWithoutRepositoryIdentity, defaultGroupingSettings),
).not.toBe(repositoryIdentity.canonicalKey);
});
it("builds one picker entry per logical project and targets the preferred environment", () => {
+31
View File
@@ -17,6 +17,37 @@ describe("resolveEnvironmentIdentificationMode", () => {
"pill",
);
});
it("uses a pill instead of artwork with a palette theme", () => {
expect(
resolveEnvironmentIdentificationMode({
mode: "artwork",
settingsHydrated: true,
paletteThemeActive: true,
}),
).toBe("pill");
});
it("respects none with a palette theme", () => {
expect(
resolveEnvironmentIdentificationMode({
mode: "none",
settingsHydrated: true,
paletteThemeActive: true,
}),
).toBe("none");
});
it("keeps artwork when the palette theme opts into it", () => {
expect(
resolveEnvironmentIdentificationMode({
mode: "artwork",
settingsHydrated: true,
paletteThemeActive: true,
paletteThemeAllowsArtwork: true,
}),
).toBe("artwork");
});
});
describe("mergeEnvironmentSettings", () => {
+39 -24
View File
@@ -25,13 +25,18 @@ import {
type UnifiedSettings,
} from "@t3tools/contracts/settings";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { APP_STAGE_LABEL } from "~/branding";
import { resolveSidebarV2Enabled } from "~/branding.logic";
import { ensureLocalApi } from "~/localApi";
import {
getThemeDefinition,
getThemePreviewSidebarArtwork,
resolveThemeHalf,
subscribeToThemePreview,
} from "~/themePalette";
import * as Struct from "effect/Struct";
import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
import { usePrimaryEnvironment } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
import { useTheme } from "./useTheme";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
@@ -226,41 +231,51 @@ export function useClientSettings<T = ClientSettings>(
export function resolveEnvironmentIdentificationMode(input: {
mode: EnvironmentIdentificationMode;
settingsHydrated: boolean;
paletteThemeActive?: boolean;
paletteThemeAllowsArtwork?: boolean;
}): EnvironmentIdentificationMode {
// Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
return input.settingsHydrated ? input.mode : "none";
if (!input.settingsHydrated) return "none";
// Stage artwork has fixed colors that can clash with palette themes. Keep an
// explicit "none", but use the theme-aware pill in place of artwork.
return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
? "pill"
: input.mode;
}
export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
const settingsHydrated = useClientSettingsHydrated();
const mode = useClientSettingsValue().environmentIdentificationMode;
return resolveEnvironmentIdentificationMode({ mode, settingsHydrated });
const { resolvedTheme, theme, themeHalves } = useTheme();
const previewSidebarArtwork = useSyncExternalStore(
subscribeToThemePreview,
getThemePreviewSidebarArtwork,
() => null,
);
const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
const activeThemeDefinition = getThemeDefinition(activeTheme);
return resolveEnvironmentIdentificationMode({
mode,
settingsHydrated,
paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
paletteThemeAllowsArtwork:
previewSidebarArtwork ?? activeThemeDefinition?.sidebarArtwork === true,
});
}
/**
* Resolved sidebar v2 state: an explicit choice in Settings → Beta if the user
* has made one, otherwise the default for this build stage (on for nightly and
* dev, off for production). Every consumer must read through this rather than
* `settings.sidebarV2Enabled`, which is only meaningful alongside
* `sidebarV2ConfiguredByUser`.
* Whether the legacy sidebar (Settings → General → Legacy features) replaces
* the default one.
*
* Held at v1 until client settings hydrate. The pre-hydration snapshot is just
* the schema defaults, so resolving against it would mount one sidebar and then
* swap it out once persisted settings land — remounting the whole tree.
* Held at the default sidebar until client settings hydrate: the pre-hydration
* snapshot is just the schema defaults, so resolving against it could mount one
* sidebar and then swap it out once persisted settings land — remounting the
* whole tree for everyone instead of only for legacy opt-ins.
*/
export function useSidebarV2Enabled(): boolean {
export function useLegacySidebarEnabled(): boolean {
const settingsHydrated = useClientSettingsHydrated();
const settings = useClientSettingsValue();
return useMemo(
() =>
resolveSidebarV2Enabled({
enabled: settings.sidebarV2Enabled,
configuredByUser: settings.sidebarV2ConfiguredByUser,
settingsHydrated,
stageLabel: APP_STAGE_LABEL,
}),
[settings.sidebarV2Enabled, settings.sidebarV2ConfiguredByUser, settingsHydrated],
);
const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled;
return settingsHydrated && legacySidebarEnabled;
}
/** Read current settings for one environment, merged with client-local preferences. */
+6 -10
View File
@@ -995,12 +995,10 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
}
}
/* Keep both navigation implementations on the same quiet zinc hierarchy:
zinc-50 navigation, zinc-25 hover, and white selected/raised surfaces.
The version attribute remains useful for layout-specific styling without
changing the color system when the beta is toggled. */
[data-sidebar-version="v1"],
[data-sidebar-version="v2"] {
/* Keep both sidebar implementations (default and legacy) on the same quiet
zinc hierarchy: zinc-50 navigation, zinc-25 hover, and white selected/raised
surfaces. */
[data-app-sidebar] {
--background: var(--color-zinc-25);
--foreground: var(--color-zinc-800);
--card: var(--color-white);
@@ -1023,8 +1021,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
background-color: var(--sidebar);
}
.dark [data-sidebar-version="v1"],
.dark [data-sidebar-version="v2"] {
.dark [data-app-sidebar] {
--background: #000;
--foreground: #f1f3f7;
--card: #000;
@@ -1321,8 +1318,7 @@ html[data-theme-id] .chat-markdown .chat-markdown-chrome-action[aria-pressed="tr
color: var(--code-foreground);
}
html[data-theme-id] [data-sidebar-version="v1"],
html[data-theme-id] [data-sidebar-version="v2"] {
html[data-theme-id] [data-app-sidebar] {
--background: var(--app-theme-canvas);
--foreground: var(--app-theme-text);
--card: var(--app-theme-surface);
+21 -21
View File
@@ -9,6 +9,7 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as UsageRouteImport } from './routes/usage'
import { Route as SettingsRouteImport } from './routes/settings'
import { Route as PairRouteImport } from './routes/pair'
import { Route as ConnectRouteImport } from './routes/connect'
@@ -20,13 +21,17 @@ import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybi
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsBetaRouteImport } from './routes/settings.beta'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
const UsageRoute = UsageRouteImport.update({
id: '/usage',
path: '/usage',
getParentRoute: () => rootRouteImport,
} as any)
const SettingsRoute = SettingsRouteImport.update({
id: '/settings',
path: '/settings',
@@ -81,11 +86,6 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({
path: '/connections',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsBetaRoute = SettingsBetaRouteImport.update({
id: '/beta',
path: '/beta',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
id: '/archived',
path: '/archived',
@@ -118,10 +118,10 @@ export interface FileRoutesByFullPath {
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/usage': typeof UsageRoute
'/connect/callback': typeof ConnectCallbackRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -135,10 +135,10 @@ export interface FileRoutesByTo {
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/usage': typeof UsageRoute
'/connect/callback': typeof ConnectCallbackRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -155,10 +155,10 @@ export interface FileRoutesById {
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/usage': typeof UsageRoute
'/connect_/callback': typeof ConnectCallbackRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -176,10 +176,10 @@ export interface FileRouteTypes {
| '/connect'
| '/pair'
| '/settings'
| '/usage'
| '/connect/callback'
| '/settings/appearance'
| '/settings/archived'
| '/settings/beta'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -193,10 +193,10 @@ export interface FileRouteTypes {
| '/connect'
| '/pair'
| '/settings'
| '/usage'
| '/connect/callback'
| '/settings/appearance'
| '/settings/archived'
| '/settings/beta'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -212,10 +212,10 @@ export interface FileRouteTypes {
| '/connect'
| '/pair'
| '/settings'
| '/usage'
| '/connect_/callback'
| '/settings/appearance'
| '/settings/archived'
| '/settings/beta'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -232,11 +232,19 @@ export interface RootRouteChildren {
ConnectRoute: typeof ConnectRoute
PairRoute: typeof PairRoute
SettingsRoute: typeof SettingsRouteWithChildren
UsageRoute: typeof UsageRoute
ConnectCallbackRoute: typeof ConnectCallbackRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/usage': {
id: '/usage'
path: '/usage'
fullPath: '/usage'
preLoaderRoute: typeof UsageRouteImport
parentRoute: typeof rootRouteImport
}
'/settings': {
id: '/settings'
path: '/settings'
@@ -314,13 +322,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsConnectionsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/beta': {
id: '/settings/beta'
path: '/beta'
fullPath: '/settings/beta'
preLoaderRoute: typeof SettingsBetaRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/archived': {
id: '/settings/archived'
path: '/archived'
@@ -376,7 +377,6 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
interface SettingsRouteChildren {
SettingsAppearanceRoute: typeof SettingsAppearanceRoute
SettingsArchivedRoute: typeof SettingsArchivedRoute
SettingsBetaRoute: typeof SettingsBetaRoute
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
@@ -388,7 +388,6 @@ interface SettingsRouteChildren {
const SettingsRouteChildren: SettingsRouteChildren = {
SettingsAppearanceRoute: SettingsAppearanceRoute,
SettingsArchivedRoute: SettingsArchivedRoute,
SettingsBetaRoute: SettingsBetaRoute,
SettingsConnectionsRoute: SettingsConnectionsRoute,
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
@@ -406,6 +405,7 @@ const rootRouteChildren: RootRouteChildren = {
ConnectRoute: ConnectRoute,
PairRoute: PairRoute,
SettingsRoute: SettingsRouteWithChildren,
UsageRoute: UsageRoute,
ConnectCallbackRoute: ConnectCallbackRoute,
}
export const routeTree = rootRouteImport
+7 -7
View File
@@ -3,7 +3,7 @@ import { useAtomValue } from "@effect/atom-react";
import { useEffect, useMemo } from "react";
import { isCommandPaletteOpen } from "../commandPaletteBus";
import { useClientSettings, useSidebarV2Enabled } from "../hooks/useSettings";
import { useClientSettings, useLegacySidebarEnabled } from "../hooks/useSettings";
import { openCommandPalette } from "../commandPaletteBus";
import { useProjects } from "../state/entities";
import { usePrimaryEnvironmentId } from "../state/environments";
@@ -28,7 +28,7 @@ function ChatRouteGlobalShortcuts() {
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
useHandleNewThread();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const sidebarV2Enabled = useSidebarV2Enabled();
const legacySidebarEnabled = useLegacySidebarEnabled();
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const projects = useProjects();
const primaryEnvironmentId = usePrimaryEnvironmentId();
@@ -92,10 +92,10 @@ function ChatRouteGlobalShortcuts() {
if (command === "chat.new") {
event.preventDefault();
event.stopPropagation();
// Sidebar v2 routes creation through the command palette whenever
// there is a real choice to make; v1 (and single-project setups)
// keep the immediate contextual create.
if (sidebarV2Enabled && projectGroupCount > 1) {
// The default sidebar routes creation through the command palette
// whenever there is a real choice to make; the legacy sidebar (and
// single-project setups) keep the immediate contextual create.
if (!legacySidebarEnabled && projectGroupCount > 1) {
openCommandPalette({ open: "new-thread-in" });
return;
}
@@ -167,7 +167,7 @@ function ChatRouteGlobalShortcuts() {
projectGroupCount,
routeThreadRef,
selectedThreadKeysSize,
sidebarV2Enabled,
legacySidebarEnabled,
terminalOpen,
]);
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more