Compare commits

..
Author SHA1 Message Date
t3-code[bot] d93833fd3e fix(desktop): confirm before quitting the app 2026-08-04 21:21:41 +00:00
162 changed files with 1978 additions and 7959 deletions

No files matched your search

+12 -6
View File
@@ -747,9 +747,15 @@ jobs:
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: write
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
with:
@@ -817,7 +823,7 @@ jobs:
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -834,11 +840,11 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ github.token }}
token: ${{ steps.app_token.outputs.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -854,7 +860,7 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ github.token }}
token: ${{ steps.app_token.outputs.token }}
deploy_web:
name: Deploy hosted web app
+2 -2
View File
@@ -16,7 +16,7 @@ import {
DesktopPreviewSetColorSchemeInputSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationSubmissionResultSchema,
PreviewAnnotationPayloadSchema,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
@@ -227,7 +227,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
export const pickElement = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.pickElement(tabId);
@@ -1,28 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
const keyboardEvent = (
overrides: Partial<Parameters<typeof resolveAnnotationSubmission>[0]> = {},
) => ({
key: "Enter",
metaKey: false,
ctrlKey: false,
shiftKey: false,
isComposing: false,
...overrides,
});
describe("resolveAnnotationSubmission", () => {
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
});
it("leaves Shift+Enter and composition events available for editing", () => {
expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
});
});
@@ -1,16 +0,0 @@
import type { PreviewAnnotationSubmission } from "@t3tools/contracts";
interface AnnotationKeyboardEvent {
readonly key: string;
readonly metaKey: boolean;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly isComposing: boolean;
}
export function resolveAnnotationSubmission(
event: AnnotationKeyboardEvent,
): PreviewAnnotationSubmission | null {
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
return event.metaKey || event.ctrlKey ? "send" : "attach";
}
@@ -23,10 +23,6 @@ const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
"clipboard-sanitized-write",
"notifications",
"geolocation",
// Deliberately NOT local-fonts: preview sessions run untrusted web content,
// and silently granting it would hand every page the user's installed-font
// fingerprint (and font file bytes via FontData.blob()). The app's own font
// picker runs in the main window session, which is unaffected by this list.
]);
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
-22
View File
@@ -36,28 +36,6 @@ describe("fitPictureInPictureContentSize", () => {
});
});
describe("isPreviewRefreshShortcut", () => {
const input = (overrides: Partial<Electron.Input> = {}) =>
({
type: "keyDown",
key: "r",
meta: true,
control: false,
shift: false,
alt: false,
...overrides,
}) as Electron.Input;
it("recognizes the platform refresh chord without matching modified variants", () => {
expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true);
expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe(
true,
);
expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false);
expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false);
});
});
const {
browserWindowConstructor,
createFromPath,
+6 -25
View File
@@ -11,7 +11,6 @@ import type {
DesktopPreviewPointerEvent,
PreviewAnnotationPayload,
PreviewAnnotationRect,
PreviewAnnotationSubmissionResult,
DesktopPreviewRecordingArtifact,
DesktopPreviewRecordingFrame,
DesktopPreviewScreenshotArtifact,
@@ -407,13 +406,6 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
{ key: "w", meta: true, shift: false, control: false },
]);
export const isPreviewRefreshShortcut = (input: Electron.Input): boolean =>
input.type === "keyDown" &&
input.key.toLowerCase() === "r" &&
(input.meta || input.control) &&
!input.shift &&
!input.alt;
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
if (value.kind === "pointer") {
@@ -1373,15 +1365,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
});
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
if (isPreviewRefreshShortcut(input)) {
event.preventDefault();
runFork(
attempt({ operation: "shortcut.refresh", tabId, webContentsId: wc.id }, () =>
wc.reload(),
).pipe(Effect.ignore),
);
return;
}
runFork(forwardShortcut(event, input));
};
yield* Scope.addFinalizer(
@@ -1809,7 +1792,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const wc = yield* requireWebContents(tabId);
yield* cancelPickElement(tabId);
const annotationTheme = yield* Ref.get(annotationThemeRef);
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
return yield* Effect.callback<PreviewAnnotationPayload | null, PreviewManagerError>(
(resume) => {
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
@@ -1824,14 +1807,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
payload: PreviewAnnotationSubmissionResult | null,
payload: PreviewAnnotationPayload | null,
) {
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
if (!active || active.cancel !== cancel) return;
yield* cleanup();
resume(Effect.succeed(payload));
});
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
const settle = (payload: PreviewAnnotationPayload | null) => {
runFork(settlePick(payload));
};
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
@@ -1861,13 +1844,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return;
}
const cropRect = normalizeCaptureRect(args[1]);
const submission = args[2] === "send" ? "send" : "attach";
runFork(
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
Effect.matchEffect({
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
onSuccess: (screenshot) =>
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
onFailure: () => Effect.sync(() => settle(payload)),
onSuccess: (screenshot) => Effect.sync(() => settle({ ...payload, screenshot })),
}),
Effect.ensuring(
attempt(
@@ -3605,7 +3586,7 @@ export class PreviewManager extends Context.Service<
) => Effect.Effect<void, PreviewManagerError>;
readonly pickElement: (
tabId: string,
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly captureScreenshot: (
tabId: string,
+7 -14
View File
@@ -11,10 +11,8 @@ import type {
PreviewAnnotationRegionTarget,
PreviewAnnotationStrokeTarget,
PreviewAnnotationStyleChange,
PreviewAnnotationSubmission,
} from "@t3tools/contracts";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
import {
ANNOTATION_CAPTURED_CHANNEL,
@@ -428,7 +426,7 @@ function startAnnotation(): void {
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
composerRow.appendChild(dragHandle);
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
const submit = createButton("Attach", "Attach annotation and screenshot");
submit.className +=
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
composerRow.appendChild(submit);
@@ -1184,7 +1182,7 @@ function startAnnotation(): void {
refreshToolButtons();
};
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
submit.addEventListener("click", () => {
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
return;
pendingCapture = true;
@@ -1225,18 +1223,13 @@ function startAnnotation(): void {
...regions.map((region) => region.rect),
...strokes.map((stroke) => stroke.bounds),
]);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
});
};
submit.addEventListener("click", () => submitAnnotation("attach"));
root.addEventListener("keydown", (event) => {
const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
// Keep this in the bubble phase so editor inputs receive the event before
// it is isolated from listeners installed by the inspected page.
event.stopImmediatePropagation();
if (!submission) return;
});
comment.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
event.preventDefault();
submitAnnotation(submission);
submit.click();
});
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
@@ -20,15 +20,6 @@ const clientSettings: ClientSettings = {
diffIgnoreWhitespace: true,
environmentIdentificationMode: "artwork",
favorites: [],
fontFamilyCode: "",
fontFamilyComposer: "",
fontFamilySans: "",
fontFamilyTerminal: "",
fontSizeCode: 13,
fontSizeInterface: 16,
fontSizePrompt: 14,
fontSizeTerminal: 12,
fontSmoothing: true,
glassOpacity: 80,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
@@ -28,34 +28,39 @@ const environmentInput = {
runningUnderArm64Translation: false,
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
const makeElectronAppLayer = (quit: Effect.Effect<void> = Effect.void) =>
Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
confirm: () => Effect.succeed(false),
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialog["Service"]);
const makeElectronDialogLayer = (
showMessageBox: ElectronDialog.ElectronDialog["Service"]["showMessageBox"] = () =>
Effect.succeed({ response: 0, checkboxChecked: false }),
) =>
Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
confirm: () => Effect.succeed(false),
showMessageBox,
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialog["Service"]);
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
getState: Effect.die("unexpected getState"),
@@ -109,8 +114,8 @@ describe("DesktopApplicationMenu", () => {
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(makeElectronDialogLayer()),
Layer.provideMerge(makeElectronAppLayer()),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
@@ -137,4 +142,69 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
it.effect("confirms Cmd+Q before quitting on macOS", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
const promptOptions = yield* Deferred.make<Electron.MessageBoxOptions>();
const quitRequested = yield* Deferred.make<void>();
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(
makeElectronDialogLayer((options) =>
Deferred.succeed(promptOptions, options).pipe(
Effect.as({ response: 1, checkboxChecked: false }),
),
),
),
Layer.provideMerge(
makeElectronAppLayer(Deferred.succeed(quitRequested, undefined).pipe(Effect.asVoid)),
),
Layer.provideMerge(
DesktopEnvironment.layer({ ...environmentInput, platform: "darwin" }).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
const template = yield* Deferred.await(applicationMenuTemplate);
const appMenu = template.find((item) => item.label === "T3 Code");
assert.isDefined(appMenu);
if (!Array.isArray(appMenu.submenu)) {
throw new Error("Expected application menu submenu to be an array.");
}
const quitItem = appMenu.submenu.find((item) => item.label === "Quit T3 Code");
assert.isDefined(quitItem);
assert.equal(quitItem.accelerator, "CmdOrCtrl+Q");
if (typeof quitItem.click !== "function") {
throw new Error("Expected Quit menu item to have a click handler.");
}
quitItem.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.deepEqual(yield* Deferred.await(promptOptions), {
type: "warning",
title: "Quit T3 Code?",
message: "Quit T3 Code?",
detail: "All running agents will be stopped.",
buttons: ["Cancel", "Quit"],
defaultId: 0,
cancelId: 0,
noLink: true,
});
yield* Deferred.await(quitRequested);
}),
);
});
@@ -96,6 +96,21 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
yield* checkForUpdatesFromMenu;
}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
const confirmQuit = Effect.gen(function* () {
const electronDialog = yield* ElectronDialog.ElectronDialog;
const result = yield* electronDialog.showMessageBox({
type: "warning",
title: "Quit T3 Code?",
message: "Quit T3 Code?",
detail: "All running agents will be stopped.",
buttons: ["Cancel", "Quit"],
defaultId: 0,
cancelId: 0,
noLink: true,
});
return result.response === 1;
}).pipe(Effect.withSpan("desktop.menu.confirmQuit"));
export const make = Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronMenu = yield* ElectronMenu.ElectronMenu;
@@ -127,6 +142,30 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
let quitConfirmationOpen = false;
const quitClick = () => {
if (quitConfirmationOpen) return;
quitConfirmationOpen = true;
runMenuEffect(
"quit",
Effect.gen(function* () {
if (yield* confirmQuit) {
yield* electronApp.quit;
}
}).pipe(
Effect.ensuring(
Effect.sync(() => {
quitConfirmationOpen = false;
}),
),
),
);
};
const quitMenuItem: Electron.MenuItemConstructorOptions = {
label: `Quit ${appName}`,
accelerator: "CmdOrCtrl+Q",
click: quitClick,
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -151,7 +190,7 @@ export const make = Effect.gen(function* () {
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
quitMenuItem,
],
});
}
@@ -170,7 +209,7 @@ export const make = Effect.gen(function* () {
},
{ type: "separator" as const },
]),
{ role: environment.platform === "darwin" ? "close" : "quit" },
environment.platform === "darwin" ? { role: "close" } : quitMenuItem,
],
},
{ role: "editMenu" },
-8
View File
@@ -47,7 +47,6 @@ import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsCl
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
import {
@@ -176,13 +175,6 @@ const SettingsSheetStack = createNativeStackNavigator({
title: "Appearance",
},
}),
SettingsProjectGrouping: createNativeStackScreen({
screen: SettingsProjectGroupingRouteScreen,
linking: "project-grouping",
options: {
title: "Project Grouping",
},
}),
SettingsClientStorage: createNativeStackScreen({
screen: SettingsClientStorageRouteScreen,
linking: "client-storage",
@@ -70,7 +70,7 @@ export function AndroidScreenHeader(props: {
accessibilityRole="button"
hitSlop={8}
onPress={props.onBack}
className="-mr-2 size-11 items-center justify-center"
className="size-11 items-center justify-center"
>
<SymbolView
name="chevron.left"
-4
View File
@@ -50,8 +50,6 @@ import {
IconMinus,
IconNetwork,
IconPalette,
IconPin,
IconPinnedOff,
IconPlayerPlay,
IconPlayerStopFilled,
IconPlus,
@@ -123,8 +121,6 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
magnifyingglass: IconSearch,
paintbrush: IconPalette,
"person.crop.circle": IconUserCircle,
pin: IconPin,
"pin.slash": IconPinnedOff,
play: IconPlayerPlay,
plus: IconPlus,
"qrcode.viewfinder": IconQrcode,
@@ -42,8 +42,6 @@ export function HomeRouteScreen() {
settleThread,
snoozeThread,
unsnoozeThread,
pinThread,
unpinThread,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -157,8 +155,6 @@ export function HomeRouteScreen() {
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
+1 -38
View File
@@ -111,8 +111,6 @@ interface HomeScreenProps {
) => Promise<boolean>;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -518,18 +516,6 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onUnsnoozeThread],
);
const handlePinThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onPinThread(thread);
},
[props.onPinThread],
);
const handleUnpinThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onUnpinThread(thread);
},
[props.onUnpinThread],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -589,15 +575,6 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const pinningEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinning === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -694,11 +671,7 @@ export function HomeScreen(props: HomeScreenProps) {
);
const renderV2Item = useCallback(
({ item, index }: { readonly item: ThreadListV2ListItem; readonly index: number }) => {
const nextItem = threadListV2Items[index + 1];
const showTrailingDivider =
nextItem?.type === "v2-thread" ||
(nextItem?.type === "v2-pending" && !nextItem.showPendingDivider);
({ item }: { readonly item: ThreadListV2ListItem }) => {
if (item.type === "v2-pending") {
const pendingScopeKey = scopedProjectKey(
item.pendingTask.message.environmentId,
@@ -716,7 +689,6 @@ export function HomeScreen(props: HomeScreenProps) {
: null
}
showPendingDivider={item.showPendingDivider}
showTrailingDivider={showTrailingDivider}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
@@ -746,10 +718,8 @@ export function HomeScreen(props: HomeScreenProps) {
thread={thread}
variant={item.item.variant}
snoozed={item.item.snoozed}
pinned={item.item.pinned}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
showTrailingDivider={showTrailingDivider}
project={
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
@@ -783,12 +753,9 @@ export function HomeScreen(props: HomeScreenProps) {
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={handleSnoozeThread}
onUnsnoozeThread={handleUnsnoozeThread}
onUnsettleThread={handleUnsettleThread}
onPinThread={handlePinThread}
onUnpinThread={handleUnpinThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
@@ -801,15 +768,12 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleChangeRequestState,
handleDeleteThread,
handlePinThread,
handleSettleThread,
handleSnoozeThread,
handleUnpinThread,
handleUnsnoozeThread,
handleSwipeableClose,
handleSwipeableWillOpen,
handleUnsettleThread,
pinningEnvironmentIds,
projectByKey,
projectCwdByKey,
props.onArchiveThread,
@@ -820,7 +784,6 @@ export function HomeScreen(props: HomeScreenProps) {
serverConfigs,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
toggleSettledShelf,
toggleSnoozedShelf,
@@ -31,6 +31,12 @@ export interface ResolvedHomeListOptions extends HomeListOptions {
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
export function resolveProjectGroupingMode(
projectGroupingEnabled: boolean | undefined,
): SidebarProjectGroupingMode {
return projectGroupingEnabled === false ? "separate" : "repository";
}
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
readonly value: HomeProjectSortOrder;
readonly label: string;
@@ -70,9 +76,7 @@ const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>
export function HomeListOptionsProvider({
children,
projectGroupingMode,
}: PropsWithChildren<{
readonly projectGroupingMode: SidebarProjectGroupingMode;
}>) {
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
const value = useMemo(
() => ({ options, setOptions, projectGroupingMode }),
@@ -375,7 +375,7 @@ describe("buildHomeThreadGroups", () => {
).toHaveLength(2);
});
it("uses the physical project title for a singleton scope", () => {
it("uses the repository label for a singleton repository scope", () => {
const project = makeProject({
environmentId: EnvironmentId.make("environment-1"),
id: ProjectId.make("project-1"),
@@ -408,8 +408,8 @@ describe("buildHomeThreadGroups", () => {
],
);
expect(scopes[0]?.title).toBe("local-worktree-name");
expect(groups[0]?.title).toBe("local-worktree-name");
expect(scopes[0]?.title).toBe("codething-mvp");
expect(groups[0]?.title).toBe("codething-mvp");
});
it("sorts the newest thread first regardless of snapshot order", () => {
@@ -565,16 +565,10 @@ describe("buildHomeThreadGroups", () => {
);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
expect(
buildGroups(projects, threads, { projectGroupingMode: "repository_path" }).map(
(group) => group.title,
),
).toEqual(["Mobile", "Web"]);
expect(
buildGroups(projects, threads, { projectGroupingMode: "separate" }).map(
(group) => group.title,
),
).toEqual(["Mobile", "Web"]);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
2,
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
});
it("default view shows only threads from the last 5 days", () => {
+63 -18
View File
@@ -1,5 +1,5 @@
import {
buildProjectGroups,
deriveLogicalProjectKey,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
} from "@t3tools/client-runtime/state/project-grouping";
@@ -37,6 +37,10 @@ export interface HomeProjectScope {
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
}
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
}
function getProjectSortTimestamp(
project: EnvironmentProject,
sortOrder: HomeProjectSortOrder,
@@ -56,19 +60,64 @@ export function buildHomeProjectScopes(input: {
const projects = input.projects.filter(
(project) => input.environmentId === null || project.environmentId === input.environmentId,
);
return buildProjectGroups({
projects,
settings: {
sidebarProjectGroupingMode: input.projectGroupingMode,
sidebarProjectGroupingOverrides: {},
},
}).map((group) => {
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
for (const project of projects) {
const physicalKey = derivePhysicalProjectKey(project);
const existing = projectsByPhysicalKey.get(physicalKey);
if (existing) existing.push(project);
else projectsByPhysicalKey.set(physicalKey, [project]);
}
const winnersByPhysicalKey = new Map<
string,
{ readonly key: string; readonly project: EnvironmentProject }
>();
for (const [physicalKey, members] of projectsByPhysicalKey) {
const project = members.reduce((winner, candidate) => {
const freshnessDelta =
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
? candidate
: winner;
});
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
winnersByPhysicalKey.set(physicalKey, {
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
project,
});
}
const groups = new Map<string, EnvironmentProject[]>();
for (const { key, project } of winnersByPhysicalKey.values()) {
const existing = groups.get(key);
if (existing) existing.push(project);
else groups.set(key, [project]);
}
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
const seenProjectRefs = new Set<string>();
for (const project of projects) {
const refKey = scopedProjectKey(project.environmentId, project.id);
if (seenProjectRefs.has(refKey)) continue;
seenProjectRefs.add(refKey);
const key =
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
const refs = projectRefsByGroup.get(key);
const projectRef = { environmentId: project.environmentId, projectId: project.id };
if (refs) refs.push(projectRef);
else projectRefsByGroup.set(key, [projectRef]);
}
return Array.from(groups, ([key, projects]) => {
const representative = projects[0]!;
return {
key: group.key,
title: group.label,
representative: group.representative,
projects: group.members.map((member) => member.project),
projectRefs: group.memberProjectRefs,
key,
title: deriveProjectGroupLabel({ representative, members: projects }),
representative,
projects,
projectRefs: projectRefsByGroup.get(key) ?? [],
};
});
}
@@ -215,11 +264,9 @@ export function buildHomeThreadGroups(input: {
}): ReadonlyArray<HomeThreadGroup> {
const now = input.now ?? Date.now();
const groups = new Map<string, MutableHomeThreadGroup>();
const groupTitleByKey = new Map<string, string>();
const groupKeyByProjectKey = new Map<string, string>();
for (const scope of buildHomeProjectScopes(input)) {
groupTitleByKey.set(scope.key, scope.title);
groups.set(scope.key, {
key: scope.key,
projects: [...scope.projects],
@@ -298,9 +345,7 @@ export function buildHomeThreadGroups(input: {
continue;
}
const title =
groupTitleByKey.get(group.key) ??
deriveProjectGroupLabel({ representative, members: group.projects });
const title = deriveProjectGroupLabel({ representative, members: group.projects });
const groupMatches =
query.length === 0 ||
title.toLocaleLowerCase().includes(query) ||
@@ -29,13 +29,6 @@ function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["enviro
);
}
function environmentSupportsPinning(environmentId: EnvironmentThreadShell["environmentId"]) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadPinning === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -209,14 +202,10 @@ export function useThreadListActions(): {
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
@@ -321,62 +310,6 @@ export function useThreadListActions(): {
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
[executeAction],
);
const pinThread = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!environmentSupportsPinning(thread.environmentId)) {
Alert.alert(
"Could not pin thread",
"This environment's server does not support pinning yet. Update the server to use Pin.",
);
return false;
}
selectionHaptic();
const result = await pinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not pin thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be pinned.",
);
return false;
}
return true;
},
[pinMutation],
);
const unpinThread = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!environmentSupportsPinning(thread.environmentId)) {
Alert.alert(
"Could not unpin thread",
"This environment's server does not support pinning yet. Update the server to use Pin.",
);
return false;
}
selectionHaptic();
const result = await unpinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not unpin thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be unpinned.",
);
return false;
}
return true;
},
[unpinMutation],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
@@ -387,8 +320,6 @@ export function useThreadListActions(): {
snoozeThread,
unsnoozeThread,
unsettleThread,
pinThread,
unpinThread,
};
}
@@ -37,15 +37,11 @@ import {
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { mobilePreferencesAtom } from "../../state/preferences";
import {
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
resolveMobileProjectGroupingSettings,
} from "../../state/project-grouping";
import {
parseActiveThreadPath,
useHardwareKeyboardCommand,
} from "../keyboard/hardwareKeyboardCommands";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
@@ -194,17 +190,15 @@ export function AdaptiveWorkspaceLayout(props: {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
if (!AsyncResult.isSuccess(preferencesResult)) {
return AsyncResult.isFailure(preferencesResult) ? (
<AdaptiveWorkspaceLayoutContent
{...props}
projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
/>
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
) : null;
}
const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
return (
<AdaptiveWorkspaceLayoutContent
{...props}
projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
projectGroupingMode={resolveProjectGroupingMode(
preferencesResult.value.projectGroupingEnabled,
)}
/>
);
}
@@ -1,25 +1,15 @@
import { useNavigation } from "@react-navigation/native";
import { Platform, ScrollView, View } from "react-native";
import { ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { CodeAppearanceSection } from "./appearance/sections/CodeAppearanceSection";
import { TerminalAppearanceSection } from "./appearance/sections/TerminalAppearanceSection";
import { TextAppearanceSection } from "./appearance/sections/TextAppearanceSection";
export function SettingsAppearanceRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
return (
<View collapsable={false} className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Appearance" onBack={() => navigation.goBack()} />
</>
) : null}
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
@@ -1,106 +0,0 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
import { AsyncResult } from "effect/unstable/reactivity";
import { Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { SymbolView } from "../../components/AppSymbol";
import { useThemeColor } from "../../lib/useThemeColor";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import {
mobileProjectGroupingModePatch,
resolveMobileProjectGroupingSettings,
} from "../../state/project-grouping";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { SettingsSection } from "./components/SettingsSection";
const GROUPING_OPTIONS: ReadonlyArray<{
readonly mode: SidebarProjectGroupingMode;
readonly label: string;
readonly description: string;
}> = [
{
mode: "repository",
label: "Group by repository",
description: "Matching repositories appear as one project.",
},
{
mode: "repository_path",
label: "Group by repository path",
description: "Keep monorepo paths separate.",
},
{
mode: "separate",
label: "Keep separate",
description: "Show every workspace as its own project.",
},
];
export function SettingsProjectGroupingRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const checkmarkColor = useThemeColor("--color-icon");
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
const selectedMode = AsyncResult.isSuccess(preferencesResult)
? resolveMobileProjectGroupingSettings(preferencesResult.value).sidebarProjectGroupingMode
: null;
return (
<View collapsable={false} className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Project Grouping" onBack={() => navigation.goBack()} />
</>
) : null}
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-3 px-5 pt-4"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
>
<SettingsSection title="Default grouping">
{GROUPING_OPTIONS.map((option, index) => (
<Pressable
key={option.mode}
accessibilityRole="radio"
accessibilityState={{
checked: selectedMode === option.mode,
disabled: !preferencesReady,
}}
disabled={!preferencesReady}
onPress={() => savePreferences(mobileProjectGroupingModePatch(option.mode))}
className={
index === 0
? "flex-row items-center gap-4 p-4"
: "flex-row items-center gap-4 border-t border-border-subtle p-4"
}
>
<View className="min-w-0 flex-1 gap-1">
<Text className="text-lg text-foreground">{option.label}</Text>
<Text className="text-sm leading-normal text-foreground-muted">
{option.description}
</Text>
</View>
{selectedMode === option.mode ? (
<SymbolView
name="checkmark"
size={18}
tintColor={checkmarkColor}
type="monochrome"
weight="semibold"
/>
) : null}
</Pressable>
))}
</SettingsSection>
</ScrollView>
</View>
);
}
@@ -530,9 +530,20 @@ function ConfiguredSettingsRouteScreen() {
}
function GeneralSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.projectGroupingEnabled !== false
: true;
return (
<SettingsSection title="General">
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
<SettingsSwitchRow
icon="folder"
label="Project Grouping"
value={projectGroupingEnabled}
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
/>
</SettingsSection>
);
}
@@ -1,11 +1,4 @@
import {
Platform,
ScrollView,
type StyleProp,
type TextStyle,
View,
useColorScheme,
} from "react-native";
import { Platform, ScrollView, View, useColorScheme } from "react-native";
import { AppText as Text } from "../../../../components/AppText";
import {
@@ -61,48 +54,14 @@ export function TerminalAppearancePreview(props: { readonly fontSize: number })
fontSize: props.fontSize,
lineHeight,
} as const;
// AppText stamps the sans font on every node, so nested spans must
// re-apply the terminal font instead of relying on inheritance, exactly
// like the code preview's tokens below.
const span = (color: string, extra?: TextStyle): StyleProp<TextStyle> => [
lineStyle,
{ color, ...extra },
];
return (
<View className="p-4">
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.palette[6])}>t3code </Text>
<Text style={span(theme.palette[4])}>git:(</Text>
<Text style={span(theme.palette[1])}>main</Text>
<Text style={span(theme.palette[4])}>)</Text>
<Text style={span(theme.palette[3])}> ✗</Text>
<Text style={span(theme.foreground)}> vpr dev</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>VITE v7.1.1</Text>
<Text style={span(theme.mutedForeground)}> ready in</Text>
<Text style={span(theme.foreground)}> 1.24s</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.mutedForeground)}>Local: </Text>
<Text style={span(theme.palette[6], { textDecorationLine: "underline" })}>
http://127.0.0.1:5173/
</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>✓ 85 passed</Text>
<Text style={span(theme.palette[3])}> △ 2 warnings</Text>
<Text style={span(theme.palette[1])}> ✗ 0 failed</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.background, { backgroundColor: theme.palette[2] })}>
{" READY "}
</Text>
<Text style={span(theme.mutedForeground)}> watching for changes</Text>{" "}
<Text style={span(theme.cursorForeground)}>▏</Text>
<Text style={[lineStyle, { color: theme.foreground }]}>$ npm run dev</Text>
<Text style={[lineStyle, { color: theme.palette[2] }]}>✓ Ready in 430ms</Text>
<Text style={[lineStyle, { color: theme.foreground }]}>
Local: http://localhost:3000{" "}
<Text style={[lineStyle, { color: theme.cursorForeground }]}>▏</Text>
</Text>
</View>
);
@@ -2,7 +2,6 @@ export type SettingsSheetTarget =
| "SettingsEnvironments"
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsProjectGrouping"
| "SettingsClientStorage";
export type SettingsLegalDocumentTarget = "SettingsLegal";
@@ -50,7 +50,6 @@ import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../sta
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
import { resolveDraftProjectSelection } from "./new-task-project-selection";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
function formatWorkspaceLabel(input: {
@@ -90,7 +89,7 @@ export function NewTaskDraftScreen(props: {
const colorScheme = useColorScheme();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
const { logicalProjects, selectedProject, setProject } = flow;
const { connectedEnvironments } = useRemoteConnectionStatus();
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
@@ -278,25 +277,24 @@ export function NewTaskDraftScreen(props: {
return;
}
const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
if (selection.kind === "preserve") {
if (selectedProject) {
return;
}
if (selection.kind === "select") {
setProject(selection.project);
if (logicalProjects.length === 1) {
setProject(logicalProjects[0]!.project);
return;
}
navigation.dispatch(StackActions.replace("NewTask"));
}, [
projectScopes,
logicalProjects,
projects,
props.initialProjectRef,
props.incomingShareId,
props.pendingTaskId,
navigation,
selectedProject,
selectedProjectKey,
setProject,
]);
@@ -1,8 +1,8 @@
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { SymbolView } from "../../components/AppSymbol";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { useEffect, useRef, useState } from "react";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useEffect, useMemo, useRef } from "react";
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -11,13 +11,12 @@ import { cn } from "../../lib/cn";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { useProjects } from "../../state/entities";
import { useProjects, useThreadShells } from "../../state/entities";
import type { WorkspaceState } from "../../state/workspaceModel";
import { useWorkspaceState } from "../../state/workspace";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
import { useNewTaskFlow } from "./new-task-flow-provider";
type NewTaskRouteParams = {
readonly incomingShareId?: string | string[];
@@ -80,7 +79,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
const projects = useProjects();
const { projectScopes } = useNewTaskFlow();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const navigation = useNavigation();
const isFocused = useIsFocused();
@@ -88,7 +87,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
const accentColor = useThemeColor("--color-icon-muted");
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
const { getShare, releaseShareReservation } = useIncomingShare();
const routeShareId = Array.isArray(route.params?.incomingShareId)
? route.params.incomingShareId[0]
@@ -102,6 +100,33 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
: `Choose a project for the ${incomingShare.attachments.length} images you shared`
: null;
const screenTitle = incomingShare ? "Start a task" : "Choose project";
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const items = useMemo(() => {
const nextItems: Array<{
readonly environmentId: EnvironmentId;
readonly id: ProjectId;
readonly key: string;
readonly title: string;
readonly workspaceRoot: string;
}> = [];
for (const group of repositoryGroups) {
const project = group.projects[0]?.project;
if (!project) {
continue;
}
nextItems.push({
environmentId: project.environmentId,
id: project.id,
key: group.key,
title: project.title,
workspaceRoot: project.workspaceRoot,
});
}
return nextItems;
}, [repositoryGroups]);
const projectEmptyState = deriveProjectEmptyState(catalogState);
const resumedDestinationKeyRef = useRef<string | null>(null);
const reservedDestinationProject = incomingShare?.destination
@@ -112,7 +137,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
) ?? null)
: null;
async function selectProject(project: EnvironmentProject): Promise<void> {
async function selectProject(item: (typeof items)[number]): Promise<void> {
if (incomingShare?.destination && !reservedDestinationProject) {
try {
await releaseShareReservation(incomingShare.id, incomingShare.destination);
@@ -129,26 +154,14 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: project.environmentId,
projectId: project.id,
title: project.title,
environmentId: item.environmentId,
projectId: item.id,
title: item.title,
incomingShareId: incomingShare?.id,
},
});
}
function toggleGroup(groupKey: string): void {
setExpandedGroupKeys((current) => {
const next = new Set(current);
if (next.has(groupKey)) {
next.delete(groupKey);
} else {
next.add(groupKey);
}
return next;
});
}
useEffect(() => {
const destination = incomingShare?.destination;
if (!destination) {
@@ -238,12 +251,11 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 12,
paddingBottom: 8,
paddingHorizontal: 20,
paddingTop: 8,
}}
>
{projectScopes.length === 0 ? (
{items.length === 0 ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
{projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
<Text className="text-center text-lg font-t3-bold text-foreground">
@@ -274,89 +286,42 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
</View>
) : (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{projectScopes.map((scope, scopeIndex) => {
const hasMultipleProjects = scope.projects.length > 1;
const expanded = expandedGroupKeys.has(scope.key);
const singleProject = hasMultipleProjects ? null : scope.projects[0];
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
return (
<View
key={scope.key}
className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
<Pressable
key={item.key}
disabled={reservedDestinationProject !== null}
onPress={() => void selectProject(item)}
className={cn(
"bg-card px-4 py-3.5",
!isFirst && "border-t border-border-subtle",
isFirst && "rounded-t-[24px]",
isLast && "rounded-b-[24px]",
)}
>
<Pressable
disabled={singleProject !== null && reservedDestinationProject !== null}
onPress={() => {
if (singleProject) {
void selectProject(singleProject);
} else {
toggleGroup(scope.key);
}
}}
className="flex-row items-center gap-3 bg-card px-4 py-3.5"
>
<View className="flex-row items-center justify-between gap-3">
<View className="h-7 w-7 items-center justify-center">
<ProjectFavicon
environmentId={scope.representative.environmentId}
environmentId={item.environmentId}
size={20}
projectTitle={scope.title}
workspaceRoot={scope.representative.workspaceRoot}
projectTitle={item.title}
workspaceRoot={item.workspaceRoot}
/>
</View>
<View className="min-w-0 flex-1">
<Text className="text-base leading-snug font-t3-bold">{scope.title}</Text>
<Text
className="text-xs leading-snug text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={1}
>
{hasMultipleProjects
? `${scope.projects.length} workspaces`
: singleProject?.workspaceRoot}
</Text>
<View className="flex-1">
<Text className="text-base leading-snug font-t3-bold">{item.title}</Text>
</View>
<SymbolView
name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</Pressable>
{hasMultipleProjects && expanded
? scope.projects.map((project) => (
<Pressable
key={scopedProjectKey(project.environmentId, project.id)}
disabled={reservedDestinationProject !== null}
onPress={() => void selectProject(project)}
className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"
>
<ProjectFavicon
environmentId={project.environmentId}
size={18}
projectTitle={project.title}
workspaceRoot={project.workspaceRoot}
/>
<View className="min-w-0 flex-1">
<Text className="text-sm font-t3-bold text-foreground">
{project.title}
</Text>
<Text
className="text-xs text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={1}
>
{project.workspaceRoot}
</Text>
</View>
<SymbolView
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</Pressable>
))
: null}
</View>
</View>
</Pressable>
);
})}
</View>
@@ -205,8 +205,6 @@ function ThreadNavigationSidebarPane(
snoozeThread,
unsnoozeThread,
unsettleThread,
pinThread,
unpinThread,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -483,15 +481,6 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const pinningEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinning === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -803,7 +792,6 @@ function ThreadNavigationSidebarPane(
previous.item.thread === item.item.thread &&
previous.item.variant === item.item.variant &&
previous.item.snoozed === item.item.snoozed &&
previous.item.pinned === item.item.pinned &&
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
);
}
@@ -891,7 +879,6 @@ function ThreadNavigationSidebarPane(
thread={thread}
variant={item.item.variant}
snoozed={item.item.snoozed}
pinned={item.item.pinned}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
project={projectByKey.get(scopeKey) ?? null}
@@ -928,12 +915,9 @@ function ThreadNavigationSidebarPane(
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
onSwipeableClose={handleSwipeableClose}
@@ -1061,8 +1045,6 @@ function ThreadNavigationSidebarPane(
handleSwipeableClose,
handleSwipeableWillOpen,
openPendingTask,
pinThread,
pinningEnvironmentIds,
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
@@ -1082,7 +1064,6 @@ function ThreadNavigationSidebarPane(
nowMinute,
toggleSettledShelf,
toggleSnoozedShelf,
unpinThread,
unsettleThread,
unsnoozeThread,
updateGroupDisplay,
@@ -27,6 +27,7 @@ import {
groupByProvider,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
import {
@@ -58,12 +59,6 @@ import {
} from "../../state/use-remote-environment-registry";
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
import {
buildHomeProjectScopes,
sortHomeProjectScopes,
type HomeProjectScope,
} from "../home/homeThreadList";
import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
type WorkspaceMode = "local" | "worktree";
@@ -114,7 +109,10 @@ export function branchBadgeLabel(input: {
}
type NewTaskFlowContextValue = {
readonly projectScopes: ReadonlyArray<HomeProjectScope>;
readonly logicalProjects: ReadonlyArray<{
readonly key: string;
readonly project: EnvironmentProject;
}>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly selectedModelKey: string | null;
@@ -177,20 +175,32 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const projects = useProjects();
const threads = useThreadShells();
const { savedConnectionsById } = useSavedRemoteConnections();
const groupingSettings = useMobileProjectGroupingSettings();
const projectScopes = useMemo(
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const logicalProjects = useMemo(
() =>
sortHomeProjectScopes({
scopes: buildHomeProjectScopes({
projects,
environmentId: null,
projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
pipe(
repositoryGroups,
Arr.map((group) => {
const primaryProject = group.projects[0]?.project;
if (!primaryProject) {
return null;
}
return { key: group.key, project: primaryProject };
}),
threads,
pendingTasks: [],
projectSortOrder: "updated_at",
}),
[groupingSettings.sidebarProjectGroupingMode, projects, threads],
Arr.filter(
(
entry,
): entry is {
readonly key: string;
readonly project: EnvironmentProject;
} => entry !== null,
),
),
[repositoryGroups],
);
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
@@ -836,7 +846,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const value = useMemo<NewTaskFlowContextValue>(
() => ({
projectScopes,
logicalProjects,
selectedEnvironmentId,
selectedProjectKey,
selectedModelKey,
@@ -902,7 +912,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
finishEditingPendingTask,
interactionMode,
loadBranches,
projectScopes,
logicalProjects,
modelOptions,
prompt,
providerGroups,
@@ -1,82 +0,0 @@
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import type { HomeProjectScope } from "../home/homeThreadList";
import {
getOnlySelectableProject,
resolveDraftProjectSelection,
} from "./new-task-project-selection";
function makeProject(id: string): EnvironmentProject {
return {
environmentId: EnvironmentId.make("environment"),
id: ProjectId.make(id),
title: id,
workspaceRoot: `/work/${id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-01T00:00:00.000Z",
updatedAt: "2026-07-01T00:00:00.000Z",
};
}
function makeScope(projects: ReadonlyArray<EnvironmentProject>): HomeProjectScope {
return {
key: "github.com/t3tools/t3code",
title: "T3 Code",
representative: projects[0]!,
projects,
projectRefs: projects.map((project) => ({
environmentId: project.environmentId,
projectId: project.id,
})),
};
}
describe("getOnlySelectableProject", () => {
it("auto-selects when there is exactly one physical project", () => {
const project = makeProject("t3code");
expect(getOnlySelectableProject([makeScope([project])])).toBe(project);
});
it("does not auto-select a representative when one group has multiple clones", () => {
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
expect(getOnlySelectableProject([makeScope(projects)])).toBeNull();
});
});
describe("resolveDraftProjectSelection", () => {
it("preserves an explicit project selection", () => {
const project = makeProject("t3code");
expect(
resolveDraftProjectSelection("environment:t3code", [project], [makeScope([project])]),
).toEqual({ kind: "preserve" });
});
it("selects the only physical project when no project was explicitly selected", () => {
const project = makeProject("t3code");
expect(resolveDraftProjectSelection(null, [project], [makeScope([project])])).toEqual({
kind: "select",
project,
});
});
it("opens the picker for multiple physical projects in one logical group", () => {
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
expect(resolveDraftProjectSelection(null, projects, [makeScope(projects)])).toEqual({
kind: "pick",
});
});
it("does not preserve a project key that is missing from the catalog", () => {
const project = makeProject("t3code");
expect(
resolveDraftProjectSelection("environment:removed", [project], [makeScope([project])]),
).toEqual({
kind: "select",
project,
});
});
});
@@ -1,34 +0,0 @@
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { scopedProjectKey } from "../../lib/scopedEntities";
import type { HomeProjectScope } from "../home/homeThreadList";
export type DraftProjectSelectionResolution =
| { readonly kind: "preserve" }
| { readonly kind: "select"; readonly project: EnvironmentProject }
| { readonly kind: "pick" };
export function getOnlySelectableProject(
projectScopes: ReadonlyArray<HomeProjectScope>,
): EnvironmentProject | null {
const onlyScope = projectScopes.length === 1 ? projectScopes[0] : null;
return onlyScope?.projects.length === 1 ? (onlyScope.projects[0] ?? null) : null;
}
export function resolveDraftProjectSelection(
selectedProjectKey: string | null,
projects: ReadonlyArray<EnvironmentProject>,
projectScopes: ReadonlyArray<HomeProjectScope>,
): DraftProjectSelectionResolution {
const hasExplicitProjectSelection =
selectedProjectKey !== null &&
projects.some(
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
);
if (hasExplicitProjectSelection) {
return { kind: "preserve" };
}
const onlyProject = getOnlySelectableProject(projectScopes);
return onlyProject ? { kind: "select", project: onlyProject } : { kind: "pick" };
}
@@ -204,8 +204,6 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
readonly pane?: "screen" | "sidebar";
/** Draws the "Pending" divider above the first queued row. */
readonly showPendingDivider: boolean;
/** Keeps row hairlines inside a section; section headers draw their own rule. */
readonly showTrailingDivider?: boolean;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
}) {
@@ -293,9 +291,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
) : (
<View className="bg-screen">
<View className="px-5 py-2.5">{rowContent}</View>
{props.showTrailingDivider !== false ? (
<View className="ml-5 h-px bg-border-subtle" />
) : null}
<View className="ml-5 h-px bg-border-subtle" />
</View>
)}
</Pressable>
@@ -309,8 +305,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly variant: "card" | "slim";
/** Snoozed-shelf row: shows its wake time and offers Wake. */
readonly snoozed?: boolean;
/** Pinned-block row: shows the pin glyph and offers Unpin. */
readonly pinned?: boolean;
/** Preformatted against the parent minute tick so this memoized row's
countdown keeps moving. */
readonly snoozeWakeLabelText?: string;
@@ -331,8 +325,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
into the drawer surface, selection filled with the accent color —
matching the v1 sidebar rows. */
readonly pane?: "screen" | "sidebar";
/** Keeps row hairlines inside a section; section headers draw their own rule. */
readonly showTrailingDivider?: boolean;
/** Highlights the thread open in the detail pane (iPad split view). The
compact Home list never sets it — phones navigate away on select. */
readonly selected?: boolean;
@@ -345,15 +337,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onPinThread: (thread: EnvironmentThreadShell) => void;
readonly onUnpinThread: (thread: EnvironmentThreadShell) => void;
/** False on environments whose server predates thread.settle/unsettle:
swipe + menu fall back to Archive instead of failing on use. */
readonly settlementSupported: boolean;
/** False on servers that predate thread.snooze/unsnooze. */
readonly snoozeSupported: boolean;
/** False on servers that predate thread.pin/unpin. */
readonly pinningSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
@@ -380,12 +368,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onUnsnoozeThread,
onUnsettleThread,
onArchiveThread,
onPinThread,
onUnpinThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
const pinnedRow = props.pinned === true;
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
const prState = pr?.state ?? null;
@@ -398,7 +383,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const drawerColor = useThemeColor("--color-drawer");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const pinTintColor = useThemeColor("--color-foreground-muted");
const sidebarPane = props.pane === "sidebar";
const selected = props.selected === true;
@@ -414,8 +398,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
);
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
// Swipe: the v2 primary action is the lifecycle transition. Every settled
@@ -452,20 +434,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
})),
[snoozePresets],
);
// Pinned cards keep the full lifecycle menu; only the pin item flips to
// Unpin. (Settling a pinned thread clears the pin server-side; snoozing
// hides the card until wake with the pin intact.)
const pinMenuItem = useMemo<MenuAction[]>(
() =>
props.pinningSupported
? [
pinnedRow
? { id: "unpin", title: "Unpin", image: "pin.slash" }
: { id: "pin", title: "Pin", image: "pin" },
]
: [],
[pinnedRow, props.pinningSupported],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
{ id: "settle", title: "Settle", image: "checkmark" },
@@ -475,22 +443,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
image: "clock",
subactions: snoozePresetActions,
},
...pinMenuItem,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[pinMenuItem, snoozePresetActions],
);
const cardMenuActions = useMemo<MenuAction[]>(
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
[pinMenuItem],
[snoozePresetActions],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "settle") handleSettle();
if (nativeEvent.event === "unsettle") handleUnsettle();
if (nativeEvent.event === "unsnooze") handleUnsnooze();
if (nativeEvent.event === "pin") handlePin();
if (nativeEvent.event === "unpin") handleUnpin();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
@@ -507,10 +468,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handlePin,
handleSettle,
handleSnooze,
handleUnpin,
handleUnsettle,
handleUnsnooze,
snoozePresets,
@@ -601,9 +560,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
>
{props.projectTitle ?? props.project?.title ?? ""}
</Text>
{pinnedRow ? (
<SymbolView name="pin" size={11} tintColor={pinTintColor} type="monochrome" />
) : null}
<Text
className={cn(
"text-xs tabular-nums",
@@ -734,9 +690,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
actions reveal behind the row. */
<View className="bg-screen">
<View className="px-5 py-2.5">{cardContent}</View>
{props.showTrailingDivider !== false ? (
<View className="ml-5 h-px bg-border-subtle" />
) : null}
<View className="ml-5 h-px bg-border-subtle" />
</View>
)}
</Pressable>
@@ -851,7 +805,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
? SLIM_MENU_ACTIONS
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: cardMenuActions
: CARD_MENU_ACTIONS
}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
@@ -288,57 +288,6 @@ describe("buildThreadListV2Items", () => {
expect(layout.snoozedCount).toBe(1);
});
it("renders pinned threads first and exempts them from auto-settle — parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("pinned-settled"),
title: "Pinned while settled",
pinnedAt: "2026-06-01T12:00:00.000Z",
// Stale settled state (the decider clears it on pin): the pin wins.
settledOverride: "settled",
settledAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["pinned-settled", "active"]);
expect(layout.items.map((item) => item.pinned)).toEqual([true, false]);
expect(layout.settledCount).toBe(0);
});
it("snooze hides a pinned thread and wake restores it to the pinned block", () => {
const snoozedInput = {
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("pinned-snoozed"),
title: "Pinned and snoozed",
pinnedAt: "2026-06-01T12:00:00.000Z",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T11:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
};
// Before the wake time: the snooze wins; the pin holds underneath.
const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, now: NOW });
expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]);
expect(whileSnoozed.snoozedCount).toBe(1);
// After the wake time: the thread returns pinned, back on top.
const afterWake = buildThreadListV2Items({ ...snoozedInput, now: "2026-06-03T10:00:00.000Z" });
expect(afterWake.items.map((item) => item.thread.id)).toEqual(["pinned-snoozed", "active"]);
expect(afterWake.items[0]?.pinned).toBe(true);
expect(afterWake.snoozedCount).toBe(0);
});
it("classifies snooze with the second-precise clock and reports the next wake", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -180,8 +180,6 @@ export interface ThreadListV2Item {
readonly variant: "card" | "slim";
/** Snoozed-shelf row: shows the wake countdown and offers Wake. */
readonly snoozed: boolean;
/** Pinned-block row: renders the pin glyph and offers Unpin. */
readonly pinned: boolean;
readonly isLast: boolean;
}
@@ -353,7 +351,6 @@ export function buildThreadListV2Items(input: {
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
: null;
const pinned: EnvironmentThreadShell[] = [];
const active: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
const snoozed: EnvironmentThreadShell[] = [];
@@ -381,10 +378,9 @@ export function buildThreadListV2Items(input: {
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: snooze outranks everything, including a
// pin — a snoozed thread leaves the list until it wakes (or raises its
// hand). The pin survives underneath, so a woken thread reappears at
// its original spot in the creation-ordered pinned block.
// Visibility parity with web: a snoozed thread leaves the list until it
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
// work). Snooze outranks settled classification, same as web.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozed.push(thread);
if (
@@ -396,12 +392,6 @@ export function buildThreadListV2Items(input: {
}
continue;
}
// A pin otherwise overrides the lifecycle: pinned threads render above
// the inbox and never auto-settle out of sight.
if (thread.pinnedAt != null) {
pinned.push(thread);
continue;
}
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
@@ -444,21 +434,11 @@ export function buildThreadListV2Items(input: {
);
const items: ThreadListV2Item[] = [];
for (const thread of sortThreadsForListV2(pinned)) {
items.push({
thread,
variant: "card",
snoozed: false,
pinned: true,
isLast: false,
});
}
for (const thread of orderedActive) {
items.push({
thread,
variant: "card",
snoozed: false,
pinned: false,
isLast: false,
});
}
@@ -468,7 +448,6 @@ export function buildThreadListV2Items(input: {
thread,
variant: "slim",
snoozed: true,
pinned: false,
isLast: false,
});
}
@@ -478,7 +457,6 @@ export function buildThreadListV2Items(input: {
thread,
variant: "slim",
snoozed: false,
pinned: false,
isLast: false,
});
}
@@ -0,0 +1,192 @@
import { describe, expect, it } from "vite-plus/test";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { groupProjectsByRepository } from "./repositoryGroups";
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
): EnvironmentProject {
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
...input,
};
}
function makeThread(
input: Partial<EnvironmentThreadShell> &
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title" | "modelSelection">,
): EnvironmentThreadShell {
return {
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
describe("groupProjectsByRepository", () => {
it("groups projects across environments by repository identity", () => {
const repoIdentity = {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:t3tools/t3code.git",
},
provider: "github",
owner: "t3tools",
name: "t3code",
displayName: "T3 Code",
};
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("project-local"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
}),
makeProject({
environmentId: EnvironmentId.make("env-staging"),
id: ProjectId.make("project-staging"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
}),
];
const threads = [
makeThread({
environmentId: EnvironmentId.make("env-staging"),
id: ThreadId.make("thread-2"),
projectId: ProjectId.make("project-staging"),
title: "Fix reconnect flow",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-02T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-local"),
title: "Polish mobile shell",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-03T12:00:00.000Z",
}),
];
const groups = groupProjectsByRepository({ projects, threads });
expect(groups).toHaveLength(1);
expect(groups[0]).toMatchObject({
key: "github.com/t3tools/t3code",
title: "T3 Code",
subtitle: "t3tools/t3code",
projectCount: 2,
threadCount: 2,
});
expect(
groups[0]?.projects.map((entry) => ({
environmentId: entry.project.environmentId,
latestActivityAt: entry.latestActivityAt,
threads: entry.threads.map((thread) => thread.id),
})),
).toEqual([
{
environmentId: "env-local",
latestActivityAt: "2026-04-03T12:00:00.000Z",
threads: ["thread-1"],
},
{
environmentId: "env-staging",
latestActivityAt: "2026-04-02T12:00:00.000Z",
threads: ["thread-2"],
},
]);
expect(groups[0]?.latestActivityAt).toBe("2026-04-03T12:00:00.000Z");
});
it("orders threads, projects, and repository groups by latest activity", () => {
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("older-project"),
title: "Older",
}),
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("newer-project"),
title: "Newer",
}),
];
const threads = [
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("older-thread"),
projectId: ProjectId.make("older-project"),
title: "Older thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-02T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("newer-thread"),
projectId: ProjectId.make("older-project"),
title: "Newer thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-04T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("newest-thread"),
projectId: ProjectId.make("newer-project"),
title: "Newest thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-05T12:00:00.000Z",
}),
];
const groups = groupProjectsByRepository({ projects, threads });
expect(groups.map((group) => group.title)).toEqual(["Newer", "Older"]);
expect(groups[1]?.projects[0]?.threads.map((thread) => thread.id)).toEqual([
"newer-thread",
"older-thread",
]);
});
it("falls back to a scoped project key when repository identity is unavailable", () => {
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("project-local"),
title: "Scratchpad",
}),
];
const groups = groupProjectsByRepository({ projects, threads: [] });
expect(groups).toHaveLength(1);
expect(groups[0]?.key).toBe("env-local:project-local");
expect(groups[0]?.title).toBe("Scratchpad");
expect(groups[0]?.subtitle).toBeNull();
});
});
+131
View File
@@ -0,0 +1,131 @@
import * as Order from "effect/Order";
import * as Arr from "effect/Array";
import type { RepositoryIdentity } from "@t3tools/contracts";
import { scopedProjectKey } from "./scopedEntities";
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
const DateDescending = Order.flip(Order.Date);
export interface RepositoryProjectGroup {
readonly key: string;
readonly project: EnvironmentProject;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly latestActivityAt: string;
}
export interface RepositoryGroup {
readonly key: string;
readonly title: string;
readonly subtitle: string | null;
readonly repositoryIdentity: RepositoryIdentity | null;
readonly projectCount: number;
readonly threadCount: number;
readonly latestActivityAt: string;
readonly projects: ReadonlyArray<RepositoryProjectGroup>;
}
function compareIsoDateDescending(left: string, right: string): number {
return new Date(right).getTime() - new Date(left).getTime();
}
function deriveRepositoryGroupKey(project: EnvironmentProject): string {
return (
project.repositoryIdentity?.canonicalKey ?? scopedProjectKey(project.environmentId, project.id)
);
}
function deriveRepositoryTitle(project: EnvironmentProject): string {
const identity = project.repositoryIdentity;
return identity?.displayName ?? identity?.name ?? project.title;
}
function deriveRepositorySubtitle(identity: RepositoryIdentity | null | undefined): string | null {
if (!identity) {
return null;
}
if (identity.owner && identity.name) {
return `${identity.owner}/${identity.name}`;
}
return identity.canonicalKey;
}
function deriveProjectLatestActivity(
project: EnvironmentProject,
threads: ReadonlyArray<EnvironmentThreadShell>,
): string {
const latestThread = threads[0];
return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt;
}
export function groupProjectsByRepository(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}): ReadonlyArray<RepositoryGroup> {
const threadsByProjectKey = new Map<string, EnvironmentThreadShell[]>();
for (const thread of input.threads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = threadsByProjectKey.get(key);
if (existing) {
existing.push(thread);
} else {
threadsByProjectKey.set(key, [thread]);
}
}
const grouped = new Map<string, RepositoryGroup>();
for (const project of input.projects) {
const key = deriveRepositoryGroupKey(project);
const projectKey = scopedProjectKey(project.environmentId, project.id);
const threads = Arr.sortWith(
threadsByProjectKey.get(projectKey) ?? [],
(s) => new Date(s.updatedAt ?? s.createdAt),
DateDescending,
);
const latestActivityAt = deriveProjectLatestActivity(project, threads);
const projectGroup: RepositoryProjectGroup = {
key: projectKey,
project,
threads,
latestActivityAt,
};
const existing = grouped.get(key);
if (!existing) {
grouped.set(key, {
key,
title: deriveRepositoryTitle(project),
subtitle: deriveRepositorySubtitle(project.repositoryIdentity),
repositoryIdentity: project.repositoryIdentity ?? null,
projectCount: 1,
threadCount: threads.length,
latestActivityAt,
projects: [projectGroup],
});
continue;
}
grouped.set(key, {
...existing,
title: existing.repositoryIdentity ? existing.title : deriveRepositoryTitle(project),
subtitle: existing.subtitle ?? deriveRepositorySubtitle(project.repositoryIdentity),
repositoryIdentity: existing.repositoryIdentity ?? project.repositoryIdentity ?? null,
projectCount: existing.projectCount + 1,
threadCount: existing.threadCount + threads.length,
latestActivityAt:
compareIsoDateDescending(existing.latestActivityAt, latestActivityAt) > 0
? latestActivityAt
: existing.latestActivityAt,
projects: Arr.sortWith(
[...existing.projects, projectGroup],
(s) => new Date(s.latestActivityAt),
DateDescending,
),
});
}
return Arr.sortWith(grouped.values(), (s) => new Date(s.latestActivityAt), DateDescending);
}
@@ -5,7 +5,6 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
import * as MobileDatabase from "./mobile-database";
import * as MobileSecureStorage from "./mobile-secure-storage";
@@ -23,9 +22,7 @@ export interface Preferences {
readonly codeWordBreak?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
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
@@ -83,7 +80,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
threadListV2Enabled?: boolean;
} = {};
@@ -114,13 +110,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
if (typeof parsed.projectGroupingEnabled === "boolean") {
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
}
if (
parsed.projectGroupingMode === "repository" ||
parsed.projectGroupingMode === "repository_path" ||
parsed.projectGroupingMode === "separate"
) {
preferences.projectGroupingMode = parsed.projectGroupingMode;
}
if (typeof parsed.threadListV2Enabled === "boolean") {
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
}
@@ -1,33 +0,0 @@
import type { ProjectGroupingSettings } from "@t3tools/client-runtime/state/project-grouping";
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
import type { Preferences } from "../persistence/mobile-preferences";
export const DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS: ProjectGroupingSettings = {
sidebarProjectGroupingMode: "repository",
sidebarProjectGroupingOverrides: {},
};
export function resolveMobileProjectGroupingSettings(
preferences: Preferences,
): ProjectGroupingSettings {
return {
sidebarProjectGroupingMode:
preferences.projectGroupingMode ??
(preferences.projectGroupingEnabled === false ? "separate" : "repository"),
sidebarProjectGroupingOverrides: {},
};
}
/**
* Dual-writes the legacy boolean for one release so an OTA rollback to an
* older mobile bundle preserves the user's grouping choice.
*/
export function mobileProjectGroupingModePatch(
mode: SidebarProjectGroupingMode,
): Partial<Preferences> {
return {
projectGroupingMode: mode,
projectGroupingEnabled: mode !== "separate",
};
}
@@ -1,33 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
mobileProjectGroupingModePatch,
resolveMobileProjectGroupingSettings,
} from "./project-grouping.logic";
describe("mobile project grouping preferences", () => {
it("maps the legacy boolean while preferring the new mode", () => {
expect(resolveMobileProjectGroupingSettings({}).sidebarProjectGroupingMode).toBe("repository");
expect(
resolveMobileProjectGroupingSettings({ projectGroupingEnabled: false })
.sidebarProjectGroupingMode,
).toBe("separate");
expect(
resolveMobileProjectGroupingSettings({
projectGroupingEnabled: false,
projectGroupingMode: "repository_path",
}).sidebarProjectGroupingMode,
).toBe("repository_path");
});
it("dual-writes the legacy boolean for rollback compatibility", () => {
expect(mobileProjectGroupingModePatch("separate")).toEqual({
projectGroupingMode: "separate",
projectGroupingEnabled: false,
});
expect(mobileProjectGroupingModePatch("repository_path")).toEqual({
projectGroupingMode: "repository_path",
projectGroupingEnabled: true,
});
});
});
-17
View File
@@ -1,17 +0,0 @@
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { mobilePreferencesAtom } from "./preferences";
import {
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
resolveMobileProjectGroupingSettings,
} from "./project-grouping.logic";
export * from "./project-grouping.logic";
export function useMobileProjectGroupingSettings() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
return AsyncResult.isSuccess(preferencesResult)
? resolveMobileProjectGroupingSettings(preferencesResult.value)
: DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS;
}
+1 -8
View File
@@ -23,7 +23,6 @@ const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLET
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
const hangFirstPrompts = Number(process.env.T3_ACP_HANG_FIRST_PROMPTS ?? "0");
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
const omitXAiPromptCompleteStopReason =
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
@@ -519,13 +518,7 @@ const program = Effect.gen(function* () {
return yield* Effect.never;
}
if (
hangPromptForever ||
(hangFirstPromptForever && promptCount === 1) ||
(Number.isFinite(hangFirstPrompts) &&
hangFirstPrompts > 0 &&
promptCount <= hangFirstPrompts)
) {
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
return yield* Effect.never;
}
-1
View File
@@ -75,7 +75,6 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.vcsSwitchRef]: AuthOrchestrationOperateScope,
[WS_METHODS.vcsInit]: AuthOrchestrationOperateScope,
[WS_METHODS.reviewGetDiffPreview]: AuthReviewWriteScope,
[WS_METHODS.reviewGetDiffFileContents]: AuthReviewWriteScope,
[WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
[WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
[WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
-10
View File
@@ -10,7 +10,6 @@ import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Terminal from "effect/Terminal";
import * as BootService from "../cloud/bootService.ts";
import {
acquireRelayClientForLink,
formatHeadlessAuthorizationPrompt,
@@ -64,15 +63,6 @@ it.effect("treats cancelling optional background setup as a successful skip", ()
}),
);
it.effect("keeps a successful connection when a remote service update is pending", () =>
Effect.gen(function* () {
const result = yield* recoverServiceOnboardingOffer(
Effect.fail(new BootService.BootServiceUpdatePendingError()),
);
assert.isFalse(result);
}),
);
it.effect("does not install the relay client when the user declines the managed download", () =>
Effect.gen(function* () {
let installCalls = 0;
-2
View File
@@ -185,8 +185,6 @@ export const recoverServiceOnboardingOffer = <R>(
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceInstallError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceUpdatePendingError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
}),
);
+6 -46
View File
@@ -15,11 +15,7 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
import * as ProcessRunner from "../processRunner.ts";
import * as BootService from "./bootService.ts";
import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
import {
parseServiceState,
SERVICE_LAUNCHER_PROTOCOL,
serviceStateHasPendingUpdate,
} from "./serviceProtocol.ts";
import { parseServiceState } from "./serviceProtocol.ts";
it("keeps systemd pinned to the stable launcher rather than a versioned server", () => {
const unit = BootService.renderBootServiceUnit({
@@ -101,24 +97,15 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
const plan = yield* service.install;
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
activeVersion: "1.2.3",
});
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
expect((yield* service.status).current).toBe(true);
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.2.3",
update: {
id: "u",
fromVersion: "1.2.3",
targetVersion: "1.2.4",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
});
yield* fs.writeFileString(statePath, pendingState);
yield* fs.writeFileString(
statePath,
'{"protocol":1,"activeVersion":"1.2.3","update":{"id":"u","fromVersion":"1.2.3","targetVersion":"1.2.4","status":"pending"}}',
);
expect((yield* service.status).current).toBe(false);
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
@@ -154,33 +141,6 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
it.effect("restarts without overwriting a pending remote update", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands } = yield* makeHarness();
yield* service.install;
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
activeVersion: "1.2.3",
update: {
id: "remote-update",
fromVersion: "1.2.3",
targetVersion: "1.2.4",
status: "pending",
},
});
yield* fs.writeFileString(statePath, pendingState);
commands.length = 0;
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
"systemctl --user stop t3code.service",
"systemctl --user restart t3code.service",
]);
}),
);
it.effect("fails closed off Linux", () =>
Effect.gen(function* () {
const { service } = yield* makeHarness("darwin");
+1 -21
View File
@@ -21,7 +21,6 @@ import {
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
parseServiceState,
serviceStateHasPendingUpdate,
type ServiceState,
} from "./serviceProtocol.ts";
@@ -111,20 +110,10 @@ export class BootServiceInstallError extends Schema.TaggedErrorClass<BootService
}
}
export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
"BootServiceUpdatePendingError",
{},
) {
override get message(): string {
return "A remote server update is still pending. Wait for it to finish, then retry.";
}
}
export type BootServiceError =
| BootServiceUnsupportedError
| BootServiceCommandError
| BootServiceInstallError
| BootServiceUpdatePendingError;
| BootServiceInstallError;
export interface BootServiceStatus {
readonly supported: boolean;
@@ -299,15 +288,6 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}
yield* Effect.gen(function* () {
if (installed) {
const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
if (
Option.isSome(previousStateText) &&
serviceStateHasPendingUpdate(previousStateText.value)
) {
return yield* new BootServiceUpdatePendingError();
}
}
yield* fs
.makeDirectory(unitDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
+2 -6
View File
@@ -11,7 +11,6 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
import * as ServerSelfUpdate from "./selfUpdate.ts";
interface HarnessOptions {
@@ -51,11 +50,7 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
const result =
options.preflight === "blocked"
? { status: "blocked", version: "1.1.0", reason: "local update required" }
: {
status: "ready",
version: "1.1.0",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
};
: { status: "ready", version: "1.1.0", launcherProtocol: 1 };
return {
// @effect-diagnostics-next-line preferSchemaOverJson:off - fake child-process stdout.
stdout: JSON.stringify(result),
@@ -69,6 +64,7 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
});
const launcher = ServiceLauncherClient.ServiceLauncherClient.of({
managed: options.managed ?? true,
trial: false,
requestUpdate:
options.requestUpdate ??
(() =>
+1 -1
View File
@@ -170,7 +170,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
yield* reportProgress("installing");
const updateId = yield* launcher
.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath })
.requestUpdate({ targetVersion })
.pipe(
Effect.mapError((error) =>
failWith(
@@ -5,7 +5,6 @@ import * as Fiber from "effect/Fiber";
import {
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_LAUNCHER_PROTOCOL,
type ServiceLauncherChildMessage,
type ServiceLauncherParentMessage,
} from "./serviceProtocol.ts";
@@ -54,11 +53,10 @@ it.effect("waits for the launcher to durably commit the trial update ID", () =>
id: "update-1",
fromVersion: "1.0.0",
targetVersion: "1.1.0",
dbPath: "/tmp/state.sqlite",
status: "pending" as const,
};
const host = new FakeLauncherProcess({
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
childVersion: "1.1.0",
update: pending,
});
@@ -81,14 +79,13 @@ it.effect("waits for the launcher to durably commit the trial update ID", () =>
it.effect("returns the launcher-generated ID only after update acceptance", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
childVersion: "1.0.0",
});
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(
client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
{ startImmediately: true },
);
const requested = yield* Effect.forkChild(client.requestUpdate({ targetVersion: "1.1.0" }), {
startImmediately: true,
});
yield* Effect.yieldNow;
host.emit({
type: "update-accepted",
@@ -100,15 +97,11 @@ it.effect("returns the launcher-generated ID only after update acceptance", () =
it.effect("preserves a launcher rejection as a distinct error", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.0.0",
});
const host = new FakeLauncherProcess({ protocol: 1, childVersion: "1.0.0" });
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(
client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
{ startImmediately: true },
);
const requested = yield* Effect.forkChild(client.requestUpdate({ targetVersion: "1.1.0" }), {
startImmediately: true,
});
yield* Effect.yieldNow;
host.emit({ type: "update-rejected", reason: "requires local update" });
expect(yield* Fiber.join(requested).pipe(Effect.flip)).toMatchObject({
@@ -122,13 +115,12 @@ it.effect("preserves a launcher rejection as a distinct error", () =>
it.effect("rejects contradictory trial context instead of leaving activation closed", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
childVersion: "1.1.0",
update: {
id: "update-1",
fromVersion: "1.0.0",
targetVersion: "1.2.0",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
});
+6 -10
View File
@@ -100,9 +100,9 @@ export class ServiceLauncherClient extends Context.Service<
ServiceLauncherClient,
{
readonly managed: boolean;
readonly trial: boolean;
readonly requestUpdate: (input: {
readonly targetVersion: string;
readonly dbPath: string;
}) => Effect.Effect<string, ServiceLauncherClientError | ServiceLauncherRejectedError>;
readonly prepareTrial: Effect.Effect<
ServerSelfUpdateOutcome | undefined,
@@ -137,8 +137,8 @@ const resolveStartup = Effect.fn("cloud.service_launcher_client.resolve_startup"
export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_client.resolve_mode")(
function* () {
const { managed } = yield* resolveStartup();
return { managed };
const { context, managed } = yield* resolveStartup();
return { managed, trial: context?.update?.status === "pending" };
},
);
@@ -199,7 +199,7 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o
}),
);
const requestUpdate = (input: { readonly targetVersion: string; readonly dbPath: string }) =>
const requestUpdate = (input: { readonly targetVersion: string }) =>
exchange(
{ type: "request-update", ...input },
(reply) => reply.type === "update-accepted" || reply.type === "update-rejected",
@@ -233,18 +233,14 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o
if (reply.type !== "committed") {
return Effect.die("service launcher returned an impossible prepared response");
}
return Effect.succeed({
id: pending.id,
fromVersion: pending.fromVersion,
targetVersion: pending.targetVersion,
status: "committed" as const,
});
return Effect.succeed({ ...pending, status: "committed" as const });
}),
)
: Effect.succeed(outcome);
return ServiceLauncherClient.of({
managed,
trial: pending !== undefined,
requestUpdate,
prepareTrial,
});
+40 -19
View File
@@ -1,26 +1,47 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as NodeSqlite from "node:sqlite";
import { migrationManifest } from "../persistence/Migrations.ts";
import { runServicePreflight } from "./servicePreflight.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
it("requires the database-snapshot launcher protocol", () => {
expect(
runServicePreflight({
databasePath: "/missing/state.sqlite",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL - 1,
version: "1.2.3",
}),
).toMatchObject({ status: "blocked", version: "1.2.3" });
it.layer(NodeServices.layer)("service update preflight", (it) => {
it.effect("requires exact migration-manifest equality without mutating the database", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-preflight-test-" });
const databasePath = path.join(root, "state.sqlite");
const database = new NodeSqlite.DatabaseSync(databasePath);
database.exec("CREATE TABLE effect_sql_migrations (migration_id INTEGER, name TEXT)");
const insert = database.prepare(
"INSERT INTO effect_sql_migrations (migration_id, name) VALUES (?, ?)",
);
for (const [id, name] of migrationManifest) insert.run(id, name);
database.close();
expect(
runServicePreflight({
databasePath: "/missing/state.sqlite",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
version: "1.2.3",
expect(runServicePreflight({ databasePath, launcherProtocol: 1, version: "1.2.3" })).toEqual({
status: "ready",
version: "1.2.3",
launcherProtocol: 1,
});
const changed = new NodeSqlite.DatabaseSync(databasePath);
changed.exec("DELETE FROM effect_sql_migrations WHERE migration_id = 35");
changed.close();
const blocked = runServicePreflight({
databasePath,
launcherProtocol: 1,
version: "1.2.3",
});
expect(blocked.status).toBe("blocked");
if (blocked.status === "blocked") {
expect(blocked.reason).toContain("npx [email protected] service update");
}
}),
).toEqual({
status: "ready",
version: "1.2.3",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
});
);
});
+38 -1
View File
@@ -1,4 +1,7 @@
import * as NodeSqlite from "node:sqlite";
import packageJson from "../../package.json" with { type: "json" };
import { migrationManifest } from "../persistence/Migrations.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
export type ServicePreflightResult =
@@ -13,8 +16,20 @@ export type ServicePreflightResult =
readonly reason: string;
};
const localUpdateReason = (version: string) =>
`This version includes a database update and cannot be installed remotely. Run \`npx t3@${version} service update\` on the server machine.`;
const isMigrationRow = (
value: unknown,
): value is { readonly migration_id: number; readonly name: string } =>
typeof value === "object" &&
value !== null &&
"migration_id" in value &&
typeof value.migration_id === "number" &&
"name" in value &&
typeof value.name === "string";
export function runServicePreflight(input: {
/** Older servers always pass this flag when invoking a staged preflight. */
readonly databasePath: string;
readonly launcherProtocol: number;
readonly version?: string;
@@ -29,6 +44,28 @@ export function runServicePreflight(input: {
};
}
try {
const database = new NodeSqlite.DatabaseSync(input.databasePath, { readOnly: true });
try {
const rows: ReadonlyArray<unknown> = database
.prepare("SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id")
.all();
const exact =
rows.length === migrationManifest.length &&
rows.every((row, index) => {
const expected = migrationManifest[index];
return (
isMigrationRow(row) && row.migration_id === expected?.[0] && row.name === expected?.[1]
);
});
if (!exact) return { status: "blocked", version, reason: localUpdateReason(version) };
} finally {
database.close();
}
} catch {
return { status: "blocked", version, reason: localUpdateReason(version) };
}
return { status: "ready", version, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL };
}
+4 -23
View File
@@ -1,7 +1,6 @@
import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
/** Protocol 2 snapshots SQLite before trials so migrations can be rolled back safely. */
export const SERVICE_LAUNCHER_PROTOCOL = 2 as const;
export const SERVICE_LAUNCHER_PROTOCOL = 1 as const;
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
export const SERVICE_LAUNCHER_FILE = "service-launcher.mjs";
export const SERVICE_STATE_FILE = "service-state.json";
@@ -10,7 +9,6 @@ export interface PendingServiceUpdate {
readonly id: string;
readonly fromVersion: string;
readonly targetVersion: string;
readonly dbPath: string;
readonly status: "pending";
}
@@ -33,7 +31,6 @@ export type ServiceLauncherChildMessage =
| {
readonly type: "request-update";
readonly targetVersion: string;
readonly dbPath: string;
}
| {
readonly type: "prepared";
@@ -81,9 +78,7 @@ export function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undef
return undefined;
}
if (status === "pending") {
return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
: undefined;
return { id, fromVersion, targetVersion, status };
}
if (
(status === "committed" || status === "rolled-back" || status === "failed") &&
@@ -170,16 +165,6 @@ export function parseServiceState(value: string): ServiceState | undefined {
}
}
/** Detects an in-flight update across launcher protocol versions before replacing its state. */
export function serviceStateHasPendingUpdate(value: string): boolean {
try {
const parsed: unknown = JSON.parse(value);
return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
} catch {
return false;
}
}
export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
let parsed: unknown;
try {
@@ -217,12 +202,8 @@ export function decodeServiceLauncherChildMessage(
value: unknown,
): ServiceLauncherChildMessage | undefined {
if (!isRecord(value)) return undefined;
if (
value.type === "request-update" &&
typeof value.targetVersion === "string" &&
typeof value.dbPath === "string"
) {
return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
if (value.type === "request-update" && typeof value.targetVersion === "string") {
return { type: value.type, targetVersion: value.targetVersion };
}
return value.type === "prepared" && typeof value.updateId === "string"
? { type: value.type, updateId: value.updateId }
@@ -145,7 +145,6 @@ export const make = Effect.gen(function* () {
connectionProbe: true,
threadSettlement: true,
threadSnooze: true,
threadPinning: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
@@ -12,19 +12,6 @@ const schemaHasDescription = (schema: unknown): boolean => {
.some((members) => members.some(schemaHasDescription));
};
const schemaHasMultipleAllOfDescriptions = (schema: unknown): boolean => {
if (!schema || typeof schema !== "object") return false;
const record = schema as Record<string, unknown>;
const allOf = Array.isArray(record.allOf) ? record.allOf : [];
const descriptionCount = allOf.filter(
(member) =>
member !== null &&
typeof member === "object" &&
typeof (member as Record<string, unknown>).description === "string",
).length;
return descriptionCount > 1 || Object.values(record).some(schemaHasMultipleAllOfDescriptions);
};
it("exports provider-compatible object schemas with described parameters", () => {
for (const tool of Object.values(PreviewToolkit.tools)) {
const schema = Tool.getJsonSchema(tool) as {
@@ -40,9 +27,6 @@ it("exports provider-compatible object schemas with described parameters", () =>
expect(schema.type, `${tool.name} must export a top-level object schema`).toBe("object");
expect(schema.anyOf, `${tool.name} must not export a root anyOf`).toBeUndefined();
expect(schema.oneOf, `${tool.name} must not export a root oneOf`).toBeUndefined();
if (tool.name === "preview_navigate") {
expect(schemaHasMultipleAllOfDescriptions(schema)).toBe(false);
}
expect(
schema.properties?.tabId,
`${tool.name} must allow an explicit collaborative browser tab target`,
@@ -611,7 +611,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
titleRegenerationRequestId: null,
titleRegenerationStartedAt: null,
latestUserMessageAt: null,
@@ -718,36 +717,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.pinned": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: event.payload.pinnedAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.unpinned": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.meta-updated": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -312,7 +312,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
titleRegeneration: null,
deletedAt: null,
messages: [
@@ -428,7 +427,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
titleRegeneration: null,
session: {
threadId: ThreadId.make("thread-1"),
@@ -384,7 +384,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -419,7 +418,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -456,7 +454,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -893,7 +890,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -1332,7 +1328,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
@@ -1536,7 +1531,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: [],
@@ -1671,7 +1665,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
@@ -1811,7 +1804,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
@@ -2083,7 +2075,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
titleRegeneration: mapTitleRegeneration(threadRow.value),
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
@@ -2183,7 +2174,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
titleRegeneration: mapTitleRegeneration(threadRow.value),
deletedAt: null,
messages: messageRows.map((row) => {
@@ -785,123 +785,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.titleRegeneration).toBeNull();
});
it("pins the first user message when regeneration context is truncated", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const firstUserMessage = `Review subagent monitoring risks. ${"Opening context. ".repeat(200)}`;
const recentUserMessage = `LATEST FINDING: ${"implementation detail ".repeat(320)}`;
harness.generateThreadTitle.mockReturnValue(
Effect.succeed({ title: "Review subagent monitoring risks" }),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-title-existing-long"),
threadId: ThreadId.make("thread-1"),
title: "Generic PR review",
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-before-long-title-regeneration"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-before-long-title-regeneration"),
role: "user",
text: firstUserMessage,
attachments: [
{
type: "image",
id: "opening-context-image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-middle-turn-before-long-title-regeneration"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("middle-message-before-long-title-regeneration"),
role: "user",
text: "Temporary handoff details.",
attachments: [
{
type: "image",
id: "middle-context-image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:01.000Z",
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-recent-turn-before-long-title-regeneration"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("recent-message-before-long-title-regeneration"),
role: "user",
text: recentUserMessage,
attachments: [
{
type: "image",
id: "recent-context-image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:02.000Z",
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-title-regenerate-long"),
threadId: ThreadId.make("thread-1"),
regenerateTitle: true,
}),
);
await harness.drain();
expect(harness.generateThreadTitle).toHaveBeenCalledTimes(1);
const input = harness.generateThreadTitle.mock.calls[0]?.[0];
if (!input) {
throw new Error("Expected a title generation input");
}
const message = input.message;
expect(message.startsWith("USER:\nReview subagent monitoring risks.")).toBe(true);
expect(message).toContain("[First user message truncated]");
expect(message).toContain("[Earlier content truncated]");
expect(message).toContain("image.png");
expect(message).toHaveLength(8_000);
expect(input.attachments?.map((attachment) => attachment.id)).toEqual([
"opening-context-image",
"recent-context-image",
]);
});
it("clears title regeneration state left pending across reactor startup", async () => {
const harness = await createHarness({
titleRegenerationBeforeStart: "one",
@@ -1089,14 +972,10 @@ describe("ProviderCommandReactor", () => {
expect(thread?.titleRegeneration).toBeNull();
});
it("pins the first user context and attachment before the retained tail", async () => {
it("keeps the full retained context and excludes attachments outside it", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const firstUserContext = "USER:\nOld visual issue\n[Attachments: old-issue.png]";
const truncationMarker = "[Earlier content truncated]\n\n";
const retainedContext = "x".repeat(
8_000 - firstUserContext.length - "\n\n".length - truncationMarker.length,
);
const retainedContext = "x".repeat(8_000);
await harness.runEffect(
harness.engine.dispatch({
@@ -1161,14 +1040,9 @@ describe("ProviderCommandReactor", () => {
await harness.drain();
expect(harness.generateThreadTitle.mock.calls[0]?.[0].message).toBe(
`${firstUserContext}\n\n${truncationMarker}${retainedContext}`,
`[Earlier content truncated]\n\n${retainedContext}`,
);
expect(harness.generateThreadTitle.mock.calls[0]?.[0].attachments).toEqual([
expect.objectContaining({
id: "old-title-context-image",
name: "old-issue.png",
}),
]);
expect(harness.generateThreadTitle.mock.calls[0]?.[0].attachments).toBeUndefined();
});
it("does not overwrite a manual rename while title regeneration is running", async () => {
@@ -94,61 +94,41 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const DEFAULT_THREAD_TITLE = "New thread";
const MAX_REGENERATION_ATTACHMENTS = 4;
const MAX_THREAD_TITLE_CONTEXT_CHARS = 8_000;
const MAX_FIRST_USER_TITLE_CONTEXT_CHARS = 2_000;
const THREAD_TITLE_CONTEXT_TRUNCATION_MARKER = "[Earlier content truncated]\n\n";
const FIRST_USER_CONTEXT_TRUNCATION_MARKER = "\n[First user message truncated]";
type ThreadTitleMessage = {
readonly role: "user" | "assistant" | "system";
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
};
function formatThreadTitleSection(message: ThreadTitleMessage): string | undefined {
if (message.role === "system") {
return undefined;
}
const text = message.text.trim();
const attachmentSummary = (message.attachments ?? [])
.map((attachment) => attachment.name)
.join(", ");
const contents = [
...(text.length > 0 ? [text] : []),
...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),
].join("\n");
return contents.length > 0 ? `${message.role.toUpperCase()}:\n${contents}` : undefined;
}
function limitFirstUserSection(section: string): string {
if (section.length <= MAX_FIRST_USER_TITLE_CONTEXT_CHARS) {
return section;
}
return `${section.slice(
0,
MAX_FIRST_USER_TITLE_CONTEXT_CHARS - FIRST_USER_CONTEXT_TRUNCATION_MARKER.length,
)}${FIRST_USER_CONTEXT_TRUNCATION_MARKER}`;
}
function collectRecentThreadTitleContext(
messages: ReadonlyArray<ThreadTitleMessage>,
maxChars: number,
function formatThreadTitleContext(
messages: ReadonlyArray<{
readonly role: "user" | "assistant" | "system";
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
}>,
): {
readonly context: string;
readonly message: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
readonly truncated: boolean;
} {
let context = "";
let truncated = false;
const retainedAttachments: Array<ChatAttachment> = [];
for (const message of messages.toReversed()) {
const section = formatThreadTitleSection(message);
if (section === undefined) {
if (message.role === "system") {
continue;
}
const text = message.text.trim();
const attachmentSummary = (message.attachments ?? [])
.map((attachment) => attachment.name)
.join(", ");
const contents = [
...(text.length > 0 ? [text] : []),
...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),
].join("\n");
if (contents.length === 0) {
continue;
}
const section = `${message.role.toUpperCase()}:\n${contents}`;
const separator = context.length > 0 ? "\n\n" : "";
const available = maxChars - context.length - separator.length;
const available = MAX_THREAD_TITLE_CONTEXT_CHARS - context.length - separator.length;
if (section.length > available) {
if (available > 0) {
context = `${section.slice(-available)}${separator}${context}`;
@@ -161,54 +141,9 @@ function collectRecentThreadTitleContext(
retainedAttachments.unshift(...(message.attachments ?? []));
}
return { context, attachments: retainedAttachments, truncated };
}
function formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>): {
readonly message: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
} {
const recent = collectRecentThreadTitleContext(messages, MAX_THREAD_TITLE_CONTEXT_CHARS);
if (!recent.truncated) {
return {
message: recent.context,
attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
};
}
const firstUserMessage = messages.find(
(message) => message.role === "user" && formatThreadTitleSection(message),
);
const firstUserSection = firstUserMessage
? formatThreadTitleSection(firstUserMessage)
: undefined;
if (!firstUserMessage || !firstUserSection) {
return {
message: `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${recent.context}`,
attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
};
}
const pinnedSection = limitFirstUserSection(firstUserSection);
const recentContextBudget =
MAX_THREAD_TITLE_CONTEXT_CHARS -
pinnedSection.length -
"\n\n".length -
THREAD_TITLE_CONTEXT_TRUNCATION_MARKER.length;
const retainedRecent = collectRecentThreadTitleContext(messages, recentContextBudget);
const pinnedAttachment = firstUserMessage.attachments?.[0];
const recentAttachments = retainedRecent.attachments.filter(
(attachment) => attachment.id !== pinnedAttachment?.id,
);
return {
message: `${pinnedSection}\n\n${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${retainedRecent.context}`,
attachments: [
...(pinnedAttachment ? [pinnedAttachment] : []),
...recentAttachments.slice(
-(MAX_REGENERATION_ATTACHMENTS - (pinnedAttachment === undefined ? 0 : 1)),
),
],
message: truncated ? `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${context}` : context,
attachments: retainedAttachments.slice(-MAX_REGENERATION_ATTACHMENTS),
};
}
-4
View File
@@ -13,8 +13,6 @@ import {
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -44,8 +42,6 @@ export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -1,226 +0,0 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const NOW = "2026-01-01T00:00:00.000Z";
const PINNED_AT = "1969-12-30T00:00:00.000Z";
function makeReadModel(input: {
readonly pinnedAt?: string | null;
readonly archivedAt?: string | null;
readonly settledOverride?: "settled" | "active" | null;
readonly settledAt?: string | null;
readonly snoozedUntil?: string | null;
readonly snoozedAt?: string | null;
}): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: input.archivedAt ?? null,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? (input.settledOverride === "settled" ? NOW : null),
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? PINNED_AT : null),
pinnedAt: input.pinnedAt ?? null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: NOW,
};
}
it.layer(NodeServices.layer)("pinned thread decider", (it) => {
it.effect("pins a thread, stamping pinnedAt and updatedAt together", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinnedAt).toBe(events[0].payload.updatedAt);
}
}),
);
it.effect("re-pinning preserves the original pinnedAt and updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-again"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinnedAt).toBe(PINNED_AT);
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("unpins a pinned thread", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.unpin",
commandId: CommandId.make("cmd-unpin"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.unpinned");
if (events[0]?.type === "thread.unpinned") {
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
}),
);
it.effect("unpinning an unpinned thread preserves updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.unpin",
commandId: CommandId.make("cmd-unpin-noop"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.unpinned");
if (events[0]?.type === "thread.unpinned") {
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("pinning a settled thread also un-settles it", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-settled"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ settledOverride: "settled" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsettled"]);
const unsettled = events.find((entry) => entry.type === "thread.unsettled");
if (unsettled?.type === "thread.unsettled") {
expect(unsettled.payload.reason).toBe("user");
}
}),
);
it.effect("pinning a snoozed thread also wakes it", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-snoozed"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ snoozedUntil: "1970-01-02T09:00:00.000Z" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsnoozed"]);
}),
);
it.effect("pinning an unparked thread emits only thread.pinned", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-plain"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned"]);
}),
);
it.effect("settling a pinned thread also unpins it", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-pinned"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.settled", "thread.unpinned"]);
}),
);
it.effect("settling an unpinned thread emits no unpin event", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-unpinned"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.settled"]);
}),
);
it.effect("rejects pinning an archived thread", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-archived"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ archivedAt: NOW }),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
+2 -117
View File
@@ -487,14 +487,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
// settledAt: the engine rejects zero-event commands, and bulk-settle /
// double-click must stay silent no-ops rather than surface errors.
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
const settledEvent = {
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.settled" as const,
type: "thread.settled",
payload: {
threadId: command.threadId,
settledAt: alreadySettled ? thread.settledAt : occurredAt,
@@ -504,29 +504,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
},
};
// Settling is "I'm done with this": it clears a pin the same way it
// parks the thread. Without this, settling a pinned thread would only
// stamp invisible state — the pin would hold the card in place until
// a separate unpin.
if (thread.pinnedAt == null) {
return settledEvent;
}
return [
settledEvent,
{
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unpinned" as const,
payload: {
threadId: command.threadId,
updatedAt: occurredAt,
},
},
];
}
case "thread.unsettle": {
@@ -653,98 +630,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.pin": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
// Re-pinning an already-pinned thread is a duplicate (double-click,
// raced clients): re-emit with the original timestamps so the
// projection is a no-op. Pinning has no lifecycle invariants — a pin
// only ever promotes visibility, so it can never hide pending work.
const existingPinnedAt = thread.pinnedAt ?? null;
const pinnedEvent = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.pinned" as const,
payload: {
threadId: command.threadId,
pinnedAt: existingPinnedAt ?? occurredAt,
updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
},
};
// Pinning is a promotion: it clears the parked states rather than
// silently outranking them. An explicit settle un-settles (reason
// "user", same override the un-settle button stamps), and a snooze's
// return ticket is spent — the thread is on top NOW, not on Tuesday.
const promotionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
if (thread.settledOverride === "settled") {
promotionEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "user",
updatedAt: occurredAt,
},
});
}
if (thread.snoozedUntil != null) {
promotionEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unsnoozed",
payload: {
threadId: command.threadId,
reason: "user",
updatedAt: occurredAt,
},
});
}
return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;
}
case "thread.unpin": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Idempotent by re-emission (see thread.settle): unpinning a thread
// that is not pinned lands on the same null state without churning
// updatedAt.
const alreadyUnpinned = thread.pinnedAt == null;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unpinned",
payload: {
threadId: command.threadId,
updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,
},
};
}
case "thread.meta.update": {
const thread = yield* requireThread({
readModel,
@@ -1,77 +0,0 @@
import {
CommandId,
EventId,
ProjectId,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
function makeEvent(input: {
readonly sequence: number;
readonly type: OrchestrationEvent["type"];
readonly payload: unknown;
}): OrchestrationEvent {
return {
sequence: input.sequence,
eventId: EventId.make(`event-${input.sequence}`),
type: input.type,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:00.000Z",
commandId: CommandId.make(`command-${input.sequence}`),
causationEventId: null,
correlationId: null,
metadata: {},
payload: input.payload as never,
} as OrchestrationEvent;
}
it.effect("projects pin lifecycle events", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const created = yield* projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "thread.created",
payload: {
threadId: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
expect(created.threads[0]?.pinnedAt ?? null).toBeNull();
const pinned = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.pinned",
payload: { threadId: ThreadId.make("thread-1"), pinnedAt: now, updatedAt: now },
}),
);
expect(pinned.threads[0]?.pinnedAt).toBe(now);
const unpinned = yield* projectEvent(
pinned,
makeEvent({
sequence: 3,
type: "thread.unpinned",
payload: { threadId: ThreadId.make("thread-1"), updatedAt: now },
}),
);
expect(unpinned.threads[0]?.pinnedAt).toBeNull();
}),
);
@@ -23,9 +23,7 @@ import {
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
ThreadPinnedPayload,
ThreadSnoozedPayload,
ThreadUnpinnedPayload,
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadUnsnoozedPayload,
@@ -396,28 +394,6 @@ export function projectEvent(
})),
);
case "thread.pinned":
return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: payload.pinnedAt,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.unpinned":
return decodeForEvent(ThreadUnpinnedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.meta-updated":
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -95,7 +95,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -158,7 +157,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
settledAt: "2026-03-25T00:00:00.000Z",
snoozedUntil: "2026-03-26T09:00:00.000Z",
snoozedAt: "2026-03-25T00:00:00.000Z",
pinnedAt: "2026-03-25T00:00:00.000Z",
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -177,7 +175,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
assert.strictEqual(row.pinnedAt, "2026-03-25T00:00:00.000Z");
// Un-settle to the keep-active pin and wake the snooze; confirm the
// flips persist.
@@ -187,7 +184,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
});
const repersisted = yield* threads.getById({
threadId: ThreadId.make("thread-settled"),
@@ -197,7 +193,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(updated?.settledAt, null);
assert.strictEqual(updated?.snoozedUntil, null);
assert.strictEqual(updated?.snoozedAt, null);
assert.strictEqual(updated?.pinnedAt, null);
}),
);
});
@@ -47,7 +47,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at,
snoozed_until,
snoozed_at,
pinned_at,
title_regeneration_request_id,
title_regeneration_started_at,
latest_user_message_at,
@@ -73,7 +72,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.settledAt},
${row.snoozedUntil},
${row.snoozedAt},
${row.pinnedAt},
${row.titleRegenerationRequestId ?? null},
${row.titleRegenerationStartedAt ?? null},
${row.latestUserMessageAt},
@@ -99,7 +97,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at = excluded.settled_at,
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
pinned_at = excluded.pinned_at,
title_regeneration_request_id = excluded.title_regeneration_request_id,
title_regeneration_started_at = excluded.title_regeneration_started_at,
latest_user_message_at = excluded.latest_user_message_at,
@@ -132,7 +129,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -167,7 +163,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
+17 -11
View File
@@ -7,6 +7,7 @@ import type { SqlError } from "effect/unstable/sql/SqlError";
import { runMigrations } from "../Migrations.ts";
import { ServerConfig } from "../../config.ts";
import * as ServiceLauncherClient from "../../cloud/serviceLauncherClient.ts";
type RuntimeSqliteLayerConfig = {
readonly filename: string;
@@ -30,24 +31,28 @@ const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
return clientModule.layer(config);
}, Layer.unwrap);
const setup = Layer.effectDiscard(
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA foreign_keys = ON;`;
yield* sql`PRAGMA journal_mode = WAL;`;
yield* runMigrations();
}),
);
const setup = (trial: boolean) =>
Layer.effectDiscard(
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA foreign_keys = ON;`;
if (!trial) {
yield* sql`PRAGMA journal_mode = WAL;`;
yield* runMigrations();
}
}),
);
export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
dbPath: string,
options?: { readonly trial?: boolean },
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
return Layer.provideMerge(
setup,
setup(options?.trial === true),
makeRuntimeSqliteLayer({
filename: dbPath,
spanAttributes: {
@@ -59,13 +64,14 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(
}, Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
setup,
setup(false),
makeRuntimeSqliteLayer({ filename: ":memory:" }),
);
export const layerConfig = Layer.unwrap(
Effect.gen(function* () {
const { dbPath } = yield* ServerConfig;
return makeSqlitePersistenceLive(dbPath);
const launcher = yield* ServiceLauncherClient.resolveServiceLauncherMode();
return makeSqlitePersistenceLive(dbPath, { trial: launcher.trial });
}),
);
@@ -48,7 +48,6 @@ import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";
import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
/**
* Migration loader with all migrations defined inline.
@@ -96,7 +95,6 @@ export const migrationEntries = [
[33, "ProjectionThreadsSettled", Migration0033],
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionThreadTitleRegeneration", Migration0035],
[36, "ProjectionThreadsPinned", Migration0036],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -1,16 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "pinned_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN pinned_at TEXT
`;
}
});
@@ -41,7 +41,6 @@ export const ProjectionThread = Schema.Struct({
settledAt: Schema.NullOr(IsoDateTime),
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
pinnedAt: Schema.NullOr(IsoDateTime),
titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),
titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
@@ -11,7 +11,6 @@ import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
@@ -61,89 +60,6 @@ exec ${JSON.stringify(mockAgentCommand)} ${mockAgentArgs.map((arg) => JSON.strin
return wrapperPath;
}
async function makeTerminalCallbackWrapper(
kind: "permission" | "question",
promptOutcome: "success" | "failure" | "hang" = "success",
) {
const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-terminal-"));
const wrapperPath = NodePath.join(dir, "fake-agent.mjs");
const callback =
kind === "permission"
? {
jsonrpc: "2.0",
id: 9001,
method: "session/request_permission",
params: {
sessionId: "terminal-callback-session",
toolCall: {
toolCallId: "terminal-tool-call",
title: "Terminal",
kind: "execute",
status: "pending",
content: [
{
type: "content",
content: { type: "text", text: "run terminal command" },
},
],
},
options: [
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
],
},
}
: {
jsonrpc: "2.0",
id: 9002,
method: "cursor/ask_question",
params: {
toolCallId: "terminal-question",
title: "Question",
questions: [
{
id: "scope",
prompt: "Which scope?",
options: [{ id: "workspace", label: "Workspace" }],
},
],
},
};
const script = `#!/usr/bin/env node
import readline from "node:readline";
const callback = ${JSON.stringify(callback)};
const kind = ${JSON.stringify(kind)};
const promptOutcome = ${JSON.stringify(promptOutcome)};
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
readline.createInterface({ input: process.stdin }).on("line", (line) => {
const message = JSON.parse(line);
if (!("method" in message)) return;
if (message.method === "initialize") {
send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: 1, agentCapabilities: {} } });
} else if (message.method === "session/new") {
send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "terminal-callback-session" } });
} else if (message.method === "session/prompt") {
const response =
promptOutcome === "failure"
? { jsonrpc: "2.0", id: message.id, error: { code: -32603, message: "prompt failed" } }
: { jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } };
const messages =
promptOutcome === "hang"
? [callback]
: kind === "question" && promptOutcome === "success"
? [response, callback]
: [callback, response];
process.stdout.write(messages.map(JSON.stringify).join("\\n") + "\\n");
} else if (message.id !== undefined) {
send({ jsonrpc: "2.0", id: message.id, result: {} });
}
});
`;
await NodeFSP.writeFile(wrapperPath, script, "utf8");
await NodeFSP.chmod(wrapperPath, 0o755);
return wrapperPath;
}
async function makeProbeWrapper(
requestLogPath: string,
argvLogPath: string,
@@ -214,24 +130,6 @@ function waitForJsonLogMatch(
});
}
function waitForJsonLogCount(
filePath: string,
predicate: (entry: Record<string, unknown>) => boolean,
expectedCount: number,
attempts = 40,
) {
return Effect.gen(function* () {
for (let attempt = 0; attempt < attempts; attempt += 1) {
const entries = yield* Effect.promise(() => readJsonLines(filePath));
if (entries.filter(predicate).length >= expectedCount) {
return entries;
}
yield* Effect.yieldNow;
}
return yield* Effect.promise(() => readJsonLines(filePath));
});
}
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
// captures `cursorSettings` once at construction, so without a resolver
@@ -1149,360 +1047,6 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.stopSession(threadId);
}),
);
it.effect("starts a fresh turn immediately after interrupting a hanging prompt", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-interrupt-follow-up-thread");
const tempDir = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-")),
);
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
const argvLogPath = NodePath.join(tempDir, "argv.txt");
yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath, {
T3_ACP_HANG_FIRST_PROMPTS: "2",
}),
);
yield* serverSettings.updateSettings({
providers: { cursor: { binaryPath: wrapperPath } },
});
const events: Array<ProviderRuntimeEvent> = [];
const firstTurnStarted = yield* Deferred.make<string>();
const secondTurnStarted = yield* Deferred.make<string>();
const startedCountRef = yield* Ref.make(0);
const twoTurnsCompleted = yield* Deferred.make<void>();
const completedCountRef = yield* Ref.make(0);
const eventFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
if (String(event.threadId) !== String(threadId)) return;
events.push(event);
if (event.type === "turn.started") {
const startedCount = yield* Ref.updateAndGet(startedCountRef, (count) => count + 1);
if (startedCount === 1) {
yield* Deferred.succeed(firstTurnStarted, String(event.turnId)).pipe(Effect.ignore);
}
if (startedCount === 2) {
yield* Deferred.succeed(secondTurnStarted, String(event.turnId)).pipe(Effect.ignore);
}
}
if (event.type === "turn.completed") {
const completedCount = yield* Ref.updateAndGet(completedCountRef, (count) => count + 1);
if (completedCount === 2) {
yield* Deferred.succeed(twoTurnsCompleted, undefined).pipe(Effect.ignore);
}
}
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: {
instanceId: ProviderInstanceId.make("cursor"),
model: "default",
},
});
const firstSendFiber = yield* adapter
.sendTurn({ threadId, input: "hang", attachments: [] })
.pipe(Effect.forkChild);
const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
yield* waitForJsonLogMatch(
requestLogPath,
(request) => request.method === "session/prompt",
80,
).pipe(Effect.timeout("2 seconds"));
yield* adapter.interruptTurn(threadId).pipe(Effect.timeout("2 seconds"));
const followUpFiber = yield* adapter
.sendTurn({ threadId, input: "follow up", attachments: [] })
.pipe(Effect.forkChild);
yield* waitForJsonLogCount(
requestLogPath,
(request) => request.method === "session/prompt",
2,
80,
).pipe(Effect.timeout("2 seconds"));
const secondTurnId = yield* Deferred.await(secondTurnStarted).pipe(
Effect.timeout("2 seconds"),
);
yield* Fiber.join(firstSendFiber).pipe(Effect.timeout("2 seconds"));
const steeredFollowUpFiber = yield* adapter
.sendTurn({ threadId, input: "steer follow up", attachments: [] })
.pipe(Effect.forkChild);
for (let attempt = 0; attempt < 10; attempt += 1) {
yield* Effect.yieldNow;
}
yield* adapter.interruptTurn(threadId).pipe(Effect.timeout("2 seconds"));
const steeredFollowUp = yield* Fiber.join(steeredFollowUpFiber).pipe(
Effect.timeout("2 seconds"),
);
const followUp = yield* Fiber.join(followUpFiber).pipe(Effect.timeout("2 seconds"));
assert.notEqual(secondTurnId, firstTurnId);
assert.equal(String(steeredFollowUp.turnId), secondTurnId);
yield* Deferred.await(twoTurnsCompleted).pipe(Effect.timeout("2 seconds"));
yield* Fiber.interrupt(eventFiber);
assert.equal(String(followUp.turnId), secondTurnId);
const completed = events.filter(
(event) => String(event.threadId) === String(threadId) && event.type === "turn.completed",
);
assert.lengthOf(completed, 2);
assert.equal(String(completed[0]?.turnId), firstTurnId);
if (completed[0]?.type === "turn.completed") {
assert.equal(completed[0].payload.state, "cancelled");
assert.equal(completed[0].payload.stopReason, "cancelled");
}
assert.equal(String(completed[1]?.turnId), secondTurnId);
if (completed[1]?.type === "turn.completed") {
assert.equal(completed[1].payload.state, "cancelled");
assert.equal(completed[1].payload.stopReason, "cancelled");
}
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
assert.lengthOf(
requests.filter((request) => request.method === "session/prompt"),
3,
);
yield* adapter.stopSession(threadId);
}).pipe(TestClock.withLive),
);
it.effect("resolves a pending permission before completing a normally returned turn", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-terminal-permission");
const events: Array<ProviderRuntimeEvent> = [];
const completed = yield* Deferred.make<void>();
const wrapperPath = yield* Effect.promise(() => makeTerminalCallbackWrapper("permission"));
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (String(event.threadId) !== String(threadId)) return Effect.void;
events.push(event);
return event.type === "turn.completed"
? Deferred.succeed(completed, undefined).pipe(Effect.ignore)
: Effect.void;
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "approval-required",
});
yield* adapter.sendTurn({
threadId,
input: "finish without permission response",
attachments: [],
});
yield* Deferred.await(completed);
yield* Fiber.interrupt(eventsFiber);
const relevant = events.filter(
(event) =>
event.type === "request.opened" ||
event.type === "request.resolved" ||
event.type === "turn.completed",
);
assert.deepStrictEqual(
relevant.map((event) => event.type),
["request.opened", "request.resolved", "turn.completed"],
);
const resolved = relevant[1];
assert.equal(resolved?.type, "request.resolved");
if (resolved?.type === "request.resolved") assert.equal(resolved.payload.decision, "cancel");
yield* adapter.stopSession(threadId);
}),
);
it.effect("settles a pending callback when the terminal prompt fails", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-terminal-failure");
const events: Array<ProviderRuntimeEvent> = [];
const requested = yield* Deferred.make<ApprovalRequestId>();
const resolved = yield* Deferred.make<void>();
const wrapperPath = yield* Effect.promise(() =>
makeTerminalCallbackWrapper("permission", "failure"),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (String(event.threadId) !== String(threadId)) return Effect.void;
events.push(event);
if (event.type === "request.opened") {
return Deferred.succeed(requested, ApprovalRequestId.make(String(event.requestId))).pipe(
Effect.ignore,
);
}
if (event.type === "request.resolved") {
return Deferred.succeed(resolved, undefined).pipe(Effect.ignore);
}
return Effect.void;
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "approval-required",
});
const sendTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "fail with a pending permission",
attachments: [],
})
.pipe(Effect.forkChild);
const requestId = yield* Deferred.await(requested);
const sendTurnExit = yield* Fiber.await(sendTurnFiber);
yield* Deferred.await(resolved);
const lateResponseExit = yield* adapter
.respondToRequest(threadId, requestId, "accept")
.pipe(Effect.exit);
assert.equal(sendTurnExit._tag, "Failure");
assert.equal(lateResponseExit._tag, "Failure");
assert.deepStrictEqual(
events
.filter(
(event) =>
event.type === "request.opened" ||
event.type === "request.resolved" ||
event.type === "turn.completed",
)
.map((event) => event.type),
["request.opened", "request.resolved"],
);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("settles a pending callback when sendTurn is interrupted", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-terminal-fiber-interruption");
const events: Array<ProviderRuntimeEvent> = [];
const requested = yield* Deferred.make<ApprovalRequestId>();
const resolved = yield* Deferred.make<void>();
const wrapperPath = yield* Effect.promise(() =>
makeTerminalCallbackWrapper("permission", "hang"),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (String(event.threadId) !== String(threadId)) return Effect.void;
events.push(event);
if (event.type === "request.opened") {
return Deferred.succeed(requested, ApprovalRequestId.make(String(event.requestId))).pipe(
Effect.ignore,
);
}
if (event.type === "request.resolved") {
return Deferred.succeed(resolved, undefined).pipe(Effect.ignore);
}
return Effect.void;
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "approval-required",
});
const sendTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "interrupt with a pending permission",
attachments: [],
})
.pipe(Effect.forkChild);
const requestId = yield* Deferred.await(requested);
yield* Fiber.interrupt(sendTurnFiber);
yield* Deferred.await(resolved);
const lateResponseExit = yield* adapter
.respondToRequest(threadId, requestId, "accept")
.pipe(Effect.exit);
assert.equal(lateResponseExit._tag, "Failure");
assert.deepStrictEqual(
events
.filter(
(event) =>
event.type === "request.opened" ||
event.type === "request.resolved" ||
event.type === "turn.completed",
)
.map((event) => event.type),
["request.opened", "request.resolved"],
);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("resolves a pending question before completing a normally returned turn", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-terminal-question");
const events: Array<ProviderRuntimeEvent> = [];
const completed = yield* Deferred.make<void>();
const wrapperPath = yield* Effect.promise(() => makeTerminalCallbackWrapper("question"));
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (String(event.threadId) !== String(threadId)) return Effect.void;
events.push(event);
return event.type === "turn.completed"
? Deferred.succeed(completed, undefined).pipe(Effect.ignore)
: Effect.void;
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId,
input: "finish without question response",
attachments: [],
});
yield* Deferred.await(completed);
yield* Fiber.interrupt(eventsFiber);
const relevant = events.filter(
(event) =>
event.type === "user-input.requested" ||
event.type === "user-input.resolved" ||
event.type === "turn.completed",
);
assert.deepStrictEqual(
relevant.map((event) => event.type),
["user-input.requested", "user-input.resolved", "turn.completed"],
);
const resolved = relevant[1];
assert.equal(resolved?.type, "user-input.resolved");
if (resolved?.type === "user-input.resolved")
assert.deepStrictEqual(resolved.payload.answers, {});
yield* adapter.stopSession(threadId);
}),
);
it.effect("stopping a session settles pending approval waits", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
+152 -324
View File
@@ -115,19 +115,11 @@ export interface CursorAdapterLiveOptions {
interface PendingApproval {
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
readonly resolutionOffered: Deferred.Deferred<void>;
readonly kind: string | "unknown";
}
interface PendingUserInput {
readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
readonly resolutionOffered: Deferred.Deferred<void>;
}
interface CallbackLifecycle {
readonly semaphore: Semaphore.Semaphore;
generation: number;
admissionOpen: boolean;
}
interface CursorSessionContext {
@@ -145,32 +137,33 @@ interface CursorSessionContext {
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
promptsInFlight: number;
readonly callbackLifecycle: CallbackLifecycle;
stopped: boolean;
}
function settlePendingCallbacks(
approvals: ReadonlyArray<PendingApproval>,
userInputs: ReadonlyArray<PendingUserInput>,
function settlePendingApprovalsAsCancelled(
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
): Effect.Effect<void> {
return Effect.gen(function* () {
yield* Effect.forEach(
approvals,
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
{ discard: true },
);
yield* Effect.forEach(
userInputs,
(pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
{ discard: true },
);
yield* Effect.forEach(approvals, (pending) => Deferred.await(pending.resolutionOffered), {
const pendingEntries = Array.from(pendingApprovals.values());
return Effect.forEach(
pendingEntries,
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
{
discard: true,
});
yield* Effect.forEach(userInputs, (pending) => Deferred.await(pending.resolutionOffered), {
},
);
}
function settlePendingUserInputsAsEmptyAnswers(
pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
): Effect.Effect<void> {
const pendingEntries = Array.from(pendingUserInputs.values());
return Effect.forEach(
pendingEntries,
(pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
{
discard: true,
});
});
},
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -465,21 +458,10 @@ export function makeCursorAdapter(
const stopSessionInternal = (ctx: CursorSessionContext) =>
Effect.gen(function* () {
const shouldStop = yield* Effect.uninterruptible(
ctx.callbackLifecycle.semaphore.withPermit(
Effect.gen(function* () {
if (ctx.stopped) return false;
ctx.stopped = true;
ctx.callbackLifecycle.admissionOpen = false;
yield* settlePendingCallbacks(
Array.from(ctx.pendingApprovals.values()),
Array.from(ctx.pendingUserInputs.values()),
);
return true;
}),
),
);
if (!shouldStop) return;
if (ctx.stopped) return;
ctx.stopped = true;
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
if (ctx.notificationFiber) {
yield* Fiber.interrupt(ctx.notificationFiber);
}
@@ -523,11 +505,6 @@ export function makeCursorAdapter(
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const callbackLifecycle: CallbackLifecycle = {
semaphore: yield* Semaphore.make(1),
generation: 0,
admissionOpen: false,
};
const sessionScope = yield* Scope.make("sequential");
let sessionScopeTransferred = false;
yield* Effect.addFinalizer(() =>
@@ -594,77 +571,47 @@ export function makeCursorAdapter(
),
);
const started = yield* Effect.gen(function* () {
yield* acp.handleExtRequest(
"cursor/ask_question",
CursorAskQuestionRequest,
(params) => {
const callbackGeneration = callbackLifecycle.generation;
return mapExtensionFailure(
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
const resolutionOffered = yield* Deferred.make<void>();
const pending: PendingUserInput = { answers, resolutionOffered };
return yield* Effect.gen(function* () {
const admitted = yield* callbackLifecycle.semaphore.withPermit(
Effect.gen(function* () {
if (
!callbackLifecycle.admissionOpen ||
callbackLifecycle.generation !== callbackGeneration ||
ctx?.stopped
) {
return false;
}
pendingUserInputs.set(requestId, pending);
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
return true;
}),
);
if (!admitted) {
return { answers: {} };
}
const resolved = yield* Deferred.await(answers);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}).pipe(
Effect.ensuring(
Effect.sync(() => pendingUserInputs.delete(requestId)).pipe(
Effect.andThen(Deferred.succeed(resolutionOffered, undefined)),
Effect.ignore,
),
),
);
}),
);
},
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
mapExtensionFailure(
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
pendingUserInputs.set(requestId, { answers });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
const resolved = yield* Deferred.await(answers);
pendingUserInputs.delete(requestId);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}),
),
);
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
mapExtensionFailure(
@@ -716,9 +663,8 @@ export function makeCursorAdapter(
}),
),
);
yield* acp.handleRequestPermission((params) => {
const callbackGeneration = callbackLifecycle.generation;
return mapExtensionFailure(
yield* acp.handleRequestPermission((params) =>
mapExtensionFailure(
Effect.gen(function* () {
yield* logNative(
input.threadId,
@@ -729,17 +675,6 @@ export function makeCursorAdapter(
if (input.runtimeMode === "full-access") {
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
if (autoApprovedOptionId !== undefined) {
const admitted = yield* callbackLifecycle.semaphore.withPermit(
Effect.sync(
() =>
callbackLifecycle.admissionOpen &&
callbackLifecycle.generation === callbackGeneration &&
!ctx?.stopped,
),
);
if (!admitted) {
return { outcome: { outcome: "cancelled" as const } };
}
return {
outcome: {
outcome: "selected" as const,
@@ -752,79 +687,53 @@ export function makeCursorAdapter(
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
const resolutionOffered = yield* Deferred.make<void>();
const pending: PendingApproval = {
pendingApprovals.set(requestId, {
decision,
resolutionOffered,
kind: permissionRequest.kind,
};
return yield* Effect.gen(function* () {
const admitted = yield* callbackLifecycle.semaphore.withPermit(
Effect.gen(function* () {
if (
!callbackLifecycle.admissionOpen ||
callbackLifecycle.generation !== callbackGeneration ||
ctx?.stopped
) {
return false;
}
pendingApprovals.set(requestId, pending);
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail:
permissionRequest.detail ??
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
"[unserializable params]",
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
return true;
}),
);
if (!admitted) {
return { outcome: { outcome: "cancelled" as const } };
}
const resolved = yield* Deferred.await(decision);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}).pipe(
Effect.ensuring(
Effect.sync(() => pendingApprovals.delete(requestId)).pipe(
Effect.andThen(Deferred.succeed(resolutionOffered, undefined)),
Effect.ignore,
),
),
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail:
permissionRequest.detail ??
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
"[unserializable params]",
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
);
});
),
);
return yield* acp.start();
}).pipe(
Effect.mapError((error) =>
@@ -870,7 +779,6 @@ export function makeCursorAdapter(
lastPlanFingerprint: undefined,
activeTurnId: undefined,
promptsInFlight: 0,
callbackLifecycle,
stopped: false,
};
@@ -1002,60 +910,15 @@ export function makeCursorAdapter(
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
const candidateTurnId = TurnId.make(yield* randomUUIDv4);
const admission = yield* ctx.callbackLifecycle.semaphore.withPermit(
Effect.gen(function* () {
if (ctx.stopped) {
return yield* new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
threadId: input.threadId,
});
}
// A prompt sent while another is in flight steers the active turn.
const startsTurn = ctx.promptsInFlight === 0;
if (startsTurn) {
ctx.callbackLifecycle.generation += 1;
ctx.callbackLifecycle.admissionOpen = true;
ctx.activeTurnId = candidateTurnId;
ctx.lastPlanFingerprint = undefined;
}
// Count it immediately so an older prompt cannot settle the shared turn.
ctx.promptsInFlight += 1;
return {
generation: ctx.callbackLifecycle.generation,
startsTurn,
turnId: ctx.activeTurnId ?? candidateTurnId,
};
}),
);
const { generation, startsTurn, turnId } = admission;
let promptFinalized = false;
const finalizePrompt = (
onLastPrompt?: () => Effect.Effect<void, ProviderAdapterRequestError>,
): Effect.Effect<boolean, ProviderAdapterRequestError> =>
Effect.uninterruptible(
ctx.callbackLifecycle.semaphore.withPermit(
Effect.gen(function* () {
if (promptFinalized) return false;
promptFinalized = true;
if (ctx.callbackLifecycle.generation !== generation) return false;
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
// Only the final prompt for this generation may settle and complete the turn.
if (ctx.promptsInFlight !== 0) return false;
ctx.callbackLifecycle.admissionOpen = false;
yield* settlePendingCallbacks(
Array.from(ctx.pendingApprovals.values()),
Array.from(ctx.pendingUserInputs.values()),
);
if (!ctx.stopped && onLastPrompt) {
yield* onLastPrompt();
}
return true;
}),
),
);
// A sendTurn while a prompt is in flight is a steer: the agent folds
// the new prompt into the ongoing work, so the active turn id is
// reused instead of opening a new turn.
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
// Count this prompt immediately so a superseded in-flight prompt
// resolving from here on does not settle the turn; the matching
// decrement is the `ensuring` below.
ctx.promptsInFlight += 1;
return yield* Effect.gen(function* () {
const turnModelSelection =
@@ -1076,13 +939,17 @@ export function makeCursorAdapter(
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
ctx.activeTurnId = turnId;
if (steeringTurnId === undefined) {
ctx.lastPlanFingerprint = undefined;
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
};
if (startsTurn) {
if (steeringTurnId === undefined) {
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
@@ -1160,53 +1027,42 @@ export function makeCursorAdapter(
model: resolvedModel,
};
yield* finalizePrompt(() =>
makeEventStamp().pipe(
Effect.flatMap((stamp) =>
offerRuntimeEvent({
type: "turn.completed",
...stamp,
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
}),
),
),
);
// Only the last remaining prompt settles the turn — a steer-
// superseded prompt resolving (usually cancelled) while another is
// in flight or pending must leave the merged turn running.
if (ctx.promptsInFlight === 1) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
}
return {
threadId: input.threadId,
turnId,
resumeCursor: ctx.session.resumeCursor,
};
}).pipe(Effect.ensuring(finalizePrompt().pipe(Effect.ignore)));
}).pipe(
Effect.ensuring(
Effect.sync(() => {
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
}),
),
);
});
const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
const interruptedTurnId = yield* Effect.uninterruptible(
ctx.callbackLifecycle.semaphore.withPermit(
Effect.gen(function* () {
const turnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
ctx.callbackLifecycle.admissionOpen = false;
yield* settlePendingCallbacks(
Array.from(ctx.pendingApprovals.values()),
Array.from(ctx.pendingUserInputs.values()),
);
if (turnId) {
ctx.promptsInFlight = 0;
ctx.callbackLifecycle.generation += 1;
ctx.lastPlanFingerprint = undefined;
}
return turnId;
}),
),
);
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
@@ -1214,20 +1070,6 @@ export function makeCursorAdapter(
),
),
);
if (interruptedTurnId && !ctx.stopped) {
yield* makeEventStamp().pipe(
Effect.flatMap((stamp) =>
offerRuntimeEvent({
type: "turn.completed",
...stamp,
provider: PROVIDER,
threadId,
turnId: interruptedTurnId,
payload: { state: "cancelled", stopReason: "cancelled" },
}),
),
);
}
});
const respondToRequest: CursorAdapterShape["respondToRequest"] = (
@@ -1245,14 +1087,7 @@ export function makeCursorAdapter(
detail: `Unknown pending approval request: ${requestId}`,
});
}
const accepted = yield* Deferred.succeed(pending.decision, decision);
if (!accepted) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/request_permission",
detail: `Approval request is no longer pending: ${requestId}`,
});
}
yield* Deferred.succeed(pending.decision, decision);
});
const respondToUserInput: CursorAdapterShape["respondToUserInput"] = (
@@ -1270,14 +1105,7 @@ export function makeCursorAdapter(
detail: `Unknown pending user-input request: ${requestId}`,
});
}
const accepted = yield* Deferred.succeed(pending.answers, answers);
if (!accepted) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "cursor/ask_question",
detail: `User-input request is no longer pending: ${requestId}`,
});
}
yield* Deferred.succeed(pending.answers, answers);
});
const readThread: CursorAdapterShape["readThread"] = (threadId) =>
@@ -57,39 +57,6 @@ describe("ReviewService", () => {
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("attributes file-content workspace violations to the file-content operation", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
const outsideRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-outside-" });
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
const detectCalls: Array<{ readonly cwd: string }> = [];
const error = yield* Effect.gen(function* () {
const review = yield* ReviewService.ReviewService;
return yield* review
.getDiffFileContents({
cwd: outsideRoot,
sourceKind: "working-tree",
changeType: "change",
baseRef: "HEAD",
headRef: null,
oldPath: "file.ts",
newPath: "file.ts",
})
.pipe(Effect.flip);
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir, detectCalls })));
assert.strictEqual(error._tag, "VcsRepositoryDetectionError");
assert.strictEqual(error.operation, "ReviewService.getDiffFileContents");
assert.match(
"detail" in error ? error.detail : "",
/must stay within the configured workspace root/,
);
assert.deepStrictEqual(detectCalls, []);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("allows diff preview cwd inside the configured workspace root", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+3 -30
View File
@@ -8,8 +8,6 @@ import * as Path from "effect/Path";
import {
VcsRepositoryDetectionError,
VcsUnsupportedOperationError,
type ReviewDiffFileContentsInput,
type ReviewDiffFileContentsResult,
type ReviewDiffPreviewError,
type ReviewDiffPreviewInput,
type ReviewDiffPreviewResult,
@@ -25,9 +23,6 @@ export class ReviewService extends Context.Service<
readonly getDiffPreview: (
input: ReviewDiffPreviewInput,
) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
readonly getDiffFileContents: (
input: ReviewDiffFileContentsInput,
) => Effect.Effect<ReviewDiffFileContentsResult, ReviewDiffPreviewError>;
}
>()("t3/review/ReviewService") {}
@@ -63,7 +58,6 @@ export const make = Effect.gen(function* () {
};
const assertWorkspaceBoundCwd = Effect.fn("ReviewService.assertWorkspaceBoundCwd")(function* (
operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents",
cwd: string,
) {
const [candidate, workspaceRoot, worktreesRoot] = yield* Effect.all([
@@ -77,19 +71,16 @@ export const make = Effect.gen(function* () {
}
return yield* new VcsRepositoryDetectionError({
operation,
operation: "ReviewService.getDiffPreview",
cwd,
detail:
operation === "ReviewService.getDiffPreview"
? "Review diff preview cwd must stay within the configured workspace root."
: "Review diff file contents cwd must stay within the configured workspace root.",
detail: "Review diff preview cwd must stay within the configured workspace root.",
});
});
const getDiffPreview: ReviewService["Service"]["getDiffPreview"] = Effect.fn(
"ReviewService.getDiffPreview",
)(function* (input) {
yield* assertWorkspaceBoundCwd("ReviewService.getDiffPreview", input.cwd);
yield* assertWorkspaceBoundCwd(input.cwd);
const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
if (!handle) {
@@ -115,26 +106,8 @@ export const make = Effect.gen(function* () {
return yield* getDriverDiffPreview(input);
});
const getDiffFileContents: ReviewService["Service"]["getDiffFileContents"] = Effect.fn(
"ReviewService.getDiffFileContents",
)(function* (input) {
yield* assertWorkspaceBoundCwd("ReviewService.getDiffFileContents", input.cwd);
const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
if (handle?.kind !== "git") {
return yield* new VcsUnsupportedOperationError({
operation: "ReviewService.getDiffFileContents",
kind: handle?.kind ?? "unknown",
detail: "Unchanged diff expansion currently requires a Git repository.",
});
}
return yield* git.getReviewDiffFileContents(input);
});
return ReviewService.of({
getDiffPreview,
getDiffFileContents,
});
});
-21
View File
@@ -5249,11 +5249,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
],
}),
getDiffFileContents: () =>
Effect.succeed({
oldContents: "before\n",
newContents: "after\n",
}),
},
},
});
@@ -5368,22 +5363,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
assert.equal(diffPreview.sources[0]?.diff, "dirty-diff");
const diffFileContents = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.reviewGetDiffFileContents]({
cwd: "/tmp/repo",
sourceKind: "working-tree",
changeType: "change",
baseRef: "HEAD",
headRef: null,
oldPath: "README.md",
newPath: "README.md",
}),
),
);
assert.equal(diffFileContents.oldContents, "before\n");
assert.equal(diffFileContents.newContents, "after\n");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+8 -95
View File
@@ -9,7 +9,6 @@ import {
compareExactServiceVersions,
decodeServiceState,
isExactServiceVersion,
SERVICE_LAUNCHER_PROTOCOL,
} from "./cloud/serviceProtocol.ts";
it("accepts only exact semantic versions", () => {
@@ -34,13 +33,12 @@ it("orders exact semantic versions without treating build metadata as precedence
it("rejects contradictory service state", () => {
assert.isUndefined(
decodeServiceState({
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
activeVersion: "0.0.31",
update: {
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.32",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
}),
@@ -48,26 +46,12 @@ it("rejects contradictory service state", () => {
assert.isUndefined(
decodeServiceState({
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.0.0",
update: {
id: "update-3",
fromVersion: "1.0.0",
targetVersion: "1.1.0",
status: "pending",
},
}),
);
assert.isUndefined(
decodeServiceState({
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
activeVersion: "1.0.0",
update: {
id: "update-2",
fromVersion: "1.0.0",
targetVersion: "0.9.0",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
}),
@@ -82,7 +66,7 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-test-" });
const statePath = path.join(root, "runtime", "service-state.json");
const state = {
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
activeVersion: "0.0.31",
} as const;
@@ -104,7 +88,7 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
yield* fs.writeFileString(path.join(versionDir, ".install-complete"), "1.0.0\n");
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
activeVersion: "1.0.0",
}),
);
@@ -122,11 +106,6 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-flow-" });
const statePath = path.join(root, "runtime", "service-state.json");
const databasePath = path.join(root, "userdata", "state.sqlite");
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
yield* fs.writeFileString(databasePath, "before trial");
// @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
const encodedDatabasePath = JSON.stringify(databasePath);
const childSource = `
const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
if (context.update?.status === "pending") {
@@ -135,7 +114,7 @@ if (context.update?.status === "pending") {
if (message.type === "committed") process.exit(0);
});
} else if (context.update === undefined) {
process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
process.send({ type: "request-update", targetVersion: "1.1.0" });
setInterval(() => {}, 1_000);
} else {
process.exit(0);
@@ -150,7 +129,7 @@ if (context.update?.status === "pending") {
}
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
activeVersion: "1.0.0",
}),
);
@@ -175,17 +154,12 @@ if (context.update?.status === "pending") {
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
const statePath = path.join(root, "runtime", "service-state.json");
const databasePath = path.join(root, "userdata", "state.sqlite");
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
yield* fs.writeFileString(databasePath, "before trial");
// @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
const encodedDatabasePath = JSON.stringify(databasePath);
const childSource = `
const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
if (context.update?.status === "pending") {
process.send({ type: "prepared", updateId: "wrong-update" });
} else if (context.update === undefined) {
process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
process.send({ type: "request-update", targetVersion: "1.1.0" });
setInterval(() => {}, 1_000);
} else {
process.exit(0);
@@ -200,7 +174,7 @@ if (context.update?.status === "pending") {
}
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: SERVICE_LAUNCHER_PROTOCOL,
protocol: 1,
activeVersion: "1.0.0",
}),
);
@@ -222,65 +196,4 @@ if (context.update?.status === "pending") {
);
}),
);
it.effect("restores the database when a migrating trial exits", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
const statePath = path.join(root, "runtime", "service-state.json");
const databasePath = path.join(root, "userdata", "state.sqlite");
const original = "database before migration";
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
yield* fs.writeFileString(databasePath, original);
// @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
const encodedDatabasePath = JSON.stringify(databasePath);
const childSource = `
import { writeFileSync } from "node:fs";
const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
if (context.update?.status === "pending") {
writeFileSync(context.update.dbPath, "database after migration");
writeFileSync(context.update.dbPath + "-wal", "trial wal");
writeFileSync(context.update.dbPath + "-shm", "trial shm");
process.exit(1);
} else if (context.update === undefined) {
process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
setInterval(() => {}, 1_000);
} else {
process.exit(0);
}
`;
for (const version of ["1.0.0", "1.1.0"]) {
const versionDir = path.join(root, "runtime", "versions", version);
const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fs.writeFileString(entryPath, childSource);
yield* fs.writeFileString(path.join(versionDir, ".install-complete"), `${version}\n`);
}
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.0.0",
}),
);
const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
yield* Effect.promise(() =>
launcher.run().then(
() => Promise.reject(new Error("launcher unexpectedly completed")),
() => Promise.resolve(),
),
);
const state = yield* Effect.promise(() => readServiceState(statePath));
assert.equal(state.activeVersion, "1.0.0");
assert.equal(state.update?.status, "rolled-back");
assert.equal(yield* fs.readFileString(databasePath), original);
assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
const updateId = state.update?.id;
assert.isDefined(updateId);
assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
}),
);
});
+4 -141
View File
@@ -48,121 +48,6 @@ const runtimePaths = (baseDir: string, version: string) => {
};
};
/** SQLite persists across the main file plus its WAL and shared-memory sidecars. */
const DB_FILE_SUFFIXES = ["", "-wal", "-shm"] as const;
const RESTORE_MARKER = ".restore-pending";
const databaseBackupDir = (baseDir: string, updateId: string) =>
NodePath.join(baseDir, "runtime", "db-backup", updateId);
const databaseBackupFile = (backupDir: string, suffix: (typeof DB_FILE_SUFFIXES)[number]) =>
NodePath.join(backupDir, suffix === "" ? "database" : `database${suffix}`);
async function pathExists(target: string): Promise<boolean> {
try {
await NodeFSP.access(target);
return true;
} catch (cause) {
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return false;
throw cause;
}
}
async function syncFile(filePath: string): Promise<void> {
const handle = await NodeFSP.open(filePath, "r");
try {
await handle.sync();
} finally {
await handle.close();
}
}
async function syncDirectory(directory: string): Promise<void> {
const handle = await NodeFSP.open(directory, "r");
try {
await handle.sync();
} finally {
await handle.close();
}
}
/**
* Snapshots the database once per update before the first trial. A completed
* backup is never overwritten because a restarted launcher may be looking at
* database writes from an earlier attempt by the same trial.
*/
async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate): Promise<void> {
const backupDir = databaseBackupDir(baseDir, pending.id);
if (await pathExists(backupDir)) return;
const stagingDir = `${backupDir}.staging`;
await NodeFSP.rm(stagingDir, { recursive: true, force: true });
await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
try {
for (const suffix of DB_FILE_SUFFIXES) {
const source = `${pending.dbPath}${suffix}`;
if (suffix !== "" && !(await pathExists(source))) continue;
const destination = databaseBackupFile(stagingDir, suffix);
await NodeFSP.copyFile(source, destination);
await syncFile(destination);
}
await NodeFSP.rename(stagingDir, backupDir);
await syncDirectory(NodePath.dirname(backupDir));
} catch (cause) {
await NodeFSP.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
throw cause;
}
}
const restoreMarkerPath = (baseDir: string, updateId: string) =>
NodePath.join(databaseBackupDir(baseDir, updateId), RESTORE_MARKER);
const databaseRestorePending = (baseDir: string, pending: PendingServiceUpdate) =>
pathExists(restoreMarkerPath(baseDir, pending.id));
/** Mark rollback before changing live files so launcher recovery cannot boot a partial restore. */
async function markDatabaseRestorePending(backupDir: string): Promise<void> {
const markerPath = NodePath.join(backupDir, RESTORE_MARKER);
if (!(await pathExists(markerPath))) {
const handle = await NodeFSP.open(markerPath, "wx", 0o600);
try {
await handle.sync();
} finally {
await handle.close();
}
await syncDirectory(backupDir);
}
}
/** Restore is retryable after any process crash while the backup directory remains. */
async function restoreDatabaseBackup(
baseDir: string,
pending: PendingServiceUpdate,
): Promise<void> {
const backupDir = databaseBackupDir(baseDir, pending.id);
if (!(await pathExists(backupDir))) return;
await markDatabaseRestorePending(backupDir);
for (const suffix of DB_FILE_SUFFIXES) {
const target = `${pending.dbPath}${suffix}`;
const source = databaseBackupFile(backupDir, suffix);
if (await pathExists(source)) {
await NodeFSP.copyFile(source, target);
await syncFile(target);
} else {
await NodeFSP.rm(target, { force: true });
}
}
await syncDirectory(NodePath.dirname(pending.dbPath));
}
async function discardDatabaseBackup(baseDir: string, updateId: string): Promise<void> {
const backupDir = databaseBackupDir(baseDir, updateId);
if (!(await pathExists(backupDir))) return;
await NodeFSP.rm(backupDir, { recursive: true, force: true });
await syncDirectory(NodePath.dirname(backupDir));
}
export async function readServiceState(filePath: string): Promise<ServiceState> {
const contents = await NodeFSP.readFile(filePath, "utf8");
const state = parseServiceState(contents);
@@ -332,16 +217,9 @@ export class Launcher {
async #recover(): Promise<void> {
const update = this.#state.update;
if (update?.status !== "pending") {
if (update !== undefined) {
await discardDatabaseBackup(this.#baseDir, update.id).catch(() => undefined);
}
await this.#startChild(this.#state.activeVersion, "active", update);
return;
}
if (await databaseRestorePending(this.#baseDir, update)) {
await this.#returnToPrevious(update, "failed", "rollback-interrupted");
return;
}
if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
await this.#returnToPrevious(update, "failed", "target-runtime-missing");
return;
@@ -350,13 +228,6 @@ export class Launcher {
}
async #startTrial(pending: PendingServiceUpdate): Promise<void> {
// The previous child is dead here, so all three SQLite files are quiescent.
try {
await backupDatabaseOnce(this.#baseDir, pending);
} catch {
await this.#returnToPrevious(pending, "failed", "db-backup-failed");
return;
}
try {
await this.#startChild(pending.targetVersion, "trial", pending);
} catch {
@@ -451,10 +322,6 @@ export class Launcher {
await reject("Remote updates must select a newer server version.");
return;
}
if (!NodePath.isAbsolute(message.dbPath)) {
await reject("The requested database path is not absolute.");
return;
}
if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
await reject("The requested target runtime is missing or incomplete.");
return;
@@ -464,7 +331,6 @@ export class Launcher {
id: NodeCrypto.randomUUID(),
fromVersion: child.version,
targetVersion: message.targetVersion,
dbPath: message.dbPath,
status: "pending",
};
const next: ServiceState = { ...this.#state, update: pending };
@@ -509,7 +375,6 @@ export class Launcher {
await writeServiceState(this.#statePath, next);
this.#state = next;
child.role = "active";
await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
await sendMessage(child.process, { type: "committed", updateId: committed.id });
}
@@ -558,11 +423,6 @@ export class Launcher {
reason: string,
child?: ManagedChild,
): Promise<void> {
if (child !== undefined) {
this.#child = null;
await terminateChild(child.process);
}
await restoreDatabaseBackup(this.#baseDir, pending);
const outcome = terminalUpdate({ pending, status, reason });
const next: ServiceState = {
...this.#state,
@@ -571,7 +431,10 @@ export class Launcher {
};
await writeServiceState(this.#statePath, next);
this.#state = next;
await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
if (child !== undefined) {
this.#child = null;
await terminateChild(child.process);
}
await this.#startChild(next.activeVersion, "active", outcome);
}
}
@@ -195,17 +195,11 @@ describe("buildThreadTitlePrompt", () => {
});
expect(result.prompt).toContain(
"Regenerate the title for an existing T3 Code thread so the user can recognize it weeks later.",
"Generate a new title that will help the user recognize this T3 Code thread weeks later.",
);
expect(result.prompt).toContain('The previous title was "Investigate reconnect regressions".');
expect(result.prompt).toContain(
"Read the USER messages first. Identify the latest explicit durable goal.",
);
expect(result.prompt).toContain(
"Do not promote one assistant finding into the thread subject unless the user adopts it as a new goal.",
);
expect(result.prompt).toContain(
'A subagent-monitoring review that finds a Codex roster bug remains "Review Subagent Monitoring Risks,"',
"Capture the current durable subject and outcome across the whole thread, not merely its initial request or latest step.",
);
expect(result.prompt).toContain("Thread contents:");
expect(result.prompt).toContain("The remaining issue is stale session state");
@@ -150,12 +150,27 @@ export interface BranchNamePromptInput {
interface PromptFromMessageInput {
instruction: string;
responseShape: string;
guidance?: ReadonlyArray<string> | undefined;
rulesLabel?: string | undefined;
rules: ReadonlyArray<string>;
message: string;
messageLabel?: string | undefined;
preserveMessageEnd?: boolean | undefined;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
additionalInstructions?: string | undefined;
}
function preserveMessageEnd(message: string): string {
const alreadyTruncated = message.startsWith(EARLIER_CONTENT_TRUNCATION_MARKER);
const contents = alreadyTruncated
? message.slice(EARLIER_CONTENT_TRUNCATION_MARKER.length)
: message;
if (!alreadyTruncated && contents.length <= 8_000) {
return contents;
}
return `${EARLIER_CONTENT_TRUNCATION_MARKER}${contents.slice(-8_000)}`;
}
function buildPromptFromMessage(input: PromptFromMessageInput): string {
const attachmentLines = (input.attachments ?? []).map(
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
@@ -164,11 +179,14 @@ function buildPromptFromMessage(input: PromptFromMessageInput): string {
const promptSections = [
input.instruction,
input.responseShape,
"Rules:",
...(input.guidance ?? []),
input.rulesLabel ?? "Rules:",
...input.rules.map((rule) => `- ${rule}`),
"",
"User message:",
limitSection(input.message, 8_000),
`${input.messageLabel ?? "User message"}:`,
input.preserveMessageEnd
? preserveMessageEnd(input.message)
: limitSection(input.message, 8_000),
...policyInstruction(input.additionalInstructions),
];
if (attachmentLines.length > 0) {
@@ -214,102 +232,57 @@ export interface ThreadTitlePromptInput {
policy?: TextGenerationPolicy | undefined;
}
// Keep shared editorial rules in these two prompts in sync. Regeneration
// intentionally adds guidance for thread history and the previous title.
const INITIAL_THREAD_TITLE_PROMPT = `Generate a title that will help the user recognize this T3 Code thread weeks later.
Return JSON with exactly one key: title.
Before answering, silently reduce the request to:
- Subject: What system, feature, or problem is this really about?
- Outcome: What does the user ultimately want to understand or change?
- Incidental instructions: What only describes how the agent should do the work?
Title the subject and outcome. Discard incidental instructions.
Editorial rules:
- 3-8 words, fewer than 40 characters.
- Use a compact noun phrase or clear action phrase.
- Capture the umbrella goal when the request lists several symptoms or steps.
- Name the product change, not the mock, plan, report, branch, or PR used to produce it.
- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.
- For reviews, name what is being reviewed and the relevant concern. Avoid generic titles such as "Review PR 123" when linked or attached context reveals the subject.
- For research, name the question domain rather than the requested research process.
- Do not claim the work is complete.
- Do not copy and truncate the user's message.
- Avoid project names already visible in the UI, quotes, labels, filler, and trailing punctuation.
- Use attached images as primary context for UI issues.
- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.`;
function regenerateThreadTitlePrompt(previousTitle: string): string {
return `Regenerate the title for an existing T3 Code thread so the user can recognize it weeks later.
The previous title was ${JSON.stringify(previousTitle)}.
Return JSON with exactly one key: title.
Determine the title in this order:
1. Read the USER messages first. Identify the latest explicit durable goal. The original subject remains the subject until the user clearly changes what the thread is about.
2. Use ASSISTANT messages to resolve vague links, unnamed code, and discovered product nouns. Do not promote one assistant finding into the thread subject unless the user adopts it as a new goal.
3. Compare that subject with the previous title. Preserve accurate scope words, especially when earlier content is truncated. Replace the previous title when it is generic, artifact-based, a completion update, or contradicted by the thread.
4. Title the durable subject and desired outcome, not the current workflow state.
Editorial rules:
- 3-8 words, fewer than 40 characters.
- Use a compact noun phrase or clear action phrase.
- Preserve the umbrella subject when later messages focus on one finding, provider, platform, or implementation detail.
- A thread progressing through research, planning, implementation, review, CI, merge, and monitoring has usually not changed subjects.
- Ignore deliverables and operations such as mocks, plans, HTML, branches, PRs, tests, CI, commits, merging, and monitoring unless they are the actual topic.
- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.
- Treat final operational follow-ups and assistant completion summaries as weak evidence of subject.
- For reviews, name the reviewed feature or system and its durable concern, not one finding from the review.
- For research, name the question domain rather than the research process.
- Do not claim the work is complete.
- Do not copy and truncate a thread message.
- Avoid project names already visible in the UI, PR numbers, quotes, labels, filler, and trailing punctuation.
- Use attached images as primary context for UI issues.
- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.
- Return a meaningfully improved title, not a cosmetic paraphrase of the previous title.
Examples of the distinction:
- A subagent-monitoring review that finds a Codex roster bug remains "Review Subagent Monitoring Risks," not "Codex Roster Bug Review."
- A vague failing-test request later identified as a lazy thread-feed mismatch becomes "Fix Lazy Thread Feed Test," not "Prevent Mobile Feed Regressions."
- A QR-sharing overhaul that ends with CI and merge work remains about QR sharing, not the PR lifecycle.`;
}
function preserveMessageEnd(message: string): string {
const alreadyTruncated = message.startsWith(EARLIER_CONTENT_TRUNCATION_MARKER);
const contents = alreadyTruncated
? message.slice(EARLIER_CONTENT_TRUNCATION_MARKER.length)
: message;
if (!alreadyTruncated && contents.length <= 8_000) {
return contents;
}
return `${EARLIER_CONTENT_TRUNCATION_MARKER}${contents.slice(-8_000)}`;
}
function threadTitlePromptSuffix(input: ThreadTitlePromptInput): string {
const additionalInstructions = policyInstruction(input.policy?.threadTitleInstructions);
const attachmentLines = (input.attachments ?? []).map(
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
);
let suffix = "";
if (additionalInstructions.length > 0) {
suffix = `\n${additionalInstructions.join("\n")}`;
}
if (attachmentLines.length > 0) {
suffix += `\n\nAttachment metadata:\n${limitSection(attachmentLines.join("\n"), 4_000)}`;
}
return suffix;
}
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
let prompt: string;
if (input.previousTitle === undefined) {
const message = limitSection(input.message, 8_000);
prompt = `${INITIAL_THREAD_TITLE_PROMPT}\n\nUser message:\n${message}${threadTitlePromptSuffix(input)}`;
} else {
const message = preserveMessageEnd(input.message);
prompt = `${regenerateThreadTitlePrompt(input.previousTitle)}\n\nThread contents:\n${message}${threadTitlePromptSuffix(input)}`;
}
const isRegeneration = input.previousTitle !== undefined;
const prompt = buildPromptFromMessage({
instruction: isRegeneration
? [
"Generate a new title that will help the user recognize this T3 Code thread weeks later.",
`The previous title was ${JSON.stringify(input.previousTitle)}.`,
].join("\n")
: "Generate a title that will help the user recognize this T3 Code thread weeks later.",
responseShape: "Return JSON with exactly one key: title.",
guidance: [
"",
"Before answering, silently reduce the request to:",
"- Subject: What system, feature, or problem is this really about?",
"- Outcome: What does the user ultimately want to understand or change?",
"- Incidental instructions: What only describes how the agent should do the work?",
"",
"Title the subject and outcome. Discard incidental instructions.",
"",
],
rulesLabel: "Editorial rules:",
rules: [
"3-8 words, fewer than 40 characters.",
"Use a compact noun phrase or clear action phrase.",
"Capture the umbrella goal when the request lists several symptoms or steps.",
"Name the product change, not the mock, plan, report, branch, or PR used to produce it.",
"Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.",
'For reviews, name what is being reviewed and the relevant concern. Avoid generic titles such as "Review PR 123" when linked or attached context reveals the subject.',
"For research, name the question domain rather than the requested research process.",
"Do not claim the work is complete.",
"Do not copy and truncate the user's message.",
"Avoid project names already visible in the UI, quotes, labels, filler, and trailing punctuation.",
"Use attached images as primary context for UI issues.",
"When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.",
...(isRegeneration
? [
"Capture the current durable subject and outcome across the whole thread, not merely its initial request or latest step.",
"Return a different title from the previous title.",
]
: []),
],
message: input.message,
...(isRegeneration
? {
messageLabel: "Thread contents",
preserveMessageEnd: true,
}
: {}),
attachments: input.attachments,
additionalInstructions: input.policy?.threadTitleInstructions,
});
const outputSchema = Schema.Struct({
title: Schema.String,
});
-5
View File
@@ -20,8 +20,6 @@ import {
type VcsCreateWorktreeResult,
type ReviewDiffPreviewInput,
type ReviewDiffPreviewResult,
type ReviewDiffFileContentsInput,
type ReviewDiffFileContentsResult,
type VcsInitInput,
type VcsListRefsInput,
type VcsListRefsResult,
@@ -223,9 +221,6 @@ export class GitVcsDriver extends Context.Service<
readonly getReviewDiffPreview: (
input: ReviewDiffPreviewInput,
) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
readonly getReviewDiffFileContents: (
input: ReviewDiffFileContentsInput,
) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;
readonly readConfigValue: (
cwd: string,
key: string,
+1 -116
View File
@@ -14,7 +14,7 @@ import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError, type ReviewDiffFileContentsInput } from "@t3tools/contracts";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import { makeGitVcsDriverCore, splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
@@ -78,20 +78,6 @@ const writeTextFile = (
yield* fileSystem.writeFileString(filePath, contents);
});
const makeReviewDiffFileContentsInput = (
cwd: string,
overrides: Partial<Omit<ReviewDiffFileContentsInput, "cwd">> = {},
): ReviewDiffFileContentsInput => ({
cwd,
sourceKind: "working-tree",
changeType: "change",
baseRef: "HEAD",
headRef: null,
oldPath: "README.md",
newPath: "README.md",
...overrides,
});
const git = (
cwd: string,
args: ReadonlyArray<string>,
@@ -817,107 +803,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
);
}),
);
it.effect("loads full file contents for working-tree diff expansion", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
const pathService = yield* Path.Path;
yield* writeTextFile(cwd, "nested/.keep", "");
yield* writeTextFile(cwd, "README.md", "# changed\nunchanged context\n");
const contents = yield* driver.getReviewDiffFileContents(
makeReviewDiffFileContentsInput(pathService.join(cwd, "nested")),
);
assert.strictEqual(contents.oldContents, "# test\n");
assert.strictEqual(contents.newContents, "# changed\nunchanged context\n");
}),
);
it.effect("attributes working-tree filesystem failures to the failing operation", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
const error = yield* driver
.getReviewDiffFileContents(
makeReviewDiffFileContentsInput(cwd, {
changeType: "new",
oldPath: "missing.ts",
newPath: "missing.ts",
}),
)
.pipe(Effect.flip);
assert.deepInclude(error, {
_tag: "GitCommandError",
operation: "GitVcsDriver.getReviewDiffFileContents.workingTree.fs.realPath",
command: "fs.realPath",
cwd,
detail: "Could not resolve diff file 'missing.ts'.",
});
}),
);
it.effect("loads new and deleted files without reading their missing side", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
yield* writeTextFile(cwd, "added.ts", "export const added = true;\n");
yield* fileSystem.remove(pathService.join(cwd, "README.md"));
const [added, deleted] = yield* Effect.all([
driver.getReviewDiffFileContents(
makeReviewDiffFileContentsInput(cwd, {
changeType: "new",
oldPath: "added.ts",
newPath: "added.ts",
}),
),
driver.getReviewDiffFileContents(
makeReviewDiffFileContentsInput(cwd, { changeType: "deleted" }),
),
]);
assert.deepStrictEqual(added, {
oldContents: "",
newContents: "export const added = true;\n",
});
assert.deepStrictEqual(deleted, {
oldContents: "# test\n",
newContents: "",
});
}),
);
it.effect("loads merge-base and head contents for branch diff expansion", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* git(cwd, ["checkout", "-b", "feature/context"]);
yield* writeTextFile(cwd, "README.md", "# branch change\nunchanged context\n");
yield* git(cwd, ["add", "README.md"]);
yield* git(cwd, ["commit", "-m", "change readme"]);
const contents = yield* driver.getReviewDiffFileContents(
makeReviewDiffFileContentsInput(cwd, {
sourceKind: "branch-range",
baseRef: initialBranch,
headRef: "feature/context",
}),
);
assert.strictEqual(contents.oldContents, "# test\n");
assert.strictEqual(contents.newContents, "# branch change\nunchanged context\n");
}),
);
});
describe("repository status", () => {
-160
View File
@@ -21,7 +21,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
GitCommandError,
type ReviewDiffFileContentsInput,
type ReviewDiffPreviewInput,
type ReviewDiffPreviewSource,
type VcsRef,
@@ -47,7 +46,6 @@ const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000;
const REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES = 80_000;
const REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000;
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
@@ -2272,163 +2270,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
};
});
const reviewDiffFileError = (
input: ReviewDiffFileContentsInput,
detail: string,
cause?: unknown,
) =>
new GitCommandError({
operation: "GitVcsDriver.getReviewDiffFileContents",
command: "git",
cwd: input.cwd,
detail,
...(cause === undefined ? {} : { cause }),
});
const isPathWithinRoot = (root: string, candidate: string) => {
const relative = path.relative(root, candidate);
return (
relative === "" ||
(relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
);
};
const readReviewFileAtRevision = Effect.fn("readReviewFileAtRevision")(function* (
input: ReviewDiffFileContentsInput,
revision: string,
relativePath: string,
) {
const result = yield* executeGit(
"GitVcsDriver.getReviewDiffFileContents.revision",
input.cwd,
["show", `${revision}:${relativePath}`],
{ maxOutputBytes: REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES },
);
if (result.stdout.includes("\0")) {
return yield* reviewDiffFileError(input, `Cannot expand binary file '${relativePath}'.`);
}
return result.stdout;
});
const readWorkingTreeReviewFile = Effect.fn("readWorkingTreeReviewFile")(function* (
input: ReviewDiffFileContentsInput,
repositoryRoot: string,
) {
const fileError = (stage: string, detail: string, cause?: unknown) =>
new GitCommandError({
operation: `GitVcsDriver.getReviewDiffFileContents.workingTree.${stage}`,
command: stage,
cwd: input.cwd,
detail,
...(cause === undefined ? {} : { cause }),
});
const requestedPath = path.resolve(repositoryRoot, input.newPath);
if (!isPathWithinRoot(repositoryRoot, requestedPath)) {
return yield* fileError(
"path.resolve",
`Diff file '${input.newPath}' resolves outside the review workspace.`,
);
}
const [realRepositoryRoot, realTarget] = yield* Effect.all([
fileSystem.realPath(repositoryRoot),
fileSystem.realPath(requestedPath),
]).pipe(
Effect.mapError((cause) =>
fileError("fs.realPath", `Could not resolve diff file '${input.newPath}'.`, cause),
),
);
if (!isPathWithinRoot(realRepositoryRoot, realTarget)) {
return yield* fileError(
"fs.realPath",
`Diff file '${input.newPath}' resolves outside the review workspace.`,
);
}
const info = yield* fileSystem
.stat(realTarget)
.pipe(
Effect.mapError((cause) =>
fileError("fs.stat", `Could not inspect diff file '${input.newPath}'.`, cause),
),
);
if (info.type !== "File") {
return yield* fileError("fs.stat", `Diff path '${input.newPath}' is not a file.`);
}
if (info.size > BigInt(REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES)) {
return yield* fileError(
"fs.stat",
`Diff file '${input.newPath}' exceeds the 1 MB expansion limit.`,
);
}
const bytes = yield* fileSystem
.readFile(realTarget)
.pipe(
Effect.mapError((cause) =>
fileError("fs.readFile", `Could not read diff file '${input.newPath}'.`, cause),
),
);
if (bytes.includes(0)) {
return yield* fileError("fs.readFile", `Cannot expand binary file '${input.newPath}'.`);
}
return new TextDecoder("utf-8").decode(bytes);
});
const getReviewDiffFileContents = Effect.fn("getReviewDiffFileContents")(function* (
input: ReviewDiffFileContentsInput,
) {
if (input.sourceKind === "working-tree") {
const repositoryRoot = yield* runGitStdout(
"GitVcsDriver.getReviewDiffFileContents.repositoryRoot",
input.cwd,
["rev-parse", "--show-toplevel"],
).pipe(Effect.map((value) => value.trim()));
if (repositoryRoot.length === 0) {
return yield* reviewDiffFileError(input, "Could not resolve the Git repository root.");
}
const [oldContents, newContents] = yield* Effect.all(
[
input.changeType === "new"
? Effect.succeed("")
: readReviewFileAtRevision(input, input.baseRef ?? "HEAD", input.oldPath),
input.changeType === "deleted"
? Effect.succeed("")
: readWorkingTreeReviewFile(input, repositoryRoot),
],
{ concurrency: 2 },
);
return { oldContents, newContents };
}
if (!input.baseRef || !input.headRef) {
return yield* reviewDiffFileError(
input,
"Branch diff file expansion requires both base and head refs.",
);
}
const mergeBase = yield* runGitStdout(
"GitVcsDriver.getReviewDiffFileContents.mergeBase",
input.cwd,
["merge-base", input.baseRef, input.headRef],
).pipe(Effect.map((value) => value.trim()));
if (mergeBase.length === 0) {
return yield* reviewDiffFileError(input, "Could not resolve the branch comparison base.");
}
const [oldContents, newContents] = yield* Effect.all(
[
input.changeType === "new"
? Effect.succeed("")
: readReviewFileAtRevision(input, mergeBase, input.oldPath),
input.changeType === "deleted"
? Effect.succeed("")
: readReviewFileAtRevision(input, input.headRef, input.newPath),
],
{ concurrency: 2 },
);
return { oldContents, newContents };
});
const readConfigValue: GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"] = (cwd, key) =>
runGitStdout("GitVcsDriver.readConfigValue", cwd, ["config", "--get", key], true).pipe(
Effect.map((stdout) => stdout.trim()),
@@ -3062,7 +2903,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
pullCurrentBranch: (cwd) => withListRefsInvalidation(cwd, pullCurrentBranch(cwd)),
readRangeContext,
getReviewDiffPreview,
getReviewDiffFileContents,
readConfigValue,
listRefs,
createWorktree: (input) => withListRefsInvalidation(input.cwd, createWorktree(input)),
-6
View File
@@ -1854,12 +1854,6 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {
"rpc.aggregate": "review",
}),
[WS_METHODS.reviewGetDiffFileContents]: (input) =>
observeRpcEffect(
WS_METHODS.reviewGetDiffFileContents,
review.getDiffFileContents(input),
{ "rpc.aggregate": "review" },
),
[WS_METHODS.terminalOpen]: (input) =>
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
"rpc.aggregate": "terminal",
+8 -1
View File
@@ -47,7 +47,14 @@
body {
background: #ffffff;
color: #262626;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
font-family:
"DM Sans Variable",
"DM Sans",
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
system-ui,
sans-serif;
}
html.dark body {
+2
View File
@@ -20,6 +20,8 @@
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@effect/atom-react": "catalog:",
"@fontsource-variable/dm-sans": "^5.2.8",
"@fontsource/jetbrains-mono": "^5.2.8",
"@formkit/auto-animate": "^0.9.0",
"@legendapp/list": "3.2.0",
"@lexical/react": "^0.41.0",
-114
View File
@@ -1,114 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
areFontAdvancesMonospace,
clampCodeFontSize,
clampInterfaceFontSize,
clampPromptFontSize,
DEFAULT_CODE_FONT_STACK,
DEFAULT_SANS_FONT_STACK,
appearanceFontStack,
cssFontFamilies,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
} from "./appearanceFonts";
describe("areFontAdvancesMonospace", () => {
it("accepts a fixed advance and rejects any proportional glyph", () => {
expect(areFontAdvancesMonospace([10, 10, 10, 10])).toBe(true);
expect(areFontAdvancesMonospace([10, 10, 7, 10])).toBe(false);
expect(areFontAdvancesMonospace([10, 10.02])).toBe(false);
});
it("fails open when canvas metrics are unavailable", () => {
expect(areFontAdvancesMonospace([])).toBe(true);
expect(areFontAdvancesMonospace([Number.NaN, Number.NaN])).toBe(true);
});
});
describe("cssFontFamilies", () => {
it("returns null for effectively empty input", () => {
expect(cssFontFamilies("")).toBeNull();
expect(cssFontFamilies(" ")).toBeNull();
expect(cssFontFamilies(" , , ")).toBeNull();
});
it("quotes names with spaces and keeps single idents bare", () => {
expect(cssFontFamilies("Fira Code")).toBe('"Fira Code"');
expect(cssFontFamilies("monospace")).toBe("monospace");
expect(cssFontFamilies('"Comic Mono"')).toBe('"Comic Mono"');
});
it("normalizes comma-separated lists and strips embedded quotes", () => {
expect(cssFontFamilies(" Fira Code , Menlo ")).toBe('"Fira Code", Menlo');
expect(cssFontFamilies('Bad"Name')).toBe('"BadName"');
});
it("quotes names that are not single CSS idents", () => {
expect(cssFontFamilies("3270 Nerd Font")).toBe('"3270 Nerd Font"');
expect(cssFontFamilies("M+ 1m")).toBe('"M+ 1m"');
});
});
describe("resolveDefaultFamilyLabel", () => {
it("skips generic keywords and returns null for a stack of only generics", () => {
expect(resolveDefaultFamilyLabel("system-ui, sans-serif")).toBeNull();
expect(resolveDefaultFamilyLabel("ui-monospace, monospace")).toBeNull();
});
});
describe("appearanceFontStack", () => {
it("prepends the custom family to the default stack", () => {
expect(appearanceFontStack("Fira Code", DEFAULT_CODE_FONT_STACK)).toBe(
`"Fira Code", ${DEFAULT_CODE_FONT_STACK}`,
);
});
it("falls back to the default stack when unset", () => {
expect(appearanceFontStack("", DEFAULT_SANS_FONT_STACK)).toBe(DEFAULT_SANS_FONT_STACK);
});
});
describe("resolveTerminalFontPreference", () => {
it("inherits the code font in simple mode", () => {
expect(
resolveTerminalFontPreference({ advanced: false, code: "Fira Code", terminal: "" }),
).toBe("Fira Code");
expect(
resolveTerminalFontPreference({
advanced: false,
code: "Fira Code",
terminal: "Berkeley Mono",
}),
).toBe("Fira Code");
});
it("keeps code and terminal fonts independent in advanced mode", () => {
expect(resolveTerminalFontPreference({ advanced: true, code: "Fira Code", terminal: "" })).toBe(
"",
);
expect(
resolveTerminalFontPreference({
advanced: true,
code: "Fira Code",
terminal: "Berkeley Mono",
}),
).toBe("Berkeley Mono");
});
});
describe("font size clamping", () => {
it("keeps sizes inside the ranges the UI can absorb", () => {
expect(clampInterfaceFontSize(16)).toBe(16);
expect(clampInterfaceFontSize(2)).toBe(12);
expect(clampInterfaceFontSize(96)).toBe(20);
expect(clampPromptFontSize(40)).toBe(20);
expect(clampCodeFontSize(1)).toBe(10);
});
it("rounds fractional values and falls back for unusable input", () => {
expect(clampCodeFontSize(13.4)).toBe(13);
expect(clampInterfaceFontSize(Number.NaN)).toBe(16);
expect(clampPromptFontSize(Number.POSITIVE_INFINITY)).toBe(14);
});
});
-386
View File
@@ -1,386 +0,0 @@
/**
* Font preferences from Settings → Appearance, applied as CSS custom
* properties. The default stacks mirror the `--font-sans` / `--font-mono`
* definitions in `index.css`; a custom family is always prepended to the
* matching default stack so glyph coverage never regresses.
*/
import {
DEFAULT_CODE_FONT_SIZE,
DEFAULT_INTERFACE_FONT_SIZE,
DEFAULT_PROMPT_FONT_SIZE,
MAX_CODE_FONT_SIZE,
MAX_INTERFACE_FONT_SIZE,
MAX_PROMPT_FONT_SIZE,
MIN_CODE_FONT_SIZE,
MIN_INTERFACE_FONT_SIZE,
MIN_PROMPT_FONT_SIZE,
} from "@t3tools/contracts";
export const DEFAULT_SANS_FONT_STACK =
'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif';
// Concrete names first: some engines alias `ui-monospace` to the
// proportional system UI font, which would break every code surface.
export const DEFAULT_CODE_FONT_STACK =
'"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace';
export const TYPOGRAPHY_ADVANCED_STORAGE_KEY = "t3code:typography-advanced";
/**
* Simple typography treats the terminal as another monospace surface. In
* Advanced mode an empty terminal preference means the terminal default,
* keeping later code-font changes isolated to code surfaces.
*/
export function resolveTerminalFontPreference(input: {
readonly advanced: boolean;
readonly code: string;
readonly terminal: string;
}): string {
if (input.advanced) return input.terminal;
return input.code;
}
function quoteFontFamilyName(name: string): string {
const bare = name.trim();
if (bare.length === 0) return "";
// Already quoted, or a single ident that needs no quoting.
if (/^(['"]).*\1$/.test(bare)) return bare;
if (/^[a-zA-Z][a-zA-Z0-9-]*$/.test(bare)) return bare;
return `"${bare.replaceAll('"', "")}"`;
}
/**
* Normalize a user-entered family (single name or comma-separated list) into a
* safe CSS font-family list, or null when the input is effectively empty.
*/
export function cssFontFamilies(input: string): string | null {
const families = input
.split(",")
.map(quoteFontFamilyName)
.filter((name) => name.length > 0);
return families.length > 0 ? families.join(", ") : null;
}
/** The full stack a preference resolves to: custom families before the default. */
export function appearanceFontStack(custom: string, defaultStack: string): string {
const families = cssFontFamilies(custom);
return families === null ? defaultStack : `${families}, ${defaultStack}`;
}
export interface AppearanceFontPreferences {
readonly sans: string;
readonly code: string;
readonly composer: string;
readonly sizeInterface: number;
readonly sizePrompt: number;
readonly sizeCode: number;
/** Grayscale `antialiased` rendering; false keeps the heavier platform default. */
readonly smoothing: boolean;
}
/**
* Apply the preferences to the root element. Unset families remove the
* override so the stylesheet defaults (and theme changes) stay in charge.
*
* Sizes are always written: the interface size drives the root font size (and
* with it every rem-based dimension), while the prompt and code sizes stay in
* absolute pixels so they do not scale twice.
*/
export function applyAppearanceFontVariables(
root: HTMLElement,
preferences: AppearanceFontPreferences,
): void {
const families: ReadonlyArray<readonly [variable: string, custom: string, fallback: string]> = [
["--font-sans", preferences.sans, DEFAULT_SANS_FONT_STACK],
["--font-mono", preferences.code, DEFAULT_CODE_FONT_STACK],
// The composer falls back to whatever the sans preference resolves to.
["--font-composer", preferences.composer, "var(--font-sans)"],
];
for (const [variable, custom, fallback] of families) {
const list = cssFontFamilies(custom);
if (list === null) {
root.style.removeProperty(variable);
} else {
root.style.setProperty(variable, `${list}, ${fallback}`);
}
}
root.style.fontSize = `${clampInterfaceFontSize(preferences.sizeInterface)}px`;
root.style.setProperty("--font-size-prompt", `${clampPromptFontSize(preferences.sizePrompt)}px`);
const code = clampCodeFontSize(preferences.sizeCode);
root.style.setProperty("--font-size-code", `${code}px`);
// The @pierre/diffs surfaces read their own hook for code text.
root.style.setProperty("--diffs-font-size", `${code}px`);
// Inherited from the root; only macOS engines honor the property, so no
// platform gate is needed here. Smoothing on means grayscale `antialiased`
// (thinner strokes); off restores the platform default, which macOS renders
// with heavier stem darkening.
if (preferences.smoothing) {
root.style.setProperty("-webkit-font-smoothing", "antialiased");
} else {
root.style.removeProperty("-webkit-font-smoothing");
}
}
function clampFontSize(value: number, minimum: number, maximum: number, fallback: number): number {
if (!Number.isFinite(value)) return fallback;
return Math.min(maximum, Math.max(minimum, Math.round(value)));
}
export function clampInterfaceFontSize(value: number): number {
return clampFontSize(
value,
MIN_INTERFACE_FONT_SIZE,
MAX_INTERFACE_FONT_SIZE,
DEFAULT_INTERFACE_FONT_SIZE,
);
}
export function clampPromptFontSize(value: number): number {
return clampFontSize(value, MIN_PROMPT_FONT_SIZE, MAX_PROMPT_FONT_SIZE, DEFAULT_PROMPT_FONT_SIZE);
}
export function clampCodeFontSize(value: number): number {
return clampFontSize(value, MIN_CODE_FONT_SIZE, MAX_CODE_FONT_SIZE, DEFAULT_CODE_FONT_SIZE);
}
const FONT_PROBE_TEXT = "mmmmmmmmMMWli1O0@# fjord";
let fontProbeContext: CanvasRenderingContext2D | null | undefined;
function probeWidth(fontList: string): number | null {
if (fontProbeContext === undefined) {
fontProbeContext = document.createElement("canvas").getContext("2d");
}
if (fontProbeContext === null) return null;
fontProbeContext.font = `16px ${fontList}`;
return fontProbeContext.measureText(FONT_PROBE_TEXT).width;
}
/**
* Canvas metric probing instead of document.fonts.check(): check() reports
* true for families that are not installed at all (nothing needs loading), so
* it cannot filter the dropdown. A family exists when falling back to at
* least one generic changes the measured advance.
*/
export function isFontFamilyAvailable(family: string): boolean {
const families = cssFontFamilies(family);
if (families === null) return false;
if (/^(system-ui|sans-serif|serif|monospace|ui-monospace)$/i.test(families)) return true;
try {
for (const generic of ["monospace", "serif", "sans-serif"]) {
const baseline = probeWidth(generic);
const candidate = probeWidth(`${families}, ${generic}`);
if (baseline === null || candidate === null) return false;
if (candidate !== baseline) return true;
}
return false;
} catch {
return false;
}
}
const MONOSPACE_PROBE_VARIANTS = ["normal 400", "normal 700", "italic 400", "italic 700"] as const;
const MONOSPACE_PROBE_GLYPHS = ["i", "M", "W", "0", "@", "#", ".", " "] as const;
const MONOSPACE_ADVANCE_TOLERANCE = 0.01;
export function areFontAdvancesMonospace(advances: readonly number[]): boolean {
const reference = advances[0];
if (
reference === undefined ||
reference <= 0 ||
advances.some((advance) => !Number.isFinite(advance) || advance <= 0)
) {
return true;
}
return advances.every((advance) => Math.abs(advance - reference) < MONOSPACE_ADVANCE_TOLERANCE);
}
/**
* Whether a family renders every character on the same advance. Cell-grid
* surfaces (the terminal) require this: a proportional face draws its text
* narrower than the lattice the cursor and selection are placed on, which
* reads as ragged gaps and a cursor stranded to the right of the text.
*
* Unmeasurable environments answer true, so a missing canvas never blocks a
* legitimate font.
*/
export function isMonospaceFamily(family: string): boolean {
const families = cssFontFamilies(family);
if (families === null) return true;
try {
if (fontProbeContext === undefined) {
fontProbeContext = document.createElement("canvas").getContext("2d");
}
if (fontProbeContext === null) return true;
const context = fontProbeContext;
// Fall back to a generic mono so an absent face measures as monospace and
// is left for the normal fallback chain to resolve.
for (const variant of MONOSPACE_PROBE_VARIANTS) {
context.font = `${variant} 32px ${families}, monospace`;
const advances = MONOSPACE_PROBE_GLYPHS.map((glyph) => context.measureText(glyph).width);
if (!areFontAdvancesMonospace(advances)) return false;
}
return true;
} catch {
return true;
}
}
// Nameable faces the platform generics commonly map to, likeliest first.
// Pixel-comparing a generic against these names the actual face; Apple's own
// UI fonts are deliberately not CSS-nameable, so a miss on an Apple platform
// identifies San Francisco itself.
const SANS_GENERIC_CANDIDATES = [
"Segoe UI",
"Roboto",
"Noto Sans",
"Ubuntu",
"Cantarell",
"DejaVu Sans",
"Liberation Sans",
"Helvetica Neue",
"Arial",
] as const;
const MONO_GENERIC_CANDIDATES = [
"Menlo",
"Consolas",
"Cascadia Mono",
"DejaVu Sans Mono",
"Ubuntu Mono",
"Liberation Mono",
"Noto Sans Mono",
"Roboto Mono",
"Monaco",
"Courier New",
] as const;
const GENERIC_PROBE_TEXT = "RagIl10O@ fjord quiz";
/**
* Advance width of the probe text laid out by the DOM - not canvas, whose
* generic-family mapping diverges from real rendering (this engine draws
* `ui-monospace` as the proportional UI font on canvas but not in CSS).
* Identical widths at this size mean the same face for practical purposes.
*/
function measureDomProbeWidth(fontFamily: string): number | null {
try {
const body = document.body;
if (!body) return null;
const span = document.createElement("span");
span.style.cssText =
"position:absolute;left:-9999px;top:0;visibility:hidden;white-space:pre;font-size:100px;";
span.style.fontFamily = fontFamily;
span.textContent = GENERIC_PROBE_TEXT;
body.appendChild(span);
const width = span.getBoundingClientRect().width;
span.remove();
return width > 0 ? width : null;
} catch {
return null;
}
}
function widthsMatch(left: number, right: number): boolean {
return Math.abs(left - right) < 0.01;
}
/**
* Name the concrete face a generic keyword renders as, by measuring the
* generic against nameable candidates. Null when the face cannot be
* identified (and the platform gives no definitional answer).
*/
function resolveGenericFamilyLabel(generic: string): string | null {
const lower = generic.toLowerCase();
if (lower === "serif") return null;
const monoLike = lower === "ui-monospace" || lower === "monospace";
const genericWidth = measureDomProbeWidth(generic);
if (genericWidth === null) return null;
for (const candidate of monoLike ? MONO_GENERIC_CANDIDATES : SANS_GENERIC_CANDIDATES) {
if (!isFontFamilyAvailable(candidate)) continue;
const candidateWidth = measureDomProbeWidth(`"${candidate}"`);
if (candidateWidth !== null && widthsMatch(genericWidth, candidateWidth)) {
return candidate;
}
}
// No nameable face matched; on Apple platforms that means one of the San
// Francisco faces, which CSS cannot name. Comparing against -apple-system
// tells the UI face apart from SF Mono.
if (/mac|iphone|ipad|ipod/i.test(navigator.platform)) {
const systemWidth = measureDomProbeWidth("-apple-system");
if (systemWidth !== null && widthsMatch(genericWidth, systemWidth)) return "SF Pro";
return monoLike ? "SF Mono" : "SF Pro";
}
return null;
}
/**
* The first family of a default stack that will actually render - what the
* "Default" choice means on this machine. Concrete names are probed for
* availability; generic keywords are resolved to the face they draw with
* where identifiable. Null when nothing can be named.
*/
export function resolveDefaultFamilyLabel(stack: string): string | null {
for (const raw of stack.split(",")) {
const family = raw.trim().replace(/^(['"])(.*)\1$/, "$2");
if (family.length === 0) continue;
if (
/^(system-ui|sans-serif|serif|monospace|ui-monospace|-apple-system|BlinkMacSystemFont)$/i.test(
family,
)
) {
const resolved = resolveGenericFamilyLabel(family);
if (resolved !== null) return resolved;
continue;
}
if (isFontFamilyAvailable(family)) return family;
}
return null;
}
export interface InstalledFontFamiliesResult {
readonly families: readonly string[];
/**
* "unsupported" - the engine has no Local Font Access API (Safari,
* Firefox); "denied" - the API exists but the user declined the permission
* prompt. Both fall back to the curated catalog.
*/
readonly status: "granted" | "denied" | "unsupported";
}
let installedFamiliesCache: InstalledFontFamiliesResult | null = null;
/**
* Every installed family via the Local Font Access API (Chromium and
* Electron). Call from a user gesture: the first call raises the browser's
* local-fonts permission prompt. A denial is not cached, so reopening the
* picker can ask again after the user changes the site setting.
*/
export async function queryInstalledFontFamilies(): Promise<InstalledFontFamiliesResult> {
if (installedFamiliesCache !== null) return installedFamiliesCache;
const query = (
window as Window & {
queryLocalFonts?: () => Promise<ReadonlyArray<{ readonly family: string }>>;
}
).queryLocalFonts;
if (typeof query !== "function") {
installedFamiliesCache = { families: [], status: "unsupported" };
return installedFamiliesCache;
}
try {
const fonts = await query.call(window);
const families = [...new Set(fonts.map((font) => font.family))]
// Dot-prefixed families are macOS-internal UI faces; selecting one is
// never intended and most refuse to render for web content anyway.
.filter((family) => !family.startsWith("."))
.sort((left, right) => left.localeCompare(right));
// A denied permission check resolves with an empty list instead of
// throwing; no machine has zero fonts, so treat empty as denied.
if (families.length === 0) return { families: [], status: "denied" };
installedFamiliesCache = { families, status: "granted" };
return installedFamiliesCache;
} catch {
return { families: [], status: "denied" };
}
}
+2 -100
View File
@@ -9,7 +9,7 @@ import {
HistoryIcon,
MonitorIcon,
} from "lucide-react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { memo, useCallback, useMemo } from "react";
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
@@ -214,98 +214,6 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
);
});
/**
* Collapse the strip's labels to icons only when the text no longer fits.
*
* Hidden labels stay measurable (they collapse to invisible absolute boxes,
* which keep their natural width), so the required width can be recomputed in
* either state on every pass - no remembered widths that could go stale or
* latch the strip compact. A small hysteresis keeps the boundary from
* flapping between states.
*/
const COMPACT_EXPAND_HYSTERESIS_PX = 16;
function useLabelsOverflow(element: HTMLDivElement | null): boolean {
const [overflows, setOverflows] = useState(false);
// A render-synced mirror instead of useEffectEvent: the compiler memoizes
// the event callback, which left observers reading the first render's null
// element forever.
const stateRef = useRef({ element, overflows });
stateRef.current = { element, overflows };
const measure = useCallback(() => {
const { element: current, overflows: compact } = stateRef.current;
if (!current) return;
const available = current.clientWidth;
if (available === 0) return;
// flex-1 stretches the groups to fill the strip, so their own boxes always
// measure "full". Sum the laid-out content instead, skipping hidden form
// artifacts and absolutely-positioned nodes (the compact-hidden labels).
const contentWidth = (parent: Element): number => {
const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
let width = 0;
let counted = 0;
for (const child of parent.children) {
if (!(child instanceof HTMLElement)) continue;
if (child.offsetWidth <= 1) continue;
const position = getComputedStyle(child).position;
if (position === "absolute" || position === "fixed") continue;
width += child.offsetWidth;
counted += 1;
}
return width + gap * Math.max(0, counted - 1);
};
const stripGap = Number.parseFloat(getComputedStyle(current).columnGap) || 0;
let needed = 0;
let groups = 0;
for (const child of current.children) {
if (!(child instanceof HTMLElement) || child.offsetWidth <= 1) continue;
needed += contentWidth(child);
groups += 1;
}
needed += stripGap * Math.max(0, groups - 1);
for (const label of current.querySelectorAll<HTMLElement>("[data-composer-label]")) {
// The clipping can happen below the marker (SelectValue truncates
// internally), where the outer span's scrollWidth matches its clipped
// box. The text's real width is the largest scrollWidth in the subtree.
let textWidth = label.scrollWidth;
for (const inner of label.querySelectorAll<HTMLElement>("*")) {
textWidth = Math.max(textWidth, inner.scrollWidth);
}
if (compact) {
// Compact: the label is squeezed to zero width but keeps reporting
// the full width it would need when expanded.
needed += textWidth;
} else {
// Expanded: the label is in flow; only the clipped remainder is
// missing from the content sum.
needed += Math.max(0, textWidth - label.clientWidth);
}
}
setOverflows(compact ? needed > available - COMPACT_EXPAND_HYSTERESIS_PX : needed > available);
}, []);
// Label widths can change without the strip box moving (font family or
// size preferences), so re-measure on every render as well as on resize
// and font loads.
useEffect(() => {
measure();
});
useEffect(() => {
if (!element) return;
const observer = new ResizeObserver(measure);
observer.observe(element);
document.fonts.addEventListener("loadingdone", measure);
return () => {
observer.disconnect();
document.fonts.removeEventListener("loadingdone", measure);
};
}, [element, measure]);
return overflows;
}
export const BranchToolbar = memo(function BranchToolbar({
environmentId,
threadId,
@@ -392,17 +300,11 @@ export const BranchToolbar = memo(function BranchToolbar({
canPickEnvironment: showEnvironmentPicker,
});
const isMobile = useIsMobile();
const [stripElement, setStripElement] = useState<HTMLDivElement | null>(null);
const labelsOverflow = useLabelsOverflow(stripElement);
if (!hasActiveThread || !activeProject) return null;
return (
<div
ref={setStripElement}
data-compact={labelsOverflow ? "" : undefined}
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1"
>
<div className="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1">
{isMobile ? (
<MobileRunContextSelector
envLocked={envLocked}
@@ -749,12 +749,7 @@ export function BranchToolbarBranchSelector({
disabled={isInitialBranchesLoadPending || isBranchActionPending}
>
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
<span
data-composer-label
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
>
{triggerLabel}
</span>
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</ComboboxTrigger>
</span>
@@ -82,7 +82,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
<SelectTrigger
variant="ghost"
size="xs"
className="min-w-0 shrink font-medium"
className="shrink-0 font-medium"
aria-label="Workspace"
>
{effectiveEnvMode === "worktree" ? (
@@ -92,12 +92,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
) : (
<FolderIcon className="size-3" />
)}
<span
data-composer-label
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
>
<SelectValue />
</span>
<SelectValue />
</SelectTrigger>
<SelectPopup>
<SelectGroup>
@@ -49,12 +49,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
) : (
<CloudIcon className="size-3 shrink-0" />
)}
<span
data-composer-label
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
>
{activeEnvironment?.label ?? "Run on"}
</span>
<span className="truncate">{activeEnvironment?.label ?? "Run on"}</span>
</span>
);
}
@@ -77,12 +72,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
) : (
<CloudIcon className="size-3 shrink-0" />
)}
<span
data-composer-label
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
>
<SelectValue />
</span>
<SelectValue />
</SelectTrigger>
<SelectPopup>
<SelectGroup>
-4
View File
@@ -1363,9 +1363,6 @@ function ChatMarkdown({
},
[createAssetUrl, openPreview, preparedConnection, threadRef],
);
/* eslint-disable react/no-unstable-nested-components -- ReactMarkdown requires component
* renderers that close over this message's metadata. useMemo keeps them stable until that
* metadata changes. */
const markdownComponents = useMemo<Components>(() => {
const fileLinkChip = (
fileLinkMeta: MarkdownFileLinkMeta,
@@ -1596,7 +1593,6 @@ function ChatMarkdown({
text,
threadRef,
]);
/* eslint-enable react/no-unstable-nested-components */
return (
<div
+7 -63
View File
@@ -8,7 +8,6 @@ import {
type ProjectScript,
type ProjectId,
type ProviderApprovalDecision,
type PreviewAnnotationPayload,
ProviderInstanceId,
type ServerProvider,
type ResolvedKeybindingsConfig,
@@ -4562,24 +4561,8 @@ function ChatViewContent(props: ChatViewProps) {
],
);
const onSend = async (
e?: { preventDefault: () => void },
directAnnotation?: {
annotation: PreviewAnnotationPayload;
image: ComposerImageAttachment | null;
},
) => {
const onSend = async (e?: { preventDefault: () => void }) => {
e?.preventDefault();
const notifyDirectAnnotationAttached = () => {
if (!directAnnotation) return;
toastManager.add(
stackedThreadToast({
type: "info",
title: "Annotation attached to draft",
description: "Sending is unavailable right now. Finish the current action, then send.",
}),
);
};
if (
!activeThread ||
isSendBusy ||
@@ -4587,28 +4570,19 @@ function ChatViewContent(props: ChatViewProps) {
threadDetailLoading ||
activeEnvironmentUnavailable ||
sendInFlightRef.current
) {
notifyDirectAnnotationAttached();
)
return;
}
if (activePendingProgress) {
if (directAnnotation) {
notifyDirectAnnotationAttached();
return;
}
onAdvanceActivePendingUserInput();
return;
}
const sendCtx = composerRef.current?.getSendContext();
if (!sendCtx?.providerAvailable) {
notifyDirectAnnotationAttached();
return;
}
if (!sendCtx?.providerAvailable) return;
const {
images: sendContextImages,
images: composerImages,
terminalContexts: composerTerminalContexts,
elementContexts: composerElementContexts,
previewAnnotations: sendContextPreviewAnnotations,
previewAnnotations: composerPreviewAnnotations,
reviewComments: composerReviewComments,
selectedProvider: ctxSelectedProvider,
selectedModel: ctxSelectedModel,
@@ -4616,26 +4590,6 @@ function ChatViewContent(props: ChatViewProps) {
selectedPromptEffort: ctxSelectedPromptEffort,
selectedModelSelection: ctxSelectedModelSelection,
} = sendCtx;
const composerImages =
directAnnotation?.image &&
!sendContextImages.some((image) => image.id === directAnnotation.image?.id)
? [...sendContextImages, directAnnotation.image]
: sendContextImages;
const composerPreviewAnnotations =
directAnnotation &&
!sendContextPreviewAnnotations.some(
(annotation) => annotation.id === directAnnotation.annotation.id,
)
? [
...sendContextPreviewAnnotations,
{
...directAnnotation.annotation,
screenshot: directAnnotation.annotation.screenshot
? { ...directAnnotation.annotation.screenshot, dataUrl: "" }
: null,
},
]
: sendContextPreviewAnnotations;
const promptForSend = promptRef.current;
const {
trimmedPrompt: trimmed,
@@ -4651,7 +4605,7 @@ function ChatViewContent(props: ChatViewProps) {
composerPreviewAnnotations.length +
composerReviewComments.length,
});
if (!directAnnotation && showPlanFollowUpPrompt && activeProposedPlan) {
if (showPlanFollowUpPrompt && activeProposedPlan) {
const followUp = resolvePlanFollowUpSubmission({
draftText: trimmed,
planMarkdown: activeProposedPlan.planMarkdown,
@@ -5694,14 +5648,7 @@ function ChatViewContent(props: ChatViewProps) {
/>
);
const panelLayoutControls = (
<div
className={cn(
"workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]",
rightPanelOpen && !shouldUsePlanSidebarSheet
? "right-2 wco:right-[var(--workspace-controls-right)]"
: "mr-px",
)}
>
<div className="workspace-titlebar-controls z-50 mr-px gap-1 [-webkit-app-region:no-drag]">
{rightPanelOpen && !shouldUsePlanSidebarSheet ? (
<RightPanelMaximizeControl
maximized={rightPanelMaximized}
@@ -5720,9 +5667,6 @@ function ChatViewContent(props: ChatViewProps) {
tabId={activeRightPanelSurface.resourceId}
configuredUrls={configuredPreviewUrls}
visible
onSendAnnotation={(annotation, image) => {
void onSend(undefined, { annotation, image });
}}
/>
</Suspense>
) : activeRightPanelSurface?.kind === "terminal" ? (
+14 -13
View File
@@ -138,20 +138,9 @@ import {
buildSidebarProjectPickerEntries,
buildSidebarProjectSnapshots,
} from "../sidebarProjectGrouping";
import type { Project } from "../types";
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
function projectFavicon(project: Project) {
return (
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
className={ITEM_ICON_CLASS}
/>
);
}
function getLocalFileManagerName(platform: string): string {
if (isMacPlatform(platform)) {
return "Finder";
@@ -935,7 +924,13 @@ function OpenCommandPaletteDialog(props: {
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
);
},
icon: projectFavicon,
icon: (project) => (
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
className={ITEM_ICON_CLASS}
/>
),
runProject: openProjectFromSearch,
}),
[openProjectFromSearch, pickerProjects, projectGroupByTargetKey],
@@ -953,7 +948,13 @@ function OpenCommandPaletteDialog(props: {
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
);
},
icon: projectFavicon,
icon: (project) => (
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
className={ITEM_ICON_CLASS}
/>
),
runProject: async (project) => {
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
const contextualRefBelongsToGroup =
@@ -1747,14 +1747,12 @@ function ComposerPromptEditorInner({
return (
<ComposerTerminalContextActionsContext value={terminalContextActions}>
<div className="composer-editor-surface relative">
<div className="relative">
<PlainTextPlugin
contentEditable={
<ContentEditable
className={cn(
// The size comes from .composer-editor-surface so Settings -> Appearance
// can drive it; keep everything else here.
"block max-h-50 min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap wrap-break-word bg-transparent leading-relaxed text-foreground focus:outline-none",
"block max-h-50 min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap wrap-break-word bg-transparent text-[16px] leading-relaxed text-foreground focus:outline-none sm:text-[14px]",
className,
)}
data-testid="composer-editor"
@@ -1765,7 +1763,7 @@ function ComposerPromptEditorInner({
}
placeholder={
terminalContexts.length > 0 ? null : (
<div className="pointer-events-none absolute inset-0 leading-relaxed text-muted-foreground/35">
<div className="pointer-events-none absolute inset-0 text-[16px] leading-relaxed text-muted-foreground/35 sm:text-[14px]">
{placeholder}
</div>
)
+40 -329
View File
@@ -1,5 +1,4 @@
import { useAtomValue } from "@effect/atom-react";
import type { FileDiffContentsLoader } from "@pierre/diffs";
import { useParams } from "@tanstack/react-router";
import {
isAtomCommandInterrupted,
@@ -16,7 +15,6 @@ import {
ChevronsUpDownIcon,
Columns2Icon,
PilcrowIcon,
RefreshCwIcon,
Rows3Icon,
SearchIcon,
TextWrapIcon,
@@ -69,7 +67,6 @@ import {
} from "./ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { useEnvironmentQuery } from "../state/query";
import { useAtomCommand } from "../state/use-atom-command";
import { serverEnvironment } from "../state/server";
import { reviewEnvironment } from "../state/review";
import { vcsEnvironment } from "../state/vcs";
@@ -94,9 +91,9 @@ const DIFF_PANEL_UNSAFE_CSS = `
[data-virtualizer-buffer] {
--diffs-header-font-family: var(--font-sans) !important;
--diffs-font-family: var(--font-mono) !important;
--diffs-bg: var(--background) !important;
--diffs-light-bg: var(--background) !important;
--diffs-dark-bg: var(--background) !important;
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
--diffs-token-light-bg: transparent;
--diffs-token-dark-bg: transparent;
@@ -105,25 +102,13 @@ const DIFF_PANEL_UNSAFE_CSS = `
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
--diffs-bg-addition-override: light-dark(
color-mix(in srgb, var(--background) 50%, var(--success)),
color-mix(in srgb, var(--background) 70%, var(--success))
);
--diffs-bg-addition-number-override: light-dark(
color-mix(in srgb, var(--background) 35%, var(--success)),
color-mix(in srgb, var(--background) 60%, var(--success))
);
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
--diffs-bg-deletion-override: light-dark(
color-mix(in srgb, var(--background) 50%, var(--destructive)),
color-mix(in srgb, var(--background) 70%, var(--destructive))
);
--diffs-bg-deletion-number-override: light-dark(
color-mix(in srgb, var(--background) 35%, var(--destructive)),
color-mix(in srgb, var(--background) 60%, var(--destructive))
);
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
--diffs-bg-deletion-emphasis-override: color-mix(
in srgb,
@@ -134,66 +119,9 @@ const DIFF_PANEL_UNSAFE_CSS = `
background-color: var(--diffs-bg) !important;
}
:is(
[data-line],
[data-line-annotation],
[data-merge-conflict],
[data-merge-conflict-actions],
[data-no-newline]
)[data-selected-line] {
--diffs-line-bg: light-dark(
color-mix(
in lab,
var(--background) 88%,
color-mix(in srgb, var(--background) 50%, var(--diffs-modified-base))
),
color-mix(
in lab,
var(--background) 80%,
color-mix(in srgb, var(--background) 70%, var(--diffs-modified-base))
)
) !important;
}
:is([data-gutter-buffer], [data-column-number])[data-selected-line] {
--diffs-line-bg: light-dark(
color-mix(
in lab,
var(--background) 91%,
color-mix(in srgb, var(--background) 35%, var(--diffs-modified-base))
),
color-mix(
in lab,
var(--background) 85%,
color-mix(in srgb, var(--background) 60%, var(--diffs-modified-base))
)
) !important;
}
[data-indicators="bars"]
:is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line] {
position: relative;
}
[data-indicators="bars"]
:is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line]::before {
position: absolute !important;
inset-block: 0 !important;
inset-inline-start: 0 !important;
display: block !important;
width: 4px !important;
min-width: 4px !important;
max-width: 4px !important;
height: auto !important;
padding: 0 !important;
content: "" !important;
background-color: var(--diffs-modified-base) !important;
background-image: none !important;
}
[data-file-info] {
background-color: var(--background) !important;
border-block-color: transparent !important;
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
border-block-color: var(--border) !important;
color: var(--foreground) !important;
}
@@ -201,103 +129,14 @@ const DIFF_PANEL_UNSAFE_CSS = `
position: sticky !important;
top: 0;
z-index: 4;
background-color: var(--background) !important;
border-bottom-color: transparent !important;
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
border-bottom: 1px solid var(--border) !important;
align-items: center !important;
font-family: var(--font-sans) !important;
font-size: 12px !important;
line-height: 1 !important;
min-height: 32px !important;
padding-block: 6px !important;
padding-inline: 8px 12px !important;
}
[data-diffs-header]:hover {
background-color: color-mix(in srgb, var(--background) 97%, var(--foreground)) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]) {
height: 24px !important;
margin-block: 0 !important;
background-color: var(--background) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-separator-wrapper] {
padding-inline: 8px 12px !important;
background-color: transparent !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-separator-content] {
gap: 8px;
padding-inline: 0 !important;
background-color: transparent !important;
color: color-mix(in srgb, var(--foreground) 52%, var(--background)) !important;
font-family: var(--font-sans) !important;
font-size: 11px !important;
text-decoration: none !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-unmodified-lines] {
display: flex !important;
min-width: 0;
flex: 1 1 auto;
align-items: center;
gap: 8px;
cursor: pointer;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-unmodified-lines]::before,
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-unmodified-lines]::after {
width: auto;
height: 1px;
flex: 1 1 auto;
content: "";
background-color: color-mix(in srgb, var(--background) 92%, var(--foreground));
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
[data-separator-wrapper] {
grid-template-columns: 0 minmax(0, 1fr) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
[data-separator-content] {
grid-column: 2 !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-expand-button] {
display: none !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
)
[data-separator-content] {
cursor: pointer;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
):hover
[data-separator-content] {
color: color-mix(in srgb, var(--foreground) 76%, var(--background)) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
):hover
[data-unmodified-lines]::before,
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
):hover
[data-unmodified-lines]::after {
background-color: color-mix(in srgb, var(--background) 84%, var(--foreground));
}
[data-diffs-header] [data-header-content] {
@@ -366,12 +205,7 @@ export default function DiffPanel({
scopeKey: null,
fileKeys: EMPTY_COLLAPSED_DIFF_FILE_KEYS,
}));
const [codeViewRevision, setCodeViewRevision] = useState(0);
const codeViewRef = useRef<AnnotatableCodeViewHandle>(null);
const lastCompletedTurnRefreshRef = useRef<{
readonly threadKey: string | null;
readonly turnId: TurnId | null;
} | null>(null);
const routeThreadRef = useParams({
strict: false,
@@ -396,7 +230,6 @@ export default function DiffPanel({
activeThread?.environmentId ?? null,
serverConfig?.availableEditors ?? [],
);
const getDiffFileContents = useAtomCommand(reviewEnvironment.diffFileContents);
const gitStatusQuery = useEnvironmentQuery(
activeThread !== null && activeThread !== undefined && activeCwd != null
? vcsEnvironment.status({
@@ -465,7 +298,6 @@ export default function DiffPanel({
const collapseScopeKey = routeThreadRef
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
: null;
const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;
const collapsedDiffFileKeys =
collapsedDiffFiles.scopeKey === collapseScopeKey
? collapsedDiffFiles.fileKeys
@@ -528,93 +360,9 @@ export default function DiffPanel({
const branchDiffPreview = shouldRetryBranchDiffAtEnvironmentCwd
? fallbackBranchDiffPreview
: primaryBranchDiffPreview;
const refreshBranchDiffPreview = branchDiffPreview.refresh;
const canRefreshGitDiff =
isGitRepo && selectedTurnId === null && activeThread != null && activeCwd != null;
const activeThreadRefreshKey = routeThreadRef
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
: null;
useEffect(() => {
if (!canRefreshGitDiff) return;
const refreshOnFocus = () => refreshBranchDiffPreview();
window.addEventListener("focus", refreshOnFocus);
return () => window.removeEventListener("focus", refreshOnFocus);
}, [canRefreshGitDiff, refreshBranchDiffPreview]);
useEffect(() => {
const current = {
threadKey: activeThreadRefreshKey,
turnId: latestTurn?.turnId ?? null,
};
const previous = lastCompletedTurnRefreshRef.current;
if (!canRefreshGitDiff) {
return;
}
if (previous === null || previous.threadKey !== current.threadKey) {
lastCompletedTurnRefreshRef.current = current;
return;
}
if (previous.turnId === current.turnId) return;
refreshBranchDiffPreview();
lastCompletedTurnRefreshRef.current = current;
}, [activeThreadRefreshKey, canRefreshGitDiff, latestTurn?.turnId, refreshBranchDiffPreview]);
const selectedGitSource = branchDiffPreview.data?.sources.find(
(source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"),
);
const loadDiffFiles = useMemo<FileDiffContentsLoader | undefined>(() => {
const preview = branchDiffPreview.data;
if (selectedTurnId !== null || !activeThread || !preview || !selectedGitSource) {
return undefined;
}
const source = selectedGitSource;
return async (fileDiff) => {
const newPath = resolveFileDiffPath(fileDiff);
const oldPath = fileDiff.prevName
? resolveFileDiffPath({ ...fileDiff, name: fileDiff.prevName })
: newPath;
const result = await getDiffFileContents({
environmentId: activeThread.environmentId,
input: {
cwd: preview.cwd,
sourceKind: source.kind,
changeType: fileDiff.type,
baseRef: source.baseRef,
headRef: source.headRef,
oldPath,
newPath,
},
});
if (result._tag !== "Success") {
throw squashAtomCommandFailure(result);
}
const newFile = {
name: newPath,
contents: result.value.newContents,
cacheKey: `${source.diffHash}:new:${newPath}`,
};
if (fileDiff.type === "rename-pure") {
return { oldFile: null, newFile };
}
return {
oldFile: {
name: oldPath,
contents: result.value.oldContents,
cacheKey: `${source.diffHash}:old:${oldPath}`,
},
newFile,
};
};
}, [
activeThread,
branchDiffPreview.data,
getDiffFileContents,
selectedGitSource,
selectedTurnId,
]);
const localBranchRefs = useEnvironmentQuery(
selectedTurnId === null &&
selectedGitScope === "branch" &&
@@ -691,17 +439,10 @@ export default function DiffPanel({
}),
);
}, [renderablePatch]);
const renderableFileEntries = useMemo(
() =>
renderableFiles.map((fileDiff) => ({
fileDiff,
fileKey: buildFileDiffRenderKey(fileDiff),
})),
[renderableFiles],
);
const codeViewFiles = useMemo(
() =>
renderableFileEntries.map(({ fileDiff, fileKey }) => {
renderableFiles.map((fileDiff) => {
const fileKey = buildFileDiffRenderKey(fileDiff);
return {
fileDiff,
filePath: resolveFileDiffPath(fileDiff),
@@ -709,19 +450,18 @@ export default function DiffPanel({
collapsed: collapsedDiffFileKeys.has(fileKey),
};
}),
[collapsedDiffFileKeys, renderableFileEntries],
[collapsedDiffFileKeys, renderableFiles],
);
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
const diffLineStat = useMemo(() => getDiffLineStat(renderableFiles), [renderableFiles]);
const selectedDiffFileKey = selectedFilePath
? (codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath)?.fileKey ?? null)
: null;
useEffect(() => {
if (!selectedDiffFileKey) return;
codeViewRef.current?.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });
}, [codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);
if (!selectedFilePath) return;
const file = codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath);
if (!file) return;
codeViewRef.current?.scrollTo({ type: "item", id: file.fileKey, align: "start" });
}, [codeViewFiles, selectedFilePath, selectedFileRevealRequestId]);
const openDiffFile = useCallback(
(filePath: string) => {
@@ -766,7 +506,6 @@ export default function DiffPanel({
);
const toggleDiffFileCollapse = useCallback(() => {
setCodeViewRevision((current) => current + 1);
setCollapsedDiffFiles((current) => {
const currentKeys =
current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
@@ -985,45 +724,23 @@ export default function DiffPanel({
layout="inline"
/>
)}
{canRefreshGitDiff && (
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-sm"
variant="ghost"
aria-label={branchDiffPreview.isPending ? "Refreshing diff" : "Refresh diff"}
onClick={refreshBranchDiffPreview}
/>
}
>
<RefreshCwIcon
className={cn("size-3.5", branchDiffPreview.isPending && "animate-spin")}
/>
</TooltipTrigger>
<TooltipPopup side="top">
{branchDiffPreview.isPending ? "Refreshing diff…" : "Refresh diff"}
</TooltipPopup>
</Tooltip>
)}
{codeViewFiles.length > 0 && (
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-sm"
variant="ghost"
size="icon-xs"
variant="outline"
aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
onClick={toggleDiffFileCollapse}
/>
}
>
{allDiffFilesCollapsed ? (
<ChevronsUpDownIcon className="size-3.5" />
<ChevronsUpDownIcon className="size-3" />
) : (
<ChevronsDownUpIcon className="size-3.5" />
<ChevronsDownUpIcon className="size-3" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
@@ -1032,8 +749,9 @@ export default function DiffPanel({
</Tooltip>
)}
<ToggleGroup
className="shrink-0 gap-1"
size="sm"
className="shrink-0"
variant="outline"
size="xs"
value={[diffRenderMode]}
onValueChange={(value) => {
const next = value[0];
@@ -1042,11 +760,11 @@ export default function DiffPanel({
}
}}
>
<Toggle aria-label="Stacked diff view" value="stacked" variant="ghost">
<Rows3Icon className="size-3.5" />
<Toggle aria-label="Stacked diff view" value="stacked">
<Rows3Icon className="size-3" />
</Toggle>
<Toggle aria-label="Split diff view" value="split" variant="ghost">
<Columns2Icon className="size-3.5" />
<Toggle aria-label="Split diff view" value="split">
<Columns2Icon className="size-3" />
</Toggle>
</ToggleGroup>
<Tooltip>
@@ -1054,8 +772,8 @@ export default function DiffPanel({
render={
<Toggle
aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
variant="ghost"
size="sm"
variant="outline"
size="xs"
pressed={wordWrap}
onPressedChange={(pressed) => {
setWordWrap(Boolean(pressed));
@@ -1063,7 +781,7 @@ export default function DiffPanel({
/>
}
>
<TextWrapIcon className="size-3.5" />
<TextWrapIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">
{wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
@@ -1076,8 +794,8 @@ export default function DiffPanel({
aria-label={
diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
}
variant="ghost"
size="sm"
variant="outline"
size="xs"
pressed={diffIgnoreWhitespace}
onPressedChange={(pressed) => {
setDiffIgnoreWhitespace(Boolean(pressed));
@@ -1085,7 +803,7 @@ export default function DiffPanel({
/>
}
>
<PilcrowIcon className="size-3.5" />
<PilcrowIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">
{diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
@@ -1157,9 +875,8 @@ export default function DiffPanel({
}}
>
<AnnotatableCodeView
key={collapseScopeKey ?? reviewSectionId}
viewerRef={codeViewRef}
codeViewKey={codeViewMountKey}
key={collapseScopeKey ?? reviewSectionId}
className="diff-render-surface h-full min-h-0 overflow-auto"
files={codeViewFiles}
sectionId={reviewSectionId}
@@ -1174,7 +891,7 @@ export default function DiffPanel({
<button
type="button"
className={cn(
"-ms-0.5 inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
getDiffCollapseIconClassName(fileDiff),
)}
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
@@ -1206,14 +923,8 @@ export default function DiffPanel({
themeType: resolvedTheme as DiffThemeType,
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
stickyHeaders: true,
...(loadDiffFiles ? { loadDiffFiles } : {}),
itemMetrics: {
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
paddingTop: 0,
paddingBottom: 0,
},
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
itemMetrics: { diffHeaderHeight: 33 },
layout: { paddingTop: 0, paddingBottom: 8, gap: 8 },
}}
/>
</div>
+22 -46
View File
@@ -10,8 +10,7 @@ export type DiffPanelMode = "inline" | "sheet" | "sidebar" | "embedded";
function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) {
const shouldUseDragRegion = isElectron && mode !== "sheet" && mode !== "embedded";
return cn(
"flex items-center justify-between gap-2",
mode === "embedded" ? "px-2" : "px-4",
"flex items-center justify-between gap-2 px-4",
shouldUseDragRegion
? "drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]"
: "surface-subheader",
@@ -60,53 +59,30 @@ export function DiffPanelHeaderSkeleton() {
);
}
function DiffFileHeaderSkeleton({ titleClassName }: { titleClassName: string }) {
return (
<div className="flex h-8 items-center gap-2 px-2 pr-3">
<div className="flex size-5 shrink-0 items-center justify-center">
<Skeleton className="size-2.5 rounded-[2px]" />
</div>
<Skeleton className="size-5 shrink-0 rounded-md" />
<Skeleton className={cn("h-3 rounded-full", titleClassName)} />
<div className="ml-auto flex shrink-0 items-center gap-2">
<Skeleton className="h-3 w-5 rounded-full" />
<Skeleton className="h-3 w-5 rounded-full" />
</div>
</div>
);
}
function DiffCodeLineSkeleton({ contentClassName }: { contentClassName: string }) {
return (
<div className="flex items-center gap-3">
<Skeleton className="h-2.5 w-5 shrink-0 rounded-full" />
<Skeleton className={cn("h-2.5 rounded-full", contentClassName)} />
</div>
);
}
export function DiffPanelLoadingState(props: { label: string }) {
return (
<div
className="min-h-0 flex-1 overflow-hidden bg-background"
role="status"
aria-live="polite"
aria-label={props.label}
>
<DiffFileHeaderSkeleton titleClassName="w-1/2 max-w-64" />
<div className="flex h-6 items-center gap-2 px-2 pr-3">
<div className="h-px flex-1 bg-border/40" />
<Skeleton className="h-2.5 w-24 rounded-full" />
<div className="h-px flex-1 bg-border/40" />
<div className="flex min-h-0 flex-1 flex-col p-2">
<div
className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/60 bg-card/25"
role="status"
aria-live="polite"
aria-label={props.label}
>
<div className="flex items-center gap-2 border-b border-border/50 px-3 py-2">
<Skeleton className="h-4 w-32 rounded-full" />
<Skeleton className="ml-auto h-4 w-20 rounded-full" />
</div>
<div className="flex min-h-0 flex-1 flex-col gap-4 px-3 py-4">
<div className="space-y-2">
<Skeleton className="h-3 w-full rounded-full" />
<Skeleton className="h-3 w-full rounded-full" />
<Skeleton className="h-3 w-10/12 rounded-full" />
<Skeleton className="h-3 w-11/12 rounded-full" />
<Skeleton className="h-3 w-9/12 rounded-full" />
</div>
<span className="sr-only">{props.label}</span>
</div>
</div>
<div className="space-y-2 px-3 py-2">
<DiffCodeLineSkeleton contentClassName="w-2/3" />
<DiffCodeLineSkeleton contentClassName="w-4/5" />
<DiffCodeLineSkeleton contentClassName="w-3/5" />
</div>
<DiffFileHeaderSkeleton titleClassName="w-2/5 max-w-52" />
<DiffFileHeaderSkeleton titleClassName="w-3/5 max-w-72" />
<span className="sr-only">{props.label}</span>
</div>
);
}
+39 -34
View File
@@ -221,14 +221,14 @@ function surfaceTitle(
function PreviewFavicon({ url }: { url: string | null }) {
const faviconUrl = faviconUrlForOrigin(url, 32);
const [failedUrl, setFailedUrl] = useState<string | null>(null);
if (!faviconUrl || failedUrl === faviconUrl) return <Globe2 className="size-3 shrink-0" />;
if (!faviconUrl || failedUrl === faviconUrl) return <Globe2 className="size-3.5 shrink-0" />;
return (
<img
src={faviconUrl}
alt=""
aria-hidden
draggable={false}
className="size-3 shrink-0 rounded-sm"
className="size-3.5 shrink-0 rounded-sm"
onError={() => setFailedUrl(faviconUrl)}
/>
);
@@ -250,22 +250,22 @@ function SurfaceIcon({
return <PreviewFavicon url={url} />;
}
case "diff":
return <FileDiff className="size-3 shrink-0" />;
return <FileDiff className="size-3.5 shrink-0" />;
case "files":
return <Files className="size-3 shrink-0" />;
return <Files className="size-3.5 shrink-0" />;
case "file":
return (
<PierreEntryIcon
pathValue={surface.relativePath}
kind="file"
theme={theme}
className="size-3"
className="size-3.5"
/>
);
case "terminal":
return <TerminalSquare className="size-3 shrink-0" />;
return <TerminalSquare className="size-3.5 shrink-0" />;
case "plan":
return <ClipboardList className="size-3 shrink-0" />;
return <ClipboardList className="size-3.5 shrink-0" />;
}
}
@@ -358,7 +358,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<div
className={cn(
"workspace-topbar gap-1 pl-2",
props.mode !== "inline" && "[--workspace-topbar-height:--spacing(11)]",
!ownsDesktopTitleBar && "[--workspace-topbar-height:--spacing(11)]",
props.mode === "inline" ? "pr-28" : "pr-3",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
@@ -385,57 +385,62 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
onAuxClick={(event) => handleTabAuxClick(event, surface)}
onContextMenu={(event) => void handleTabContextMenu(event, surface)}
className={cn(
"group/tab flex h-6 max-w-36 shrink-0 items-center gap-0.5 rounded-md pr-2 pl-1.5 text-xs",
"group flex h-7 min-w-25 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm",
active
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
)}
>
<button
type="button"
className="group/close relative flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
aria-label={`Close ${title}`}
onClick={() => props.onCloseSurface(surface)}
>
<span className="relative flex size-3 items-center justify-center group-hover/tab:hidden group-focus-visible/close:hidden">
<SurfaceIcon
surface={surface}
sessions={props.previewSessions}
theme={resolvedTheme}
/>
{pending ? (
<span
className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
aria-hidden
/>
) : null}
</span>
<X className="hidden size-3 group-hover/tab:block group-focus-visible/close:block" />
</button>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className="flex min-w-0 items-center"
className="flex min-w-0 flex-1 items-center gap-1.5"
onClick={() => props.onActivate(surface)}
>
<SurfaceIcon
surface={surface}
sessions={props.previewSessions}
theme={resolvedTheme}
/>
<span className="truncate">{title}</span>
</button>
}
/>
<TooltipPopup>{title}</TooltipPopup>
</Tooltip>
<button
type="button"
className={cn(
"relative flex size-4 shrink-0 items-center justify-center rounded hover:bg-muted focus:opacity-100",
pending ? "opacity-100" : "opacity-0 group-hover:opacity-100",
)}
aria-label={`Close ${title}`}
onClick={() => props.onCloseSurface(surface)}
>
{pending ? (
<>
<span
className="size-2 rounded-full bg-current group-hover:hidden"
aria-hidden
/>
<X className="hidden size-3 group-hover:block" />
</>
) : (
<X className="size-3" />
)}
</button>
</div>
);
})}
{props.surfaces.length > 0 ? (
<Menu>
<MenuTrigger
className="relative inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
className="relative inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
aria-label="Add panel surface"
>
<Plus className="size-3.5" />
<Plus className="size-4" />
</MenuTrigger>
<MenuPopup align="start" side="bottom" sideOffset={6} className="min-w-44">
<SurfaceMenuItem
@@ -473,7 +478,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
</ScrollArea>
{props.layoutControls}
</div>
<div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
<div className="flex min-h-0 flex-1 flex-col">
{props.activeSurfaceId === null ? (
<RightPanelEmptyState
onAddBrowser={props.onAddBrowser}
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more