Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bcebb793b0 | ||
|
|
0dd887c3e9 | ||
|
|
6f07f6853b | ||
|
|
fc3a695383 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
description: Launch, retain, and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, cross-turn dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, iteratively test UI behavior with a human, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
---
|
||||
|
||||
# Test T3 App
|
||||
@@ -20,16 +20,6 @@ Treat a base directory as disposable only when it was created or deliberately se
|
||||
|
||||
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
|
||||
|
||||
## Preserve the environment while iterating
|
||||
|
||||
Treat the overall testing or implementation loop—not an assistant turn or one verification pass—as the environment lifecycle boundary.
|
||||
|
||||
- Keep the dev process, base directory, selected ports, authenticated browser tab, registered projects, and seeded fixtures alive while the user may inspect the result or request follow-up changes.
|
||||
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
|
||||
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
|
||||
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
|
||||
@@ -68,17 +58,9 @@ Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before chang
|
||||
|
||||
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
|
||||
|
||||
## Tear down only when the testing loop is finished
|
||||
## Finish the test
|
||||
|
||||
Tear down when the user explicitly asks, confirms the iteration is finished, or the overall task is genuinely complete with no pending human review. Do not infer completion from the end of an assistant turn.
|
||||
|
||||
When teardown is appropriate:
|
||||
|
||||
1. Stop the dev process with its terminal interrupt.
|
||||
2. Preserve the isolated base directory when it contains useful reproduction evidence or state for a likely follow-up.
|
||||
3. Otherwise remove only a path created for this test after resolving and verifying the exact target.
|
||||
|
||||
If completion is uncertain, keep the environment alive and mention that it is retained for further iteration. A fresh isolated base directory remains the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
|
||||
## Troubleshoot predictably
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
interface:
|
||||
display_name: "T3 App Testing"
|
||||
short_description: "Launch and retain isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 environment and iteratively test it in the browser while preserving state."
|
||||
short_description: "Launch and seed isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
|
||||
@@ -50,7 +50,6 @@ export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
|
||||
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
|
||||
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
|
||||
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
|
||||
export const PREVIEW_SET_COLOR_SCHEME_CHANNEL = "desktop:preview-set-color-scheme";
|
||||
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
|
||||
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
|
||||
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
DesktopPreviewRecordingSaveInputSchema,
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
@@ -139,15 +138,6 @@ export const hardReload = tabMethod(
|
||||
"desktop.ipc.preview.hardReload",
|
||||
(manager, tabId) => manager.hardReload(tabId),
|
||||
);
|
||||
export const setColorScheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL,
|
||||
payload: DesktopPreviewSetColorSchemeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.setColorScheme")(function* ({ tabId, colorScheme }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.setColorScheme(tabId, colorScheme);
|
||||
}),
|
||||
});
|
||||
export const openDevTools = tabMethod(
|
||||
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
|
||||
"desktop.ipc.preview.openDevTools",
|
||||
@@ -356,7 +346,6 @@ export const methods = [
|
||||
zoomOut,
|
||||
resetZoom,
|
||||
hardReload,
|
||||
setColorScheme,
|
||||
openDevTools,
|
||||
clearCookies,
|
||||
clearCache,
|
||||
|
||||
@@ -160,8 +160,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }),
|
||||
resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }),
|
||||
hardReload: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, { tabId }),
|
||||
setColorScheme: (tabId, colorScheme) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, { tabId, colorScheme }),
|
||||
openDevTools: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
|
||||
clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
|
||||
|
||||
@@ -365,79 +365,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("emulates prefers-color-scheme and re-applies it across webview swaps", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const makeWebContents = (id: number) => {
|
||||
const sendCommand = vi.fn(async () => undefined);
|
||||
return {
|
||||
sendCommand,
|
||||
wc: {
|
||||
id,
|
||||
isDestroyed: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never,
|
||||
};
|
||||
};
|
||||
const first = makeWebContents(42);
|
||||
fromId.mockReturnValue(first.wc);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_scheme");
|
||||
yield* manager.registerWebview("tab_scheme", 42);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* manager.setColorScheme("tab_scheme", "dark");
|
||||
|
||||
expect(first.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "dark" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("dark");
|
||||
|
||||
const replacement = makeWebContents(43);
|
||||
fromId.mockReturnValue(replacement.wc);
|
||||
yield* manager.registerWebview("tab_scheme", 43);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "dark" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("dark");
|
||||
|
||||
yield* manager.setColorScheme("tab_scheme", "system");
|
||||
|
||||
expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("system");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
*/
|
||||
import type {
|
||||
DesktopPreviewAnnotationTheme,
|
||||
DesktopPreviewColorScheme,
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
@@ -85,7 +84,6 @@ export interface PreviewTabState {
|
||||
canGoBack: boolean;
|
||||
canGoForward: boolean;
|
||||
zoomFactor: number;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -1290,7 +1288,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1323,7 +1320,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1390,7 +1386,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(restoreControlSession(tabId, wc));
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
const registeredAt = yield* currentIso;
|
||||
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
@@ -1461,7 +1457,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: current?.canGoBack ?? false,
|
||||
canGoForward: current?.canGoForward ?? false,
|
||||
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: current?.colorScheme ?? "system",
|
||||
controller: current?.controller ?? "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1530,7 +1525,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* detachControlSession(wc.id);
|
||||
yield* attempt({ operation: "openDevTools", tabId, webContentsId: wc.id }, () => {
|
||||
wc.once("devtools-closed", () => {
|
||||
if (!wc.isDestroyed()) runFork(restoreControlSession(tabId, wc));
|
||||
if (!wc.isDestroyed()) runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
});
|
||||
wc.openDevTools({ mode: "detach" });
|
||||
});
|
||||
@@ -1689,65 +1684,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* update(tabId, { zoomFactor: next });
|
||||
});
|
||||
|
||||
// Emulated media lives on the CDP debugger session, not the WebContents, so
|
||||
// it is lost whenever the session detaches (webview swap, DevTools
|
||||
// open/close) and must be re-applied after every (re)attach.
|
||||
const applyColorScheme = Effect.fn("PreviewManager.applyColorScheme")(function* (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) {
|
||||
yield* ensureControlSession(wc);
|
||||
yield* attemptPromise({ operation: "applyColorScheme", tabId, webContentsId: wc.id }, () =>
|
||||
wc.debugger.sendCommand("Emulation.setEmulatedMedia", {
|
||||
features: [
|
||||
{
|
||||
name: "prefers-color-scheme",
|
||||
// An empty value clears the override so the page follows the OS.
|
||||
value: colorScheme === "system" ? "" : colorScheme,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Re-establish the control session after a detach, restoring any
|
||||
// color-scheme override the tab carries. The scheme is read after the
|
||||
// session attaches so a concurrent setColorScheme is not overwritten with
|
||||
// a stale snapshot.
|
||||
const restoreControlSession = (tabId: string, wc: Electron.WebContents) =>
|
||||
ensureControlSession(wc).pipe(
|
||||
Effect.andThen(SynchronizedRef.get(tabsRef)),
|
||||
Effect.flatMap((tabs) => {
|
||||
const colorScheme = tabs.get(tabId)?.colorScheme ?? "system";
|
||||
return colorScheme === "system" ? Effect.void : applyColorScheme(tabId, wc, colorScheme);
|
||||
}),
|
||||
Effect.ignore,
|
||||
);
|
||||
|
||||
const setColorScheme = Effect.fn("PreviewManager.setColorScheme")(function* (
|
||||
tabId: string,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) {
|
||||
const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
if (!tab) {
|
||||
return yield* new PreviewTabNotFoundError({ tabId });
|
||||
}
|
||||
if (tab.colorScheme !== colorScheme) {
|
||||
// Record the choice even when the CDP call below can't run yet (no
|
||||
// webview, DevTools holding the debugger) — it is re-applied on the
|
||||
// next control-session (re)attach.
|
||||
yield* update(tabId, { colorScheme });
|
||||
}
|
||||
// Re-read after the update: registerWebview may have swapped the guest
|
||||
// in the meantime and the override must land on the current one.
|
||||
const webContentsId = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.webContentsId;
|
||||
if (webContentsId == null) return;
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
if (!wc || wc.isDestroyed()) return;
|
||||
yield* applyColorScheme(tabId, wc, colorScheme);
|
||||
});
|
||||
|
||||
const captureScreenshot = Effect.fn("PreviewManager.captureScreenshot")(function* (
|
||||
tabId: string,
|
||||
) {
|
||||
@@ -2590,7 +2526,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
revealArtifact,
|
||||
saveRecording,
|
||||
setAnnotationTheme,
|
||||
setColorScheme,
|
||||
setMainWindow,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
@@ -2895,10 +2830,6 @@ export class PreviewManager extends Context.Service<
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly setColorScheme: (
|
||||
tabId: string,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
@@ -2990,7 +2921,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
zoomOut: operations.zoomOut,
|
||||
resetZoom: operations.resetZoom,
|
||||
hardReload: operations.hardReload,
|
||||
setColorScheme: operations.setColorScheme,
|
||||
openDevTools: operations.openDevTools,
|
||||
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* () {
|
||||
yield* browserSession
|
||||
|
||||
@@ -385,6 +385,10 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
title="Thread list options"
|
||||
separateBackground
|
||||
>
|
||||
<NativeHeaderToolbar.MenuAction onPress={props.onOpenSettings}>
|
||||
<NativeHeaderToolbar.Label>Settings</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Environment">
|
||||
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -15,7 +16,6 @@ import { AndroidHomeFabLayout } from "./AndroidHomeFab";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
import { useHomeListOptions } from "./home-list-options";
|
||||
import { buildHomeProjectScopes } from "./homeThreadList";
|
||||
import { usePendingTaskListActions } from "./usePendingTaskListActions";
|
||||
import { useThreadListActions } from "./useThreadListActions";
|
||||
|
||||
@@ -61,15 +61,16 @@ export function HomeRouteScreen() {
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: selectedEnvironmentId,
|
||||
projectGroupingMode: listOptions.projectGroupingMode,
|
||||
}).map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[listOptions.projectGroupingMode, projects, selectedEnvironmentId],
|
||||
projects
|
||||
.filter(
|
||||
(project) =>
|
||||
selectedEnvironmentId === null || project.environmentId === selectedEnvironmentId,
|
||||
)
|
||||
.map((project) => ({
|
||||
key: scopedProjectKey(project.environmentId, project.id),
|
||||
label: project.title,
|
||||
})),
|
||||
[projects, selectedEnvironmentId],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
|
||||
@@ -245,69 +245,43 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects: props.projects,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
|
||||
);
|
||||
const selectedProjectScope = useMemo(
|
||||
const scopedProject = useMemo(
|
||||
() =>
|
||||
props.selectedProjectKey === null
|
||||
? null
|
||||
: (projectScopes.find(
|
||||
(scope) =>
|
||||
scope.key === props.selectedProjectKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
props.selectedProjectKey,
|
||||
),
|
||||
: (props.projects.find(
|
||||
(project) =>
|
||||
scopedProjectKey(project.environmentId, project.id) === props.selectedProjectKey &&
|
||||
(props.selectedEnvironmentId === null ||
|
||||
project.environmentId === props.selectedEnvironmentId),
|
||||
) ?? null),
|
||||
[projectScopes, props.selectedProjectKey],
|
||||
);
|
||||
const selectedProjectRefKeys = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
[props.projects, props.selectedEnvironmentId, props.selectedProjectKey],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.projects
|
||||
: props.projects.filter((project) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[props.projects, selectedProjectRefKeys],
|
||||
() => (scopedProject === null ? props.projects : [scopedProject]),
|
||||
[props.projects, scopedProject],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
scopedProject === null
|
||||
? props.threads
|
||||
: props.threads.filter((thread) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
: props.threads.filter(
|
||||
(thread) =>
|
||||
thread.environmentId === scopedProject.environmentId &&
|
||||
thread.projectId === scopedProject.id,
|
||||
),
|
||||
[props.threads, selectedProjectRefKeys],
|
||||
[props.threads, scopedProject],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
scopedProject === null
|
||||
? props.pendingTasks
|
||||
: props.pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
: props.pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
pendingTask.message.environmentId === scopedProject.environmentId &&
|
||||
pendingTask.creation.projectId === scopedProject.id,
|
||||
),
|
||||
[props.pendingTasks, selectedProjectRefKeys],
|
||||
[props.pendingTasks, scopedProject],
|
||||
);
|
||||
|
||||
const projectGroups = useMemo(
|
||||
@@ -365,18 +339,22 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const v2ScopeProjects = useMemo(
|
||||
() =>
|
||||
sortHomeProjectScopes({
|
||||
scopes: projectScopes,
|
||||
scopes: buildHomeProjectScopes({
|
||||
projects: props.projects,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projectGroupingMode,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
projectScopes,
|
||||
],
|
||||
);
|
||||
const v2ScopedProjectGroup = useMemo(
|
||||
@@ -394,21 +372,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
) ?? null),
|
||||
[v2ProjectScopeKey, v2ScopeProjects],
|
||||
);
|
||||
const v2ProjectTitleByProjectKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
v2ScopeProjects.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.title,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
[v2ScopeProjects],
|
||||
);
|
||||
const v2ScopedProjectKeys = useMemo(
|
||||
() =>
|
||||
v2ScopedProjectGroup === null
|
||||
@@ -472,10 +435,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -497,18 +456,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
@@ -518,38 +467,20 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProjectGroup,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
@@ -562,9 +493,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
projectTitle={v2ProjectTitleByProjectKey.get(
|
||||
scopedProjectKey(item.thread.environmentId, item.thread.projectId),
|
||||
)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(item.thread.environmentId)
|
||||
@@ -608,7 +536,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
@@ -828,9 +755,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : selectedProjectScope !== null ? (
|
||||
) : scopedProject !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedProjectScope.title}`}
|
||||
title={`No threads in ${scopedProject.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : selectedEnvironmentLabel ? (
|
||||
@@ -845,31 +772,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. Snoozed threads outrank the rest: "No
|
||||
// threads yet" over an inbox that is merely all-snoozed reads as data
|
||||
// loss. Pending tasks render in the header, so the list showing them
|
||||
// isn't empty in the user's eyes.
|
||||
const v2SnoozedCount = threadListV2Layout.snoozedCount;
|
||||
// fact when a query is active. Pending tasks render in the header, so the
|
||||
// list showing them isn't empty in the user's eyes.
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={
|
||||
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
|
||||
}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
|
||||
@@ -24,7 +24,6 @@ describe("buildHomeListFilterMenu", () => {
|
||||
const projectMenu = menu.items.find(
|
||||
(item) => item.type === "submenu" && item.title === "Project",
|
||||
);
|
||||
expect(menu.items.some((item) => item.title === "Settings")).toBe(false);
|
||||
expect(projectMenu).toMatchObject({
|
||||
type: "submenu",
|
||||
items: [
|
||||
|
||||
@@ -43,6 +43,7 @@ export function buildHomeListFilterMenu(props: {
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onOpenSettings?: () => void;
|
||||
/** False hides the sort/group submenus. Thread List v2 uses a fixed
|
||||
creation-order layout, so offering those controls while it silently
|
||||
ignores them would be a lie; the environment filter still applies. */
|
||||
@@ -50,6 +51,14 @@ export function buildHomeListFilterMenu(props: {
|
||||
}): HomeListFilterMenu {
|
||||
const items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu> = [];
|
||||
|
||||
if (props.onOpenSettings) {
|
||||
items.push({
|
||||
type: "action",
|
||||
title: "Settings",
|
||||
onPress: props.onOpenSettings,
|
||||
});
|
||||
}
|
||||
|
||||
items.push({
|
||||
type: "submenu",
|
||||
title: "Environment",
|
||||
|
||||
@@ -104,7 +104,6 @@ describe("buildHomeThreadGroups", () => {
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.title).toBe("t3code");
|
||||
expect(scopes[0]?.projects).toEqual(projects);
|
||||
expect(scopes[0]?.projectRefs).toEqual(
|
||||
projects.map((project) => ({
|
||||
@@ -374,43 +373,6 @@ describe("buildHomeThreadGroups", () => {
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("uses the repository label for a singleton repository scope", () => {
|
||||
const project = makeProject({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "local-worktree-name",
|
||||
repositoryIdentity: {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
displayName: "codething-mvp",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [project],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
const groups = buildGroups(
|
||||
[project],
|
||||
[
|
||||
makeThread({
|
||||
environmentId: project.environmentId,
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: project.id,
|
||||
title: "Thread",
|
||||
}),
|
||||
],
|
||||
);
|
||||
|
||||
expect(scopes[0]?.title).toBe("codething-mvp");
|
||||
expect(groups[0]?.title).toBe("codething-mvp");
|
||||
});
|
||||
|
||||
it("sorts the newest thread first regardless of snapshot order", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
|
||||
@@ -113,7 +113,10 @@ export function buildHomeProjectScopes(input: {
|
||||
const representative = projects[0]!;
|
||||
return {
|
||||
key,
|
||||
title: deriveProjectGroupLabel({ representative, members: projects }),
|
||||
title:
|
||||
projects.length > 1
|
||||
? deriveProjectGroupLabel({ representative, members: projects })
|
||||
: representative.title,
|
||||
representative,
|
||||
projects,
|
||||
projectRefs: projectRefsByGroup.get(key) ?? [],
|
||||
@@ -343,7 +346,10 @@ export function buildHomeThreadGroups(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const title = deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const title =
|
||||
group.projects.length > 1
|
||||
? deriveProjectGroupLabel({ representative, members: group.projects })
|
||||
: representative.title;
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
title.toLocaleLowerCase().includes(query) ||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { ActivityIndicator, Pressable, StyleSheet, useColorScheme, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import { ActivityIndicator, Pressable, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -11,9 +10,6 @@ import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { GitActionProgress } from "../../state/use-vcs-action-state";
|
||||
|
||||
const OVERLAY_LAYOUT_TRANSITION = LinearTransition.duration(220);
|
||||
const AnimatedLiquidGlassView = Animated.createAnimatedComponent(LiquidGlassView);
|
||||
|
||||
export function GitActionProgressOverlay(props: {
|
||||
readonly progress: GitActionProgress;
|
||||
readonly onDismiss: () => void;
|
||||
@@ -49,7 +45,7 @@ export function GitActionProgressOverlay(props: {
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
entering={isLiquidGlassSupported ? undefined : FadeIn.duration(200)}
|
||||
entering={FadeIn.duration(200)}
|
||||
exiting={FadeOut.duration(150)}
|
||||
className="absolute inset-x-3 z-[100]"
|
||||
style={{ top: insets.top + 48 }}
|
||||
@@ -65,11 +61,16 @@ export function GitActionProgressOverlay(props: {
|
||||
function OverlayContent(props: { readonly progress: GitActionProgress }) {
|
||||
const { progress } = props;
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const glassBorder = useThemeColor("--color-header-border");
|
||||
const glassTint = useThemeColor("--color-glass-tint");
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const content = (
|
||||
<>
|
||||
|
||||
const bgClass =
|
||||
progress.phase === "error"
|
||||
? "bg-red-50 dark:bg-red-950/80 border-red-200 dark:border-red-800"
|
||||
: "bg-card border-border";
|
||||
|
||||
return (
|
||||
<View
|
||||
className={`flex-row items-center gap-2.5 rounded-2xl border px-3.5 py-3 shadow-lg shadow-black/10 ${bgClass}`}
|
||||
>
|
||||
<OverlayIcon phase={progress.phase} iconColor={iconColor} />
|
||||
|
||||
<View className="flex-1 gap-0.5">
|
||||
@@ -88,56 +89,7 @@ function OverlayContent(props: { readonly progress: GitActionProgress }) {
|
||||
{progress.prUrl ? (
|
||||
<SymbolView name="arrow.up.right" size={13} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
if (isLiquidGlassSupported) {
|
||||
return (
|
||||
<Animated.View
|
||||
layout={OVERLAY_LAYOUT_TRANSITION}
|
||||
style={{
|
||||
backgroundColor: glassTint,
|
||||
borderColor: glassBorder,
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 26,
|
||||
borderWidth: StyleSheet.hairlineWidth,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<AnimatedLiquidGlassView
|
||||
colorScheme={isDarkMode ? "dark" : "light"}
|
||||
effect="regular"
|
||||
interactive
|
||||
layout={OVERLAY_LAYOUT_TRANSITION}
|
||||
style={{
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 26,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<Animated.View
|
||||
entering={FadeIn.delay(60).duration(140)}
|
||||
className="flex-row items-center gap-2.5 px-3.5 py-3"
|
||||
>
|
||||
{content}
|
||||
</Animated.View>
|
||||
</AnimatedLiquidGlassView>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
const bgClass =
|
||||
progress.phase === "error"
|
||||
? "bg-red-50 dark:bg-red-950/80 border-red-200 dark:border-red-800"
|
||||
: "bg-card border-border";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
layout={OVERLAY_LAYOUT_TRANSITION}
|
||||
className={`flex-row items-center gap-2.5 rounded-[26px] border border-continuous px-3.5 py-3 shadow-lg shadow-black/10 ${bgClass}`}
|
||||
>
|
||||
{content}
|
||||
</Animated.View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -236,21 +236,6 @@ function ThreadNavigationSidebarPane(
|
||||
})),
|
||||
[projectScopes],
|
||||
);
|
||||
const projectTitleByProjectKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
projectScopes.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.title,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
[projectScopes],
|
||||
);
|
||||
const selectedProjectScope = useMemo(
|
||||
() =>
|
||||
selectedProjectKey === null
|
||||
@@ -399,10 +384,6 @@ function ThreadNavigationSidebarPane(
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
@@ -424,18 +405,8 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
@@ -443,38 +414,20 @@ function ThreadNavigationSidebarPane(
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Enabled,
|
||||
threads,
|
||||
selectedProjectScope,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const listItems = useMemo<readonly SidebarListItem[]>(() => {
|
||||
if (!threadListV2Enabled) return listLayout.items;
|
||||
// Queued offline tasks render above the thread rows (mirrors the
|
||||
@@ -775,7 +728,6 @@ function ThreadNavigationSidebarPane(
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
projectTitle={projectTitleByProjectKey.get(scopeKey)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(thread.environmentId)
|
||||
@@ -905,7 +857,6 @@ function ThreadNavigationSidebarPane(
|
||||
openPendingTask,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
props.onNewThreadInProject,
|
||||
props.selectedThreadKey,
|
||||
props.width,
|
||||
@@ -962,28 +913,15 @@ function ThreadNavigationSidebarPane(
|
||||
}),
|
||||
[filterIcon, filterMenu, props.onOpenSettings],
|
||||
);
|
||||
// "No threads yet" over an inbox that is merely all-snoozed reads as
|
||||
// data loss; name the snoozed threads instead.
|
||||
const snoozedCount = threadListV2Layout.snoozedCount;
|
||||
const listEmpty = (
|
||||
<Text className="px-2 py-4 text-sm text-foreground-muted">
|
||||
{catalogState.isLoadingConnections
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? snoozedCount > 0
|
||||
? // Snoozed matches passed this same search filter — "No
|
||||
// matching threads" would misreport them as nonexistent.
|
||||
snoozedCount === 1
|
||||
? "1 matching thread snoozed"
|
||||
: "All matching threads snoozed"
|
||||
: "No matching threads"
|
||||
: snoozedCount > 0
|
||||
? snoozedCount === 1
|
||||
? "1 thread snoozed"
|
||||
: `${snoozedCount} threads snoozed`
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
? "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
|
||||
@@ -90,7 +90,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly variant: "card" | "slim";
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly providerDriver: string | null;
|
||||
/** Which machine hosts the thread. Null when only one environment is
|
||||
connected — repeating the same label on every row is noise. Mirrors
|
||||
@@ -220,7 +219,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
@@ -231,7 +230,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.projectTitle ?? props.project?.title ?? ""}
|
||||
{props.project?.title ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
@@ -394,7 +393,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -77,85 +77,6 @@ describe("sortThreadsForListV2", () => {
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("hides snoozed threads and counts them — visibility parity with web", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("woken"),
|
||||
title: "Woken",
|
||||
// Wake time already passed: back in the active list.
|
||||
snoozedUntil: "2026-06-01T18:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
// Same createdAt → static sort tiebreaks by id; the point is the woken
|
||||
// thread is BACK in the card block and the snoozed one is gone.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("classifies snooze with the second-precise clock and reports the next wake", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("just-woke"),
|
||||
title: "Just woke",
|
||||
// Woke 30s ago: hidden under the minute-floored clock, visible
|
||||
// under the precise one.
|
||||
snoozedUntil: "2026-06-02T00:00:30.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("still-snoozed"),
|
||||
title: "Still snoozed",
|
||||
snoozedUntil: "2026-06-02T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
// Minute-floored partition clock vs precise snooze clock.
|
||||
now: "2026-06-02T00:01:00.000Z",
|
||||
snoozeNow: "2026-06-02T00:01:07.500Z",
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["just-woke"]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
|
||||
});
|
||||
|
||||
it("keeps snoozed threads visible on environments without the snooze capability", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
snoozeEnvironmentIds: new Set(),
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
|
||||
expect(layout.snoozedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("partitions settled threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
@@ -84,13 +84,6 @@ export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
/** Snoozed threads hidden from the list (visibility parity with web's
|
||||
collapsed Snoozed shelf; mobile has no shelf UI yet). */
|
||||
readonly snoozedCount: number;
|
||||
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
|
||||
a timeout at this boundary so the list re-partitions the moment a
|
||||
snooze expires instead of on the next minute tick. */
|
||||
readonly nextSnoozeWakeAt: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,22 +106,13 @@ export function buildThreadListV2Items(input: {
|
||||
other environments never classify as settled — the user could neither
|
||||
un-settle nor pin them. Absent = no gating (tests). */
|
||||
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
/** Environments whose server supports thread.snooze/unsnooze. Same
|
||||
contract as settlementEnvironmentIds. */
|
||||
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
readonly now?: string;
|
||||
/** Second-precise clock for snooze classification. Callers pass a
|
||||
minute-quantized `now` for memoization; snooze wake times are
|
||||
second-precise, so classifying with the floored minute would hold a
|
||||
woken thread hidden for up to a minute. Defaults to `now`. */
|
||||
readonly snoozeNow?: string;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const projectKeys = input.projectRefs
|
||||
@@ -137,8 +121,6 @@ export function buildThreadListV2Items(input: {
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
let snoozedCount = 0;
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
@@ -148,23 +130,8 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: a snoozed thread leaves the list until it
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozedCount += 1;
|
||||
if (
|
||||
thread.snoozedUntil != null &&
|
||||
(nextSnoozeWakeAt === null ||
|
||||
parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
|
||||
) {
|
||||
nextSnoozeWakeAt = thread.snoozedUntil;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
@@ -201,10 +168,5 @@ export function buildThreadListV2Items(input: {
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
|
||||
}
|
||||
@@ -60,8 +60,6 @@ function threadDetailToShell(
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
snoozedUntil: thread.snoozedUntil ?? null,
|
||||
snoozedAt: thread.snoozedAt ?? null,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: latestUserMessageAt(thread),
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -31,8 +31,7 @@
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"yaml": "catalog:"
|
||||
"node-pty": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
|
||||
+55
-40
@@ -12,8 +12,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
DEVELOPMENT_ICON_OVERRIDES,
|
||||
resolveWebAssetBrandForPackageVersion,
|
||||
resolveWebIconOverrides,
|
||||
PUBLISH_ICON_OVERRIDES,
|
||||
} from "../../../scripts/lib/brand-assets.ts";
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
@@ -82,34 +81,50 @@ const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Stan
|
||||
}
|
||||
});
|
||||
|
||||
const preparePublishIcons = Effect.fn("preparePublishIcons")(function* (
|
||||
interface PublishIconBackup {
|
||||
readonly targetPath: string;
|
||||
readonly backupPath: string;
|
||||
}
|
||||
|
||||
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
|
||||
repoRoot: string,
|
||||
serverDir: string,
|
||||
version: string,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const brand = resolveWebAssetBrandForPackageVersion(version);
|
||||
const icons = resolveWebIconOverrides(brand, "dist/client").map((override) => ({
|
||||
sourcePath: path.join(repoRoot, override.sourceRelativePath),
|
||||
targetPath: path.join(serverDir, override.targetRelativePath),
|
||||
}));
|
||||
const backups: PublishIconBackup[] = [];
|
||||
|
||||
for (const icon of icons) {
|
||||
if (!(yield* fs.exists(icon.sourcePath))) {
|
||||
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath: icon.sourcePath });
|
||||
for (const override of PUBLISH_ICON_OVERRIDES) {
|
||||
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
|
||||
const targetPath = path.join(serverDir, override.targetRelativePath);
|
||||
const backupPath = `${targetPath}.publish-bak`;
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath });
|
||||
}
|
||||
if (!(yield* fs.exists(icon.targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath: icon.targetPath });
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath });
|
||||
}
|
||||
|
||||
yield* fs.copyFile(targetPath, backupPath);
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
backups.push({ targetPath, backupPath });
|
||||
}
|
||||
|
||||
return yield* Effect.forEach(icons, (icon) =>
|
||||
Effect.all({
|
||||
original: fs.readFile(icon.targetPath),
|
||||
publish: fs.readFile(icon.sourcePath),
|
||||
}).pipe(Effect.map((contents) => ({ ...icon, ...contents }))),
|
||||
);
|
||||
yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
|
||||
return backups as ReadonlyArray<PublishIconBackup>;
|
||||
});
|
||||
|
||||
const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
|
||||
backups: ReadonlyArray<PublishIconBackup>,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
for (const backup of backups) {
|
||||
if (!(yield* fs.exists(backup.backupPath))) {
|
||||
continue;
|
||||
}
|
||||
yield* fs.rename(backup.backupPath, backup.targetPath);
|
||||
}
|
||||
});
|
||||
|
||||
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
|
||||
@@ -221,6 +236,7 @@ const publishCmd = Command.make(
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
|
||||
@@ -231,7 +247,7 @@ const publishCmd = Command.make(
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: resolve publish metadata and read every original before mutation.
|
||||
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const workspaceConfig = yield* readWorkspaceConfig();
|
||||
@@ -257,22 +273,19 @@ const publishCmd = Command.make(
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
packageJsonString: yield* encodePackageJson(pkg),
|
||||
originalPackageJson: yield* fs.readFile(packageJsonPath),
|
||||
icons: yield* preparePublishIcons(repoRoot, serverDir, version),
|
||||
};
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
const packageJsonString = yield* encodePackageJson(pkg);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
yield* fs.writeFileString(packageJsonPath, `${packageJsonString}\n`);
|
||||
yield* Effect.log("[cli] Prepared package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
}),
|
||||
// Use: pnpm publish from the workspace root so pnpm-only workspace
|
||||
// config, including override selectors, is interpreted correctly.
|
||||
(resource) =>
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
yield* fs.writeFileString(packageJsonPath, `${resource.packageJsonString}\n`);
|
||||
for (const icon of resource.icons) {
|
||||
yield* fs.writeFile(icon.targetPath, icon.publish);
|
||||
}
|
||||
yield* Effect.log("[cli] Applied package metadata and publish icon overrides");
|
||||
|
||||
const args = createVpPmPublishArgs(config);
|
||||
const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
|
||||
|
||||
@@ -286,14 +299,16 @@ const publishCmd = Command.make(
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore every file even if applying overrides or publishing fails.
|
||||
(resource) =>
|
||||
// Release: restore
|
||||
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* fs.writeFile(packageJsonPath, resource.originalPackageJson);
|
||||
for (const icon of resource.icons) {
|
||||
yield* fs.writeFile(icon.targetPath, icon.original);
|
||||
}
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original publish assets");
|
||||
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
|
||||
),
|
||||
);
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -69,6 +69,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
return "full thread diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -177,6 +178,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -260,6 +262,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -301,6 +304,102 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("filters git-attributed sections and reports gitFileCount from patch sections", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-attribution");
|
||||
const threadId = ThreadId.make("thread-attribution");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const patch = [
|
||||
"diff --git a/agent.ts b/agent.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/agent.ts",
|
||||
"+++ b/agent.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/pulled.ts b/pulled.ts",
|
||||
"index 3333333..4444444 100644",
|
||||
"--- a/pulled.ts",
|
||||
"+++ b/pulled.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
// Attribution also tags a path that has no section in this patch
|
||||
// (e.g. whitespace-only change elided by ignoreWhitespace) — it must
|
||||
// not count toward gitFileCount.
|
||||
const attribution = new Map<string, "agent" | "git">([
|
||||
["agent.ts", "agent"],
|
||||
["pulled.ts", "git"],
|
||||
["whitespace-only.ts", "git"],
|
||||
]);
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(patch),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(attribution),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const { filtered, revealed } = yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
const filtered = yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
const revealed = yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
includeGitChanges: true,
|
||||
});
|
||||
return { filtered, revealed };
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(filtered.diff).toContain("agent.ts");
|
||||
expect(filtered.diff).not.toContain("pulled.ts");
|
||||
expect(filtered.gitFileCount).toBe(1);
|
||||
expect(revealed.diff).toBe(patch);
|
||||
expect(revealed.gitFileCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not preflight checkpoint refs before diffing", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-no-preflight");
|
||||
@@ -328,6 +427,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed("diff patch"),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -381,6 +481,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(""),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from "./Errors.ts";
|
||||
import type { CheckpointServiceError } from "./Errors.ts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import { filterUnifiedDiffFiles, listUnifiedDiffPaths } from "./Diffs.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
|
||||
/** Service tag for checkpoint diff queries. */
|
||||
@@ -66,12 +67,14 @@ function buildTurnDiffResult(
|
||||
readonly toTurnCount: number;
|
||||
},
|
||||
diff: string,
|
||||
gitFileCount?: number,
|
||||
): OrchestrationGetTurnDiffResultType {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff,
|
||||
...(gitFileCount !== undefined ? { gitFileCount } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -79,6 +82,51 @@ export const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
|
||||
// Drop file sections attributed to pre-existing git history from a patch
|
||||
// unless the caller opted in. Attribution failures degrade to the
|
||||
// unfiltered patch — never block the diff on attribution. The returned
|
||||
// gitFileCount comes from the SAME attribution pass that produced the
|
||||
// patch, so UI driven by it always agrees with what is rendered;
|
||||
// undefined means attribution was unavailable and nothing was filtered.
|
||||
const applyAttributionFilter = Effect.fn("applyAttributionFilter")(function* (input: {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly diff: string;
|
||||
readonly includeGitChanges: boolean;
|
||||
}): Effect.fn.Return<{ readonly diff: string; readonly gitFileCount: number | undefined }> {
|
||||
if (input.diff.trim().length === 0) {
|
||||
return { diff: input.diff, gitFileCount: undefined };
|
||||
}
|
||||
const attribution = yield* checkpointStore
|
||||
.attributeCheckpointDiff({
|
||||
cwd: input.cwd,
|
||||
fromCheckpointRef: input.fromCheckpointRef,
|
||||
toCheckpointRef: input.toCheckpointRef,
|
||||
})
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (attribution === null) {
|
||||
return { diff: input.diff, gitFileCount: undefined };
|
||||
}
|
||||
// Count only git-attributed paths with a section in THIS patch. The
|
||||
// attribution map can include paths absent from the patch (e.g.
|
||||
// whitespace-only changes elided by ignoreWhitespace) — counting those
|
||||
// would advertise hidden files the toggle can never reveal.
|
||||
let gitFileCount = 0;
|
||||
for (const path of listUnifiedDiffPaths(input.diff)) {
|
||||
if (attribution.get(path) === "git") {
|
||||
gitFileCount += 1;
|
||||
}
|
||||
}
|
||||
if (input.includeGitChanges || gitFileCount === 0) {
|
||||
return { diff: input.diff, gitFileCount };
|
||||
}
|
||||
return {
|
||||
diff: filterUnifiedDiffFiles(input.diff, (path) => attribution.get(path) !== "git"),
|
||||
gitFileCount,
|
||||
};
|
||||
});
|
||||
|
||||
const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
@@ -164,7 +212,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const diff = yield* checkpointStore
|
||||
const rawDiff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
@@ -173,8 +221,15 @@ export const make = Effect.gen(function* () {
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
|
||||
const filtered = yield* applyAttributionFilter({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
diff: rawDiff,
|
||||
includeGitChanges: input.includeGitChanges ?? false,
|
||||
});
|
||||
|
||||
const turnDiff = buildTurnDiffResult(input, diff);
|
||||
const turnDiff = buildTurnDiffResult(input, filtered.diff, filtered.gitFileCount);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
operation,
|
||||
@@ -254,15 +309,24 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const diff = yield* checkpointStore
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, 0);
|
||||
const toCheckpointRef = threadContext.value.toCheckpointRef as CheckpointRef;
|
||||
const rawDiff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
|
||||
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
|
||||
const filtered = yield* applyAttributionFilter({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
diff: rawDiff,
|
||||
includeGitChanges: input.includeGitChanges ?? false,
|
||||
});
|
||||
|
||||
const turnDiff = buildTurnDiffResult(
|
||||
{
|
||||
@@ -270,7 +334,8 @@ export const make = Effect.gen(function* () {
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
},
|
||||
diff,
|
||||
filtered.diff,
|
||||
filtered.gitFileCount,
|
||||
);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
|
||||
@@ -55,6 +55,7 @@ function writeTextFile(
|
||||
function git(
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
env?: NodeJS.ProcessEnv,
|
||||
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
|
||||
return Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
@@ -63,12 +64,19 @@ function git(
|
||||
command: "git",
|
||||
cwd,
|
||||
args,
|
||||
...(env ? { env: { ...global.process.env, ...env } } : {}),
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
return result.stdout.trim();
|
||||
});
|
||||
}
|
||||
|
||||
/** Author and committer dates both in the past: a genuinely pre-existing commit. */
|
||||
const PRE_EXISTING_COMMIT_ENV: NodeJS.ProcessEnv = {
|
||||
GIT_AUTHOR_DATE: "2020-01-01T00:00:00Z",
|
||||
GIT_COMMITTER_DATE: "2020-01-01T00:00:00Z",
|
||||
};
|
||||
|
||||
function initRepoWithCommit(
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
@@ -222,4 +230,237 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("attributeCheckpointDiff", () => {
|
||||
it.effect("returns an empty map when HEAD did not move", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-no-head-move");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.size).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("attributes a branch switch to git while keeping tool edits as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
// A second branch with a pre-existing commit, created before the turn.
|
||||
yield* git(tmp, ["checkout", "-b", "feature"]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "feature.ts"), "export const feature = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "feature work"], PRE_EXISTING_COMMIT_ENV);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-branch-switch");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": switch branches (history-driven) and also edit a file.
|
||||
yield* git(tmp, ["checkout", "feature"]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("feature.ts")).toBe("git");
|
||||
expect(attribution!.get("edited.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps files committed during the turn as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-own-commit");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": edit and commit — HEAD moves, but by a turn-authored commit.
|
||||
yield* writeTextFile(NodePath.join(tmp, "committed.ts"), "export const done = true;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "agent commit"]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("committed.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("attributes a cherry-pick of a pre-existing commit to git", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
// Pre-existing commit on another branch, authored before the turn.
|
||||
yield* git(tmp, ["checkout", "-b", "source"]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "picked.ts"), "export const picked = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(
|
||||
tmp,
|
||||
[
|
||||
"-c",
|
||||
"[email protected]",
|
||||
"-c",
|
||||
"user.name=Other",
|
||||
"commit",
|
||||
"-m",
|
||||
"source work",
|
||||
],
|
||||
PRE_EXISTING_COMMIT_ENV,
|
||||
);
|
||||
const pickedOid = yield* git(tmp, ["rev-parse", "HEAD"]);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-cherry-pick");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
yield* git(tmp, ["cherry-pick", pickedOid]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("picked.ts")).toBe("git");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps an amend of a pre-turn commit as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
// Pre-turn commit with an old author date, as amend preserves it.
|
||||
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "pre-turn work", "--date", "2020-01-01T00:00:00Z"]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-amend");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": edit the file and amend it into the pre-turn commit.
|
||||
// The author date stays 2020, but the content is new agent work.
|
||||
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 2;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "--amend", "--no-edit"]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("amended.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a whitespace-only amend of a pre-turn commit as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
// Pre-turn commit; its pre-amend state stays reachable via reflog,
|
||||
// which is exactly the patch-id collision candidate.
|
||||
yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "pre-turn work"], PRE_EXISTING_COMMIT_ENV);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-ws-amend");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": whitespace-only reformat amended into the pre-turn
|
||||
// commit. `git patch-id --stable` would hash this identically to the
|
||||
// original (it strips whitespace); --verbatim must not.
|
||||
yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "--amend", "--no-edit"]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("style.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null for legacy checkpoints without head metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-legacy");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
// Simulate a pre-attribution checkpoint: commit the tree with the old
|
||||
// single-line message format.
|
||||
const treeOid = yield* git(tmp, ["write-tree"]);
|
||||
const legacyCommit = yield* git(tmp, [
|
||||
"commit-tree",
|
||||
treeOid,
|
||||
"-m",
|
||||
`t3 checkpoint ref=${fromCheckpointRef}`,
|
||||
]);
|
||||
yield* git(tmp, ["update-ref", fromCheckpointRef, legacyCommit]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).toBe(null);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -46,6 +46,18 @@ export interface DeleteCheckpointRefsInput {
|
||||
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
|
||||
}
|
||||
|
||||
export interface AttributeCheckpointDiffInput {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-path origin classification of a checkpoint tree delta, or null when
|
||||
* attribution is unavailable (see VcsCheckpointAttribution).
|
||||
*/
|
||||
export type CheckpointAttribution = ReadonlyMap<string, "agent" | "git"> | null;
|
||||
|
||||
/** Service tag for checkpoint persistence and restore operations. */
|
||||
export class CheckpointStore extends Context.Service<
|
||||
CheckpointStore,
|
||||
@@ -93,6 +105,17 @@ export class CheckpointStore extends Context.Service<
|
||||
readonly deleteCheckpointRefs: (
|
||||
input: DeleteCheckpointRefsInput,
|
||||
) => Effect.Effect<void, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Classify each path in a checkpoint-to-checkpoint tree delta as
|
||||
* agent-authored or explained by pre-existing git history.
|
||||
*
|
||||
* Returns null when attribution is unavailable (legacy checkpoints
|
||||
* without HEAD metadata, or truncated git output).
|
||||
*/
|
||||
readonly attributeCheckpointDiff: (
|
||||
input: AttributeCheckpointDiffInput,
|
||||
) => Effect.Effect<CheckpointAttribution, CheckpointStoreError>;
|
||||
}
|
||||
>()("t3/checkpointing/CheckpointStore") {}
|
||||
|
||||
@@ -157,6 +180,16 @@ export const make = Effect.gen(function* () {
|
||||
return yield* checkpoints.deleteCheckpointRefs(input);
|
||||
});
|
||||
|
||||
const attributeCheckpointDiff: CheckpointStore["Service"]["attributeCheckpointDiff"] = Effect.fn(
|
||||
"attributeCheckpointDiff",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints(
|
||||
"CheckpointStore.attributeCheckpointDiff",
|
||||
input.cwd,
|
||||
);
|
||||
return yield* checkpoints.attributeCheckpointDiff(input);
|
||||
});
|
||||
|
||||
return CheckpointStore.of({
|
||||
isGitRepository,
|
||||
captureCheckpoint,
|
||||
@@ -164,6 +197,7 @@ export const make = Effect.gen(function* () {
|
||||
restoreCheckpoint,
|
||||
diffCheckpoints,
|
||||
deleteCheckpointRefs,
|
||||
attributeCheckpointDiff,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
|
||||
import { filterUnifiedDiffFiles, parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
|
||||
|
||||
describe("parseTurnDiffFilesFromUnifiedDiff", () => {
|
||||
it("returns empty list for empty diff", () => {
|
||||
@@ -66,3 +66,159 @@ describe("parseTurnDiffFilesFromUnifiedDiff", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterUnifiedDiffFiles", () => {
|
||||
const twoFileDiff = [
|
||||
"diff --git a/kept.ts b/kept.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/kept.ts",
|
||||
"+++ b/kept.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/dropped.ts b/dropped.ts",
|
||||
"index 3333333..4444444 100644",
|
||||
"--- a/dropped.ts",
|
||||
"+++ b/dropped.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
it("removes sections whose path is rejected", () => {
|
||||
const filtered = filterUnifiedDiffFiles(twoFileDiff, (path) => path !== "dropped.ts");
|
||||
expect(filtered).toContain("kept.ts");
|
||||
expect(filtered).not.toContain("dropped.ts");
|
||||
expect(parseTurnDiffFilesFromUnifiedDiff(filtered)).toEqual([
|
||||
{ path: "kept.ts", additions: 1, deletions: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns the diff unchanged when everything is kept", () => {
|
||||
expect(filterUnifiedDiffFiles(twoFileDiff, () => true)).toBe(twoFileDiff);
|
||||
});
|
||||
|
||||
it("filters deleted files via the --- a/ path", () => {
|
||||
const deletionDiff = [
|
||||
"diff --git a/removed.ts b/removed.ts",
|
||||
"deleted file mode 100644",
|
||||
"index 1111111..0000000",
|
||||
"--- a/removed.ts",
|
||||
"+++ /dev/null",
|
||||
"@@ -1,1 +0,0 @@",
|
||||
"-gone",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(deletionDiff, (path) => path !== "removed.ts").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("filters simple header-only sections via the diff --git header", () => {
|
||||
const oddDiff = ["diff --git a/x b/x", "Binary files differ", ""].join("\n");
|
||||
expect(filterUnifiedDiffFiles(oddDiff, (path) => path !== "x").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("keeps unparseable sections", () => {
|
||||
const oddDiff = ["diff --git malformed-header", "Binary files differ", ""].join("\n");
|
||||
expect(filterUnifiedDiffFiles(oddDiff, () => false)).toBe(oddDiff);
|
||||
});
|
||||
|
||||
it("returns empty diff unchanged", () => {
|
||||
expect(filterUnifiedDiffFiles("", () => false)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDiffSectionPath via renames", () => {
|
||||
it("filters rename sections by the post-image path", () => {
|
||||
const renameDiff = [
|
||||
"diff --git a/old/name.ts b/new/name.ts",
|
||||
"similarity index 90%",
|
||||
"rename from old/name.ts",
|
||||
"rename to new/name.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/old/name.ts",
|
||||
"+++ b/new/name.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
// The attribution map is keyed by post-image paths; a filter that only
|
||||
// knows the new path must still match this section.
|
||||
expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "new/name.ts").trim()).toBe("");
|
||||
expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "old/name.ts")).toBe(renameDiff);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterUnifiedDiffFiles fallback paths", () => {
|
||||
it("filters binary sections via the diff --git header", () => {
|
||||
const binaryDiff = [
|
||||
"diff --git a/assets/logo.png b/assets/logo.png",
|
||||
"index 1111111..2222222 100644",
|
||||
"Binary files a/assets/logo.png and b/assets/logo.png differ",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(binaryDiff, (path) => path !== "assets/logo.png").trim()).toBe(
|
||||
"",
|
||||
);
|
||||
expect(filterUnifiedDiffFiles(binaryDiff, () => true)).toBe(binaryDiff);
|
||||
});
|
||||
|
||||
it("filters mode-only sections via the diff --git header", () => {
|
||||
const modeDiff = [
|
||||
"diff --git a/scripts/run.sh b/scripts/run.sh",
|
||||
"old mode 100644",
|
||||
"new mode 100755",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(modeDiff, (path) => path !== "scripts/run.sh").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("filters binary sections with spaces in the path", () => {
|
||||
const binaryDiff = [
|
||||
"diff --git a/my assets/logo file.png b/my assets/logo file.png",
|
||||
"Binary files differ",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(
|
||||
filterUnifiedDiffFiles(binaryDiff, (path) => path !== "my assets/logo file.png").trim(),
|
||||
).toBe("");
|
||||
});
|
||||
|
||||
it("decodes git C-style quoted paths", () => {
|
||||
const quotedDiff = [
|
||||
'diff --git "a/sp\\303\\244ce.ts" "b/sp\\303\\244ce.ts"',
|
||||
"index 1111111..2222222 100644",
|
||||
'--- "a/sp\\303\\244ce.ts"',
|
||||
'+++ "b/sp\\303\\244ce.ts"',
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"",
|
||||
].join("\n");
|
||||
// git octal-escapes the raw UTF-8 bytes (`ä` = \303\244); the decoder
|
||||
// must reassemble them into the real character, not per-byte mojibake.
|
||||
expect(filterUnifiedDiffFiles(quotedDiff, (path) => path !== "späce.ts").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("filters rename-only sections without hunks via rename metadata", () => {
|
||||
const renameOnlyDiff = [
|
||||
"diff --git a/old.ts b/new.ts",
|
||||
"similarity index 100%",
|
||||
"rename from old.ts",
|
||||
"rename to new.ts",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "new.ts").trim()).toBe("");
|
||||
expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "old.ts")).toBe(
|
||||
renameOnlyDiff,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps ambiguous unquoted rename headers", () => {
|
||||
// Rename of a space-containing path is ambiguous in the header when git
|
||||
// does not quote; with no other metadata the section must be kept.
|
||||
const ambiguous = ["diff --git a/x y b/y z", "Binary files differ", ""].join("\n");
|
||||
expect(filterUnifiedDiffFiles(ambiguous, () => false)).toBe(ambiguous);
|
||||
});
|
||||
});
|
||||
@@ -25,3 +25,179 @@ export function parseTurnDiffFilesFromUnifiedDiff(
|
||||
|
||||
return files.toSorted((left, right) => left.path.localeCompare(right.path));
|
||||
}
|
||||
|
||||
const SIMPLE_ESCAPES: Record<string, number> = {
|
||||
"\\": 0x5c,
|
||||
'"': 0x22,
|
||||
a: 0x07,
|
||||
b: 0x08,
|
||||
f: 0x0c,
|
||||
n: 0x0a,
|
||||
r: 0x0d,
|
||||
t: 0x09,
|
||||
v: 0x0b,
|
||||
};
|
||||
|
||||
function stripGitPathQuoting(value: string): string {
|
||||
if (!(value.startsWith('"') && value.endsWith('"') && value.length >= 2)) {
|
||||
return value;
|
||||
}
|
||||
// Git C-style quoting: octal escapes are raw UTF-8 BYTES (e.g. `ä` is
|
||||
// `\303\244`), so decode into a byte buffer first and UTF-8-decode the
|
||||
// whole path at the end — per-escape String.fromCharCode would yield
|
||||
// mojibake that never matches attribution map keys.
|
||||
const inner = value.slice(1, -1);
|
||||
const bytes: Array<number> = [];
|
||||
const encoder = new TextEncoder();
|
||||
for (let index = 0; index < inner.length; index += 1) {
|
||||
const char = inner[index]!;
|
||||
if (char !== "\\" || index === inner.length - 1) {
|
||||
bytes.push(...encoder.encode(char));
|
||||
continue;
|
||||
}
|
||||
const next = inner[index + 1]!;
|
||||
const simple = SIMPLE_ESCAPES[next];
|
||||
if (simple !== undefined) {
|
||||
bytes.push(simple);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
const octal = /^[0-7]{1,3}/.exec(inner.slice(index + 1))?.[0];
|
||||
if (octal) {
|
||||
bytes.push(parseInt(octal, 8) & 0xff);
|
||||
index += octal.length;
|
||||
continue;
|
||||
}
|
||||
bytes.push(...encoder.encode(char));
|
||||
}
|
||||
return new TextDecoder("utf-8", { fatal: false }).decode(new Uint8Array(bytes));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the post-image path out of a `diff --git a/<path> b/<path>` header.
|
||||
*
|
||||
* Only trustworthy when both paths are quoted or the two paths are equal
|
||||
* (no rename): for unquoted renamed paths containing spaces the split is
|
||||
* ambiguous, so return null and let the caller keep the section.
|
||||
*/
|
||||
function resolveDiffGitHeaderPath(headerLine: string): string | null {
|
||||
const spec = headerLine.slice("diff --git ".length).trim();
|
||||
const quotedMatch = /^("(?:[^"\\]|\\.)*"|\S+) ("(?:[^"\\]|\\.)*"|\S+)$/.exec(spec);
|
||||
if (quotedMatch) {
|
||||
const source = stripGitPathQuoting(quotedMatch[1]!);
|
||||
const target = stripGitPathQuoting(quotedMatch[2]!);
|
||||
if (source.startsWith("a/") && target.startsWith("b/")) {
|
||||
return target.slice(2);
|
||||
}
|
||||
}
|
||||
// Paths with spaces are unquoted in this header; recover the symmetric
|
||||
// a/X b/X form (covers everything but renames of space-containing paths).
|
||||
if (spec.length % 2 === 1) {
|
||||
const midpoint = (spec.length - 1) / 2;
|
||||
const source = spec.slice(0, midpoint);
|
||||
const target = spec.slice(midpoint + 1);
|
||||
if (source.startsWith("a/") && target.startsWith("b/") && source.slice(2) === target.slice(2)) {
|
||||
return target.slice(2);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the post-image path of one `diff --git` section, preferring the
|
||||
* `+++ b/` line and falling back to `--- a/` for deletions. Binary and
|
||||
* mode-only sections have neither, so fall back to rename/copy metadata and
|
||||
* finally the `diff --git` header itself. Returns null when the section is
|
||||
* unparseable; callers should keep such sections.
|
||||
*/
|
||||
function resolveDiffSectionPath(section: string): string | null {
|
||||
// `--- a/` precedes `+++ b/` in a section, so resolve the post-image path
|
||||
// in a full pass before falling back — for renames the two differ, and the
|
||||
// attribution map is keyed by the post-image path.
|
||||
let fallbackSource: string | null = null;
|
||||
let renameTarget: string | null = null;
|
||||
let headerPath: string | null = null;
|
||||
for (const line of section.split("\n")) {
|
||||
if (line.startsWith("+++ ")) {
|
||||
const target = stripGitPathQuoting(line.slice(4).trim());
|
||||
if (target !== "/dev/null") {
|
||||
return target.startsWith("b/") ? target.slice(2) : target;
|
||||
}
|
||||
} else if (line.startsWith("--- ") && fallbackSource === null) {
|
||||
const source = stripGitPathQuoting(line.slice(4).trim());
|
||||
if (source !== "/dev/null" && source.startsWith("a/")) {
|
||||
fallbackSource = source.slice(2);
|
||||
}
|
||||
} else if (
|
||||
(line.startsWith("rename to ") || line.startsWith("copy to ")) &&
|
||||
renameTarget === null
|
||||
) {
|
||||
renameTarget = stripGitPathQuoting(line.slice(line.indexOf(" to ") + 4));
|
||||
} else if (line.startsWith("diff --git ") && headerPath === null) {
|
||||
headerPath = resolveDiffGitHeaderPath(line);
|
||||
}
|
||||
}
|
||||
return fallbackSource ?? renameTarget ?? headerPath;
|
||||
}
|
||||
|
||||
function splitUnifiedDiffSections(diff: string): ReadonlyArray<string> {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
if (normalized.trim().length === 0) {
|
||||
return [];
|
||||
}
|
||||
const sections: Array<string> = [];
|
||||
let currentStart = -1;
|
||||
const lines = normalized.split("\n");
|
||||
const flush = (endExclusive: number) => {
|
||||
if (currentStart >= 0) {
|
||||
sections.push(lines.slice(currentStart, endExclusive).join("\n"));
|
||||
}
|
||||
};
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
if (lines[index]!.startsWith("diff --git ")) {
|
||||
flush(index);
|
||||
currentStart = index;
|
||||
}
|
||||
}
|
||||
flush(lines.length);
|
||||
return sections;
|
||||
}
|
||||
|
||||
/**
|
||||
* List the resolvable post-image paths of a unified diff's file sections.
|
||||
* Unparseable sections are omitted.
|
||||
*/
|
||||
export function listUnifiedDiffPaths(diff: string): ReadonlyArray<string> {
|
||||
const paths: Array<string> = [];
|
||||
for (const section of splitUnifiedDiffSections(diff)) {
|
||||
const path = resolveDiffSectionPath(section);
|
||||
if (path !== null) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove file sections from a unified diff by path.
|
||||
*
|
||||
* Sections whose path cannot be determined are kept (fail toward showing).
|
||||
*/
|
||||
export function filterUnifiedDiffFiles(
|
||||
diff: string,
|
||||
shouldKeepPath: (path: string) => boolean,
|
||||
): string {
|
||||
const sections = splitUnifiedDiffSections(diff);
|
||||
if (sections.length === 0) {
|
||||
return diff;
|
||||
}
|
||||
|
||||
const kept = sections.filter((section) => {
|
||||
const path = resolveDiffSectionPath(section);
|
||||
return path === null || shouldKeepPath(path);
|
||||
});
|
||||
if (kept.length === sections.length) {
|
||||
return diff;
|
||||
}
|
||||
return kept.join("\n");
|
||||
}
|
||||
@@ -141,7 +141,6 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewTabId,
|
||||
@@ -59,8 +58,6 @@ const handlers = {
|
||||
invokeTargeted<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
|
||||
preview_resize: (input) =>
|
||||
invokeTargeted<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
|
||||
preview_set_appearance: (input) =>
|
||||
invokeTargeted<PreviewAutomationSetColorSchemeResult>("setColorScheme", input),
|
||||
preview_snapshot: (input) => invokeTargeted<PreviewAutomationSnapshot>("snapshot", input ?? {}),
|
||||
preview_click: (input) =>
|
||||
invokeTargeted<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
|
||||
@@ -10,8 +10,6 @@ import {
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSetColorSchemeInput,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewAutomationTabTargetInput,
|
||||
@@ -88,19 +86,6 @@ export const PreviewResizeTool = safeBrowserTool(
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSetAppearanceTool = safeBrowserTool(
|
||||
Tool.make("preview_set_appearance", {
|
||||
description:
|
||||
"Emulate prefers-color-scheme in a collaborative browser tab, optionally selected by tabId. Use {colorScheme:'dark'} or {colorScheme:'light'} to preview the page in that appearance, and {colorScheme:'system'} to clear the override and follow the OS appearance.",
|
||||
parameters: PreviewAutomationSetColorSchemeInput,
|
||||
success: PreviewAutomationSetColorSchemeResult,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Set preview appearance")
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
Tool.make("preview_snapshot", {
|
||||
description:
|
||||
@@ -204,7 +189,6 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSetAppearanceTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -221,7 +205,6 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSetAppearanceTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -256,6 +256,27 @@ const make = Effect.gen(function* () {
|
||||
// reflects files created or deleted during this turn.
|
||||
yield* workspaceEntries.refresh(input.cwd);
|
||||
|
||||
// Best-effort per-path attribution: paths whose change is fully explained
|
||||
// by pre-existing history moving through HEAD (pull, checkout,
|
||||
// cherry-pick, rebase) are tagged origin "git" so the UI can demote them.
|
||||
// Attribution must never block the checkpoint pipeline — any failure
|
||||
// degrades to unattributed files (all shown as agent work).
|
||||
const attribution = yield* checkpointStore
|
||||
.attributeCheckpointDiff({
|
||||
cwd: input.cwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to attribute checkpoint diff", {
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: input.cwd,
|
||||
@@ -271,6 +292,7 @@ const make = Effect.gen(function* () {
|
||||
kind: "modified" as const,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
...(attribution ? { origin: attribution.get(file.path) ?? "agent" } : {}),
|
||||
})),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
|
||||
@@ -609,8 +609,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -681,38 +679,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.snoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: event.payload.snoozedUntil,
|
||||
snoozedAt: event.payload.snoozedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unsnoozed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -310,8 +310,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -424,8 +422,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
|
||||
@@ -336,8 +336,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -368,8 +366,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -402,8 +398,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -768,8 +762,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -1204,8 +1196,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1406,8 +1396,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1539,8 +1527,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1677,8 +1663,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1921,8 +1905,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
@@ -2019,8 +2001,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
|
||||
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -40,8 +38,6 @@ export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSet
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
|
||||
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -1,286 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
// The decider's clock is the Effect test clock, pinned to the epoch, so
|
||||
// "future" wake times are relative to 1970-01-01T00:00:00.000Z.
|
||||
const FUTURE_WAKE = "1970-01-02T09:00:00.000Z";
|
||||
const PAST_WAKE = "1969-12-31T09:00:00.000Z";
|
||||
const SNOOZED_AT = "1969-12-30T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(input: {
|
||||
readonly snoozedUntil?: string | null;
|
||||
readonly snoozedAt?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
readonly activities?: OrchestrationThread["activities"];
|
||||
readonly messages?: OrchestrationThread["messages"];
|
||||
}): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: input.archivedAt ?? null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: input.snoozedUntil ?? null,
|
||||
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
|
||||
deletedAt: null,
|
||||
messages: input.messages ?? [],
|
||||
proposedPlans: [],
|
||||
activities: input.activities ?? [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("snoozed thread decider", (it) => {
|
||||
it.effect("snoozes a thread to a future wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.snoozed");
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe(FUTURE_WAKE);
|
||||
expect(events[0].payload.snoozedAt).toBe(events[0].payload.updatedAt);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a wake time that is not in the future", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-past"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: PAST_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects an unparseable wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
// IsoDateTime is structurally a string, so garbage can reach the
|
||||
// decider; a NaN wake time must never persist as snooze state.
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-garbage"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "not-a-date",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing blocked-on-you work", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestActivity = {
|
||||
id: EventId.make("activity-req-1"),
|
||||
tone: "approval" as const,
|
||||
kind: "approval.requested",
|
||||
summary: "approval.requested",
|
||||
payload: { requestId: "req-1" },
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
} as OrchestrationThread["activities"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-blocked"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ activities: [requestActivity] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-emits idempotently for a duplicate snooze to the same wake time", () =>
|
||||
Effect.gen(function* () {
|
||||
const reEmit = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(reEmit) ? reEmit : [reEmit];
|
||||
expect(events).toHaveLength(1);
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
// Original snoozedAt preserved; updatedAt must not churn.
|
||||
expect(events[0].payload.snoozedAt).toBe(SNOOZED_AT);
|
||||
expect(events[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-snoozing to a DIFFERENT wake time stamps fresh", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-extend"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: "1970-01-03T09:00:00.000Z",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
if (events[0]?.type === "thread.snoozed") {
|
||||
expect(events[0].payload.snoozedUntil).toBe("1970-01-03T09:00:00.000Z");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unsnoozes with reason user and re-emits idempotently when awake", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events[0]?.type).toBe("thread.unsnoozed");
|
||||
if (events[0]?.type === "thread.unsnoozed") {
|
||||
expect(events[0].payload.reason).toBe("user");
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
|
||||
const awake = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsnooze",
|
||||
commandId: CommandId.make("cmd-unsnooze-awake"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const awakeEvents = Array.isArray(awake) ? awake : [awake];
|
||||
expect(awakeEvents[0]?.type).toBe("thread.unsnoozed");
|
||||
if (awakeEvents[0]?.type === "thread.unsnoozed") {
|
||||
// No state change — keep the existing updatedAt.
|
||||
expect(awakeEvents[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing a thread with a queued turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
// The decider clock is the Effect test clock pinned to the epoch: a
|
||||
// user message 30s before it with no adopting turn is queued work.
|
||||
const queuedMessage = {
|
||||
id: MessageId.make("message-queued"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "1969-12-31T23:59:30.000Z",
|
||||
updatedAt: "1969-12-31T23:59:30.000Z",
|
||||
} as OrchestrationThread["messages"][number];
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-queued"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ messages: [queuedMessage] }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects snoozing an archived thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.snooze",
|
||||
commandId: CommandId.make("cmd-snooze-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
snoozedUntil: FUTURE_WAKE,
|
||||
},
|
||||
readModel: makeReadModel({ archivedAt: NOW }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("a user message spends the snooze return ticket (activity wake)", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-1"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
|
||||
});
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
|
||||
expect(unsnoozed).toBeDefined();
|
||||
if (unsnoozed?.type === "thread.unsnoozed") {
|
||||
expect(unsnoozed.payload.reason).toBe("activity");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -53,13 +53,6 @@ function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): b
|
||||
);
|
||||
}
|
||||
|
||||
// Scans the read model's activities, which the projector caps at the most
|
||||
// recent 500. That bound is safe here: an OPEN approval/user-input request
|
||||
// blocks its turn, so the thread cannot accumulate hundreds of later
|
||||
// activities while one is outstanding — a request that has scrolled out of
|
||||
// the window is one whose turn kept running, i.e. it was resolved or went
|
||||
// stale. (The projection pipeline's pendingApprovalCount reads the same
|
||||
// capped stream and stays consistent with this view.)
|
||||
function hasOpenBlockingRequest(thread: {
|
||||
readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
|
||||
}): boolean {
|
||||
@@ -86,62 +79,6 @@ function hasOpenBlockingRequest(thread: {
|
||||
return openRequestIds.size > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A queued turn start — a user message no turn has picked up yet — is work
|
||||
* in flight even though session is still null (turn.start emits
|
||||
* message-sent + turn-start-requested; the session arrives later). Detection
|
||||
* mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
* strictly newer than every latestTurn timestamp (adoption stamps the new
|
||||
* turn's requestedAt with the message time, clearing this), and only within
|
||||
* the adoption grace window — historical threads whose last user message
|
||||
* postdates their turn timestamps (older-server data, mid-turn messages)
|
||||
* must not be blocked forever. A failed session start (status "error")
|
||||
* clears the block immediately.
|
||||
*
|
||||
* The age check is bounded on BOTH sides: message timestamps are
|
||||
* client-supplied, so a client clock ahead of the server yields a negative
|
||||
* age. Without the lower bound that negative age satisfies `<= grace` for
|
||||
* as long as the skew lasts, extending the block far past the intended two
|
||||
* minutes.
|
||||
*/
|
||||
function threadHasQueuedTurnStart(
|
||||
thread: {
|
||||
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
|
||||
readonly latestTurn: {
|
||||
readonly requestedAt: string;
|
||||
readonly startedAt: string | null;
|
||||
readonly completedAt: string | null;
|
||||
} | null;
|
||||
readonly session: { readonly status: string } | null;
|
||||
},
|
||||
occurredAt: string,
|
||||
): boolean {
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
return (
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS
|
||||
);
|
||||
}
|
||||
|
||||
function withEventBase(
|
||||
input: Pick<OrchestrationCommand, "commandId"> & {
|
||||
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
|
||||
@@ -474,8 +411,46 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
);
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
// Settling inside the adoption window would hide just-requested work.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
// A queued turn start — a user message no turn has picked up yet — is
|
||||
// work in flight even though session is still null (turn.start emits
|
||||
// message-sent + turn-start-requested; the session arrives later).
|
||||
// Settling in that window would hide just-requested work. Detection
|
||||
// mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
// strictly newer than every latestTurn timestamp (adoption stamps the
|
||||
// new turn's requestedAt with the message time, clearing this), and
|
||||
// only within the adoption grace window — historical threads whose
|
||||
// last user message postdates their turn timestamps (older-server
|
||||
// data, mid-turn messages) must stay settleable. A failed session
|
||||
// start (status "error") clears the block immediately.
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
// The age check is bounded on BOTH sides: message timestamps are
|
||||
// client-supplied, so a client clock ahead of the server yields a
|
||||
// negative age. Without the lower bound that negative age satisfies
|
||||
// `<= grace` for as long as the skew lasts, extending the settle
|
||||
// block far past the intended two minutes.
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
const hasQueuedTurnStart =
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS;
|
||||
if (hasQueuedTurnStart) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
@@ -533,103 +508,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.snooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
// A wake time in the past would create a thread that is snoozed and
|
||||
// woken at once — the row would never leave the inbox but still carry
|
||||
// snooze state. Reject instead of silently normalizing. The negated
|
||||
// comparison also catches unparseable wake times (IsoDateTime is
|
||||
// structurally just a string): NaN fails every comparison, and an
|
||||
// unparseable snoozedUntil must never persist.
|
||||
if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Blocked-on-you work must not be snoozed away: a pending approval or
|
||||
// user-input request is the agent waiting on the user, and hiding it
|
||||
// defeats the request. (A running session IS snoozable — snooze only
|
||||
// affects visibility, never the agent.)
|
||||
if (hasOpenBlockingRequest(thread)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// A queued turn start — a user message no turn has adopted yet — is
|
||||
// invisible pending work: no session, no pending flags. Snoozing in
|
||||
// that window would hide a just-requested turn exactly the way settle
|
||||
// would.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Re-snoozing an already-snoozed thread to the SAME wake time is a
|
||||
// duplicate (double-click, raced clients): re-emit with the original
|
||||
// timestamps so the projection is a no-op. A different wake time is a
|
||||
// real change and stamps fresh.
|
||||
const existingSnoozedAt =
|
||||
thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
|
||||
? thread.snoozedAt
|
||||
: null;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.snoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
snoozedUntil: command.snoozedUntil,
|
||||
snoozedAt: existingSnoozedAt ?? occurredAt,
|
||||
updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unsnooze": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Idempotent by re-emission (see thread.settle): waking a thread that
|
||||
// is not snoozed lands on the same null state without churning
|
||||
// updatedAt.
|
||||
const alreadyAwake = thread.snoozedUntil == null;
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: command.reason,
|
||||
updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
@@ -785,42 +663,24 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
// Real activity resets ANY override: it wakes an explicitly settled
|
||||
// thread, and it clears a keep-active pin back to neutral so the
|
||||
// thread can auto-settle again after this burst of work goes stale.
|
||||
// A snooze clears the same way — sending a message to a snoozed
|
||||
// thread is the user re-engaging, so the return ticket is spent.
|
||||
const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
if (targetThread.settledOverride !== null) {
|
||||
lifecycleResetEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
});
|
||||
if (targetThread.settledOverride === null) {
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
if (targetThread.snoozedUntil != null) {
|
||||
lifecycleResetEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
|
||||
case "thread.turn.interrupt": {
|
||||
@@ -962,12 +822,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
// Only a session coming alive is activity worth waking a settled thread
|
||||
// for — status writes like ready/stopped/error arrive after the fact and
|
||||
// must not fight a user's explicit settle. Snooze is deliberately NOT
|
||||
// cleared here: snooze never pauses the agent, so its session starting
|
||||
// or erroring is not the user re-engaging. Blocked/failed work still
|
||||
// surfaces immediately — effectiveSnoozed refuses to classify a thread
|
||||
// with a raised hand (approval / input / failure / fresh completion)
|
||||
// as snoozed, without spending the return ticket.
|
||||
// must not fight a user's explicit settle.
|
||||
const isSessionActivity =
|
||||
command.session.status === "starting" || command.session.status === "running";
|
||||
// Real activity resets ANY override (settled wakes, active unpins).
|
||||
|
||||
@@ -91,8 +91,6 @@ describe("orchestration projector", () => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -23,10 +23,8 @@ import {
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadSnoozedPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadUnsnoozedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -292,8 +290,6 @@ export function projectEvent(
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -369,30 +365,6 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.snoozed":
|
||||
return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: payload.snoozedUntil,
|
||||
snoozedAt: payload.snoozedAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unsnoozed":
|
||||
return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
@@ -93,8 +93,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -155,8 +153,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-03-25T00:00:00.000Z",
|
||||
snoozedUntil: "2026-03-26T09:00:00.000Z",
|
||||
snoozedAt: "2026-03-25T00:00:00.000Z",
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -173,17 +169,12 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
}
|
||||
assert.strictEqual(row.settledOverride, "settled");
|
||||
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
|
||||
|
||||
// Un-settle to the keep-active pin and wake the snooze; confirm the
|
||||
// flips persist.
|
||||
// Un-settle to the keep-active pin and confirm the flip persists.
|
||||
yield* threads.upsert({
|
||||
...row,
|
||||
settledOverride: "active",
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
});
|
||||
const repersisted = yield* threads.getById({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
@@ -191,8 +182,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
const updated = Option.getOrNull(repersisted);
|
||||
assert.strictEqual(updated?.settledOverride, "active");
|
||||
assert.strictEqual(updated?.settledAt, null);
|
||||
assert.strictEqual(updated?.snoozedUntil, null);
|
||||
assert.strictEqual(updated?.snoozedAt, null);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -45,8 +45,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
snoozed_until,
|
||||
snoozed_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
@@ -68,8 +66,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.archivedAt},
|
||||
${row.settledOverride},
|
||||
${row.settledAt},
|
||||
${row.snoozedUntil},
|
||||
${row.snoozedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -91,8 +87,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at = excluded.archived_at,
|
||||
settled_override = excluded.settled_override,
|
||||
settled_at = excluded.settled_at,
|
||||
snoozed_until = excluded.snoozed_until,
|
||||
snoozed_at = excluded.snoozed_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
@@ -121,8 +115,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -153,8 +145,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
|
||||
@@ -46,7 +46,6 @@ import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.
|
||||
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
|
||||
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
|
||||
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
|
||||
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -92,7 +91,6 @@ export const migrationEntries = [
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (!columns.some((column) => column.name === "snoozed_until")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_until TEXT
|
||||
`;
|
||||
}
|
||||
|
||||
if (!columns.some((column) => column.name === "snoozed_at")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN snoozed_at TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -38,8 +38,6 @@ export const ProjectionThread = Schema.Struct({
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
|
||||
settledAt: Schema.NullOr(IsoDateTime),
|
||||
snoozedUntil: Schema.NullOr(IsoDateTime),
|
||||
snoozedAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
|
||||
@@ -118,7 +118,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { cwd } = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
@@ -166,11 +165,9 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
effectiveConfig,
|
||||
() => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
|
||||
processEnv,
|
||||
cwd,
|
||||
).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,205 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import { discoverClaudeSkills } from "./ClaudeSkills.ts";
|
||||
|
||||
const writeSkill = Effect.fn(function* (
|
||||
skillsDir: string,
|
||||
directoryName: string,
|
||||
contents: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const skillDir = path.join(skillsDir, directoryName);
|
||||
yield* fs.makeDirectory(skillDir, { recursive: true });
|
||||
yield* fs.writeFileString(path.join(skillDir, "SKILL.md"), contents);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
|
||||
it.effect("discovers user and project skills with frontmatter metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const configDir = path.join(tempDir, "claude-home");
|
||||
const workspace = path.join(tempDir, "workspace");
|
||||
|
||||
yield* writeSkill(
|
||||
path.join(configDir, "skills"),
|
||||
"codex-review",
|
||||
[
|
||||
"---",
|
||||
"name: codex-review",
|
||||
"description: Ask Codex for a review.",
|
||||
"---",
|
||||
"",
|
||||
"# Body",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* writeSkill(
|
||||
path.join(workspace, ".claude", "skills"),
|
||||
"deploy",
|
||||
["---", "name: deploy", "description: Deploy the app.", "---", "", "# Deploy"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
|
||||
|
||||
assert.deepEqual(skills, [
|
||||
{
|
||||
name: "codex-review",
|
||||
path: path.join(configDir, "skills", "codex-review", "SKILL.md"),
|
||||
enabled: true,
|
||||
scope: "user",
|
||||
description: "Ask Codex for a review.",
|
||||
},
|
||||
{
|
||||
name: "deploy",
|
||||
path: path.join(workspace, ".claude", "skills", "deploy", "SKILL.md"),
|
||||
enabled: true,
|
||||
scope: "project",
|
||||
description: "Deploy the app.",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers project skills over user skills on name collisions", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const configDir = path.join(tempDir, "claude-home");
|
||||
const workspace = path.join(tempDir, "workspace");
|
||||
|
||||
yield* writeSkill(
|
||||
path.join(configDir, "skills"),
|
||||
"deploy",
|
||||
["---", "name: deploy", "description: User deploy.", "---"].join("\n"),
|
||||
);
|
||||
yield* writeSkill(
|
||||
path.join(workspace, ".claude", "skills"),
|
||||
"deploy",
|
||||
["---", "name: deploy", "description: Project deploy.", "---"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
|
||||
|
||||
assert.equal(skills.length, 1);
|
||||
assert.equal(skills[0]?.scope, "project");
|
||||
assert.equal(skills[0]?.description, "Project deploy.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the directory name and skips malformed frontmatter", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const configDir = path.join(tempDir, "claude-home");
|
||||
const skillsDir = path.join(configDir, "skills");
|
||||
|
||||
yield* writeSkill(skillsDir, "no-frontmatter", "# Just a heading\n");
|
||||
yield* writeSkill(skillsDir, "broken-yaml", "---\nname: [unclosed\n---\n");
|
||||
// A stray file (not a directory with SKILL.md) must be skipped.
|
||||
yield* fs.makeDirectory(skillsDir, { recursive: true });
|
||||
yield* fs.writeFileString(path.join(skillsDir, "README.md"), "not a skill");
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: configDir }, undefined);
|
||||
|
||||
// A skill with no frontmatter falls back to its directory name; a skill
|
||||
// whose frontmatter fails to parse is skipped entirely (Claude Code
|
||||
// won't load it either).
|
||||
assert.deepEqual(
|
||||
skills.map((skill) => skill.name),
|
||||
["no-frontmatter"],
|
||||
);
|
||||
assert.equal(skills[0]?.description, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("honors CLAUDE_CONFIG_DIR from the environment when homePath is unset", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const environmentConfigDir = path.join(tempDir, "env-config");
|
||||
|
||||
yield* writeSkill(
|
||||
path.join(environmentConfigDir, "skills"),
|
||||
"env-skill",
|
||||
["---", "name: env-skill", "description: From env config dir.", "---"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: "" }, undefined, {
|
||||
CLAUDE_CONFIG_DIR: environmentConfigDir,
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
skills.map((skill) => skill.name),
|
||||
["env-skill"],
|
||||
);
|
||||
|
||||
// An explicit homePath wins over the environment variable, matching
|
||||
// makeClaudeEnvironment which overwrites CLAUDE_CONFIG_DIR for the CLI.
|
||||
const explicitHome = path.join(tempDir, "explicit-home");
|
||||
yield* writeSkill(
|
||||
path.join(explicitHome, "skills"),
|
||||
"explicit-skill",
|
||||
["---", "name: explicit-skill", "---"].join("\n"),
|
||||
);
|
||||
const explicitSkills = yield* discoverClaudeSkills({ homePath: explicitHome }, undefined, {
|
||||
CLAUDE_CONFIG_DIR: environmentConfigDir,
|
||||
});
|
||||
assert.deepEqual(
|
||||
explicitSkills.map((skill) => skill.name),
|
||||
["explicit-skill"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves a relative CLAUDE_CONFIG_DIR against the workspace cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const workspace = path.join(tempDir, "workspace");
|
||||
yield* fs.makeDirectory(workspace, { recursive: true });
|
||||
|
||||
// The spawned CLI resolves a relative CLAUDE_CONFIG_DIR against its own
|
||||
// cwd (the workspace), so discovery must do the same.
|
||||
yield* writeSkill(
|
||||
path.join(workspace, "relative-config", "skills"),
|
||||
"relative-skill",
|
||||
["---", "name: relative-skill", "---"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: "" }, workspace, {
|
||||
CLAUDE_CONFIG_DIR: "relative-config",
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
skills.map((skill) => skill.name),
|
||||
["relative-skill"],
|
||||
);
|
||||
assert.equal(skills[0]?.scope, "user");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns an empty list when no skill roots exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
|
||||
const skills = yield* discoverClaudeSkills(
|
||||
{ homePath: path.join(tempDir, "missing-home") },
|
||||
path.join(tempDir, "missing-workspace"),
|
||||
);
|
||||
|
||||
assert.deepEqual(skills, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,148 +0,0 @@
|
||||
/**
|
||||
* ClaudeSkills — filesystem discovery of Claude Code skills for the `$` picker.
|
||||
*
|
||||
* Claude Code loads skills from `<config dir>/skills` (user scope) and
|
||||
* `<cwd>/.claude/skills` (project scope), one directory per skill with a
|
||||
* `SKILL.md` carrying YAML frontmatter. The Agent SDK init handshake surfaces
|
||||
* skills only as slash commands without their filesystem paths, so the
|
||||
* provider snapshot scans the same locations directly, mirroring how the
|
||||
* Codex app-server reports its skills.
|
||||
*
|
||||
* @module provider/Drivers/ClaudeSkills
|
||||
*/
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import { parse as parseYamlDocument } from "yaml";
|
||||
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
|
||||
type ClaudeSkillScope = "user" | "project";
|
||||
|
||||
const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
|
||||
|
||||
type SkillFrontmatter =
|
||||
| { readonly kind: "missing" }
|
||||
| { readonly kind: "malformed" }
|
||||
| { readonly kind: "parsed"; readonly name?: string; readonly description?: string };
|
||||
|
||||
function parseSkillFrontmatter(contents: string): SkillFrontmatter {
|
||||
const match = FRONTMATTER_PATTERN.exec(contents);
|
||||
if (!match) {
|
||||
return { kind: "missing" };
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = parseYamlDocument(match[1] ?? "");
|
||||
} catch {
|
||||
return { kind: "malformed" };
|
||||
}
|
||||
if (typeof parsed !== "object" || parsed === null) {
|
||||
return { kind: "malformed" };
|
||||
}
|
||||
|
||||
const record = parsed as Record<string, unknown>;
|
||||
const name = typeof record.name === "string" ? record.name.trim() : "";
|
||||
const description = typeof record.description === "string" ? record.description.trim() : "";
|
||||
return {
|
||||
kind: "parsed",
|
||||
...(name ? { name } : {}),
|
||||
...(description ? { description } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the Claude config directory the CLI would use, matching the
|
||||
* precedence the spawned CLI sees: the instance's `homePath` (exported as
|
||||
* `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`
|
||||
* already present in the process environment, then `~/.claude`.
|
||||
*/
|
||||
const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
|
||||
config: Pick<ClaudeSettings, "homePath">,
|
||||
environment: NodeJS.ProcessEnv,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<string, never, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const homePath = config.homePath.trim();
|
||||
if (homePath.length > 0) {
|
||||
return path.resolve(expandHomePath(homePath));
|
||||
}
|
||||
// No tilde expansion here: the spawned CLI receives this env var verbatim
|
||||
// (env vars are never shell-expanded), so a literal `~` must stay literal
|
||||
// for discovery to scan the same directory the runtime would. A relative
|
||||
// value is resolved against the workspace cwd — the subprocess's own cwd —
|
||||
// for the same reason.
|
||||
const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
|
||||
if (environmentConfigDir.length > 0) {
|
||||
return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
|
||||
}
|
||||
return path.join(NodeOS.homedir(), ".claude");
|
||||
});
|
||||
|
||||
/**
|
||||
* Enumerate Claude Code skills from the user config dir and the workspace.
|
||||
* Discovery is best-effort: unreadable roots and malformed skill entries are
|
||||
* skipped so a broken skill never degrades the provider snapshot. On name
|
||||
* collisions the project-scoped skill wins, matching Claude Code's
|
||||
* most-specific-wins resolution.
|
||||
*/
|
||||
export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
|
||||
config: Pick<ClaudeSettings, "homePath">,
|
||||
cwd?: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
|
||||
|
||||
const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [
|
||||
{ directory: path.join(configDirPath, "skills"), scope: "user" },
|
||||
...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
|
||||
];
|
||||
|
||||
const skillsByName = new Map<string, ServerProviderSkill>();
|
||||
for (const root of roots) {
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(root.directory)
|
||||
.pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
|
||||
|
||||
for (const entry of [...entries].sort()) {
|
||||
const skillPath = path.join(root.directory, entry, "SKILL.md");
|
||||
const contents = yield* fileSystem
|
||||
.readFileString(skillPath)
|
||||
.pipe(Effect.orElseSucceed(() => undefined));
|
||||
if (contents === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const frontmatter = parseSkillFrontmatter(contents);
|
||||
// Malformed frontmatter means the skill won't load in Claude Code
|
||||
// either — skip it rather than surfacing a broken entry under its
|
||||
// directory name.
|
||||
if (frontmatter.kind === "malformed") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = (frontmatter.kind === "parsed" ? frontmatter.name : undefined) ?? entry.trim();
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
skillsByName.set(name, {
|
||||
name,
|
||||
path: skillPath,
|
||||
enabled: true,
|
||||
scope: root.scope,
|
||||
...(frontmatter.kind === "parsed" && frontmatter.description
|
||||
? { description: frontmatter.description }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Result from "effect/Result";
|
||||
@@ -41,7 +40,6 @@ import {
|
||||
} from "../providerSnapshot.ts";
|
||||
import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
|
||||
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
|
||||
import { discoverClaudeSkills } from "../Drivers/ClaudeSkills.ts";
|
||||
|
||||
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [],
|
||||
@@ -734,11 +732,10 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings: ClaudeSettings,
|
||||
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
ChildProcessSpawner.ChildProcessSpawner | Path.Path
|
||||
> {
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
@@ -848,7 +845,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
const capabilities = resolveCapabilities
|
||||
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
|
||||
: undefined;
|
||||
const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
|
||||
const slashCommands = capabilities?.slashCommands ?? [];
|
||||
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
|
||||
|
||||
@@ -859,7 +855,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -881,7 +876,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
classifyCheckpointPaths,
|
||||
formatCheckpointCommitMessage,
|
||||
parseCheckpointCommitMessage,
|
||||
parseRawDiffEntries,
|
||||
type RawDiffEntry,
|
||||
} from "./CheckpointAttribution.ts";
|
||||
|
||||
const ZERO_OID = "0".repeat(40);
|
||||
|
||||
function entry(overrides: Partial<RawDiffEntry> & { path: string }): RawDiffEntry {
|
||||
return {
|
||||
srcMode: "100644",
|
||||
dstMode: "100644",
|
||||
srcOid: "a".repeat(40),
|
||||
dstOid: "b".repeat(40),
|
||||
status: "M",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("checkpoint commit message metadata", () => {
|
||||
it("round-trips head and branch", () => {
|
||||
const message = formatCheckpointCommitMessage({
|
||||
checkpointRef: "refs/t3/checkpoints/x/turn/3",
|
||||
headOid: "c".repeat(40),
|
||||
branch: "feature/attribution",
|
||||
});
|
||||
expect(parseCheckpointCommitMessage(message)).toEqual({
|
||||
headOid: "c".repeat(40),
|
||||
branch: "feature/attribution",
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips null head (unborn HEAD)", () => {
|
||||
const message = formatCheckpointCommitMessage({
|
||||
checkpointRef: "refs/t3/checkpoints/x/turn/0",
|
||||
headOid: null,
|
||||
branch: null,
|
||||
});
|
||||
expect(parseCheckpointCommitMessage(message)).toEqual({ headOid: null, branch: null });
|
||||
});
|
||||
|
||||
it("returns null for legacy messages without metadata", () => {
|
||||
expect(parseCheckpointCommitMessage("t3 checkpoint ref=refs/t3/checkpoints/x/turn/1")).toBe(
|
||||
null,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseRawDiffEntries", () => {
|
||||
it("parses NUL-separated raw records", () => {
|
||||
const src = "a".repeat(40);
|
||||
const dst = "b".repeat(40);
|
||||
const output = `:100644 100644 ${src} ${dst} M\0src/index.ts\0:000000 100644 ${ZERO_OID} ${dst} A\0new file.ts\0`;
|
||||
expect(parseRawDiffEntries(output)).toEqual([
|
||||
{
|
||||
srcMode: "100644",
|
||||
dstMode: "100644",
|
||||
srcOid: src,
|
||||
dstOid: dst,
|
||||
status: "M",
|
||||
path: "src/index.ts",
|
||||
},
|
||||
{
|
||||
srcMode: "000000",
|
||||
dstMode: "100644",
|
||||
srcOid: ZERO_OID,
|
||||
dstOid: dst,
|
||||
status: "A",
|
||||
path: "new file.ts",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns empty for empty output", () => {
|
||||
expect(parseRawDiffEntries("")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyCheckpointPaths", () => {
|
||||
it("attributes a pull-only change to git", () => {
|
||||
const pulled = entry({ path: "upstream.ts" });
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [pulled],
|
||||
historyDelta: [pulled],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("upstream.ts")).toBe("git");
|
||||
});
|
||||
|
||||
it("attributes tool edits to agent (no history match)", () => {
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [entry({ path: "edited.ts" })],
|
||||
historyDelta: [],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("edited.ts")).toBe("agent");
|
||||
});
|
||||
|
||||
it("keeps a file the agent committed during the turn as agent work", () => {
|
||||
const committed = entry({ path: "committed.ts" });
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [committed],
|
||||
historyDelta: [committed],
|
||||
turnAuthoredPaths: new Set(["committed.ts"]),
|
||||
});
|
||||
expect(origins.get("committed.ts")).toBe("agent");
|
||||
});
|
||||
|
||||
it("attributes a pulled-then-edited file to agent (blob transition differs)", () => {
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [entry({ path: "both.ts", dstOid: "d".repeat(40) })],
|
||||
historyDelta: [entry({ path: "both.ts", dstOid: "e".repeat(40) })],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("both.ts")).toBe("agent");
|
||||
});
|
||||
|
||||
it("attributes mode-only mismatches to agent", () => {
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [entry({ path: "script.sh", dstMode: "100755" })],
|
||||
historyDelta: [entry({ path: "script.sh", dstMode: "100644" })],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("script.sh")).toBe("agent");
|
||||
});
|
||||
|
||||
it("attributes checkout deletions and additions to git", () => {
|
||||
const removed = entry({
|
||||
path: "only-on-old-branch.ts",
|
||||
dstMode: "000000",
|
||||
dstOid: ZERO_OID,
|
||||
status: "D",
|
||||
});
|
||||
const added = entry({
|
||||
path: "only-on-new-branch.ts",
|
||||
srcMode: "000000",
|
||||
srcOid: ZERO_OID,
|
||||
status: "A",
|
||||
});
|
||||
const origins = classifyCheckpointPaths({
|
||||
treeDelta: [removed, added],
|
||||
historyDelta: [removed, added],
|
||||
turnAuthoredPaths: new Set(),
|
||||
});
|
||||
expect(origins.get("only-on-old-branch.ts")).toBe("git");
|
||||
expect(origins.get("only-on-new-branch.ts")).toBe("git");
|
||||
});
|
||||
});
|
||||
Binary file not shown.
@@ -29,6 +29,12 @@ import {
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
|
||||
import {
|
||||
classifyCheckpointPaths,
|
||||
formatCheckpointCommitMessage,
|
||||
parseCheckpointCommitMessage,
|
||||
parseRawDiffEntries,
|
||||
} from "./CheckpointAttribution.ts";
|
||||
import * as VcsDriver from "./VcsDriver.ts";
|
||||
import * as VcsProcess from "./VcsProcess.ts";
|
||||
|
||||
@@ -636,6 +642,22 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
}),
|
||||
);
|
||||
|
||||
const resolveHeadBranch = (cwd: string) =>
|
||||
execute({
|
||||
operation: "GitVcsDriver.checkpoints.resolveHeadBranch",
|
||||
cwd,
|
||||
args: ["symbolic-ref", "--short", "--quiet", "HEAD"],
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
return null;
|
||||
}
|
||||
const branch = result.stdout.trim();
|
||||
return branch.length > 0 ? branch : null;
|
||||
}),
|
||||
);
|
||||
|
||||
const resolveGitCommonDir = (cwd: string) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* execute({
|
||||
@@ -669,8 +691,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
.pipe(Effect.ignore);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
const headCommit = yield* resolveHeadCommit(input.cwd);
|
||||
const headBranch = yield* resolveHeadBranch(input.cwd);
|
||||
if (headCommit) {
|
||||
yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
@@ -703,7 +726,11 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
});
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const message = formatCheckpointCommitMessage({
|
||||
checkpointRef: input.checkpointRef,
|
||||
headOid: headCommit,
|
||||
branch: headBranch,
|
||||
});
|
||||
const commitTreeResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
@@ -848,6 +875,262 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
attributeCheckpointDiff: Effect.fn("GitVcsDriver.checkpoints.attributeCheckpointDiff")(
|
||||
function* (input) {
|
||||
const operation = "GitVcsDriver.checkpoints.attributeCheckpointDiff";
|
||||
|
||||
const readCommitField = (revision: string, format: string) =>
|
||||
execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["log", "-1", `--format=${format}`, revision, "--"],
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trimEnd() : null)));
|
||||
|
||||
const fromMessage = yield* readCommitField(`${input.fromCheckpointRef}^{commit}`, "%B");
|
||||
const toMessage = yield* readCommitField(`${input.toCheckpointRef}^{commit}`, "%B");
|
||||
if (fromMessage === null || toMessage === null) {
|
||||
return null;
|
||||
}
|
||||
const fromMetadata = parseCheckpointCommitMessage(fromMessage);
|
||||
const toMetadata = parseCheckpointCommitMessage(toMessage);
|
||||
// Checkpoints captured before attribution metadata existed: unavailable.
|
||||
if (fromMetadata === null || toMetadata === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// HEAD did not move during the turn (or the repo has no commits):
|
||||
// every tree change is agent-authored. An empty map means "classified,
|
||||
// no git-origin paths".
|
||||
if (fromMetadata.headOid === toMetadata.headOid || fromMetadata.headOid === null) {
|
||||
return new Map<string, "agent" | "git">();
|
||||
}
|
||||
if (toMetadata.headOid === null) {
|
||||
// HEAD disappeared mid-turn (e.g. re-init); fail toward "agent".
|
||||
return new Map<string, "agent" | "git">();
|
||||
}
|
||||
|
||||
const rawDiff = (fromRevision: string, toRevision: string) =>
|
||||
execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"diff-tree",
|
||||
"-r",
|
||||
"-z",
|
||||
"--no-abbrev",
|
||||
"--no-renames",
|
||||
fromRevision,
|
||||
toRevision,
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
}).pipe(
|
||||
Effect.map((result) =>
|
||||
result.exitCode === 0 && !result.stdoutTruncated
|
||||
? parseRawDiffEntries(result.stdout)
|
||||
: null,
|
||||
),
|
||||
);
|
||||
|
||||
const treeDelta = yield* rawDiff(
|
||||
`${input.fromCheckpointRef}^{commit}`,
|
||||
`${input.toCheckpointRef}^{commit}`,
|
||||
);
|
||||
const historyDelta = yield* rawDiff(fromMetadata.headOid, toMetadata.headOid);
|
||||
if (treeDelta === null || historyDelta === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The baseline checkpoint commit is created at turn start, so its
|
||||
// committer timestamp is the turn-start time. Commits in the HEAD
|
||||
// range split three ways:
|
||||
// - authored at/after turn start: made during the turn → agent work.
|
||||
// - authored before AND committed before: pre-existing content that
|
||||
// moved into the range wholesale (pull, checkout, merge fast path).
|
||||
// - authored before but COMMITTED during the turn: rewritten by a
|
||||
// history-editing command. Cherry-pick and rebase preserve author
|
||||
// dates while re-committing, and so does `commit --amend` — but an
|
||||
// amend carries NEW agent content while a replay carries old
|
||||
// content. Disambiguated below by patch-id (--verbatim, so
|
||||
// whitespace-only amends don't collide with their pre-amend
|
||||
// original): a rewritten commit whose byte-exact patch exists
|
||||
// elsewhere in the repo (branches, remotes, or reflog — the
|
||||
// latter catches pre-rebase originals) is a replay → demote;
|
||||
// otherwise treat as agent work → show.
|
||||
const fromCommitTimeRaw = yield* readCommitField(
|
||||
`${input.fromCheckpointRef}^{commit}`,
|
||||
"%ct",
|
||||
);
|
||||
const fromCommitTime = fromCommitTimeRaw === null ? NaN : Number(fromCommitTimeRaw);
|
||||
if (!Number.isFinite(fromCommitTime)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const headRangeResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"log",
|
||||
"--format=%H %at %ct %p",
|
||||
`${fromMetadata.headOid}..${toMetadata.headOid}`,
|
||||
"--",
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (headRangeResult.exitCode !== 0 || headRangeResult.stdoutTruncated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
interface RangeCommit {
|
||||
readonly oid: string;
|
||||
readonly isMerge: boolean;
|
||||
}
|
||||
const turnAuthoredCommits: Array<RangeCommit> = [];
|
||||
const rewrittenCommits: Array<RangeCommit> = [];
|
||||
for (const line of headRangeResult.stdout.split("\n")) {
|
||||
const [oid, authorTime, commitTime, ...parents] = line.trim().split(" ");
|
||||
if (!oid || !authorTime || !commitTime) {
|
||||
continue;
|
||||
}
|
||||
const authoredAt = Number(authorTime);
|
||||
const committedAt = Number(commitTime);
|
||||
if (!Number.isFinite(authoredAt) || !Number.isFinite(committedAt)) {
|
||||
continue;
|
||||
}
|
||||
const commit: RangeCommit = { oid, isMerge: parents.length > 1 };
|
||||
if (authoredAt >= fromCommitTime) {
|
||||
turnAuthoredCommits.push(commit);
|
||||
} else if (committedAt >= fromCommitTime) {
|
||||
rewrittenCommits.push(commit);
|
||||
}
|
||||
}
|
||||
if (rewrittenCommits.length > 100) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Batch patch-id computation: diff-tree --stdin -p streams every
|
||||
// commit's patch prefixed by its oid, which `git patch-id` consumes
|
||||
// directly. Failures degrade to an empty map, which classifies the
|
||||
// affected rewritten commits as agent work (shown).
|
||||
const patchIdsForCommits = (oids: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
if (oids.length === 0) {
|
||||
return new Map<string, string>();
|
||||
}
|
||||
const patches = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["diff-tree", "--stdin", "-p", "--no-renames", "--root"],
|
||||
stdin: `${oids.join("\n")}\n`,
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (patches.exitCode !== 0 || patches.stdoutTruncated) {
|
||||
return new Map<string, string>();
|
||||
}
|
||||
const ids = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["patch-id", "--verbatim"],
|
||||
stdin: patches.stdout,
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (ids.exitCode !== 0 || ids.stdoutTruncated) {
|
||||
return new Map<string, string>();
|
||||
}
|
||||
const byCommit = new Map<string, string>();
|
||||
for (const line of ids.stdout.split("\n")) {
|
||||
const [patchId, commitId] = line.trim().split(" ");
|
||||
if (patchId && commitId) {
|
||||
byCommit.set(commitId, patchId);
|
||||
}
|
||||
}
|
||||
return byCommit;
|
||||
});
|
||||
|
||||
if (rewrittenCommits.length > 0) {
|
||||
const candidatesResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"rev-list",
|
||||
"-n",
|
||||
"500",
|
||||
"--branches",
|
||||
"--tags",
|
||||
"--remotes",
|
||||
"--reflog",
|
||||
"--not",
|
||||
toMetadata.headOid,
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
const candidateOids =
|
||||
candidatesResult.exitCode === 0 && !candidatesResult.stdoutTruncated
|
||||
? candidatesResult.stdout.split("\n").filter((line) => line.length > 0)
|
||||
: [];
|
||||
const candidatePatchIds = new Set((yield* patchIdsForCommits(candidateOids)).values());
|
||||
const rewrittenPatchIds = yield* patchIdsForCommits(
|
||||
rewrittenCommits.map((commit) => commit.oid),
|
||||
);
|
||||
for (const commit of rewrittenCommits) {
|
||||
const patchId = rewrittenPatchIds.get(commit.oid);
|
||||
if (patchId === undefined || !candidatePatchIds.has(patchId)) {
|
||||
turnAuthoredCommits.push(commit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A pathological number of turn-authored commits (e.g. clock skew
|
||||
// misclassifying a pulled range) would mean one diff-tree call per
|
||||
// commit; skip attribution instead — the diff renders unfiltered.
|
||||
if (turnAuthoredCommits.length > 100) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const turnAuthoredPaths = new Set<string>();
|
||||
for (const commit of turnAuthoredCommits) {
|
||||
const pathsResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"diff-tree",
|
||||
"-r",
|
||||
"-z",
|
||||
"--no-commit-id",
|
||||
"--name-only",
|
||||
// Root commits (orphan branches) have no parent; without
|
||||
// --root they would list no paths and their agent-authored
|
||||
// content would be misattributed to history.
|
||||
"--root",
|
||||
// For merges, the combined diff lists only paths whose result
|
||||
// differs from every parent — i.e. conflict resolutions the
|
||||
// agent authored. Paths taken wholesale from one side are
|
||||
// pre-existing content and stay attributable to history.
|
||||
...(commit.isMerge ? ["-c"] : []),
|
||||
commit.oid,
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (pathsResult.exitCode !== 0 || pathsResult.stdoutTruncated) {
|
||||
return null;
|
||||
}
|
||||
for (const pathValue of pathsResult.stdout.split("\0")) {
|
||||
if (pathValue.length > 0) {
|
||||
turnAuthoredPaths.add(pathValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return classifyCheckpointPaths({ treeDelta, historyDelta, turnAuthoredPaths });
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -38,6 +38,24 @@ export interface VcsDeleteCheckpointRefsInput {
|
||||
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
|
||||
}
|
||||
|
||||
export interface VcsAttributeCheckpointDiffInput {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-path attribution of a checkpoint-to-checkpoint tree delta.
|
||||
*
|
||||
* Paths mapped to "git" are byte-for-byte explained by pre-existing commits
|
||||
* that moved through HEAD during the turn (pull, checkout, cherry-pick,
|
||||
* rebase). Paths mapped to "agent" — and paths absent from the map — were
|
||||
* authored during the turn. `null` means attribution is unavailable (HEAD
|
||||
* metadata missing on either snapshot); callers must treat every path as
|
||||
* agent-authored.
|
||||
*/
|
||||
export type VcsCheckpointAttribution = ReadonlyMap<string, "agent" | "git"> | null;
|
||||
|
||||
export interface VcsCheckpointOps {
|
||||
readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect<void, VcsError>;
|
||||
readonly hasCheckpointRef: (
|
||||
@@ -50,6 +68,9 @@ export interface VcsCheckpointOps {
|
||||
readonly deleteCheckpointRefs: (
|
||||
input: VcsDeleteCheckpointRefsInput,
|
||||
) => Effect.Effect<void, VcsError>;
|
||||
readonly attributeCheckpointDiff: (
|
||||
input: VcsAttributeCheckpointDiffInput,
|
||||
) => Effect.Effect<VcsCheckpointAttribution, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsDriver extends Context.Service<
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { EnvironmentId, ProjectId, type VcsRef } from "@t3tools/contracts";
|
||||
import { EnvironmentId, type VcsRef } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
buildCheckoutWorkspaceChoices,
|
||||
dedupeCheckoutOptions,
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
resolveEnvironmentOptionLabel,
|
||||
@@ -14,8 +12,6 @@ import {
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolveLocalCheckoutBranchMismatch,
|
||||
resolvePreviousWorktreeLabel,
|
||||
resolvePreviousWorktreeSeed,
|
||||
shouldIncludeBranchPickerItem,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
@@ -23,175 +19,6 @@ import {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
|
||||
describe("resolvePreviousWorktreeSeed", () => {
|
||||
it("picks the most recently updated worktree thread", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [
|
||||
{
|
||||
branch: "t3/older",
|
||||
worktreePath: "/repo/.t3/worktrees/older",
|
||||
updatedAt: "2026-07-20T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
branch: "t3/newer",
|
||||
worktreePath: "/repo/.t3/worktrees/newer",
|
||||
updatedAt: "2026-07-22T00:00:00.000Z",
|
||||
},
|
||||
{ branch: "main", worktreePath: null, updatedAt: "2026-07-23T00:00:00.000Z" },
|
||||
],
|
||||
currentWorktreePath: null,
|
||||
}),
|
||||
).toEqual({ branch: "t3/newer", worktreePath: "/repo/.t3/worktrees/newer" });
|
||||
});
|
||||
|
||||
it("skips the worktree the composer already points at", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [
|
||||
{
|
||||
branch: "t3/current",
|
||||
worktreePath: "/repo/.t3/worktrees/current",
|
||||
updatedAt: "2026-07-22T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
currentWorktreePath: "/repo/.t3/worktrees/current",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when no thread has a worktree", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [{ branch: "main", worktreePath: null, updatedAt: "2026-07-22T00:00:00.000Z" }],
|
||||
currentWorktreePath: null,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores archived threads and threads with unparseable timestamps", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [
|
||||
{
|
||||
branch: "t3/archived",
|
||||
worktreePath: "/repo/.t3/worktrees/archived",
|
||||
updatedAt: "2026-07-23T00:00:00.000Z",
|
||||
archivedAt: "2026-07-23T01:00:00.000Z",
|
||||
},
|
||||
{
|
||||
branch: "t3/garbage-timestamp",
|
||||
worktreePath: "/repo/.t3/worktrees/garbage",
|
||||
updatedAt: "not-a-date",
|
||||
},
|
||||
{
|
||||
branch: "t3/live",
|
||||
worktreePath: "/repo/.t3/worktrees/live",
|
||||
updatedAt: "2026-07-21T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
},
|
||||
],
|
||||
currentWorktreePath: null,
|
||||
}),
|
||||
).toEqual({ branch: "t3/live", worktreePath: "/repo/.t3/worktrees/live" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePreviousWorktreeLabel", () => {
|
||||
it("includes the branch when known", () => {
|
||||
expect(resolvePreviousWorktreeLabel({ branch: "t3/fix-thing", worktreePath: "/wt" })).toBe(
|
||||
"Previous worktree (t3/fix-thing)",
|
||||
);
|
||||
expect(resolvePreviousWorktreeLabel({ branch: null, worktreePath: "/wt" })).toBe(
|
||||
"Previous worktree",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCheckoutWorkspaceChoices", () => {
|
||||
it("keeps every same-repository clone selectable as a checkout or worktree base", () => {
|
||||
const firstProjectId = ProjectId.make("project-first-clone");
|
||||
const secondProjectId = ProjectId.make("project-second-clone");
|
||||
|
||||
expect(
|
||||
buildCheckoutWorkspaceChoices([
|
||||
{
|
||||
projectId: firstProjectId,
|
||||
title: "t3code",
|
||||
workspaceRoot: "/src/t3code",
|
||||
},
|
||||
{
|
||||
projectId: secondProjectId,
|
||||
title: "t3code-3",
|
||||
workspaceRoot: "/src/t3code-3",
|
||||
},
|
||||
]).map(({ projectId, mode }) => ({ projectId, mode })),
|
||||
).toEqual([
|
||||
{ projectId: firstProjectId, mode: "local" },
|
||||
{ projectId: firstProjectId, mode: "worktree" },
|
||||
{ projectId: secondProjectId, mode: "local" },
|
||||
{ projectId: secondProjectId, mode: "worktree" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dedupeCheckoutOptions", () => {
|
||||
it("keeps the active project when duplicate normalized roots exist", () => {
|
||||
const staleProjectId = ProjectId.make("project-stale");
|
||||
const activeProjectId = ProjectId.make("project-active");
|
||||
|
||||
expect(
|
||||
dedupeCheckoutOptions(
|
||||
[
|
||||
{
|
||||
projectId: staleProjectId,
|
||||
title: "Stale checkout",
|
||||
workspaceRoot: "C:\\src\\t3code",
|
||||
},
|
||||
{
|
||||
projectId: activeProjectId,
|
||||
title: "Active checkout",
|
||||
workspaceRoot: "C:/src/t3code",
|
||||
},
|
||||
],
|
||||
activeProjectId,
|
||||
),
|
||||
).toEqual([
|
||||
{
|
||||
projectId: activeProjectId,
|
||||
title: "Active checkout",
|
||||
workspaceRoot: "C:/src/t3code",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves checkouts that differ only by path casing", () => {
|
||||
const lowerProjectId = ProjectId.make("project-lower");
|
||||
const upperProjectId = ProjectId.make("project-upper");
|
||||
const checkouts = [
|
||||
{ projectId: lowerProjectId, title: "Lowercase", workspaceRoot: "/src/t3code" },
|
||||
{ projectId: upperProjectId, title: "Uppercase", workspaceRoot: "/src/T3Code" },
|
||||
];
|
||||
|
||||
expect(dedupeCheckoutOptions(checkouts, lowerProjectId)).toEqual(checkouts);
|
||||
});
|
||||
|
||||
it("deduplicates paths that differ only by trailing separators", () => {
|
||||
const staleProjectId = ProjectId.make("project-trailing-slash");
|
||||
const activeProjectId = ProjectId.make("project-no-trailing-slash");
|
||||
|
||||
expect(
|
||||
dedupeCheckoutOptions(
|
||||
[
|
||||
{ projectId: staleProjectId, title: "Stale", workspaceRoot: "/src/t3code/" },
|
||||
{ projectId: activeProjectId, title: "Active", workspaceRoot: "/src/t3code" },
|
||||
],
|
||||
activeProjectId,
|
||||
).map((checkout) => checkout.projectId),
|
||||
).toEqual([activeProjectId]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
|
||||
expect(
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
|
||||
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { toSortableTimestamp } from "../lib/threadSort";
|
||||
export {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
@@ -14,50 +12,9 @@ export interface EnvironmentOption {
|
||||
isPrimary: boolean;
|
||||
}
|
||||
|
||||
export interface CheckoutOption {
|
||||
projectId: ProjectId;
|
||||
title: string;
|
||||
workspaceRoot: string;
|
||||
}
|
||||
|
||||
export interface CheckoutWorkspaceChoice {
|
||||
projectId: ProjectId;
|
||||
mode: EnvMode;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export function dedupeCheckoutOptions(
|
||||
checkouts: readonly CheckoutOption[],
|
||||
activeProjectId: ProjectId,
|
||||
): CheckoutOption[] {
|
||||
const activeCheckout = checkouts.find((checkout) => checkout.projectId === activeProjectId);
|
||||
const orderedCheckouts = activeCheckout
|
||||
? [activeCheckout, ...checkouts.filter((checkout) => checkout.projectId !== activeProjectId)]
|
||||
: checkouts;
|
||||
const seenWorkspaceRoots = new Set<string>();
|
||||
return orderedCheckouts.filter((checkout) => {
|
||||
const workspaceRoot = normalizeProjectPathForComparison(checkout.workspaceRoot);
|
||||
if (seenWorkspaceRoots.has(workspaceRoot)) return false;
|
||||
seenWorkspaceRoots.add(workspaceRoot);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
export const EnvMode = Schema.Literals(["local", "worktree"]);
|
||||
export type EnvMode = typeof EnvMode.Type;
|
||||
|
||||
export function buildCheckoutWorkspaceChoices(
|
||||
checkouts: readonly CheckoutOption[],
|
||||
): CheckoutWorkspaceChoice[] {
|
||||
return checkouts.flatMap((checkout) =>
|
||||
(["local", "worktree"] as const).map((mode) => ({
|
||||
projectId: checkout.projectId,
|
||||
mode,
|
||||
value: JSON.stringify([checkout.projectId, mode]),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const GENERIC_LOCAL_ENVIRONMENT_LABELS = new Set(["local", "local environment"]);
|
||||
|
||||
function normalizeDisplayLabel(value: string | null | undefined): string | null {
|
||||
@@ -108,53 +65,6 @@ export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null):
|
||||
return activeWorktreePath ? "Worktree" : "Local checkout";
|
||||
}
|
||||
|
||||
export interface PreviousWorktreeSeed {
|
||||
branch: string | null;
|
||||
worktreePath: string;
|
||||
}
|
||||
|
||||
// The most recently touched worktree in the project that the composer isn't
|
||||
// already pointing at. Backs the "Previous worktree" entry in the workspace
|
||||
// selector so a follow-up thread can hop back into the worktree you just
|
||||
// worked in without hunting for its branch. Archived threads don't compete —
|
||||
// the rest of the UI hides them, so their worktrees shouldn't resurface here.
|
||||
export function resolvePreviousWorktreeSeed(input: {
|
||||
threads: ReadonlyArray<{
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
updatedAt: string;
|
||||
archivedAt?: string | null;
|
||||
}>;
|
||||
currentWorktreePath: string | null;
|
||||
}): PreviousWorktreeSeed | null {
|
||||
let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
|
||||
for (const thread of input.threads) {
|
||||
if (
|
||||
!thread.worktreePath ||
|
||||
thread.worktreePath === input.currentWorktreePath ||
|
||||
(thread.archivedAt ?? null) !== null
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const updatedAt = toSortableTimestamp(thread.updatedAt);
|
||||
if (updatedAt === null) {
|
||||
continue;
|
||||
}
|
||||
if (latest === null || updatedAt > latest.updatedAt) {
|
||||
latest = {
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
|
||||
}
|
||||
|
||||
export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
|
||||
return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
|
||||
}
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
hasServerThread: boolean;
|
||||
|
||||
@@ -6,24 +6,20 @@ import {
|
||||
FolderGit2Icon,
|
||||
FolderGitIcon,
|
||||
FolderIcon,
|
||||
HistoryIcon,
|
||||
MonitorIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useMemo } from "react";
|
||||
import { memo, useMemo } from "react";
|
||||
|
||||
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
|
||||
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
import { useIsMobile } from "../hooks/useMediaQuery";
|
||||
import {
|
||||
type CheckoutOption,
|
||||
type EnvMode,
|
||||
type EnvironmentOption,
|
||||
resolveCurrentWorkspaceLabel,
|
||||
resolveEnvModeLabel,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolvePreviousWorktreeLabel,
|
||||
resolvePreviousWorktreeSeed,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
@@ -57,8 +53,6 @@ interface BranchToolbarProps {
|
||||
onComposerFocusRequest?: () => void;
|
||||
availableEnvironments?: readonly EnvironmentOption[];
|
||||
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
|
||||
availableCheckouts?: readonly CheckoutOption[];
|
||||
onWorkspaceChange?: (projectId: CheckoutOption["projectId"], mode: EnvMode) => void;
|
||||
}
|
||||
|
||||
interface MobileRunContextSelectorProps {
|
||||
@@ -72,8 +66,6 @@ interface MobileRunContextSelectorProps {
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
previousWorktreeLabel: string | null;
|
||||
onUsePreviousWorktree: () => void;
|
||||
}
|
||||
|
||||
const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
@@ -87,8 +79,6 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
onEnvModeChange,
|
||||
previousWorktreeLabel,
|
||||
onUsePreviousWorktree,
|
||||
}: MobileRunContextSelectorProps) {
|
||||
const activeEnvironment = useMemo(
|
||||
() => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null,
|
||||
@@ -176,13 +166,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<MenuGroupLabel>Workspace</MenuGroupLabel>
|
||||
<MenuRadioGroup
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value) => {
|
||||
if (value === "previous-worktree") {
|
||||
onUsePreviousWorktree();
|
||||
return;
|
||||
}
|
||||
onEnvModeChange(value as EnvMode);
|
||||
}}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
>
|
||||
<MenuRadioItem disabled={envModeLocked} value="local">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
@@ -202,14 +186,6 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
{previousWorktreeLabel ? (
|
||||
<MenuRadioItem disabled={envModeLocked} value="previous-worktree">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
<HistoryIcon className="size-3" />
|
||||
<span className="min-w-0 truncate">{previousWorktreeLabel}</span>
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
) : null}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</MenuPopup>
|
||||
@@ -232,8 +208,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
onComposerFocusRequest,
|
||||
availableEnvironments,
|
||||
onEnvironmentChange,
|
||||
availableCheckouts,
|
||||
onWorkspaceChange,
|
||||
}: BranchToolbarProps) {
|
||||
const threadRef = useMemo(
|
||||
() => scopeThreadRef(environmentId, threadId),
|
||||
@@ -243,7 +217,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const activeProjectRef = serverThread
|
||||
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
|
||||
: draftThread
|
||||
@@ -261,40 +234,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
});
|
||||
const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
|
||||
|
||||
// "Previous worktree" hops a draft into the most recently active worktree
|
||||
// of this project — the "keep going where I just was" follow-up flow. Only
|
||||
// drafts can hop; started server threads have their workspace pinned.
|
||||
const canUsePreviousWorktree = draftThread !== null && serverThread === null && !envModeLocked;
|
||||
const projectRefsForWorktreeLookup = useMemo(
|
||||
() => (canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []),
|
||||
[canUsePreviousWorktree, activeProjectRef],
|
||||
);
|
||||
const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
|
||||
const previousWorktreeSeed = useMemo(
|
||||
() =>
|
||||
canUsePreviousWorktree
|
||||
? resolvePreviousWorktreeSeed({
|
||||
threads: projectThreads,
|
||||
currentWorktreePath: activeWorktreePath,
|
||||
})
|
||||
: null,
|
||||
[activeWorktreePath, canUsePreviousWorktree, projectThreads],
|
||||
);
|
||||
const previousWorktreeLabel = previousWorktreeSeed
|
||||
? resolvePreviousWorktreeLabel(previousWorktreeSeed)
|
||||
: null;
|
||||
const onUsePreviousWorktree = useCallback(() => {
|
||||
if (!previousWorktreeSeed || !activeProjectRef) return;
|
||||
// Same shape the branch selector writes when picking a branch that
|
||||
// already lives in a worktree: point the draft at the existing tree.
|
||||
setDraftThreadContext(draftId ?? threadRef, {
|
||||
branch: previousWorktreeSeed.branch,
|
||||
worktreePath: previousWorktreeSeed.worktreePath,
|
||||
envMode: "worktree",
|
||||
projectRef: activeProjectRef,
|
||||
});
|
||||
}, [activeProjectRef, draftId, previousWorktreeSeed, setDraftThreadContext, threadRef]);
|
||||
|
||||
const showEnvironmentPicker = Boolean(
|
||||
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
|
||||
);
|
||||
@@ -309,7 +248,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
if (!hasActiveThread || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<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 px-1 pt-5 pb-1">
|
||||
<div className="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-1.5rem)] max-w-[calc(48rem-1.5rem)] items-center gap-2 pt-5 pb-1 ps-1">
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
@@ -322,8 +261,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
previousWorktreeLabel={previousWorktreeLabel}
|
||||
onUsePreviousWorktree={onUsePreviousWorktree}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
@@ -343,11 +280,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
previousWorktreeLabel={previousWorktreeLabel}
|
||||
onUsePreviousWorktree={onUsePreviousWorktree}
|
||||
activeProjectId={activeProject.id}
|
||||
availableCheckouts={availableCheckouts ?? []}
|
||||
{...(onWorkspaceChange ? { onWorkspaceChange } : {})}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -731,7 +731,7 @@ export function BranchToolbarBranchSelector({
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="min-w-0 max-w-full text-muted-foreground/70 hover:text-foreground/80"
|
||||
className="min-w-0 text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={isInitialBranchesLoadPending || isBranchActionPending}
|
||||
>
|
||||
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon, HistoryIcon } from "lucide-react";
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon } from "lucide-react";
|
||||
import { memo, useMemo } from "react";
|
||||
|
||||
import {
|
||||
buildCheckoutWorkspaceChoices,
|
||||
type CheckoutOption,
|
||||
resolveCurrentWorkspaceLabel,
|
||||
resolveEnvModeLabel,
|
||||
resolveLockedWorkspaceLabel,
|
||||
@@ -19,30 +17,11 @@ import {
|
||||
SelectValue,
|
||||
} from "./ui/select";
|
||||
|
||||
export const PREVIOUS_WORKTREE_SELECT_VALUE = "previous-worktree";
|
||||
|
||||
interface BranchToolbarEnvModeSelectorProps {
|
||||
envLocked: boolean;
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
activeProjectId: CheckoutOption["projectId"];
|
||||
availableCheckouts: readonly CheckoutOption[];
|
||||
onWorkspaceChange?: (projectId: CheckoutOption["projectId"], mode: EnvMode) => void;
|
||||
previousWorktreeLabel?: string | null;
|
||||
onUsePreviousWorktree?: () => void;
|
||||
}
|
||||
|
||||
function formatCheckoutPath(path: string): string {
|
||||
const normalized = path.replaceAll("\\", "/");
|
||||
const homePrefix = "/Users/";
|
||||
if (normalized.startsWith(homePrefix)) {
|
||||
const segments = normalized.slice(homePrefix.length).split("/");
|
||||
if (segments.length > 1) {
|
||||
return `~/${segments.slice(1).join("/")}`;
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({
|
||||
@@ -50,54 +29,13 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
onEnvModeChange,
|
||||
activeProjectId,
|
||||
availableCheckouts,
|
||||
onWorkspaceChange,
|
||||
previousWorktreeLabel,
|
||||
onUsePreviousWorktree,
|
||||
}: BranchToolbarEnvModeSelectorProps) {
|
||||
const showPreviousWorktree = Boolean(previousWorktreeLabel && onUsePreviousWorktree);
|
||||
const hasMultipleCheckouts = availableCheckouts.length > 1 && onWorkspaceChange !== undefined;
|
||||
const activeCheckout =
|
||||
availableCheckouts.find((checkout) => checkout.projectId === activeProjectId) ?? null;
|
||||
const checkoutChoices = useMemo(
|
||||
() => buildCheckoutWorkspaceChoices(availableCheckouts),
|
||||
[availableCheckouts],
|
||||
);
|
||||
const choiceValue = (projectId: CheckoutOption["projectId"], mode: EnvMode) =>
|
||||
checkoutChoices.find((choice) => choice.projectId === projectId && choice.mode === mode)
|
||||
?.value ?? "";
|
||||
const envModeItems = useMemo(
|
||||
() =>
|
||||
hasMultipleCheckouts
|
||||
? checkoutChoices.map((choice) => {
|
||||
const checkout = availableCheckouts.find(
|
||||
(candidate) => candidate.projectId === choice.projectId,
|
||||
)!;
|
||||
return {
|
||||
value: choice.value,
|
||||
label: `${checkout.title} — ${
|
||||
choice.mode === "local"
|
||||
? resolveCurrentWorkspaceLabel(activeWorktreePath)
|
||||
: resolveEnvModeLabel("worktree")
|
||||
}`,
|
||||
};
|
||||
})
|
||||
: [
|
||||
{ value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) },
|
||||
{ value: "worktree", label: resolveEnvModeLabel("worktree") },
|
||||
...(showPreviousWorktree && previousWorktreeLabel
|
||||
? [{ value: PREVIOUS_WORKTREE_SELECT_VALUE, label: previousWorktreeLabel }]
|
||||
: []),
|
||||
],
|
||||
[
|
||||
activeWorktreePath,
|
||||
availableCheckouts,
|
||||
checkoutChoices,
|
||||
hasMultipleCheckouts,
|
||||
previousWorktreeLabel,
|
||||
showPreviousWorktree,
|
||||
() => [
|
||||
{ value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) },
|
||||
{ value: "worktree", label: resolveEnvModeLabel("worktree") },
|
||||
],
|
||||
[activeWorktreePath],
|
||||
);
|
||||
|
||||
if (envLocked) {
|
||||
@@ -121,23 +59,8 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
return (
|
||||
<Select
|
||||
modal={false}
|
||||
value={
|
||||
hasMultipleCheckouts ? choiceValue(activeProjectId, effectiveEnvMode) : effectiveEnvMode
|
||||
}
|
||||
onValueChange={(value) => {
|
||||
if (value === PREVIOUS_WORKTREE_SELECT_VALUE) {
|
||||
onUsePreviousWorktree?.();
|
||||
return;
|
||||
}
|
||||
if (!hasMultipleCheckouts) {
|
||||
onEnvModeChange(value as EnvMode);
|
||||
return;
|
||||
}
|
||||
const selected = checkoutChoices.find((option) => option.value === value);
|
||||
if (selected) {
|
||||
onWorkspaceChange(selected.projectId, selected.mode);
|
||||
}
|
||||
}}
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
items={envModeItems}
|
||||
>
|
||||
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Workspace">
|
||||
@@ -148,82 +71,28 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
) : (
|
||||
<FolderIcon className="size-3" />
|
||||
)}
|
||||
{hasMultipleCheckouts && activeCheckout ? (
|
||||
<span className="max-w-44 truncate">
|
||||
{activeCheckout.title} ·{" "}
|
||||
{effectiveEnvMode === "worktree"
|
||||
? resolveEnvModeLabel("worktree")
|
||||
: resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
</span>
|
||||
) : (
|
||||
<SelectValue />
|
||||
)}
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup matchTriggerWidth={!hasMultipleCheckouts}>
|
||||
{hasMultipleCheckouts ? (
|
||||
availableCheckouts.map((checkout) => (
|
||||
<SelectGroup key={checkout.projectId}>
|
||||
<SelectGroupLabel>
|
||||
<span className="flex min-w-64 max-w-96 flex-col gap-0.5 py-0.5">
|
||||
<span className="truncate text-foreground">{checkout.title}</span>
|
||||
<span className="truncate font-normal text-muted-foreground/70">
|
||||
{formatCheckoutPath(checkout.workspaceRoot)}
|
||||
</span>
|
||||
</span>
|
||||
</SelectGroupLabel>
|
||||
<SelectItem value={choiceValue(checkout.projectId, "local")}>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<FolderIcon className="size-3" />
|
||||
Current checkout
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value={choiceValue(checkout.projectId, "worktree")}>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<FolderGit2Icon className="size-3" />
|
||||
New worktree…
|
||||
</span>
|
||||
</SelectItem>
|
||||
{checkout.projectId === activeProjectId &&
|
||||
showPreviousWorktree &&
|
||||
previousWorktreeLabel ? (
|
||||
<SelectItem value={PREVIOUS_WORKTREE_SELECT_VALUE}>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<HistoryIcon className="size-3" />
|
||||
{previousWorktreeLabel}
|
||||
</span>
|
||||
</SelectItem>
|
||||
) : null}
|
||||
</SelectGroup>
|
||||
))
|
||||
) : (
|
||||
<SelectGroup>
|
||||
<SelectGroupLabel>Workspace</SelectGroupLabel>
|
||||
<SelectItem value="local">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
{activeWorktreePath ? (
|
||||
<FolderGitIcon className="size-3" />
|
||||
) : (
|
||||
<FolderIcon className="size-3" />
|
||||
)}
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value="worktree">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<FolderGit2Icon className="size-3" />
|
||||
{resolveEnvModeLabel("worktree")}
|
||||
</span>
|
||||
</SelectItem>
|
||||
{showPreviousWorktree && previousWorktreeLabel ? (
|
||||
<SelectItem value={PREVIOUS_WORKTREE_SELECT_VALUE}>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<HistoryIcon className="size-3" />
|
||||
{previousWorktreeLabel}
|
||||
</span>
|
||||
</SelectItem>
|
||||
) : null}
|
||||
</SelectGroup>
|
||||
)}
|
||||
<SelectPopup>
|
||||
<SelectGroup>
|
||||
<SelectGroupLabel>Workspace</SelectGroupLabel>
|
||||
<SelectItem value="local">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
{activeWorktreePath ? (
|
||||
<FolderGitIcon className="size-3" />
|
||||
) : (
|
||||
<FolderIcon className="size-3" />
|
||||
)}
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value="worktree">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<FolderGit2Icon className="size-3" />
|
||||
{resolveEnvModeLabel("worktree")}
|
||||
</span>
|
||||
</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
);
|
||||
|
||||
@@ -12,20 +12,16 @@ import type { Thread } from "../types";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
branchMismatchKey,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildThreadTurnInterruptInput,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
dismissBranchMismatchForSession,
|
||||
getStartedThreadModelChangeBlockReason,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
isBranchMismatchDismissedForSession,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
reconcileRetainedMountedThreadIds,
|
||||
resolveThreadMetadataUpdateForNextTurn,
|
||||
resolveSendEnvMode,
|
||||
shouldShowBranchMismatchBanner,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
} from "./ChatView.logic";
|
||||
|
||||
@@ -296,61 +292,6 @@ describe("resolveSendEnvMode", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("branchMismatchKey", () => {
|
||||
it("builds a key from thread id and both branches", () => {
|
||||
expect(branchMismatchKey("thread-1", { threadBranch: "feat/a", currentBranch: "feat/b" })).toBe(
|
||||
"thread-1:feat/a:feat/b",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null without a thread or mismatch", () => {
|
||||
expect(branchMismatchKey(null, { threadBranch: "a", currentBranch: "b" })).toBeNull();
|
||||
expect(branchMismatchKey("thread-1", null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldShowBranchMismatchBanner", () => {
|
||||
const base = {
|
||||
hasMismatch: true,
|
||||
isDismissed: false,
|
||||
composerHasContent: false,
|
||||
wasShownForCurrentMismatch: false,
|
||||
};
|
||||
|
||||
it("stays hidden during passive browsing (even though the composer autofocuses)", () => {
|
||||
expect(shouldShowBranchMismatchBanner(base)).toBe(false);
|
||||
});
|
||||
|
||||
it("shows once the composer has draft content", () => {
|
||||
expect(shouldShowBranchMismatchBanner({ ...base, composerHasContent: true })).toBe(true);
|
||||
});
|
||||
|
||||
it("stays mounted after the draft clears once shown for the current mismatch", () => {
|
||||
expect(shouldShowBranchMismatchBanner({ ...base, wasShownForCurrentMismatch: true })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("never shows when dismissed or without a mismatch", () => {
|
||||
expect(
|
||||
shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, isDismissed: true }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, hasMismatch: false }),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("session branch mismatch dismissal", () => {
|
||||
it("tracks dismissed keys and treats other keys as active", () => {
|
||||
expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(false);
|
||||
dismissBranchMismatchForSession("t1:a:b");
|
||||
expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(true);
|
||||
expect(isBranchMismatchDismissedForSession("t1:a:c")).toBe(false);
|
||||
expect(isBranchMismatchDismissedForSession(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileMountedTerminalThreadIds", () => {
|
||||
it("keeps open threads and makes the active thread most recent", () => {
|
||||
expect(
|
||||
|
||||
@@ -289,46 +289,6 @@ export function buildExpiredTerminalContextToastCopy(
|
||||
};
|
||||
}
|
||||
|
||||
export function branchMismatchKey(
|
||||
threadId: string | null,
|
||||
mismatch: { threadBranch: string; currentBranch: string } | null,
|
||||
): string | null {
|
||||
if (!threadId || !mismatch) {
|
||||
return null;
|
||||
}
|
||||
return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
|
||||
}
|
||||
|
||||
// The mismatch banner only matters when the user is about to send: passive
|
||||
// reading of an old thread carries no risk (the branch picker tint already
|
||||
// covers ambient awareness). Draft content is the intent signal — composer
|
||||
// focus is useless here because ChatView autofocuses the composer on every
|
||||
// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
|
||||
// revealed so it doesn't flicker away when the draft is cleared.
|
||||
export function shouldShowBranchMismatchBanner(input: {
|
||||
hasMismatch: boolean;
|
||||
isDismissed: boolean;
|
||||
composerHasContent: boolean;
|
||||
wasShownForCurrentMismatch: boolean;
|
||||
}): boolean {
|
||||
if (!input.hasMismatch || input.isDismissed) {
|
||||
return false;
|
||||
}
|
||||
return input.composerHasContent || input.wasShownForCurrentMismatch;
|
||||
}
|
||||
|
||||
// Session-scoped (module-level so it survives ChatView remounts, e.g. route
|
||||
// changes). Durable cross-device dismissal is planned as a server-side ack.
|
||||
const sessionDismissedBranchMismatchKeys = new Set<string>();
|
||||
|
||||
export function dismissBranchMismatchForSession(key: string): void {
|
||||
sessionDismissedBranchMismatchKeys.add(key);
|
||||
}
|
||||
|
||||
export function isBranchMismatchDismissedForSession(key: string | null): boolean {
|
||||
return key !== null && sessionDismissedBranchMismatchKeys.has(key);
|
||||
}
|
||||
|
||||
export function threadHasStarted(thread: Thread | null | undefined): boolean {
|
||||
return Boolean(
|
||||
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
@@ -139,14 +138,7 @@ import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import {
|
||||
AlarmClockIcon,
|
||||
CheckCircle2Icon,
|
||||
ChevronDownIcon,
|
||||
GitBranchIcon,
|
||||
TriangleAlertIcon,
|
||||
WifiOffIcon,
|
||||
} from "lucide-react";
|
||||
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
|
||||
import { cn, randomHex } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
@@ -161,8 +153,7 @@ import {
|
||||
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
|
||||
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { useNowMinute } from "../hooks/useNowMinute";
|
||||
import { useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { getTerminalFocusOwner } from "../lib/terminalFocus";
|
||||
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
|
||||
@@ -211,7 +202,6 @@ import {
|
||||
useThread,
|
||||
useThreadProposedPlans,
|
||||
useThreadRefs,
|
||||
useThreadShell,
|
||||
} from "../state/entities";
|
||||
import { environmentShell } from "../state/shell";
|
||||
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
|
||||
@@ -223,18 +213,13 @@ import { ChatHeader } from "./chat/ChatHeader";
|
||||
import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";
|
||||
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
|
||||
import { NoActiveThreadState } from "./NoActiveThreadState";
|
||||
import {
|
||||
dedupeCheckoutOptions,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveLocalCheckoutBranchMismatch,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { resolveEffectiveEnvMode, resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
|
||||
import {
|
||||
getProviderStatusBannerKey,
|
||||
ProviderStatusBanner,
|
||||
shouldShowProviderStatusBanner,
|
||||
} from "./chat/ProviderStatusBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import { resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
|
||||
import {
|
||||
DRAFT_HERO_TRANSITION_ANIMATION_ID,
|
||||
@@ -246,17 +231,13 @@ import {
|
||||
} from "./chat/draftHeroTransition";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
branchMismatchKey,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildLocalDraftThread,
|
||||
buildThreadTurnInterruptInput,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
dismissBranchMismatchForSession,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
isBranchMismatchDismissedForSession,
|
||||
shouldShowBranchMismatchBanner,
|
||||
getStartedThreadModelChangeBlockReason,
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
LastInvokedScriptByProjectSchema,
|
||||
@@ -279,16 +260,6 @@ import { RightPanelSheet } from "./RightPanelSheet";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogClose,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogPopup,
|
||||
AlertDialogTitle,
|
||||
} from "./ui/alert-dialog";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { ServerUpdateAction } from "./ServerUpdateAction";
|
||||
import {
|
||||
buildVersionMismatchDismissalKey,
|
||||
@@ -1673,22 +1644,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
return envs;
|
||||
}, [activeProject, allProjects, projectGroupingSettings, primaryEnvironmentId, environmentById]);
|
||||
const hasMultipleEnvironments = logicalProjectEnvironments.length > 1;
|
||||
const logicalProjectCheckouts = useMemo(() => {
|
||||
if (!activeProject) return [];
|
||||
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
|
||||
const checkouts = allProjects
|
||||
.filter(
|
||||
(project) =>
|
||||
project.environmentId === activeProject.environmentId &&
|
||||
deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings) === logicalKey,
|
||||
)
|
||||
.map((project) => ({
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
}));
|
||||
return dedupeCheckoutOptions(checkouts, activeProject.id);
|
||||
}, [activeProject, allProjects, projectGroupingSettings]);
|
||||
|
||||
const openPullRequestDialog = useCallback(
|
||||
(reference?: string) => {
|
||||
@@ -2397,7 +2352,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null;
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const showComposerContextStrip = isGitRepo && activeProject !== null;
|
||||
const initialDiffPanelGitScope =
|
||||
gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch";
|
||||
const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending";
|
||||
@@ -2462,32 +2416,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
[draftId, envLocked, logicalProjectEnvironments, setDraftThreadContext],
|
||||
);
|
||||
|
||||
const onWorkspaceChange = useCallback(
|
||||
(projectId: ProjectId, mode: DraftThreadEnvMode) => {
|
||||
if (envLocked || !draftId || !activeProject) return;
|
||||
const target = logicalProjectCheckouts.find((checkout) => checkout.projectId === projectId);
|
||||
if (!target) return;
|
||||
setDraftThreadContext(draftId, {
|
||||
projectRef: scopeProjectRef(activeProject.environmentId, target.projectId),
|
||||
envMode: mode,
|
||||
startFromOrigin: resolveNewDraftStartFromOrigin({
|
||||
envMode: mode,
|
||||
newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
|
||||
}),
|
||||
...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}),
|
||||
});
|
||||
},
|
||||
[
|
||||
activeProject,
|
||||
draftId,
|
||||
draftThread?.worktreePath,
|
||||
envLocked,
|
||||
logicalProjectCheckouts,
|
||||
primaryServerSettings.newWorktreesStartFromOrigin,
|
||||
setDraftThreadContext,
|
||||
],
|
||||
);
|
||||
|
||||
const activeTerminalGroup =
|
||||
terminalUiState.terminalGroups.find(
|
||||
(group) => group.id === terminalUiState.activeTerminalGroupId,
|
||||
@@ -3880,159 +3808,52 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: null,
|
||||
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
|
||||
);
|
||||
// Settled state of the open thread, resolved exactly like the sidebar
|
||||
// partition (same shell, same capability gate, same PR auto-settle input)
|
||||
// so the banner and the sidebar row never disagree.
|
||||
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
|
||||
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
|
||||
const activeThreadPr = resolveThreadPr({
|
||||
threadBranch: activeThread?.branch ?? null,
|
||||
gitStatus: gitStatusQuery.data ?? null,
|
||||
hasDedicatedWorktree: (activeThread?.worktreePath ?? null) !== null,
|
||||
});
|
||||
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
|
||||
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
|
||||
const nowMinute = useNowMinute();
|
||||
const activeThreadSnoozed =
|
||||
activeThreadShell !== null &&
|
||||
supportsSnooze &&
|
||||
effectiveSnoozed(activeThreadShell, { now: new Date().toISOString() });
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
void snoozeWakeTick;
|
||||
if (!activeThreadSnoozed) return;
|
||||
const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
|
||||
if (!Number.isFinite(wakeAtMs)) return;
|
||||
const id = window.setTimeout(
|
||||
() => bumpSnoozeWakeTick((tick) => tick + 1),
|
||||
Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
|
||||
);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
|
||||
const activeThreadSettled = useMemo(() => {
|
||||
if (activeThreadShell === null || !supportsSettlement) return false;
|
||||
return effectiveSettled(activeThreadShell, {
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
autoSettleAfterDays,
|
||||
changeRequestState: activeThreadPr?.state ?? null,
|
||||
const [branchRepairAction, setBranchRepairAction] = useState<
|
||||
"update-thread" | "switch-checkout" | null
|
||||
>(null);
|
||||
const handleUpdateThreadToCheckout = useCallback(async () => {
|
||||
if (!activeThread || !localCheckoutBranchMismatch || branchRepairAction !== null) {
|
||||
return;
|
||||
}
|
||||
setBranchRepairAction("update-thread");
|
||||
const updateResult = await updateThreadMetadata({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: activeThread.id,
|
||||
branch: localCheckoutBranchMismatch.currentBranch,
|
||||
worktreePath: null,
|
||||
},
|
||||
});
|
||||
setBranchRepairAction(null);
|
||||
if (updateResult._tag === "Failure" && !isAtomCommandInterrupted(updateResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to update thread branch",
|
||||
description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
scheduleComposerFocus();
|
||||
}, [
|
||||
activeThreadPr?.state,
|
||||
activeThreadShell,
|
||||
autoSettleAfterDays,
|
||||
nowMinute,
|
||||
supportsSettlement,
|
||||
]);
|
||||
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
|
||||
reportFailure: false,
|
||||
});
|
||||
// Keyed by thread, not a boolean: the pending state must follow the thread
|
||||
// it belongs to across navigation, and a request resolving for thread A
|
||||
// must never clear (or re-enable) thread B's button.
|
||||
const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
|
||||
const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
|
||||
const handleUnsettleActiveThread = useCallback(async () => {
|
||||
if (!activeThreadRef) return;
|
||||
const threadKey = scopedThreadKey(activeThreadRef);
|
||||
setUnsettlingThreadKey(threadKey);
|
||||
try {
|
||||
const result = await unsettleThreadMutation({
|
||||
environmentId: activeThreadRef.environmentId,
|
||||
input: { threadId: activeThreadRef.threadId, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to un-settle thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
|
||||
}
|
||||
}, [activeThreadRef, unsettleThreadMutation]);
|
||||
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
|
||||
const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
|
||||
const handleUnsnoozeActiveThread = useCallback(async () => {
|
||||
if (!activeThreadRef) return;
|
||||
const threadKey = scopedThreadKey(activeThreadRef);
|
||||
setUnsnoozingThreadKey(threadKey);
|
||||
try {
|
||||
const result = await unsnoozeThreadMutation({
|
||||
environmentId: activeThreadRef.environmentId,
|
||||
input: { threadId: activeThreadRef.threadId, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to wake thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
|
||||
}
|
||||
}, [activeThreadRef, unsnoozeThreadMutation]);
|
||||
const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
|
||||
const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
|
||||
// Once revealed for a given mismatch, the banner stays mounted until the
|
||||
// mismatch changes or resolves, so clearing the draft doesn't flicker it.
|
||||
const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
|
||||
// Dismissal lives in a module-level set (survives remounts); this tick just
|
||||
// forces a re-render so the banner leaves immediately.
|
||||
const [, setBranchMismatchDismissTick] = useState(0);
|
||||
const composerHasDraftContent = useComposerDraftStore((store) => {
|
||||
const draft = store.getComposerDraft(composerDraftTarget);
|
||||
return Boolean(
|
||||
draft &&
|
||||
(draft.prompt.trim().length > 0 ||
|
||||
draft.images.length > 0 ||
|
||||
draft.terminalContexts.length > 0 ||
|
||||
draft.elementContexts.length > 0 ||
|
||||
draft.previewAnnotations.length > 0 ||
|
||||
draft.reviewComments.length > 0),
|
||||
);
|
||||
});
|
||||
const activeBranchMismatchKey = branchMismatchKey(
|
||||
activeThread?.id ?? null,
|
||||
activeThread,
|
||||
branchRepairAction,
|
||||
environmentId,
|
||||
localCheckoutBranchMismatch,
|
||||
);
|
||||
const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
|
||||
hasMismatch: localCheckoutBranchMismatch !== null,
|
||||
isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
|
||||
composerHasContent: composerHasDraftContent,
|
||||
wasShownForCurrentMismatch:
|
||||
revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
|
||||
});
|
||||
useEffect(() => {
|
||||
setRevealedBranchMismatchKey((revealed) => {
|
||||
if (showBranchMismatchBanner) {
|
||||
return activeBranchMismatchKey;
|
||||
}
|
||||
// Hysteresis is scoped to an uninterrupted mismatch: reset when the
|
||||
// mismatch resolves or changes so a recurrence re-gates on intent.
|
||||
return revealed !== null && revealed !== activeBranchMismatchKey ? null : revealed;
|
||||
});
|
||||
}, [activeBranchMismatchKey, showBranchMismatchBanner]);
|
||||
scheduleComposerFocus,
|
||||
updateThreadMetadata,
|
||||
]);
|
||||
const handleSwitchCheckoutToThread = useCallback(async () => {
|
||||
if (
|
||||
!activeProjectCwd ||
|
||||
!activeThread ||
|
||||
!localCheckoutBranchMismatch ||
|
||||
isRestoringThreadBranch
|
||||
branchRepairAction !== null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setIsRestoringThreadBranch(true);
|
||||
setBranchRepairAction("switch-checkout");
|
||||
const checkoutResult = await switchGitRef({
|
||||
environmentId,
|
||||
input: {
|
||||
@@ -4041,7 +3862,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
},
|
||||
});
|
||||
if (checkoutResult._tag === "Failure") {
|
||||
setIsRestoringThreadBranch(false);
|
||||
setBranchRepairAction(null);
|
||||
if (!isAtomCommandInterrupted(checkoutResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
@@ -4061,7 +3882,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
|
||||
});
|
||||
if (updateResult._tag === "Failure") {
|
||||
setIsRestoringThreadBranch(false);
|
||||
setBranchRepairAction(null);
|
||||
if (!isAtomCommandInterrupted(updateResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
@@ -4076,125 +3897,76 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
}
|
||||
gitStatusQuery.refresh();
|
||||
setIsRestoringThreadBranch(false);
|
||||
setBranchRepairAction(null);
|
||||
scheduleComposerFocus();
|
||||
}, [
|
||||
activeProjectCwd,
|
||||
activeThread,
|
||||
branchRepairAction,
|
||||
environmentId,
|
||||
gitStatusQuery,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
scheduleComposerFocus,
|
||||
switchGitRef,
|
||||
updateThreadMetadata,
|
||||
]);
|
||||
// The stack renders items[0] front-most and tucks the rest behind hover, so
|
||||
// ordering is priority: system banners, then the branch-mismatch notice,
|
||||
// and the informational parked-thread banner last — it must never cover another.
|
||||
const parkedThreadBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
|
||||
if (!activeThreadSnoozed && !activeThreadSettled) {
|
||||
return null;
|
||||
}
|
||||
const isSnoozed = activeThreadSnoozed;
|
||||
return {
|
||||
id: `thread-${isSnoozed ? "snoozed" : "settled"}:${activeThread?.id ?? "unknown"}`,
|
||||
variant: "info",
|
||||
icon: isSnoozed ? <AlarmClockIcon /> : <CheckCircle2Icon />,
|
||||
title: `This thread is ${isSnoozed ? "snoozed" : "settled"}`,
|
||||
description: isSnoozed
|
||||
? "Sending a message wakes it and moves it back to Active in the sidebar."
|
||||
: "Sending a message moves it back to Active in the sidebar.",
|
||||
actions: (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isSnoozed ? isUnsnoozing : isUnsettling}
|
||||
onClick={() =>
|
||||
void (isSnoozed ? handleUnsnoozeActiveThread() : handleUnsettleActiveThread())
|
||||
}
|
||||
>
|
||||
{isSnoozed
|
||||
? isUnsnoozing
|
||||
? "Waking..."
|
||||
: "Wake now"
|
||||
: isUnsettling
|
||||
? "Un-settling..."
|
||||
: "Un-settle"}
|
||||
</Button>
|
||||
),
|
||||
};
|
||||
}, [
|
||||
activeThread?.id,
|
||||
activeThreadSettled,
|
||||
activeThreadSnoozed,
|
||||
handleUnsnoozeActiveThread,
|
||||
handleUnsettleActiveThread,
|
||||
isUnsnoozing,
|
||||
isUnsettling,
|
||||
]);
|
||||
const handleRestoreThreadBranch = useCallback(() => {
|
||||
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
|
||||
setBranchRestoreConfirmOpen(true);
|
||||
return;
|
||||
}
|
||||
void handleSwitchCheckoutToThread();
|
||||
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
|
||||
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
|
||||
return [...systemComposerBannerItems, ...parkedThreadItems];
|
||||
if (!localCheckoutBranchMismatch) {
|
||||
return systemComposerBannerItems;
|
||||
}
|
||||
const isRepairingBranch = branchRepairAction !== null;
|
||||
return [
|
||||
...systemComposerBannerItems,
|
||||
{
|
||||
id: `branch-mismatch:${activeBranchMismatchKey}`,
|
||||
variant: "info",
|
||||
icon: <GitBranchIcon />,
|
||||
title: (
|
||||
<span className="flex min-w-0 items-baseline gap-1.5">
|
||||
<span className="shrink-0 font-normal text-muted-foreground">Branch changed — was</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<code className="min-w-0 truncate font-medium text-foreground">
|
||||
{localCheckoutBranchMismatch.threadBranch}
|
||||
</code>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-80">
|
||||
This thread last ran on {localCheckoutBranchMismatch.threadBranch}. Sending will
|
||||
continue on {localCheckoutBranchMismatch.currentBranch}.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</span>
|
||||
id: `branch-mismatch:${activeThread?.id ?? "unknown"}:${localCheckoutBranchMismatch.threadBranch}:${localCheckoutBranchMismatch.currentBranch}`,
|
||||
variant: "warning",
|
||||
icon: <TriangleAlertIcon />,
|
||||
title: "You're on a different branch",
|
||||
className:
|
||||
"text-base sm:text-sm [&>div]:items-start max-sm:[&>div]:flex-wrap max-sm:[&>div>div:last-child]:w-full max-sm:[&>div>div:last-child]:self-start dark:shadow-none",
|
||||
actionClassName:
|
||||
"max-sm:w-full max-sm:border-t max-sm:border-border/60 max-sm:pt-2 max-sm:pl-6 sm:border-l sm:border-border/60 sm:pl-3",
|
||||
description: (
|
||||
<p className="text-pretty">
|
||||
This thread is on{" "}
|
||||
<code className="font-medium text-foreground">
|
||||
{localCheckoutBranchMismatch.threadBranch}
|
||||
</code>
|
||||
, but you're currently checked out at{" "}
|
||||
<code className="font-medium text-foreground">
|
||||
{localCheckoutBranchMismatch.currentBranch}
|
||||
</code>
|
||||
. Sending a message will update the thread.
|
||||
</p>
|
||||
),
|
||||
className: "dark:shadow-none",
|
||||
actions: (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={isRestoringThreadBranch}
|
||||
onClick={handleRestoreThreadBranch}
|
||||
>
|
||||
{isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
|
||||
</Button>
|
||||
<>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isRepairingBranch}
|
||||
onClick={() => void handleUpdateThreadToCheckout()}
|
||||
>
|
||||
{branchRepairAction === "update-thread" ? "Moving..." : "Move thread here"}
|
||||
</Button>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={isRepairingBranch}
|
||||
onClick={() => void handleSwitchCheckoutToThread()}
|
||||
>
|
||||
{branchRepairAction === "switch-checkout" ? "Switching..." : "Checkout thread branch"}
|
||||
</Button>
|
||||
</>
|
||||
),
|
||||
dismissLabel: "Dismiss branch change notice",
|
||||
onDismiss: () => {
|
||||
dismissBranchMismatchForSession(activeBranchMismatchKey);
|
||||
setBranchMismatchDismissTick((tick) => tick + 1);
|
||||
},
|
||||
},
|
||||
...parkedThreadItems,
|
||||
];
|
||||
}, [
|
||||
activeBranchMismatchKey,
|
||||
handleRestoreThreadBranch,
|
||||
isRestoringThreadBranch,
|
||||
activeThread?.id,
|
||||
branchRepairAction,
|
||||
handleSwitchCheckoutToThread,
|
||||
handleUpdateThreadToCheckout,
|
||||
localCheckoutBranchMismatch,
|
||||
parkedThreadBannerItem,
|
||||
showBranchMismatchBanner,
|
||||
systemComposerBannerItems,
|
||||
]);
|
||||
|
||||
@@ -5820,132 +5592,119 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"chat-composer-glass-shell relative mx-auto w-full max-w-3xl",
|
||||
showComposerContextStrip && "chat-composer-glass-shell-with-context",
|
||||
)}
|
||||
>
|
||||
<div className="chat-composer-glass-host relative z-10 w-full rounded-[22px]">
|
||||
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
|
||||
projectSelectionRequired={isLocalDraftThread && activeProject === null}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={
|
||||
activeProject?.defaultModelSelection
|
||||
}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={
|
||||
onSelectActivePendingUserInputOption
|
||||
}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
</div>
|
||||
<div className="chat-composer-glass-host relative z-10 mx-auto w-full max-w-3xl rounded-[22px]">
|
||||
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
|
||||
projectSelectionRequired={isLocalDraftThread && activeProject === null}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={
|
||||
onSelectActivePendingUserInputOption
|
||||
}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
</div>
|
||||
<div className="min-h-0">
|
||||
<div
|
||||
data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
|
||||
className="relative z-0"
|
||||
>
|
||||
{showComposerContextStrip && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange:
|
||||
setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
availableCheckouts={logicalProjectCheckouts}
|
||||
{...(routeKind === "draft" && !isServerThread
|
||||
? { onWorkspaceChange }
|
||||
: {})}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-h-0">
|
||||
<div
|
||||
data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
|
||||
className="relative z-0"
|
||||
>
|
||||
{isGitRepo && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange:
|
||||
setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
@@ -5957,36 +5716,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={branchRestoreConfirmOpen} onOpenChange={setBranchRestoreConfirmOpen}>
|
||||
<AlertDialogPopup>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
Switch to{" "}
|
||||
<code className="font-medium">
|
||||
{localCheckoutBranchMismatch?.threadBranch ?? ""}
|
||||
</code>
|
||||
?
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
You have uncommitted changes. They'll carry over to the other branch, or block
|
||||
the switch if they conflict.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
setBranchRestoreConfirmOpen(false);
|
||||
void handleSwitchCheckoutToThread();
|
||||
}}
|
||||
>
|
||||
Switch branch
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogPopup>
|
||||
</AlertDialog>
|
||||
|
||||
{pullRequestDialogState ? (
|
||||
<PullRequestThreadDialog
|
||||
key={pullRequestDialogState.key}
|
||||
|
||||
@@ -58,7 +58,11 @@ import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
|
||||
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import {
|
||||
resolveThreadActionProjectRef,
|
||||
startNewThreadInProjectFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import {
|
||||
appendBrowsePathSegment,
|
||||
canNavigateUp,
|
||||
@@ -833,7 +837,13 @@ function OpenCommandPaletteDialog(props: {
|
||||
projectRef.environmentId === contextualProjectRef.environmentId &&
|
||||
projectRef.projectId === contextualProjectRef.projectId,
|
||||
);
|
||||
await handleNewThread(
|
||||
await startNewThreadInProjectFromContext(
|
||||
{
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
},
|
||||
contextualRefBelongsToGroup
|
||||
? contextualProjectRef
|
||||
: scopeProjectRef(project.environmentId, project.id),
|
||||
@@ -841,7 +851,15 @@ function OpenCommandPaletteDialog(props: {
|
||||
},
|
||||
}),
|
||||
),
|
||||
[contextualProjectRef, handleNewThread, pickerProjects, projectGroupByTargetKey],
|
||||
[
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
contextualProjectRef,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
pickerProjects,
|
||||
projectGroupByTargetKey,
|
||||
],
|
||||
);
|
||||
|
||||
const allThreadItems = useMemo(
|
||||
|
||||
@@ -194,6 +194,12 @@ export default function DiffPanel({
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
// Scoped per turn selection so revealing git changes on one turn doesn't
|
||||
// leak into other turns or threads.
|
||||
const [includeGitChangesState, setIncludeGitChangesState] = useState<{
|
||||
scopeKey: string | null;
|
||||
value: boolean;
|
||||
}>(() => ({ scopeKey: null, value: false }));
|
||||
const [baseRefQuery, setBaseRefQuery] = useState("");
|
||||
const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
|
||||
scopeKey: null,
|
||||
@@ -311,6 +317,12 @@ export default function DiffPanel({
|
||||
: null,
|
||||
[selectedCheckpointTurnCount],
|
||||
);
|
||||
const includeGitChanges =
|
||||
includeGitChangesState.scopeKey === collapseScopeKey && includeGitChangesState.value;
|
||||
const setIncludeGitChanges = useCallback(
|
||||
(value: boolean) => setIncludeGitChangesState({ scopeKey: collapseScopeKey, value }),
|
||||
[collapseScopeKey],
|
||||
);
|
||||
const activeCheckpointDiff = useCheckpointDiff(
|
||||
{
|
||||
environmentId: activeThread?.environmentId ?? null,
|
||||
@@ -318,10 +330,17 @@ export default function DiffPanel({
|
||||
fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
|
||||
ignoreWhitespace: diffIgnoreWhitespace,
|
||||
includeGitChanges,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : null,
|
||||
},
|
||||
{ enabled: isGitRepo && selectedTurn !== undefined },
|
||||
);
|
||||
// Number of files in the selected turn whose change came from pre-existing
|
||||
// git history; drives the hidden-changes banner. Comes from the diff
|
||||
// response so it reflects the same attribution pass that produced (or
|
||||
// deliberately kept) the rendered patch — the turn summary's origin tags
|
||||
// are computed by a separate pass and could disagree after failures.
|
||||
const selectedTurnGitFileCount = activeCheckpointDiff.data?.gitFileCount ?? 0;
|
||||
const primaryBranchDiffPreview = useEnvironmentQuery(
|
||||
selectedTurnId === null && activeThread && activeCwd
|
||||
? reviewEnvironment.diffPreview({
|
||||
@@ -783,6 +802,36 @@ export default function DiffPanel({
|
||||
incomplete.
|
||||
</p>
|
||||
)}
|
||||
{selectedTurn && selectedTurnGitFileCount > 0 && (
|
||||
<p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-[11px] text-muted-foreground">
|
||||
{includeGitChanges ? (
|
||||
<>
|
||||
Showing {selectedTurnGitFileCount} file
|
||||
{selectedTurnGitFileCount === 1 ? "" : "s"} changed via git (pull, checkout,
|
||||
rebase, …).{" "}
|
||||
<button
|
||||
type="button"
|
||||
className="cursor-pointer underline underline-offset-2 hover:text-foreground"
|
||||
onClick={() => setIncludeGitChanges(false)}
|
||||
>
|
||||
Hide them
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{selectedTurnGitFileCount} file{selectedTurnGitFileCount === 1 ? "" : "s"}{" "}
|
||||
changed via git (pull, checkout, rebase, …) are hidden.{" "}
|
||||
<button
|
||||
type="button"
|
||||
className="cursor-pointer underline underline-offset-2 hover:text-foreground"
|
||||
onClick={() => setIncludeGitChanges(true)}
|
||||
>
|
||||
Show them
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{selectedPatchError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{selectedPatchError}</p>
|
||||
|
||||
@@ -14,16 +14,15 @@ import {
|
||||
isTrailingDoubleClick,
|
||||
orderItemsByPreferredIds,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveSidebarV2Status,
|
||||
resolveThreadStatusPill,
|
||||
resolveWorkingStartedAt,
|
||||
formatWorkingDurationLabel,
|
||||
shouldNavigateAfterProjectRemoval,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortLogicalProjectsForSidebar,
|
||||
sortSettledThreadsForSidebarV2,
|
||||
sortThreadsForSidebarV2,
|
||||
sortProjectsForSidebar,
|
||||
sortScopedProjectsForSidebar,
|
||||
@@ -210,10 +209,8 @@ function makeLatestTurn(overrides?: {
|
||||
state: "completed",
|
||||
assistantMessageId: null,
|
||||
requestedAt: "2026-03-09T10:00:00.000Z",
|
||||
startedAt:
|
||||
overrides?.startedAt !== undefined ? overrides.startedAt : "2026-03-09T10:00:00.000Z",
|
||||
completedAt:
|
||||
overrides?.completedAt !== undefined ? overrides.completedAt : "2026-03-09T10:05:00.000Z",
|
||||
startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
|
||||
completedAt: overrides?.completedAt ?? "2026-03-09T10:05:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -369,6 +366,112 @@ describe("isTrailingDoubleClick", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarNewThreadEnvMode", () => {
|
||||
it("uses the app default when the caller does not request a specific mode", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadEnvMode({
|
||||
defaultEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
});
|
||||
|
||||
it("preserves an explicit requested mode over the app default", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadEnvMode({
|
||||
requestedEnvMode: "local",
|
||||
defaultEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("local");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarNewThreadSeedContext", () => {
|
||||
it("prefers the default worktree mode over active thread context", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "worktree",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/existing",
|
||||
worktreePath: "/repo/.t3/worktrees/existing",
|
||||
},
|
||||
activeDraftThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/draft",
|
||||
worktreePath: "/repo/.t3/worktrees/draft",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
|
||||
it("inherits the active server thread context when creating a new thread in the same project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "local",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: null,
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the active draft thread context when it matches the target project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "local",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the default env mode when there is no matching active thread context", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-2",
|
||||
defaultEnvMode: "worktree",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: null,
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("orderItemsByPreferredIds", () => {
|
||||
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
|
||||
const ordered = orderItemsByPreferredIds({
|
||||
@@ -680,141 +783,6 @@ describe("sortThreadsForSidebarV2", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortSettledThreadsForSidebarV2", () => {
|
||||
const settled = (input: {
|
||||
id: string;
|
||||
settledAt?: string | null;
|
||||
latestUserMessageAt?: string | null;
|
||||
latestTurn?: OrchestrationLatestTurn | null;
|
||||
updatedAt?: string;
|
||||
}) => ({
|
||||
id: input.id,
|
||||
settledAt: input.settledAt ?? null,
|
||||
latestUserMessageAt: input.latestUserMessageAt ?? null,
|
||||
latestTurn: input.latestTurn ?? null,
|
||||
updatedAt: input.updatedAt ?? "2026-03-09T09:00:00.000Z",
|
||||
});
|
||||
|
||||
it("orders by settle time, most recently settled first", () => {
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({
|
||||
id: "settled-first",
|
||||
settledAt: "2026-03-09T10:00:00.000Z",
|
||||
// Created/active later than the other thread: settle time must win.
|
||||
latestUserMessageAt: "2026-03-09T09:59:00.000Z",
|
||||
}),
|
||||
settled({
|
||||
id: "settled-last",
|
||||
settledAt: "2026-03-09T12:00:00.000Z",
|
||||
latestUserMessageAt: "2026-03-09T08:00:00.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["settled-last", "settled-first"]);
|
||||
});
|
||||
|
||||
it("falls back to last activity for auto-settled threads without a settledAt stamp", () => {
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({ id: "auto-old", latestUserMessageAt: "2026-03-09T08:00:00.000Z" }),
|
||||
settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }),
|
||||
settled({ id: "auto-recent", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["auto-recent", "explicit", "auto-old"]);
|
||||
});
|
||||
|
||||
it("counts a turn completion as activity for auto-settled threads", () => {
|
||||
// The message came in before the other thread's, but its turn finished
|
||||
// after: completion time is the real "work ended" moment.
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }),
|
||||
settled({
|
||||
id: "completed-later",
|
||||
latestUserMessageAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: makeLatestTurn({ completedAt: "2026-03-09T10:30:00.000Z" }),
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["completed-later", "message-only"]);
|
||||
});
|
||||
|
||||
it("breaks timestamp ties by id so the order is stable", () => {
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }),
|
||||
settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWorkingStartedAt", () => {
|
||||
const session = {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running" as const,
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
activeTurnId: "turn-1" as never,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-09T10:02:00.000Z",
|
||||
};
|
||||
|
||||
it("uses the running turn's start time", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn({ completedAt: null }),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("uses the request time while a turn awaits adoption", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn({ startedAt: null, completedAt: null }),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to the session transition when the latest turn already completed", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn(),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:02:00.000Z");
|
||||
});
|
||||
|
||||
it("skips a malformed startedAt instead of returning it", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn({ startedAt: "not-a-date", completedAt: null }),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("returns null with neither a running turn nor a session", () => {
|
||||
expect(resolveWorkingStartedAt({ latestTurn: null, session: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatWorkingDurationLabel", () => {
|
||||
it("formats seconds, minutes, and hours", () => {
|
||||
expect(formatWorkingDurationLabel(0)).toBe("0s");
|
||||
expect(formatWorkingDurationLabel(42_000)).toBe("42s");
|
||||
expect(formatWorkingDurationLabel(5 * 60_000)).toBe("5m");
|
||||
expect(formatWorkingDurationLabel(90 * 60_000)).toBe("1h 30m");
|
||||
});
|
||||
|
||||
it("clamps negative and non-finite elapsed values to zero", () => {
|
||||
expect(formatWorkingDurationLabel(-5_000)).toBe("0s");
|
||||
expect(formatWorkingDurationLabel(Number.NaN)).toBe("0s");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadStatusPill", () => {
|
||||
const baseThread = {
|
||||
hasActionableProposedPlan: false,
|
||||
|
||||
@@ -18,6 +18,7 @@ export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
|
||||
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
|
||||
// nearby thread usually reuses an already-hot subscription.
|
||||
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -245,6 +246,62 @@ export function isTrailingDoubleClick(detail: number): boolean {
|
||||
return detail > 1;
|
||||
}
|
||||
|
||||
export function resolveSidebarNewThreadEnvMode(input: {
|
||||
requestedEnvMode?: SidebarNewThreadEnvMode;
|
||||
defaultEnvMode: SidebarNewThreadEnvMode;
|
||||
}): SidebarNewThreadEnvMode {
|
||||
return input.requestedEnvMode ?? input.defaultEnvMode;
|
||||
}
|
||||
|
||||
export function resolveSidebarNewThreadSeedContext(input: {
|
||||
projectId: string;
|
||||
defaultEnvMode: SidebarNewThreadEnvMode;
|
||||
activeThread?: {
|
||||
projectId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
} | null;
|
||||
activeDraftThread?: {
|
||||
projectId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin: boolean;
|
||||
} | null;
|
||||
}): {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin?: boolean;
|
||||
} {
|
||||
if (input.defaultEnvMode === "worktree") {
|
||||
return {
|
||||
envMode: "worktree",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeDraftThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeDraftThread.branch,
|
||||
worktreePath: input.activeDraftThread.worktreePath,
|
||||
envMode: input.activeDraftThread.envMode,
|
||||
startFromOrigin: input.activeDraftThread.startFromOrigin,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeThread.branch,
|
||||
worktreePath: input.activeThread.worktreePath,
|
||||
envMode: input.activeThread.worktreePath ? "worktree" : "local",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
envMode: input.defaultEnvMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function orderItemsByPreferredIds<TItem, TId>(input: {
|
||||
items: readonly TItem[];
|
||||
preferredIds: readonly TId[];
|
||||
@@ -445,18 +502,6 @@ export function firstValidTimestampMs(
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** String twin of firstValidTimestampMs for callers that need the ISO string
|
||||
(display labels, tick anchors) rather than epoch ms. */
|
||||
export function firstValidTimestamp(
|
||||
...candidates: ReadonlyArray<string | null | undefined>
|
||||
): string | null {
|
||||
for (const candidate of candidates) {
|
||||
if (candidate == null) continue;
|
||||
if (!Number.isNaN(Date.parse(candidate))) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// v2 sort: static creation order, newest thread on top. Activity NEVER
|
||||
// reorders the list — a row holds its position from open until settled, so
|
||||
// the screen only moves at lifecycle transitions. Status (including pending
|
||||
@@ -471,73 +516,6 @@ export function sortThreadsForSidebarV2<
|
||||
);
|
||||
}
|
||||
|
||||
type SettledTimestampInput = Pick<
|
||||
SidebarThreadSummary,
|
||||
"settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
|
||||
>;
|
||||
|
||||
/** The timestamp a settled row sorts and labels by: settledAt when stamped
|
||||
(explicit settles), otherwise last activity — the same candidates
|
||||
threadLastActivityAt feeds the auto-settle window (user message plus all
|
||||
latestTurn stamps), so a thread whose last activity was a turn completion
|
||||
doesn't sort by an older message time. updatedAt is the final net. */
|
||||
export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
|
||||
const settledAt = firstValidTimestamp(thread.settledAt);
|
||||
if (settledAt !== null) return settledAt;
|
||||
let latest: string | null = null;
|
||||
let latestMs = Number.NEGATIVE_INFINITY;
|
||||
for (const candidate of [
|
||||
thread.latestUserMessageAt,
|
||||
thread.latestTurn?.requestedAt,
|
||||
thread.latestTurn?.startedAt,
|
||||
thread.latestTurn?.completedAt,
|
||||
]) {
|
||||
if (candidate == null) continue;
|
||||
const parsed = Date.parse(candidate);
|
||||
if (!Number.isNaN(parsed) && parsed > latestMs) {
|
||||
latest = candidate;
|
||||
latestMs = parsed;
|
||||
}
|
||||
}
|
||||
return latest ?? firstValidTimestamp(thread.updatedAt);
|
||||
}
|
||||
|
||||
// Settled rows are history, so they order by when the work ENDED, not when
|
||||
// the thread was created or last touched.
|
||||
export function sortSettledThreadsForSidebarV2<
|
||||
T extends SettledTimestampInput & { readonly id: string },
|
||||
>(threads: readonly T[]): T[] {
|
||||
const timestampMs = (thread: T) => {
|
||||
const timestamp = resolveSettledTimestamp(thread);
|
||||
return timestamp === null ? 0 : Date.parse(timestamp);
|
||||
};
|
||||
return [...threads].toSorted(
|
||||
(left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
/** The timestamp a working thread's elapsed label counts from: the running
|
||||
turn's start (request time until adoption), falling back to the session's
|
||||
last transition when the turn projection lags behind. Malformed
|
||||
timestamps fall through to the next candidate, not just missing ones. */
|
||||
export function resolveWorkingStartedAt(
|
||||
thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
|
||||
): string | null {
|
||||
const turn = thread.latestTurn;
|
||||
if (turn && turn.completedAt === null) {
|
||||
return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
|
||||
}
|
||||
return firstValidTimestamp(thread.session?.updatedAt);
|
||||
}
|
||||
|
||||
export function formatWorkingDurationLabel(elapsedMs: number): string {
|
||||
const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
|
||||
if (seconds < 60) return `${seconds}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return `${minutes}m`;
|
||||
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
||||
}
|
||||
|
||||
export function resolveThreadStatusPill(input: {
|
||||
thread: ThreadStatusInput;
|
||||
}): ThreadStatusPill | null {
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveSnoozePresets, snoozeWakeDescription, snoozeWakeLabel } from "./Sidebar.snooze";
|
||||
|
||||
// Local-time constructor so preset math is timezone-stable in tests.
|
||||
function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
|
||||
return new Date(year, month - 1, day, hour, minute, 0, 0);
|
||||
}
|
||||
|
||||
describe("resolveSnoozePresets", () => {
|
||||
it("offers hour, evening, tomorrow, next week in the morning", () => {
|
||||
// Wednesday 2026-04-08 10:00 local.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
expect(presets.map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"evening",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
const evening = presets.find((preset) => preset.id === "evening");
|
||||
expect(new Date(evening!.snoozedUntil).getHours()).toBe(18);
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
const tomorrowDate = new Date(tomorrow!.snoozedUntil);
|
||||
expect(tomorrowDate.getDate()).toBe(9);
|
||||
expect(tomorrowDate.getHours()).toBe(9);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
const nextWeekDate = new Date(nextWeek!.snoozedUntil);
|
||||
expect(nextWeekDate.getDay()).toBe(1);
|
||||
expect(nextWeekDate.getDate()).toBe(13);
|
||||
});
|
||||
|
||||
it("whenLabel complements the label instead of repeating it", () => {
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
|
||||
for (const preset of presets) {
|
||||
// Day words live in the label column; the time column is time-only
|
||||
// (plus a weekday for next week, which names a different day).
|
||||
expect(preset.whenLabel.toLowerCase()).not.toContain("tomorrow");
|
||||
}
|
||||
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
|
||||
expect(tomorrow!.whenLabel).toMatch(/9/);
|
||||
const nextWeek = presets.find((preset) => preset.id === "next-week");
|
||||
expect(nextWeek!.whenLabel).toMatch(/Mon/);
|
||||
});
|
||||
|
||||
it("drops the evening preset once evening is near or past", () => {
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 17, 30)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
expect(resolveSnoozePresets(localDate(2026, 4, 8, 21)).map((preset) => preset.id)).toEqual([
|
||||
"hour",
|
||||
"tomorrow",
|
||||
"next-week",
|
||||
]);
|
||||
});
|
||||
|
||||
it("puts next week a full week out when today is Monday", () => {
|
||||
// Monday 2026-04-06.
|
||||
const presets = resolveSnoozePresets(localDate(2026, 4, 6, 10));
|
||||
const nextWeek = new Date(presets.find((preset) => preset.id === "next-week")!.snoozedUntil);
|
||||
expect(nextWeek.getDay()).toBe(1);
|
||||
expect(nextWeek.getDate()).toBe(13);
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeLabel", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("formats minutes, hours, and days, rounding up", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 30 * 60_000).toISOString(), now)).toBe("30m");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 90 * 60_000).toISOString(), now)).toBe("2h");
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() + 26 * 3_600_000).toISOString(), now)).toBe("2d");
|
||||
});
|
||||
|
||||
it("reports now for past and malformed wake times", () => {
|
||||
expect(snoozeWakeLabel(new Date(now.getTime() - 1000).toISOString(), now)).toBe("now");
|
||||
expect(snoozeWakeLabel("not-a-date", now)).toBe("now");
|
||||
});
|
||||
});
|
||||
|
||||
describe("snoozeWakeDescription", () => {
|
||||
const now = localDate(2026, 4, 8, 10);
|
||||
|
||||
it("uses bare time today, 'tomorrow' next day, weekday within the week", () => {
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now)).not.toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 9, 9).toISOString(), now)).toContain(
|
||||
"tomorrow",
|
||||
);
|
||||
expect(snoozeWakeDescription(localDate(2026, 4, 13, 9).toISOString(), now)).toMatch(/Mon/);
|
||||
});
|
||||
});
|
||||
@@ -1,127 +0,0 @@
|
||||
/**
|
||||
* Snooze preset resolution for the sidebar snooze menu. Pure functions so
|
||||
* the preset math (evening/tomorrow/next-week boundaries) is unit-testable
|
||||
* without a DOM.
|
||||
*
|
||||
* Presets deliberately skew short: agent-thread rhythms are hours (a CI
|
||||
* run, a teammate review, the next work session), not days.
|
||||
*/
|
||||
import { parseTimestampDate } from "../timestampFormat";
|
||||
|
||||
type SnoozePresetId = "hour" | "evening" | "tomorrow" | "next-week";
|
||||
|
||||
export interface SnoozePreset {
|
||||
readonly id: SnoozePresetId;
|
||||
readonly label: string;
|
||||
/** Menu-row time column. Complements the label instead of repeating it:
|
||||
"Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
|
||||
readonly whenLabel: string;
|
||||
/** ISO wake time. */
|
||||
readonly snoozedUntil: string;
|
||||
}
|
||||
|
||||
function timeOfDayLabel(date: Date): string {
|
||||
return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
}
|
||||
|
||||
const EVENING_HOUR = 18;
|
||||
const MORNING_HOUR = 9;
|
||||
const HOUR_MS = 60 * 60 * 1_000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
|
||||
function atHour(base: Date, hour: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setHours(hour, 0, 0, 0);
|
||||
return next;
|
||||
}
|
||||
|
||||
// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
|
||||
// land on the wrong local day across DST transitions (a spring-forward day
|
||||
// is 23 hours, so 23:30 + 24h skips the whole next day).
|
||||
function addDays(base: Date, days: number): Date {
|
||||
const next = new Date(base);
|
||||
next.setDate(next.getDate() + days);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Presets for "snooze until", computed against local time. "This evening"
|
||||
* only appears while it is still meaningfully before evening; after that
|
||||
* the list starts at "Tomorrow".
|
||||
*/
|
||||
export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
|
||||
const inAnHour = new Date(now.getTime() + HOUR_MS);
|
||||
const presets: SnoozePreset[] = [
|
||||
{
|
||||
id: "hour",
|
||||
label: "In 1 hour",
|
||||
whenLabel: timeOfDayLabel(inAnHour),
|
||||
snoozedUntil: inAnHour.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
const evening = atHour(now, EVENING_HOUR);
|
||||
// Suppress the evening preset once it is within an hour (or past): it
|
||||
// would duplicate "In 1 hour" or point at the past.
|
||||
if (evening.getTime() - now.getTime() > HOUR_MS) {
|
||||
presets.push({
|
||||
id: "evening",
|
||||
label: "This evening",
|
||||
whenLabel: timeOfDayLabel(evening),
|
||||
snoozedUntil: evening.toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
const tomorrow = atHour(addDays(now, 1), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "tomorrow",
|
||||
label: "Tomorrow",
|
||||
whenLabel: timeOfDayLabel(tomorrow),
|
||||
snoozedUntil: tomorrow.toISOString(),
|
||||
});
|
||||
|
||||
// Next Monday 9:00 (a week out when today is Monday).
|
||||
const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
|
||||
const nextWeek = atHour(addDays(now, daysUntilMonday), MORNING_HOUR);
|
||||
presets.push({
|
||||
id: "next-week",
|
||||
label: "Next week",
|
||||
whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${timeOfDayLabel(nextWeek)}`,
|
||||
snoozedUntil: nextWeek.toISOString(),
|
||||
});
|
||||
|
||||
return presets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
|
||||
* round up so a snooze never reads "0m" while still hidden.
|
||||
*/
|
||||
export function snoozeWakeLabel(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "now";
|
||||
const remainingMs = wake.getTime() - now.getTime();
|
||||
if (remainingMs <= 0) return "now";
|
||||
if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
|
||||
if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
|
||||
return `${Math.ceil(remainingMs / DAY_MS)}d`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human wake time for menus and toasts: "tomorrow 9:00", "Mon 9:00",
|
||||
* "17:30" (today).
|
||||
*/
|
||||
export function snoozeWakeDescription(snoozedUntil: string, now: Date): string {
|
||||
const wake = parseTimestampDate(snoozedUntil);
|
||||
if (wake === null) return "";
|
||||
const time = wake.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
|
||||
const startOfToday = new Date(now);
|
||||
startOfToday.setHours(0, 0, 0, 0);
|
||||
const dayDelta = Math.floor((wake.getTime() - startOfToday.getTime()) / DAY_MS);
|
||||
if (dayDelta === 0) return time;
|
||||
if (dayDelta === 1) return `tomorrow ${time}`;
|
||||
const weekday = wake.toLocaleDateString(undefined, { weekday: "short" });
|
||||
if (dayDelta < 7) return `${weekday} ${time}`;
|
||||
const date = wake.toLocaleDateString(undefined, { month: "short", day: "numeric" });
|
||||
return `${date}, ${time}`;
|
||||
}
|
||||
@@ -177,6 +177,8 @@ import {
|
||||
isContextMenuPointerDown,
|
||||
isTrailingDoubleClick,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
orderItemsByPreferredIds,
|
||||
@@ -191,7 +193,7 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useIsMobile } from "~/hooks/useMediaQuery";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { primaryServerKeybindingsAtom, primaryServerSettingsAtom } from "../state/server";
|
||||
import {
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupingOverrideKey,
|
||||
@@ -1101,6 +1103,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
(settings) => settings.confirmThreadArchive,
|
||||
);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
|
||||
const deleteProject = useAtomCommand(projectEnvironment.delete, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -1872,14 +1875,61 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
const createThreadForProjectMember = useCallback(
|
||||
(member: SidebarProjectGroupMember) => {
|
||||
const currentRouteParams =
|
||||
router.state.matches[router.state.matches.length - 1]?.params ?? {};
|
||||
const currentRouteTarget = resolveThreadRouteTarget(currentRouteParams);
|
||||
const currentActiveThread =
|
||||
currentRouteTarget?.kind === "server"
|
||||
? readThreadShell(currentRouteTarget.threadRef)
|
||||
: null;
|
||||
const draftStore = useComposerDraftStore.getState();
|
||||
const currentActiveDraftThread =
|
||||
currentRouteTarget?.kind === "server"
|
||||
? (draftStore.getDraftThread(currentRouteTarget.threadRef) ?? null)
|
||||
: currentRouteTarget?.kind === "draft"
|
||||
? (draftStore.getDraftSession(currentRouteTarget.draftId) ?? null)
|
||||
: null;
|
||||
const seedContext = resolveSidebarNewThreadSeedContext({
|
||||
projectId: member.id,
|
||||
// The default env mode is a user preference stored on the primary
|
||||
// environment's settings.json; remote environments never carry it.
|
||||
defaultEnvMode: resolveSidebarNewThreadEnvMode({
|
||||
defaultEnvMode: primaryServerSettings.defaultThreadEnvMode,
|
||||
}),
|
||||
activeThread:
|
||||
currentActiveThread && currentActiveThread.projectId === member.id
|
||||
? {
|
||||
projectId: currentActiveThread.projectId,
|
||||
branch: currentActiveThread.branch,
|
||||
worktreePath: currentActiveThread.worktreePath,
|
||||
}
|
||||
: null,
|
||||
activeDraftThread:
|
||||
currentActiveDraftThread && currentActiveDraftThread.projectId === member.id
|
||||
? {
|
||||
projectId: currentActiveDraftThread.projectId,
|
||||
branch: currentActiveDraftThread.branch,
|
||||
worktreePath: currentActiveDraftThread.worktreePath,
|
||||
envMode: currentActiveDraftThread.envMode,
|
||||
startFromOrigin: currentActiveDraftThread.startFromOrigin,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
if (isMobile) {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void (async () => {
|
||||
// No options: branch, worktree, and env mode come from the user's
|
||||
// configured defaults, never from the currently viewed thread.
|
||||
const result = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(member.environmentId, member.id)),
|
||||
handleNewThread(scopeProjectRef(member.environmentId, member.id), {
|
||||
...(seedContext.branch !== undefined ? { branch: seedContext.branch } : {}),
|
||||
...(seedContext.worktreePath !== undefined
|
||||
? { worktreePath: seedContext.worktreePath }
|
||||
: {}),
|
||||
envMode: seedContext.envMode,
|
||||
...(seedContext.startFromOrigin !== undefined
|
||||
? { startFromOrigin: seedContext.startFromOrigin }
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
@@ -1893,7 +1943,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}
|
||||
})();
|
||||
},
|
||||
[handleNewThread, isMobile, setOpenMobile],
|
||||
[handleNewThread, isMobile, primaryServerSettings.defaultThreadEnvMode, router, setOpenMobile],
|
||||
);
|
||||
|
||||
const handleCreateThreadClick = useCallback(
|
||||
@@ -2114,9 +2164,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
...(thread.branch
|
||||
? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }]
|
||||
: []),
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-path", label: "Copy Path" },
|
||||
@@ -2126,30 +2173,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
position,
|
||||
);
|
||||
|
||||
if (clicked === "new-thread-on-branch") {
|
||||
// Explicit branch carry-over: reuse the thread's worktree when it
|
||||
// has one, otherwise its branch on the local checkout.
|
||||
const result = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), {
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
envMode: thread.worktreePath ? "worktree" : "local",
|
||||
startFromOrigin: false,
|
||||
}),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not create thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "rename") {
|
||||
startThreadRename(threadKey, thread.title);
|
||||
return;
|
||||
@@ -2206,7 +2229,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
copyPathToClipboard,
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
handleNewThread,
|
||||
markThreadUnread,
|
||||
memberProjectByScopedKey,
|
||||
project.workspaceRoot,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,7 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
settledPrHoverColorClass,
|
||||
} from "./ThreadStatusIndicators";
|
||||
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
@@ -74,23 +70,4 @@ describe("prStatusIndicator", () => {
|
||||
tooltipTitle: "PR branch",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses red for closed pull requests", () => {
|
||||
const closedPr = status().pr;
|
||||
if (!closedPr) throw new Error("Expected pull request fixture");
|
||||
|
||||
expect(prStatusIndicator({ ...closedPr, state: "closed" }, undefined)?.colorClass).toContain(
|
||||
"text-red-600",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("settledPrHoverColorClass", () => {
|
||||
it.each([
|
||||
["open", "text-emerald-600"],
|
||||
["merged", "text-violet-600"],
|
||||
["closed", "text-red-600"],
|
||||
] as const)("restores the %s pull request color on row hover", (state, colorClass) => {
|
||||
expect(settledPrHoverColorClass(state)).toContain(`group-hover/v2-row:${colorClass}`);
|
||||
});
|
||||
});
|
||||
@@ -35,17 +35,6 @@ export interface TerminalStatusIndicator {
|
||||
|
||||
export type ThreadPr = VcsStatusResult["pr"];
|
||||
|
||||
export function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"]): string {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return "group-hover/v2-row:text-emerald-600 dark:group-hover/v2-row:text-emerald-300/90";
|
||||
case "merged":
|
||||
return "group-hover/v2-row:text-violet-600 dark:group-hover/v2-row:text-violet-300/90";
|
||||
case "closed":
|
||||
return "group-hover/v2-row:text-red-600 dark:group-hover/v2-row:text-red-300/90";
|
||||
}
|
||||
}
|
||||
|
||||
export function prStatusIndicator(
|
||||
pr: ThreadPr,
|
||||
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
|
||||
@@ -76,7 +65,7 @@ export function prStatusIndicator(
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: `${presentation.shortName} closed`,
|
||||
colorClass: "text-red-600 dark:text-red-300/90",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip,
|
||||
tooltipLead,
|
||||
tooltipTitle: pr.title,
|
||||
|
||||
@@ -10,86 +10,23 @@ describe("ChangedFilesCard", () => {
|
||||
<ChangedFilesCard
|
||||
turnId={TurnId.make("turn-1")}
|
||||
files={[{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }]}
|
||||
expanded
|
||||
showCompactPreview={false}
|
||||
allDirectoriesExpanded
|
||||
resolvedTheme="light"
|
||||
onExpandedChange={() => {}}
|
||||
onToggleAllDirectories={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-changed-files-state="expanded"');
|
||||
expect(markup).toContain('aria-expanded="true"');
|
||||
expect(markup).toContain('class="sticky top-0 z-10');
|
||||
expect(markup).not.toContain("self-start");
|
||||
expect(markup).toContain("whitespace-nowrap");
|
||||
expect(markup).toContain("!size-[22px]");
|
||||
expect(markup).toContain("size-3");
|
||||
expect(markup).toContain('aria-label="Collapse all folders"');
|
||||
expect(markup).toContain('aria-label="Open diff"');
|
||||
expect(markup).toContain('role="group" aria-label="2 additions, 1 deletions"');
|
||||
expect(markup).toContain('aria-label="Collapse all"');
|
||||
expect(markup).toContain('aria-label="View diff"');
|
||||
expect(markup).toContain("1 changed file");
|
||||
expect(markup).not.toContain("1 changed files");
|
||||
});
|
||||
|
||||
it("renders a scope and representative-file preview for a large latest change", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesCard
|
||||
turnId={TurnId.make("turn-1")}
|
||||
files={[
|
||||
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 },
|
||||
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 30, deletions: 2 },
|
||||
{
|
||||
path: "packages/shared/src/git.ts",
|
||||
kind: "modified",
|
||||
additions: 15,
|
||||
deletions: 4,
|
||||
},
|
||||
{ path: "README.md", kind: "modified", additions: 3, deletions: 0 },
|
||||
]}
|
||||
expanded={false}
|
||||
showCompactPreview
|
||||
allDirectoriesExpanded={false}
|
||||
resolvedTheme="light"
|
||||
onExpandedChange={() => {}}
|
||||
onToggleAllDirectories={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-changed-files-state="preview"');
|
||||
expect(markup).toContain('aria-expanded="false"');
|
||||
expect(markup).toContain("apps");
|
||||
expect(markup).toContain("2 files");
|
||||
expect(markup).toContain("packages");
|
||||
expect(markup).toContain("root");
|
||||
expect(markup).toContain("App.tsx");
|
||||
expect(markup).toContain("git.ts");
|
||||
expect(markup).toContain("README.md");
|
||||
expect(markup).toContain("Show all 4 files");
|
||||
expect(markup).not.toContain("App.test.tsx");
|
||||
});
|
||||
|
||||
it("keeps older collapsed changes to a one-line receipt", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesCard
|
||||
turnId={TurnId.make("turn-1")}
|
||||
files={[{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 }]}
|
||||
expanded={false}
|
||||
showCompactPreview={false}
|
||||
allDirectoriesExpanded={false}
|
||||
resolvedTheme="light"
|
||||
onExpandedChange={() => {}}
|
||||
onToggleAllDirectories={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-changed-files-state="collapsed"');
|
||||
expect(markup).toContain("1 changed file");
|
||||
expect(markup).not.toContain("Show all");
|
||||
expect(markup).not.toContain("App.tsx");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ChangedFilesTree", () => {
|
||||
|
||||
@@ -19,184 +19,95 @@ import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { PierreEntryIcon } from "./PierreEntryIcon";
|
||||
import { Button } from "../ui/button";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import {
|
||||
changedFileName,
|
||||
selectChangedFilePreview,
|
||||
summarizeChangedFileScopes,
|
||||
} from "./changedFilesPresentation";
|
||||
|
||||
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
|
||||
|
||||
export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
turnId: TurnId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
expanded: boolean;
|
||||
showCompactPreview: boolean;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onExpandedChange: (expanded: boolean) => void;
|
||||
onToggleAllDirectories: () => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const {
|
||||
turnId,
|
||||
files,
|
||||
expanded,
|
||||
showCompactPreview,
|
||||
allDirectoriesExpanded,
|
||||
resolvedTheme,
|
||||
onExpandedChange,
|
||||
onToggleAllDirectories,
|
||||
onOpenTurnDiff,
|
||||
} = props;
|
||||
const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);
|
||||
const scopeSummary = useMemo(() => summarizeChangedFileScopes(files), [files]);
|
||||
const previewFiles = useMemo(() => selectChangedFilePreview(files), [files]);
|
||||
const compactPreviewVisible = showCompactPreview && !expanded;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
|
||||
data-changed-files-state={
|
||||
expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
|
||||
}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-2 rounded-xl px-1",
|
||||
expanded &&
|
||||
"sticky top-2 z-10 mb-2 bg-secondary dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
data-scroll-anchor-ignore
|
||||
className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onExpandedChange(!expanded)}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 text-muted-foreground transition-transform",
|
||||
expanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
<span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{files.length} changed file{files.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
|
||||
<div className="sticky top-0 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
|
||||
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{files.length} changed file{files.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
<span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
|
||||
{expanded ? "Hide files" : "Show files"}
|
||||
</span>
|
||||
</button>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{expanded ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label={
|
||||
allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
|
||||
}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={onToggleAllDirectories}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
aria-label="Open diff"
|
||||
className="!size-[22px]"
|
||||
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={onToggleAllDirectories}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label="View diff"
|
||||
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
<span className="hidden sm:inline">Open diff</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Open the full diff</TooltipPopup>
|
||||
<TooltipPopup side="top">View diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
{expanded ? (
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
) : compactPreviewVisible ? (
|
||||
<div className="px-2 pb-1.5 pt-1">
|
||||
<p className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] text-muted-foreground">
|
||||
{scopeSummary.map((scope, index) => (
|
||||
<span key={scope.label} className="inline-flex items-center gap-1">
|
||||
{index > 0 ? <span aria-hidden="true">·</span> : null}
|
||||
<span className="font-mono text-foreground/75">{scope.label}</span>
|
||||
<span>
|
||||
{scope.fileCount} file{scope.fileCount === 1 ? "" : "s"}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||
{previewFiles.map((file) => (
|
||||
<button
|
||||
key={file.path}
|
||||
type="button"
|
||||
title={file.path}
|
||||
className="inline-flex max-w-48 items-center gap-1 rounded-md border border-border/70 bg-background/45 px-1.5 py-1 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onOpenTurnDiff(turnId, file.path)}
|
||||
>
|
||||
<PierreEntryIcon
|
||||
pathValue={file.path}
|
||||
kind="file"
|
||||
theme={resolvedTheme}
|
||||
className="size-3 shrink-0 text-muted-foreground/70"
|
||||
/>
|
||||
<span className="truncate">{changedFileName(file.path)}</span>
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md px-1.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onExpandedChange(true)}
|
||||
>
|
||||
Show all {files.length} files
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -31,8 +31,6 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
|
||||
<>
|
||||
{showParentheses && <span className="text-muted-foreground/70">(</span>}
|
||||
<span
|
||||
role="group"
|
||||
aria-label={`${additions} additions, ${deletions} deletions`}
|
||||
className={cn(
|
||||
layout === "inline"
|
||||
? "inline-flex items-center gap-1 tabular-nums align-middle"
|
||||
@@ -40,12 +38,8 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span aria-hidden="true" className="font-mono text-success">
|
||||
+{formatCompactDiffCount(additions)}
|
||||
</span>
|
||||
<span aria-hidden="true" className="font-mono text-destructive">
|
||||
-{formatCompactDiffCount(deletions)}
|
||||
</span>
|
||||
<span className="font-mono text-success">+{formatCompactDiffCount(additions)}</span>
|
||||
<span className="font-mono text-destructive">-{formatCompactDiffCount(deletions)}</span>
|
||||
</span>
|
||||
{showParentheses && <span className="text-muted-foreground/70">)</span>}
|
||||
</>
|
||||
|
||||
@@ -245,12 +245,6 @@ describe("MessagesTimeline", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
latestTurn={{
|
||||
turnId,
|
||||
state: "completed",
|
||||
startedAt: MESSAGE_CREATED_AT,
|
||||
completedAt: MESSAGE_CREATED_AT,
|
||||
}}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-assistant-with-files",
|
||||
@@ -286,13 +280,13 @@ describe("MessagesTimeline", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("sticky top-2 z-10");
|
||||
expect(markup).toContain('class="sticky top-2 z-10');
|
||||
expect(markup).not.toContain("self-start");
|
||||
expect(markup).toContain("whitespace-nowrap");
|
||||
expect(markup).toContain("!size-[22px]");
|
||||
expect(markup).toContain("size-3");
|
||||
expect(markup).toContain('aria-label="Collapse all folders"');
|
||||
expect(markup).toContain('aria-label="Open diff"');
|
||||
expect(markup).toContain('aria-label="Collapse all"');
|
||||
expect(markup).toContain('aria-label="View diff"');
|
||||
expect(markup).toContain("1 changed file");
|
||||
});
|
||||
|
||||
@@ -434,7 +428,6 @@ describe("MessagesTimeline", () => {
|
||||
|
||||
expect(markup).not.toContain("Show full message");
|
||||
expect(markup).toContain('data-user-message-collapsible="false"');
|
||||
expect(markup).toContain("rounded-2xl bg-accent p-3");
|
||||
});
|
||||
|
||||
it("renders inline terminal labels with the composer chip UI", () => {
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
workLogEntryIsToolLike,
|
||||
} from "../../session-logic";
|
||||
import { type TurnDiffSummary } from "../../types";
|
||||
import { partitionTurnDiffFiles, summarizeTurnDiffStats } from "../../lib/turnDiffTree";
|
||||
import {
|
||||
getRenderablePatch,
|
||||
resolveDiffThemeName,
|
||||
@@ -43,8 +44,12 @@ import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsDownUpIcon,
|
||||
ChevronsUpDownIcon,
|
||||
CircleAlertIcon,
|
||||
EyeIcon,
|
||||
FileDiffIcon,
|
||||
GitBranchIcon,
|
||||
GlobeIcon,
|
||||
HammerIcon,
|
||||
MessageCircleIcon,
|
||||
@@ -61,8 +66,8 @@ import {
|
||||
import { Button } from "../ui/button";
|
||||
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { ProposedPlanCard } from "./ProposedPlanCard";
|
||||
import { ChangedFilesCard } from "./ChangedFilesTree";
|
||||
import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation";
|
||||
import { ChangedFilesTree } from "./ChangedFilesTree";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { MessageCopyButton } from "./MessageCopyButton";
|
||||
import {
|
||||
computeStableMessagesTimelineRows,
|
||||
@@ -141,7 +146,6 @@ interface TimelineRowActivityState {
|
||||
isWorking: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
activeTurnInProgress: boolean;
|
||||
latestTurnId: TurnId | null;
|
||||
}
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
@@ -451,9 +455,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
isWorking,
|
||||
isRevertingCheckpoint,
|
||||
activeTurnInProgress,
|
||||
latestTurnId: latestTurn?.turnId ?? null,
|
||||
}),
|
||||
[activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId],
|
||||
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
|
||||
);
|
||||
|
||||
// Stable renderItem — no closure deps. Row components read shared state
|
||||
@@ -890,7 +893,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
|
||||
return (
|
||||
<div className="group flex flex-col items-end gap-1">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-accent p-3">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-secondary p-3">
|
||||
{regularImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
@@ -1247,13 +1250,17 @@ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection(
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
if (!turnSummary) return null;
|
||||
const checkpointFiles = turnSummary.files;
|
||||
if (checkpointFiles.length === 0) return null;
|
||||
if (turnSummary.files.length === 0) return null;
|
||||
// Changes explained by pre-existing git history (pull, checkout,
|
||||
// cherry-pick, rebase) collapse into a single summary row instead of
|
||||
// being listed as agent work.
|
||||
const { agentFiles, gitFiles } = partitionTurnDiffFiles(turnSummary.files);
|
||||
|
||||
return (
|
||||
<AssistantChangedFilesSectionInner
|
||||
turnSummary={turnSummary}
|
||||
checkpointFiles={checkpointFiles}
|
||||
checkpointFiles={agentFiles}
|
||||
gitFiles={gitFiles}
|
||||
routeThreadKey={routeThreadKey}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
@@ -1266,42 +1273,125 @@ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection(
|
||||
function AssistantChangedFilesSectionInner({
|
||||
turnSummary,
|
||||
checkpointFiles,
|
||||
gitFiles,
|
||||
routeThreadKey,
|
||||
resolvedTheme,
|
||||
onOpenTurnDiff,
|
||||
}: {
|
||||
turnSummary: TurnDiffSummary;
|
||||
checkpointFiles: TurnDiffSummary["files"];
|
||||
gitFiles: TurnDiffSummary["files"];
|
||||
routeThreadKey: string;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const isLatestTurn = activity.latestTurnId === turnSummary.turnId;
|
||||
const persistedExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId],
|
||||
const allDirectoriesExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
|
||||
);
|
||||
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
|
||||
const [autoExpanded] = useState(() =>
|
||||
shouldAutoExpandChangedFiles(checkpointFiles, isLatestTurn),
|
||||
);
|
||||
const [allDirectoriesExpanded, setAllDirectoriesExpanded] = useState(autoExpanded);
|
||||
const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded);
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
const gitSummaryStat = summarizeTurnDiffStats(gitFiles);
|
||||
// A git-only turn renders as a compact card with just the git summary row:
|
||||
// the "N changed files" header, expand/collapse, and View diff controls all
|
||||
// operate on agent files and would be dead weight.
|
||||
const hasAgentFiles = checkpointFiles.length > 0;
|
||||
|
||||
return (
|
||||
<ChangedFilesCard
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
expanded={expanded}
|
||||
showCompactPreview={isLatestTurn}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onExpandedChange={(nextExpanded) =>
|
||||
setExpanded(routeThreadKey, turnSummary.turnId, nextExpanded)
|
||||
}
|
||||
onToggleAllDirectories={() => setAllDirectoriesExpanded((current) => !current)}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32",
|
||||
hasAgentFiles && "pt-4",
|
||||
)}
|
||||
>
|
||||
{hasAgentFiles && (
|
||||
<div className="sticky top-2 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
|
||||
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() =>
|
||||
setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label="View diff"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">View diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{checkpointFiles.length > 0 && (
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.turnId}`}
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
)}
|
||||
{gitFiles.length > 0 && (
|
||||
<div className="flex items-center gap-1.5 rounded-xl px-2 py-1 text-muted-foreground/80">
|
||||
<GitBranchIcon aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
<span className="truncate font-mono text-[11px]">
|
||||
Updated via git — {gitFiles.length} file{gitFiles.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
{hasNonZeroStat(gitSummaryStat) && (
|
||||
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
|
||||
<DiffStatLabel
|
||||
additions={gitSummaryStat.additions}
|
||||
deletions={gitSummaryStat.deletions}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
contentClassName="flex w-full items-center gap-3"
|
||||
className={cn(
|
||||
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
|
||||
"hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-highlighted:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0 [&[data-highlighted][data-selected]]:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))]",
|
||||
"data-highlighted:bg-muted/56 data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0",
|
||||
props.disabledReason &&
|
||||
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
|
||||
)}
|
||||
|
||||
@@ -521,7 +521,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
<div
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-xl text-popover-foreground"
|
||||
data-model-picker-content="true"
|
||||
>
|
||||
{/* Sidebar */}
|
||||
@@ -568,23 +568,18 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
handleModelSelect(slug, instanceId);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
|
||||
showSidebar && "border-l",
|
||||
)}
|
||||
>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<div className="-translate-y-px rounded-lg bg-accent px-2 py-1">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
inputClassName="rounded-none bg-transparent text-sm placeholder:text-muted-foreground/80"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/80" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
|
||||
@@ -97,10 +97,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
|
||||
data-model-picker-sidebar="true"
|
||||
>
|
||||
<div className="w-12 shrink-0 overflow-hidden bg-muted/60" data-model-picker-sidebar="true">
|
||||
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<div
|
||||
ref={sidebarContentRef}
|
||||
@@ -118,14 +115,14 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
) : null}
|
||||
{/* Favorites section */}
|
||||
{showFavorites ? (
|
||||
<div className="mb-1 border-b pb-1">
|
||||
<div className="mb-1 pb-1">
|
||||
<div className="relative w-full">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
)}
|
||||
onClick={() => handleSelect("favorites")}
|
||||
type="button"
|
||||
@@ -172,7 +169,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
<button
|
||||
data-model-picker-provider={entry.instanceId}
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
|
||||
)}
|
||||
data-provider-accent-color={entry.accentColor}
|
||||
|
||||
@@ -187,8 +187,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup
|
||||
align="start"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [-webkit-backdrop-filter:none]! [--viewport-inline-padding:0] [backdrop-filter:none]!"
|
||||
viewportClassName="rounded-lg !overflow-hidden p-0"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0]"
|
||||
viewportClassName="!overflow-hidden p-0"
|
||||
>
|
||||
<ModelPickerContent
|
||||
activeInstanceId={activeInstanceId}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
changedFileName,
|
||||
selectChangedFilePreview,
|
||||
shouldAutoExpandChangedFiles,
|
||||
summarizeChangedFileScopes,
|
||||
} from "./changedFilesPresentation";
|
||||
|
||||
describe("changed-files presentation", () => {
|
||||
it("auto-expands only small, low-churn latest changes", () => {
|
||||
const smallFiles = [
|
||||
{ path: "src/a.ts", kind: "modified", additions: 80, deletions: 20 },
|
||||
{ path: "src/b.ts", kind: "modified", additions: 60, deletions: 20 },
|
||||
];
|
||||
|
||||
expect(shouldAutoExpandChangedFiles(smallFiles, true)).toBe(true);
|
||||
expect(shouldAutoExpandChangedFiles(smallFiles, false)).toBe(false);
|
||||
expect(
|
||||
shouldAutoExpandChangedFiles(
|
||||
[{ path: "src/a.ts", kind: "modified", additions: 201, deletions: 0 }],
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoExpandChangedFiles(
|
||||
Array.from({ length: 6 }, (_, index) => ({
|
||||
path: `src/${index}.ts`,
|
||||
kind: "modified",
|
||||
additions: 1,
|
||||
deletions: 0,
|
||||
})),
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("summarizes the most prominent top-level scopes", () => {
|
||||
const files = [
|
||||
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "apps/server/src/index.ts", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "apps\\mobile\\App.tsx", kind: "modified", additions: 1, deletions: 0 },
|
||||
];
|
||||
|
||||
expect(summarizeChangedFileScopes(files)).toEqual([
|
||||
{ label: "apps", fileCount: 3 },
|
||||
{ label: "root", fileCount: 1 },
|
||||
{ label: "packages", fileCount: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("previews files across different scopes before filling from one scope", () => {
|
||||
const files = [
|
||||
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
|
||||
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
|
||||
];
|
||||
|
||||
expect(selectChangedFilePreview(files).map((file) => file.path)).toEqual([
|
||||
"apps/web/src/App.tsx",
|
||||
"packages/shared/src/git.ts",
|
||||
"README.md",
|
||||
]);
|
||||
expect(changedFileName("apps\\web\\src\\App.tsx")).toBe("App.tsx");
|
||||
});
|
||||
});
|
||||
@@ -1,102 +0,0 @@
|
||||
import { type TurnDiffFileChange } from "../../types";
|
||||
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
|
||||
|
||||
export const CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT = 5;
|
||||
export const CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT = 200;
|
||||
export const CHANGED_FILES_PREVIEW_FILE_LIMIT = 3;
|
||||
export const CHANGED_FILES_PREVIEW_SCOPE_LIMIT = 4;
|
||||
|
||||
export interface ChangedFilesScopeSummary {
|
||||
readonly label: string;
|
||||
readonly fileCount: number;
|
||||
}
|
||||
|
||||
function pathSegments(pathValue: string): string[] {
|
||||
return pathValue
|
||||
.replaceAll("\\", "/")
|
||||
.split("/")
|
||||
.filter((segment) => segment.length > 0);
|
||||
}
|
||||
|
||||
export function changedFileName(pathValue: string): string {
|
||||
return pathSegments(pathValue).at(-1) ?? pathValue;
|
||||
}
|
||||
|
||||
function changedFileScope(pathValue: string): string {
|
||||
const segments = pathSegments(pathValue);
|
||||
return segments.length > 1 ? (segments[0] ?? "root") : "root";
|
||||
}
|
||||
|
||||
export function shouldAutoExpandChangedFiles(
|
||||
files: ReadonlyArray<TurnDiffFileChange>,
|
||||
isLatestTurn: boolean,
|
||||
): boolean {
|
||||
if (!isLatestTurn || files.length > CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT) {
|
||||
return false;
|
||||
}
|
||||
const stat = summarizeTurnDiffStats(files);
|
||||
return stat.additions + stat.deletions <= CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT;
|
||||
}
|
||||
|
||||
export function summarizeChangedFileScopes(
|
||||
files: ReadonlyArray<TurnDiffFileChange>,
|
||||
limit = CHANGED_FILES_PREVIEW_SCOPE_LIMIT,
|
||||
): ChangedFilesScopeSummary[] {
|
||||
const scopes = new Map<string, { fileCount: number; firstIndex: number }>();
|
||||
files.forEach((file, index) => {
|
||||
const label = changedFileScope(file.path);
|
||||
const current = scopes.get(label);
|
||||
scopes.set(label, {
|
||||
fileCount: (current?.fileCount ?? 0) + 1,
|
||||
firstIndex: current?.firstIndex ?? index,
|
||||
});
|
||||
});
|
||||
|
||||
return Array.from(scopes, ([label, scope]) => ({
|
||||
label,
|
||||
fileCount: scope.fileCount,
|
||||
firstIndex: scope.firstIndex,
|
||||
}))
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
right.fileCount - left.fileCount ||
|
||||
left.firstIndex - right.firstIndex ||
|
||||
left.label.localeCompare(right.label),
|
||||
)
|
||||
.slice(0, limit)
|
||||
.map(({ label, fileCount }) => ({ label, fileCount }));
|
||||
}
|
||||
|
||||
export function selectChangedFilePreview(
|
||||
files: ReadonlyArray<TurnDiffFileChange>,
|
||||
limit = CHANGED_FILES_PREVIEW_FILE_LIMIT,
|
||||
): TurnDiffFileChange[] {
|
||||
const selected: TurnDiffFileChange[] = [];
|
||||
const selectedPaths = new Set<string>();
|
||||
const selectedScopes = new Set<string>();
|
||||
|
||||
for (const file of files) {
|
||||
const scope = changedFileScope(file.path);
|
||||
if (selectedScopes.has(scope)) {
|
||||
continue;
|
||||
}
|
||||
selected.push(file);
|
||||
selectedPaths.add(file.path);
|
||||
selectedScopes.add(scope);
|
||||
if (selected.length === limit) {
|
||||
return selected;
|
||||
}
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
if (selectedPaths.has(file.path)) {
|
||||
continue;
|
||||
}
|
||||
selected.push(file);
|
||||
if (selected.length === limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return selected;
|
||||
}
|
||||
@@ -10,8 +10,6 @@ import {
|
||||
type PreviewAutomationOpenInput,
|
||||
type PreviewAutomationResizeInput,
|
||||
type PreviewAutomationResizeResult,
|
||||
type PreviewAutomationSetColorSchemeInput,
|
||||
type PreviewAutomationSetColorSchemeResult,
|
||||
type PreviewAutomationHost as PreviewAutomationHostState,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationStatus,
|
||||
@@ -453,15 +451,6 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
viewport,
|
||||
} satisfies PreviewAutomationResizeResult;
|
||||
}
|
||||
case "setColorScheme": {
|
||||
const ready = await requireReadyTab();
|
||||
const input = request.input as PreviewAutomationSetColorSchemeInput;
|
||||
await ready.bridge.setColorScheme(ready.tabId, input.colorScheme);
|
||||
return {
|
||||
tabId: ready.tabId,
|
||||
colorScheme: input.colorScheme,
|
||||
} satisfies PreviewAutomationSetColorSchemeResult;
|
||||
}
|
||||
case "snapshot": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.snapshot(ready.tabId);
|
||||
|
||||
@@ -1,34 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import type { DesktopPreviewColorScheme } from "@t3tools/contracts";
|
||||
import { Minus, MoreVertical, Plus as PlusIcon, RotateCcw } from "lucide-react";
|
||||
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator,
|
||||
MenuSub,
|
||||
MenuSubPopup,
|
||||
MenuSubTrigger,
|
||||
MenuTrigger,
|
||||
} from "~/components/ui/menu";
|
||||
import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "~/components/ui/menu";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
|
||||
import { previewBridge } from "./previewBridge";
|
||||
|
||||
const COLOR_SCHEME_OPTIONS: ReadonlyArray<{
|
||||
value: DesktopPreviewColorScheme;
|
||||
label: string;
|
||||
}> = [
|
||||
{ value: "system", label: "System" },
|
||||
{ value: "light", label: "Light" },
|
||||
{ value: "dark", label: "Dark" },
|
||||
];
|
||||
|
||||
interface Props {
|
||||
/** Active preview tab id. Tab-targeting actions are disabled without it. */
|
||||
tabId: string | null;
|
||||
@@ -40,8 +19,6 @@ interface Props {
|
||||
hasWebContents: boolean;
|
||||
/** Current zoom factor as a number (1.0 = 100%). */
|
||||
zoomFactor: number;
|
||||
/** Emulated `prefers-color-scheme` for the guest page. */
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
/** Fixed viewport modes expose the device toolbar and resize rails. */
|
||||
deviceToolbarVisible: boolean;
|
||||
/** Switches between fill-panel mode and a fixed responsive viewport. */
|
||||
@@ -57,7 +34,6 @@ export function PreviewMoreMenu({
|
||||
tabId,
|
||||
hasWebContents,
|
||||
zoomFactor,
|
||||
colorScheme,
|
||||
deviceToolbarVisible,
|
||||
onToggleDeviceToolbar,
|
||||
}: Props) {
|
||||
@@ -96,26 +72,6 @@ export function PreviewMoreMenu({
|
||||
<MenuItem onClick={onToggleDeviceToolbar} disabled={tabDisabled}>
|
||||
{deviceToolbarVisible ? "Hide device toolbar" : "Show device toolbar"}
|
||||
</MenuItem>
|
||||
<MenuSub>
|
||||
<MenuSubTrigger disabled={tabDisabled}>Appearance</MenuSubTrigger>
|
||||
<MenuSubPopup className="min-w-32">
|
||||
<MenuRadioGroup
|
||||
value={colorScheme}
|
||||
onValueChange={(value) => {
|
||||
if (!tabId) return;
|
||||
void bridge
|
||||
.setColorScheme(tabId, value as DesktopPreviewColorScheme)
|
||||
.catch(() => undefined);
|
||||
}}
|
||||
>
|
||||
{COLOR_SCHEME_OPTIONS.map((option) => (
|
||||
<MenuRadioItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuSubPopup>
|
||||
</MenuSub>
|
||||
<MenuSeparator />
|
||||
{/*
|
||||
Zoom row: label + inline control cluster. `closeOnClick=false`
|
||||
|
||||
@@ -40,7 +40,6 @@ vi.mock("~/previewStateStore", () => ({
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -610,7 +610,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
tabId={tabId}
|
||||
hasWebContents={desktopOverlay !== null}
|
||||
zoomFactor={desktopOverlay?.zoomFactor ?? 1}
|
||||
colorScheme={desktopOverlay?.colorScheme ?? "system"}
|
||||
deviceToolbarVisible={viewport._tag !== "fill"}
|
||||
onToggleDeviceToolbar={handleToggleDeviceToolbar}
|
||||
/>
|
||||
|
||||
@@ -77,7 +77,6 @@ function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverl
|
||||
canGoForward: state.canGoForward,
|
||||
loading: state.navStatus.kind === "Loading",
|
||||
zoomFactor: state.zoomFactor,
|
||||
colorScheme: state.colorScheme,
|
||||
controller: state.controller,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -406,15 +406,6 @@ interface ComposerDraftStoreState {
|
||||
setModelSelection: (
|
||||
threadRef: ComposerThreadTarget,
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
opts?: {
|
||||
/**
|
||||
* Replace the stored entry outright instead of preserving its
|
||||
* existing options when the incoming selection has none. Used when
|
||||
* the selection is a complete snapshot (e.g. carried from another
|
||||
* thread) rather than a model-only change.
|
||||
*/
|
||||
replaceOptions?: boolean;
|
||||
},
|
||||
) => void;
|
||||
/** Replace the model options for one or more providers in the draft. */
|
||||
setModelOptions: (
|
||||
@@ -2603,7 +2594,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadKey: nextDraftsByThreadKey };
|
||||
});
|
||||
},
|
||||
setModelSelection: (threadRef, modelSelection, opts) => {
|
||||
setModelSelection: (threadRef, modelSelection) => {
|
||||
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
||||
if (threadKey.length === 0) {
|
||||
return;
|
||||
@@ -2618,10 +2609,8 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
if (normalized) {
|
||||
const current = nextMap[normalized.instanceId];
|
||||
if (normalized.options !== undefined || opts?.replaceOptions) {
|
||||
// Explicit options provided (or the caller passed a complete
|
||||
// snapshot whose absent options mean "no options") → use the
|
||||
// selection as-is.
|
||||
if (normalized.options !== undefined) {
|
||||
// Explicit options provided → use them
|
||||
nextMap[normalized.instanceId] = normalized as ModelSelection;
|
||||
} else {
|
||||
// No options in selection → preserve existing options, update provider+model
|
||||
|
||||
@@ -54,52 +54,14 @@ export function useNewThreadHandler() {
|
||||
},
|
||||
): Promise<void> => {
|
||||
const {
|
||||
getComposerDraft,
|
||||
getDraftSessionByLogicalProjectKey,
|
||||
getDraftSession,
|
||||
getDraftThread,
|
||||
applyStickyState,
|
||||
setDraftThreadContext,
|
||||
setLogicalProjectDraftThreadId,
|
||||
setModelSelection,
|
||||
} = useComposerDraftStore.getState();
|
||||
const currentRouteTarget = getCurrentRouteTarget();
|
||||
// A new thread carries the user's *working mode* from the thread being
|
||||
// viewed: model (including options like reasoning effort and context
|
||||
// window), permission mode, and interaction mode. Branch, worktree, and
|
||||
// env mode never carry implicitly — those come from the configured
|
||||
// defaults unless the caller passes them explicitly.
|
||||
const carrySourceShell =
|
||||
currentRouteTarget?.kind === "server"
|
||||
? readThreadShell(currentRouteTarget.threadRef)
|
||||
: null;
|
||||
const carrySourceDraft =
|
||||
currentRouteTarget?.kind === "draft" ? getDraftSession(currentRouteTarget.draftId) : null;
|
||||
// Composer overrides win over the persisted thread state — they are
|
||||
// what the user currently sees in the composer controls.
|
||||
const carrySourceComposer = currentRouteTarget
|
||||
? getComposerDraft(
|
||||
currentRouteTarget.kind === "server"
|
||||
? currentRouteTarget.threadRef
|
||||
: currentRouteTarget.draftId,
|
||||
)
|
||||
: null;
|
||||
const composerActiveProvider = carrySourceComposer?.activeProvider ?? null;
|
||||
const composerModelSelection = composerActiveProvider
|
||||
? (carrySourceComposer?.modelSelectionByProvider[composerActiveProvider] ?? null)
|
||||
: null;
|
||||
const carryModelSelection =
|
||||
composerModelSelection ?? carrySourceShell?.modelSelection ?? null;
|
||||
const carryRuntimeMode =
|
||||
carrySourceComposer?.runtimeMode ??
|
||||
carrySourceShell?.runtimeMode ??
|
||||
carrySourceDraft?.runtimeMode ??
|
||||
null;
|
||||
const carryInteractionMode =
|
||||
carrySourceComposer?.interactionMode ??
|
||||
carrySourceShell?.interactionMode ??
|
||||
carrySourceDraft?.interactionMode ??
|
||||
null;
|
||||
const project = projects.find(
|
||||
(candidate) =>
|
||||
candidate.id === projectRef.projectId &&
|
||||
@@ -130,70 +92,25 @@ export function useNewThreadHandler() {
|
||||
: null;
|
||||
if (reusableStoredDraftThread) {
|
||||
return (async () => {
|
||||
const isDraftAlreadyOpen =
|
||||
currentRouteTarget?.kind === "draft" &&
|
||||
currentRouteTarget.draftId === reusableStoredDraftThread.draftId;
|
||||
const hasExplicitWorkspaceOption =
|
||||
if (
|
||||
hasBranchOption ||
|
||||
hasWorktreePathOption ||
|
||||
hasEnvModeOption ||
|
||||
hasStartFromOriginOption;
|
||||
// Resurrecting a stored draft must not resurrect its stale context:
|
||||
// explicit workspace options win outright; otherwise the env context
|
||||
// resets to the configured defaults so drafts seeded before a
|
||||
// defaults change (or by the old carry-over behavior) stop landing
|
||||
// on "current checkout" branches forever. Composer text is
|
||||
// preserved. When the draft is already open and no options were
|
||||
// passed, leave it alone entirely — the user may have just picked a
|
||||
// branch in the composer.
|
||||
const defaultEnvMode = primaryServerSettings.defaultThreadEnvMode;
|
||||
const workspaceContext = hasExplicitWorkspaceOption
|
||||
? {
|
||||
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
|
||||
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
|
||||
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
|
||||
...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
|
||||
}
|
||||
: isDraftAlreadyOpen
|
||||
? null
|
||||
: {
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
envMode: defaultEnvMode,
|
||||
startFromOrigin: resolveNewDraftStartFromOrigin({
|
||||
envMode: defaultEnvMode,
|
||||
newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
|
||||
}),
|
||||
};
|
||||
if (workspaceContext) {
|
||||
hasStartFromOriginOption
|
||||
) {
|
||||
setDraftThreadContext(reusableStoredDraftThread.draftId, {
|
||||
...workspaceContext,
|
||||
...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
|
||||
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
|
||||
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
|
||||
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
|
||||
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
|
||||
...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
|
||||
});
|
||||
if (carryModelSelection) {
|
||||
// The carried selection is a complete snapshot of the viewed
|
||||
// thread's model state: absent options mean "no options", not
|
||||
// "keep the stale draft's options".
|
||||
setModelSelection(reusableStoredDraftThread.draftId, carryModelSelection, {
|
||||
replaceOptions: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
// The workspace context must also ride along here: when projectRef
|
||||
// targets a different physical member of the logical project,
|
||||
// createDraftThreadState treats the remap as a project change and
|
||||
// would otherwise wipe branch/worktree and force "local" mode,
|
||||
// undoing the write above.
|
||||
setLogicalProjectDraftThreadId(
|
||||
logicalProjectKey,
|
||||
projectRef,
|
||||
reusableStoredDraftThread.draftId,
|
||||
{
|
||||
threadId: reusableStoredDraftThread.threadId,
|
||||
...(workspaceContext ?? {}),
|
||||
...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
|
||||
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
|
||||
},
|
||||
);
|
||||
if (
|
||||
@@ -259,18 +176,9 @@ export function useNewThreadHandler() {
|
||||
envMode: initialEnvMode,
|
||||
newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
|
||||
}),
|
||||
runtimeMode: carryRuntimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
});
|
||||
applyStickyState(draftId);
|
||||
if (carryModelSelection) {
|
||||
// After sticky state so the viewed thread's exact selection
|
||||
// (model + options like effort and context window) wins over the
|
||||
// globally sticky one. replaceOptions: the carried selection is a
|
||||
// complete snapshot — absent options mean "no options", not "keep
|
||||
// whatever sticky state just wrote".
|
||||
setModelSelection(draftId, carryModelSelection, { replaceOptions: true });
|
||||
}
|
||||
|
||||
await router.navigate({
|
||||
to: "/draft/$draftId",
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
/** Minute-quantized clock ("YYYY-MM-DDTHH:MM") for settled-state resolution.
|
||||
One module-level timer feeds every consumer through useSyncExternalStore,
|
||||
so all surfaces resolving effectiveSettled against it (sidebar partition,
|
||||
composer banner) share a single value by construction and tick on UTC
|
||||
minute boundaries together. */
|
||||
|
||||
function currentMinute(): string {
|
||||
return new Date().toISOString().slice(0, 16);
|
||||
}
|
||||
|
||||
let nowMinute = currentMinute();
|
||||
let timerId: number | null = null;
|
||||
let timerIsInterval = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function tick(): void {
|
||||
const next = currentMinute();
|
||||
if (next !== nowMinute) {
|
||||
nowMinute = next;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
}
|
||||
|
||||
function startTimer(): void {
|
||||
// Align to the next UTC minute boundary, then tick every 60s. Ticks re-read
|
||||
// the clock, so a throttled or late timer self-corrects when it fires.
|
||||
timerIsInterval = false;
|
||||
timerId = window.setTimeout(
|
||||
() => {
|
||||
tick();
|
||||
timerIsInterval = true;
|
||||
timerId = window.setInterval(tick, 60_000);
|
||||
},
|
||||
60_000 - (Date.now() % 60_000),
|
||||
);
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
if (listeners.size === 0) {
|
||||
startTimer();
|
||||
}
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0 && timerId !== null) {
|
||||
if (timerIsInterval) window.clearInterval(timerId);
|
||||
else window.clearTimeout(timerId);
|
||||
timerId = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getSnapshot(): string {
|
||||
// With no timer running (no subscribers yet — e.g. the first render after
|
||||
// a full unmount), the stored minute may be stale; re-read it so a fresh
|
||||
// mount renders the current minute instead of waiting for the first tick.
|
||||
// While the timer runs the cached value is returned untouched, as
|
||||
// useSyncExternalStore requires between change notifications.
|
||||
if (timerId === null) {
|
||||
nowMinute = currentMinute();
|
||||
}
|
||||
return nowMinute;
|
||||
}
|
||||
|
||||
export function useNowMinute(): string {
|
||||
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -22,7 +22,6 @@ import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsStat
|
||||
import { readLocalApi } from "../localApi";
|
||||
import {
|
||||
readEnvironmentSupportsSettlement,
|
||||
readEnvironmentSupportsSnooze,
|
||||
readEnvironmentThreadRefs,
|
||||
readProject,
|
||||
readThreadShell,
|
||||
@@ -70,30 +69,6 @@ export class ThreadSettleBlockedError extends Schema.TaggedErrorClass<ThreadSett
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadSnoozeUnsupportedError extends Schema.TaggedErrorClass<ThreadSnoozeUnsupportedError>()(
|
||||
"ThreadSnoozeUnsupportedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "This environment's server does not support snoozing yet. Update the server to use Snooze.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadSnoozeBlockedError extends Schema.TaggedErrorClass<ThreadSnoozeBlockedError>()(
|
||||
"ThreadSnoozeBlockedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "This thread is waiting on you. Respond to the pending request before snoozing it.";
|
||||
}
|
||||
}
|
||||
|
||||
export function useThreadActions() {
|
||||
const closeTerminal = useAtomCommand(terminalEnvironment.close);
|
||||
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
|
||||
@@ -111,12 +86,6 @@ export function useThreadActions() {
|
||||
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const snoozeThreadMutation = useAtomCommand(threadEnvironment.snooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
|
||||
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
|
||||
reportFailure: false,
|
||||
@@ -472,61 +441,6 @@ export function useThreadActions() {
|
||||
[unsettleThreadMutation],
|
||||
);
|
||||
|
||||
const snoozeThread = useCallback(
|
||||
async (target: ScopedThreadRef, snoozedUntil: string) => {
|
||||
// Version skew: never send the command to a server that predates it.
|
||||
if (!readEnvironmentSupportsSnooze(target.environmentId)) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSnoozeUnsupportedError({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
const resolved = resolveThreadTarget(target);
|
||||
// Blocked-on-you work and queued turns can't be snoozed away —
|
||||
// client-side twin of the server invariants so the UI rejects before
|
||||
// a round trip.
|
||||
if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSnoozeBlockedError({
|
||||
environmentId: resolved.threadRef.environmentId,
|
||||
threadId: resolved.threadRef.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
return snoozeThreadMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.threadId, snoozedUntil },
|
||||
});
|
||||
},
|
||||
[resolveThreadTarget, snoozeThreadMutation],
|
||||
);
|
||||
|
||||
const unsnoozeThread = useCallback(
|
||||
async (target: ScopedThreadRef) => {
|
||||
if (!readEnvironmentSupportsSnooze(target.environmentId)) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSnoozeUnsupportedError({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
return unsnoozeThreadMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.threadId, reason: "user" },
|
||||
});
|
||||
},
|
||||
[unsnoozeThreadMutation],
|
||||
);
|
||||
|
||||
const confirmAndDeleteThread = useCallback(
|
||||
async (target: ScopedThreadRef) => {
|
||||
const localApi = readLocalApi();
|
||||
@@ -563,18 +477,14 @@ export function useThreadActions() {
|
||||
confirmAndDeleteThread,
|
||||
settleThread,
|
||||
unsettleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
}),
|
||||
[
|
||||
archiveThread,
|
||||
confirmAndDeleteThread,
|
||||
deleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
],
|
||||
);
|
||||
}
|
||||
+20
-144
@@ -377,20 +377,21 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
}
|
||||
|
||||
.chat-composer-glass-shell {
|
||||
.chat-composer-glass-host {
|
||||
--chat-composer-glass-surface: var(--card);
|
||||
--chat-composer-outline: rgb(0 0 0 / 8%);
|
||||
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
box-shadow:
|
||||
0 0 0 1px rgb(0 0 0 / 8%),
|
||||
0 12px 28px -18px rgb(0 0 0 / 40%);
|
||||
}
|
||||
|
||||
.chat-composer-glass-shell::before {
|
||||
.chat-composer-glass-host::before {
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
z-index: 0;
|
||||
inset: 0;
|
||||
border-radius: 22px;
|
||||
border-radius: inherit;
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--chat-composer-glass-surface) var(--glass-opacity),
|
||||
@@ -401,76 +402,9 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
content: "";
|
||||
}
|
||||
|
||||
.chat-composer-glass-shell-with-context {
|
||||
--chat-composer-context-extension: 2.25rem;
|
||||
}
|
||||
|
||||
.chat-composer-glass-shell-with-context::before {
|
||||
border-radius: 0;
|
||||
/*
|
||||
* One continuous glass layer: a 22px composer joined to a 16px strip,
|
||||
* whose visible sides align with the composer's bottom tangents.
|
||||
*/
|
||||
clip-path: shape(
|
||||
from 0 22px,
|
||||
curve to 22px 0 with 0 9.85px / 9.85px 0,
|
||||
line to calc(100% - 22px) 0,
|
||||
curve to 100% 22px with calc(100% - 9.85px) 0 / 100% 9.85px,
|
||||
line to 100% calc(100% - var(--chat-composer-context-extension) - 22px),
|
||||
curve to calc(100% - 22px) calc(100% - var(--chat-composer-context-extension)) with 100%
|
||||
calc(100% - var(--chat-composer-context-extension) - 9.85px) / calc(100% - 9.85px)
|
||||
calc(100% - var(--chat-composer-context-extension)),
|
||||
line to calc(100% - 22px) calc(100% - 16px),
|
||||
curve to calc(100% - 38px) 100% with calc(100% - 22px) calc(100% - 7.16px) /
|
||||
calc(100% - 29.16px) 100%,
|
||||
line to 38px 100%,
|
||||
curve to 22px calc(100% - 16px) with 29.16px 100% / 22px calc(100% - 7.16px),
|
||||
line to 22px calc(100% - var(--chat-composer-context-extension)),
|
||||
curve to 0 calc(100% - var(--chat-composer-context-extension) - 22px) with 9.85px
|
||||
calc(100% - var(--chat-composer-context-extension)) / 0
|
||||
calc(100% - var(--chat-composer-context-extension) - 9.85px),
|
||||
line to 0 22px,
|
||||
close
|
||||
);
|
||||
}
|
||||
|
||||
@media (min-width: 40rem) {
|
||||
.chat-composer-glass-shell-with-context {
|
||||
/* The xs toolbar controls shrink by 4px at Tailwind's sm breakpoint. */
|
||||
--chat-composer-context-extension: 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-composer-glass-host {
|
||||
position: relative;
|
||||
box-shadow: 0 12px 28px -18px rgb(0 0 0 / 40%);
|
||||
}
|
||||
|
||||
.chat-composer-glass-host::after {
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
inset: 0;
|
||||
border: 1px solid var(--chat-composer-outline);
|
||||
border-radius: inherit;
|
||||
content: "";
|
||||
}
|
||||
|
||||
.chat-composer-glass-shell-with-context .chat-composer-glass-host::after {
|
||||
/* Keep the attachment seam open; the strip continues the outer outline below. */
|
||||
clip-path: polygon(
|
||||
0 0,
|
||||
100% 0,
|
||||
100% 100%,
|
||||
calc(100% - 22px) 100%,
|
||||
calc(100% - 22px) calc(100% - 2px),
|
||||
22px calc(100% - 2px),
|
||||
22px 100%,
|
||||
0 100%
|
||||
);
|
||||
}
|
||||
|
||||
.chat-composer-context-strip {
|
||||
--chat-composer-context-surface: var(--card);
|
||||
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
}
|
||||
@@ -479,72 +413,30 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
inset: 0;
|
||||
border: 1px solid var(--chat-composer-outline);
|
||||
border-radius: 0 0 16px 16px;
|
||||
/* Start the strip outline exactly where the composer's 22px curve reaches its tangent. */
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--chat-composer-context-surface) var(--glass-opacity),
|
||||
transparent
|
||||
);
|
||||
-webkit-mask-image: linear-gradient(to bottom, transparent 0 1rem, black 1rem);
|
||||
mask-image: linear-gradient(to bottom, transparent 0 1rem, black 1rem);
|
||||
box-shadow: 0 12px 28px -18px rgb(0 0 0 / 40%);
|
||||
content: "";
|
||||
}
|
||||
|
||||
.dark .chat-composer-glass-shell {
|
||||
--chat-composer-glass-surface: color-mix(in srgb, var(--background) 96%, var(--color-white));
|
||||
--chat-composer-outline: color-mix(in srgb, var(--color-white) 5%, transparent);
|
||||
--chat-composer-highlight: rgb(255 255 255 / 3%);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
}
|
||||
|
||||
.dark .chat-composer-glass-host {
|
||||
--chat-composer-glass-surface: color-mix(in srgb, var(--background) 96%, var(--color-white));
|
||||
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.dark .chat-composer-glass-host::after {
|
||||
box-shadow: inset 0 1px var(--chat-composer-highlight);
|
||||
}
|
||||
|
||||
.dark .chat-composer-context-strip::before {
|
||||
border-color: rgb(255 255 255 / 7%);
|
||||
background:
|
||||
linear-gradient(
|
||||
to bottom,
|
||||
transparent 0 1rem,
|
||||
rgb(0 0 0 / 18%) 1rem,
|
||||
transparent calc(1rem + 10px)
|
||||
),
|
||||
rgb(255 255 255 / 2%);
|
||||
box-shadow: 0 14px 32px -18px rgb(0 0 0 / 75%);
|
||||
}
|
||||
|
||||
@supports not (clip-path: shape(from 0 0, line to 1px 1px)) {
|
||||
.chat-composer-glass-shell-with-context::before {
|
||||
inset-block-end: var(--chat-composer-context-extension);
|
||||
border-radius: 22px;
|
||||
clip-path: none;
|
||||
}
|
||||
|
||||
.chat-composer-context-strip::before {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--chat-composer-glass-surface) var(--glass-opacity),
|
||||
transparent
|
||||
);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
}
|
||||
|
||||
.dark .chat-composer-context-strip::before {
|
||||
background:
|
||||
linear-gradient(
|
||||
to bottom,
|
||||
transparent 0 1rem,
|
||||
rgb(0 0 0 / 18%) 1rem,
|
||||
transparent calc(1rem + 10px)
|
||||
),
|
||||
linear-gradient(rgb(255 255 255 / 2%), rgb(255 255 255 / 2%)),
|
||||
color-mix(in srgb, var(--chat-composer-glass-surface) var(--glass-opacity), transparent);
|
||||
}
|
||||
}
|
||||
|
||||
.alert-glass {
|
||||
--alert-glass-tint: transparent;
|
||||
|
||||
@@ -574,6 +466,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
--alert-glass-tint: var(--warning);
|
||||
}
|
||||
|
||||
.dropdown-glass,
|
||||
.dialog-glass {
|
||||
background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
@@ -587,19 +480,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
.dropdown-glass {
|
||||
/*
|
||||
* Elevated glass needs a denser tint than broad ambient surfaces. Nesting
|
||||
* the user-controlled mix inside an 18% popover tint preserves the full
|
||||
* opacity setting range (40% -> 51%, 80% -> 84%, 100% -> 100%) while
|
||||
* keeping high-contrast page content from blooming through menus.
|
||||
*/
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--popover) 18%,
|
||||
color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)
|
||||
);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur));
|
||||
backdrop-filter: blur(var(--glass-blur));
|
||||
border: 1px solid color-mix(in srgb, var(--foreground) 10%, transparent);
|
||||
box-shadow: 0 16px 40px -18px rgb(0 0 0 / 55%);
|
||||
}
|
||||
@@ -614,11 +494,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
.dark .model-picker-surface.model-picker-surface {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--popover) 18%,
|
||||
color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)
|
||||
);
|
||||
background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);
|
||||
}
|
||||
|
||||
.dark .dialog-glass {
|
||||
@@ -765,7 +641,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
background: var(--background) !important;
|
||||
}
|
||||
|
||||
.chat-composer-glass-shell::before {
|
||||
.chat-composer-glass-host::before {
|
||||
background: var(--chat-composer-glass-surface);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
resolveThreadActionProjectRef,
|
||||
resolveNewDraftStartFromOrigin,
|
||||
startNewLocalThreadFromContext,
|
||||
startNewThreadFromContext,
|
||||
startNewThreadInProjectFromContext,
|
||||
type ChatThreadActionContext,
|
||||
} from "./chatThreadActions";
|
||||
|
||||
@@ -38,25 +40,16 @@ describe("chatThreadActions", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("prefers the active thread project when resolving thread actions", () => {
|
||||
const projectRef = resolveThreadActionProjectRef(
|
||||
createContext({
|
||||
activeThread: {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(projectRef).toEqual(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID));
|
||||
});
|
||||
|
||||
it("falls back to the active draft thread project when there is no active thread", () => {
|
||||
it("prefers the active draft thread project when resolving thread actions", () => {
|
||||
const projectRef = resolveThreadActionProjectRef(
|
||||
createContext({
|
||||
activeDraftThread: {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -74,17 +67,85 @@ describe("chatThreadActions", () => {
|
||||
expect(projectRef).toEqual(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID));
|
||||
});
|
||||
|
||||
it("inherits only the project from context, never branch or worktree state", async () => {
|
||||
it("starts a contextual new thread from the active draft thread", async () => {
|
||||
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
|
||||
|
||||
const didStart = await startNewThreadFromContext(
|
||||
createContext({
|
||||
activeDraftThread: {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
handleNewThread,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(didStart).toBe(true);
|
||||
expect(handleNewThread).toHaveBeenCalledWith(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), {
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves an explicitly disabled origin base in contextual thread options", async () => {
|
||||
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
|
||||
|
||||
await startNewThreadFromContext(
|
||||
createContext({
|
||||
activeDraftThread: {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: false,
|
||||
},
|
||||
handleNewThread,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(handleNewThread).toHaveBeenCalledWith(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), {
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not carry branch or worktree context into a different project", async () => {
|
||||
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
|
||||
const targetProjectRef = scopeProjectRef(ENVIRONMENT_ID, FALLBACK_PROJECT_ID);
|
||||
|
||||
await startNewThreadInProjectFromContext(
|
||||
createContext({
|
||||
activeThread: {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
},
|
||||
handleNewThread,
|
||||
}),
|
||||
targetProjectRef,
|
||||
);
|
||||
|
||||
expect(handleNewThread).toHaveBeenCalledWith(targetProjectRef);
|
||||
});
|
||||
|
||||
it("delegates the target environment defaults to the new-thread handler", async () => {
|
||||
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
|
||||
|
||||
const didStart = await startNewLocalThreadFromContext(
|
||||
createContext({
|
||||
defaultProjectRef: scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID),
|
||||
handleNewThread,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(didStart).toBe(true);
|
||||
|
||||
@@ -5,6 +5,13 @@ import type { DraftThreadEnvMode } from "../composerDraftStore";
|
||||
interface ThreadContextLike {
|
||||
environmentId: EnvironmentId;
|
||||
projectId: ProjectId;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}
|
||||
|
||||
interface DraftThreadContextLike extends ThreadContextLike {
|
||||
envMode: DraftThreadEnvMode;
|
||||
startFromOrigin: boolean;
|
||||
}
|
||||
|
||||
interface NewThreadHandler {
|
||||
@@ -19,8 +26,10 @@ interface NewThreadHandler {
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
type NewThreadOptions = NonNullable<Parameters<NewThreadHandler>[1]>;
|
||||
|
||||
export interface ChatThreadActionContext {
|
||||
readonly activeDraftThread: ThreadContextLike | null;
|
||||
readonly activeDraftThread: DraftThreadContextLike | null;
|
||||
readonly activeThread: ThreadContextLike | undefined;
|
||||
readonly defaultProjectRef: ScopedProjectRef | null;
|
||||
readonly handleNewThread: NewThreadHandler;
|
||||
@@ -48,12 +57,35 @@ export function resolveThreadActionProjectRef(
|
||||
return context.defaultProjectRef;
|
||||
}
|
||||
|
||||
// New threads inherit only the *project* from the current context. Branch,
|
||||
// worktree, and env mode always come from the user's configured defaults —
|
||||
// carrying them over from the viewed thread meant "new thread" silently
|
||||
// reused checkouts and branches. Explicit affordances (branch toolbar's
|
||||
// "new thread in this worktree") pass those options to handleNewThread
|
||||
// directly instead.
|
||||
function buildContextualThreadOptions(context: ChatThreadActionContext): NewThreadOptions {
|
||||
return {
|
||||
branch: context.activeThread?.branch ?? context.activeDraftThread?.branch ?? null,
|
||||
worktreePath:
|
||||
context.activeThread?.worktreePath ?? context.activeDraftThread?.worktreePath ?? null,
|
||||
envMode:
|
||||
context.activeDraftThread?.envMode ??
|
||||
(context.activeThread?.worktreePath ? "worktree" : "local"),
|
||||
...(context.activeDraftThread
|
||||
? { startFromOrigin: context.activeDraftThread.startFromOrigin }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function startNewThreadInProjectFromContext(
|
||||
context: ChatThreadActionContext,
|
||||
projectRef: ScopedProjectRef,
|
||||
): Promise<void> {
|
||||
const contextualProjectRef = resolveThreadActionProjectRef(context);
|
||||
const matchesContext =
|
||||
contextualProjectRef?.environmentId === projectRef.environmentId &&
|
||||
contextualProjectRef.projectId === projectRef.projectId;
|
||||
if (!matchesContext) {
|
||||
await context.handleNewThread(projectRef);
|
||||
return;
|
||||
}
|
||||
await context.handleNewThread(projectRef, buildContextualThreadOptions(context));
|
||||
}
|
||||
|
||||
export async function startNewThreadFromContext(
|
||||
context: ChatThreadActionContext,
|
||||
): Promise<boolean> {
|
||||
@@ -62,6 +94,18 @@ export async function startNewThreadFromContext(
|
||||
return false;
|
||||
}
|
||||
|
||||
await startNewThreadInProjectFromContext(context, projectRef);
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function startNewLocalThreadFromContext(
|
||||
context: ChatThreadActionContext,
|
||||
): Promise<boolean> {
|
||||
const projectRef = resolveThreadActionProjectRef(context);
|
||||
if (!projectRef) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await context.handleNewThread(projectRef);
|
||||
return true;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildTurnDiffTree, summarizeTurnDiffStats } from "./turnDiffTree";
|
||||
import { buildTurnDiffTree, partitionTurnDiffFiles, summarizeTurnDiffStats } from "./turnDiffTree";
|
||||
|
||||
describe("summarizeTurnDiffStats", () => {
|
||||
it("sums only files with numeric additions/deletions", () => {
|
||||
@@ -166,3 +166,33 @@ describe("buildTurnDiffTree", () => {
|
||||
expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("partitionTurnDiffFiles", () => {
|
||||
it("splits files by origin, defaulting missing origin to agent", () => {
|
||||
const agentEdit = { path: "edited.ts", kind: "modified", additions: 1, deletions: 0 } as const;
|
||||
const legacy = { path: "legacy.ts", kind: "modified", additions: 2, deletions: 0 } as const;
|
||||
const pulled = {
|
||||
path: "pulled.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
origin: "git",
|
||||
} as const;
|
||||
const explicitAgent = {
|
||||
path: "explicit.ts",
|
||||
kind: "modified",
|
||||
additions: 4,
|
||||
deletions: 0,
|
||||
origin: "agent",
|
||||
} as const;
|
||||
|
||||
const { agentFiles, gitFiles } = partitionTurnDiffFiles([
|
||||
agentEdit,
|
||||
legacy,
|
||||
pulled,
|
||||
explicitAgent,
|
||||
]);
|
||||
expect(agentFiles.map((file) => file.path)).toEqual(["edited.ts", "legacy.ts", "explicit.ts"]);
|
||||
expect(gitFiles.map((file) => file.path)).toEqual(["pulled.ts"]);
|
||||
});
|
||||
});
|
||||
@@ -96,6 +96,24 @@ function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
|
||||
return [...subdirectories, ...files];
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a turn's changed files into agent-authored work and changes that
|
||||
* arrived via pre-existing git history (pull, checkout, cherry-pick, rebase).
|
||||
* Files without an origin (captured before attribution shipped) count as
|
||||
* agent work.
|
||||
*/
|
||||
export function partitionTurnDiffFiles(files: ReadonlyArray<TurnDiffFileChange>): {
|
||||
agentFiles: ReadonlyArray<TurnDiffFileChange>;
|
||||
gitFiles: ReadonlyArray<TurnDiffFileChange>;
|
||||
} {
|
||||
const agentFiles: TurnDiffFileChange[] = [];
|
||||
const gitFiles: TurnDiffFileChange[] = [];
|
||||
for (const file of files) {
|
||||
(file.origin === "git" ? gitFiles : agentFiles).push(file);
|
||||
}
|
||||
return { agentFiles, gitFiles };
|
||||
}
|
||||
|
||||
export function summarizeTurnDiffStats(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffStat {
|
||||
return files.reduce(
|
||||
(acc, file) => {
|
||||
|
||||
@@ -295,7 +295,6 @@ describe("previewStateStore (single-tab)", () => {
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
});
|
||||
const state = readThreadPreviewState(ref);
|
||||
@@ -313,7 +312,6 @@ describe("previewStateStore (single-tab)", () => {
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
});
|
||||
setActivePreviewTab(ref, first.tabId);
|
||||
@@ -359,7 +357,6 @@ describe("previewStateStore (single-tab)", () => {
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
});
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import {
|
||||
type DesktopPreviewColorScheme,
|
||||
type PreviewEvent,
|
||||
type PreviewSessionSnapshot,
|
||||
type ScopedThreadRef,
|
||||
@@ -23,7 +22,6 @@ export interface DesktopPreviewOverlay {
|
||||
canGoForward: boolean;
|
||||
loading: boolean;
|
||||
zoomFactor: number;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
}
|
||||
|
||||
|
||||
@@ -4,14 +4,9 @@ import { useEffect } from "react";
|
||||
import ChatView from "../components/ChatView";
|
||||
import { threadHasStarted } from "../components/ChatView.logic";
|
||||
import { finalizePromotedDraftThreadByRef, useComposerDraftStore } from "../composerDraftStore";
|
||||
import { resolveThreadRouteRef, resolveThreadRouteRenderState } from "../threadRoutes";
|
||||
import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { SidebarInset } from "~/components/ui/sidebar";
|
||||
import {
|
||||
useEnvironmentThreadRefs,
|
||||
useThreadDetail,
|
||||
useThreadShell,
|
||||
useThreadStatus,
|
||||
} from "../state/entities";
|
||||
import { useEnvironmentThreadRefs, useThreadDetail, useThreadShell } from "../state/entities";
|
||||
import { useEnvironmentQuery } from "../state/query";
|
||||
import { environmentShell } from "../state/shell";
|
||||
|
||||
@@ -25,9 +20,9 @@ function ChatThreadRouteView() {
|
||||
);
|
||||
const serverThreadShell = useThreadShell(threadRef);
|
||||
const serverThreadDetail = useThreadDetail(threadRef);
|
||||
const serverThreadStatus = useThreadStatus(threadRef);
|
||||
const environmentThreadRefs = useEnvironmentThreadRefs(threadRef?.environmentId ?? null);
|
||||
const bootstrapComplete = shell.data?.snapshot._tag === "Some";
|
||||
const threadExists = serverThreadShell !== null || serverThreadDetail !== null;
|
||||
const environmentHasServerThreads = environmentThreadRefs.length > 0;
|
||||
const draftThreadExists = useComposerDraftStore((store) =>
|
||||
threadRef ? store.getDraftThreadByRef(threadRef) !== null : false,
|
||||
@@ -41,13 +36,7 @@ function ChatThreadRouteView() {
|
||||
}
|
||||
return store.hasDraftThreadsInEnvironment(threadRef.environmentId);
|
||||
});
|
||||
const renderState = resolveThreadRouteRenderState({
|
||||
bootstrapComplete,
|
||||
serverThreadShellExists: serverThreadShell !== null,
|
||||
serverThreadDetailExists: serverThreadDetail !== null,
|
||||
serverThreadDetailDeleted: serverThreadStatus === "deleted",
|
||||
draftThreadExists,
|
||||
});
|
||||
const routeThreadExists = threadExists || draftThreadExists;
|
||||
const serverThreadStarted = threadHasStarted(serverThreadDetail);
|
||||
const environmentHasAnyThreads = environmentHasServerThreads || environmentHasDraftThreads;
|
||||
|
||||
@@ -56,10 +45,10 @@ function ChatThreadRouteView() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (renderState === "missing" && environmentHasAnyThreads) {
|
||||
if (!routeThreadExists && environmentHasAnyThreads) {
|
||||
void navigate({ to: "/", replace: true });
|
||||
}
|
||||
}, [bootstrapComplete, environmentHasAnyThreads, navigate, renderState, threadRef]);
|
||||
}, [bootstrapComplete, environmentHasAnyThreads, navigate, routeThreadExists, threadRef]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!threadRef || !serverThreadStarted || !draftThread) {
|
||||
@@ -68,7 +57,7 @@ function ChatThreadRouteView() {
|
||||
finalizePromotedDraftThreadByRef(threadRef);
|
||||
}, [draftThread, serverThreadStarted, threadRef]);
|
||||
|
||||
if (!threadRef || renderState !== "ready") {
|
||||
if (!threadRef || !bootstrapComplete || !routeThreadExists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,10 @@ import { selectProjectGroupingSettings } from "../logicalProject";
|
||||
import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
|
||||
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import {
|
||||
startNewLocalThreadFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import { isPreviewFocused } from "../lib/previewFocus";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
@@ -80,7 +83,7 @@ function ChatRouteGlobalShortcuts() {
|
||||
if (command === "chat.newLocal") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void startNewThreadFromContext({
|
||||
void startNewLocalThreadFromContext({
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user