Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
368e0e1527 | ||
|
|
514fccf529 | ||
|
|
528adb2fe0 | ||
|
|
94df0a913d | ||
|
|
202e5609ff | ||
|
|
bb38c3320d | ||
|
|
6b9a5987f6 | ||
|
|
fc3f78f5d9 | ||
|
|
2f41c073a2 | ||
|
|
51672b6ecb | ||
|
|
67a7b1a1d3 | ||
|
|
ce467da9cf | ||
|
|
6ef7aa8399 | ||
|
|
193e3c62e6 | ||
|
|
91dfe60a99 | ||
|
|
edb12401e5 | ||
|
|
79fe11bc1c | ||
|
|
b3e51317e4 | ||
|
|
ddd5a46f39 | ||
|
|
88c69ffff6 | ||
|
|
979854895c | ||
|
|
9cbe50d10d | ||
|
|
9d9208cec5 | ||
|
|
57100fba85 | ||
|
|
3afb4a9ef9 | ||
|
|
315b27385d | ||
|
|
719c905eac | ||
|
|
0542abc75e | ||
|
|
7609495bf7 | ||
|
|
b41e89eba9 |
No files matched your search
@@ -50,6 +50,7 @@ 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,6 +13,7 @@ import {
|
||||
DesktopPreviewRecordingSaveInputSchema,
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
@@ -138,6 +139,15 @@ 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",
|
||||
@@ -346,6 +356,7 @@ export const methods = [
|
||||
zoomOut,
|
||||
resetZoom,
|
||||
hardReload,
|
||||
setColorScheme,
|
||||
openDevTools,
|
||||
clearCookies,
|
||||
clearCache,
|
||||
|
||||
@@ -160,6 +160,8 @@ 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,6 +365,79 @@ 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,6 +7,7 @@
|
||||
*/
|
||||
import type {
|
||||
DesktopPreviewAnnotationTheme,
|
||||
DesktopPreviewColorScheme,
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
@@ -84,6 +85,7 @@ export interface PreviewTabState {
|
||||
canGoBack: boolean;
|
||||
canGoForward: boolean;
|
||||
zoomFactor: number;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -1288,6 +1290,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1320,6 +1323,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1386,7 +1390,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
runFork(restoreControlSession(tabId, wc));
|
||||
const registeredAt = yield* currentIso;
|
||||
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
@@ -1457,6 +1461,7 @@ 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,
|
||||
};
|
||||
@@ -1525,7 +1530,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(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
if (!wc.isDestroyed()) runFork(restoreControlSession(tabId, wc));
|
||||
});
|
||||
wc.openDevTools({ mode: "detach" });
|
||||
});
|
||||
@@ -1684,6 +1689,65 @@ 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,
|
||||
) {
|
||||
@@ -2526,6 +2590,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
revealArtifact,
|
||||
saveRecording,
|
||||
setAnnotationTheme,
|
||||
setColorScheme,
|
||||
setMainWindow,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
@@ -2830,6 +2895,10 @@ 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>;
|
||||
@@ -2921,6 +2990,7 @@ 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
|
||||
|
||||
+19
-5
@@ -13,7 +13,10 @@ import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
|
||||
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import {
|
||||
AppearancePreferencesProvider,
|
||||
useAppearancePreferences,
|
||||
} from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
import { OverlayPortalHost } from "./components/OverlayPortal";
|
||||
@@ -26,6 +29,10 @@ if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
|
||||
prepareNativeShowcaseCapture();
|
||||
}
|
||||
|
||||
void SplashScreen.preventAutoHideAsync().catch(() => {
|
||||
// The native module can be unavailable in non-native test environments.
|
||||
});
|
||||
|
||||
const appLinking = {
|
||||
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
|
||||
// The Expo dev client launches the app via
|
||||
@@ -40,18 +47,25 @@ const appLinking = {
|
||||
|
||||
const Navigation = createStaticNavigation(RootStack);
|
||||
|
||||
function SplashScreenCoordinator() {
|
||||
const { isReady } = useAppearancePreferences();
|
||||
|
||||
useEffect(() => {
|
||||
if (isReady) void SplashScreen.hide();
|
||||
}, [isReady]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const colorScheme = useColorScheme();
|
||||
const statusBarBg = useThemeColor("--color-status-bar");
|
||||
|
||||
useEffect(() => {
|
||||
SplashScreen.hide();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<AppearancePreferencesProvider>
|
||||
<SplashScreenCoordinator />
|
||||
<GestureHandlerRootView className="flex-1">
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
@@ -28,7 +24,6 @@ import {
|
||||
} from "./home-list-filter-menu";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
@@ -43,13 +38,11 @@ export function HomeHeader(props: {
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
}) {
|
||||
@@ -143,20 +136,10 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
state: checkedMenuState(props.threadSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "project-grouping",
|
||||
title: "Group projects",
|
||||
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
id: `project-grouping:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.projectGroupingMode === option.value),
|
||||
})),
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
],
|
||||
[
|
||||
props.environments,
|
||||
props.projectGroupingMode,
|
||||
props.projectSortOrder,
|
||||
props.projects,
|
||||
props.selectedEnvironmentId,
|
||||
@@ -210,13 +193,6 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
props.onThreadSortOrderChange(threadSort.value);
|
||||
return;
|
||||
}
|
||||
|
||||
const grouping = PROJECT_GROUPING_OPTIONS.find(
|
||||
(option) => id === `project-grouping:${option.value}`,
|
||||
);
|
||||
if (grouping) {
|
||||
props.onProjectGroupingModeChange(grouping.value);
|
||||
}
|
||||
},
|
||||
[props],
|
||||
);
|
||||
@@ -409,10 +385,6 @@ 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
|
||||
@@ -480,20 +452,6 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Group projects">
|
||||
<NativeHeaderToolbar.Label>Group projects</NativeHeaderToolbar.Label>
|
||||
{PROJECT_GROUPING_OPTIONS.map((option) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectGroupingMode === option.value}
|
||||
onPress={() => props.onProjectGroupingModeChange(option.value)}
|
||||
subtitle={option.subtitle}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
|
||||
<NativeHeaderToolbar.SearchBarSlot />
|
||||
|
||||
@@ -4,7 +4,6 @@ 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";
|
||||
@@ -16,6 +15,7 @@ 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";
|
||||
|
||||
@@ -54,7 +54,6 @@ export function HomeRouteScreen() {
|
||||
const {
|
||||
options: listOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
} = useHomeListOptions(availableEnvironmentIds);
|
||||
@@ -62,16 +61,15 @@ export function HomeRouteScreen() {
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
projects
|
||||
.filter(
|
||||
(project) =>
|
||||
selectedEnvironmentId === null || project.environmentId === selectedEnvironmentId,
|
||||
)
|
||||
.map((project) => ({
|
||||
key: scopedProjectKey(project.environmentId, project.id),
|
||||
label: project.title,
|
||||
})),
|
||||
[projects, selectedEnvironmentId],
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: selectedEnvironmentId,
|
||||
projectGroupingMode: listOptions.projectGroupingMode,
|
||||
}).map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[listOptions.projectGroupingMode, projects, selectedEnvironmentId],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
@@ -119,11 +117,9 @@ export function HomeRouteScreen() {
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
@@ -146,7 +142,6 @@ export function HomeRouteScreen() {
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
|
||||
@@ -15,17 +15,15 @@ import type {
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
@@ -54,7 +52,12 @@ import {
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "./homeListItems";
|
||||
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
type HomeProjectSortOrder,
|
||||
} from "./homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
|
||||
@@ -79,7 +82,6 @@ interface HomeScreenProps {
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onAddConnection: () => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
@@ -243,43 +245,69 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
|
||||
const scopedProject = useMemo(
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects: props.projects,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
|
||||
);
|
||||
const selectedProjectScope = useMemo(
|
||||
() =>
|
||||
props.selectedProjectKey === null
|
||||
? null
|
||||
: (props.projects.find(
|
||||
(project) =>
|
||||
scopedProjectKey(project.environmentId, project.id) === props.selectedProjectKey &&
|
||||
(props.selectedEnvironmentId === null ||
|
||||
project.environmentId === props.selectedEnvironmentId),
|
||||
: (projectScopes.find(
|
||||
(scope) =>
|
||||
scope.key === props.selectedProjectKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
props.selectedProjectKey,
|
||||
),
|
||||
) ?? null),
|
||||
[props.projects, props.selectedEnvironmentId, props.selectedProjectKey],
|
||||
[projectScopes, props.selectedProjectKey],
|
||||
);
|
||||
const selectedProjectRefKeys = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() => (scopedProject === null ? props.projects : [scopedProject]),
|
||||
[props.projects, scopedProject],
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.projects
|
||||
: props.projects.filter((project) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[props.projects, selectedProjectRefKeys],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
scopedProject === null
|
||||
selectedProjectRefKeys === null
|
||||
? props.threads
|
||||
: props.threads.filter(
|
||||
(thread) =>
|
||||
thread.environmentId === scopedProject.environmentId &&
|
||||
thread.projectId === scopedProject.id,
|
||||
: props.threads.filter((thread) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
),
|
||||
[props.threads, scopedProject],
|
||||
[props.threads, selectedProjectRefKeys],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
scopedProject === null
|
||||
selectedProjectRefKeys === null
|
||||
? props.pendingTasks
|
||||
: props.pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
pendingTask.message.environmentId === scopedProject.environmentId &&
|
||||
pendingTask.creation.projectId === scopedProject.id,
|
||||
: props.pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
),
|
||||
[props.pendingTasks, scopedProject],
|
||||
[props.pendingTasks, selectedProjectRefKeys],
|
||||
);
|
||||
|
||||
const projectGroups = useMemo(
|
||||
@@ -334,23 +362,64 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}, [props.projects]);
|
||||
|
||||
const v2ProjectScopeKey = props.selectedProjectKey;
|
||||
const setV2ProjectScopeKey = props.onProjectChange;
|
||||
const v2ScopeProjects = useMemo(
|
||||
() =>
|
||||
props.selectedEnvironmentId === null
|
||||
? props.projects
|
||||
: props.projects.filter((project) => project.environmentId === props.selectedEnvironmentId),
|
||||
[props.projects, props.selectedEnvironmentId],
|
||||
sortHomeProjectScopes({
|
||||
scopes: projectScopes,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
projectScopes,
|
||||
],
|
||||
);
|
||||
const v2ScopedProject = useMemo(
|
||||
const v2ScopedProjectGroup = useMemo(
|
||||
() =>
|
||||
v2ProjectScopeKey === null
|
||||
? null
|
||||
: (v2ScopeProjects.find(
|
||||
(project) => scopedProjectKey(project.environmentId, project.id) === v2ProjectScopeKey,
|
||||
(scope) =>
|
||||
scope.key === v2ProjectScopeKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
v2ProjectScopeKey,
|
||||
),
|
||||
) ?? 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
|
||||
? null
|
||||
: new Set(
|
||||
v2ScopedProjectGroup.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[v2ScopedProjectGroup],
|
||||
);
|
||||
// Thread List v2 (beta): one flat list in creation order, no grouping.
|
||||
// Settled threads collapse into a recency tail below the card block.
|
||||
// Settled threads stay in the live shell stream (settled ≠ archived), so
|
||||
@@ -403,6 +472,10 @@ 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
|
||||
@@ -424,37 +497,59 @@ 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 };
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
threads: props.threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectRef:
|
||||
v2ScopedProject === null
|
||||
? null
|
||||
: {
|
||||
environmentId: v2ScopedProject.environmentId,
|
||||
projectId: v2ScopedProject.id,
|
||||
},
|
||||
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
|
||||
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,
|
||||
v2ScopedProject,
|
||||
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(
|
||||
@@ -467,6 +562,9 @@ 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)
|
||||
@@ -510,6 +608,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
@@ -699,9 +798,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
(pendingTask) =>
|
||||
(props.selectedEnvironmentId === null ||
|
||||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
|
||||
(v2ScopedProject === null ||
|
||||
(pendingTask.message.environmentId === v2ScopedProject.environmentId &&
|
||||
pendingTask.creation.projectId === v2ScopedProject.id)) &&
|
||||
(v2ScopedProjectKeys === null ||
|
||||
v2ScopedProjectKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
)) &&
|
||||
(v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
|
||||
);
|
||||
// Project scoping lives in the header filter menu (no inline chip row on
|
||||
@@ -728,9 +828,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : scopedProject !== null ? (
|
||||
) : selectedProjectScope !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${scopedProject.title}`}
|
||||
title={`No threads in ${selectedProjectScope.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : selectedEnvironmentLabel ? (
|
||||
@@ -745,14 +845,34 @@ 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. Pending tasks render in the header, so the
|
||||
// list showing them isn't empty in the user's eyes.
|
||||
// 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;
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProject !== null ? (
|
||||
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={`No threads in ${v2ScopedProject.title}`}
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -15,17 +15,16 @@ describe("buildHomeListFilterMenu", () => {
|
||||
selectedProjectKey: "environment-1:project-1",
|
||||
projectSortOrder: "updated_at",
|
||||
threadSortOrder: "updated_at",
|
||||
projectGroupingMode: "repository",
|
||||
onEnvironmentChange: vi.fn(),
|
||||
onProjectChange,
|
||||
onProjectSortOrderChange: vi.fn(),
|
||||
onThreadSortOrderChange: vi.fn(),
|
||||
onProjectGroupingModeChange: vi.fn(),
|
||||
});
|
||||
|
||||
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: [
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
import { PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS } from "./home-list-options";
|
||||
|
||||
export interface HomeListFilterMenuEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -47,13 +39,10 @@ export function buildHomeListFilterMenu(props: {
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => 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. */
|
||||
@@ -61,14 +50,6 @@ 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",
|
||||
@@ -136,17 +117,6 @@ export function buildHomeListFilterMenu(props: {
|
||||
onPress: () => props.onThreadSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Group projects",
|
||||
items: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
subtitle: option.subtitle,
|
||||
state: props.projectGroupingMode === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectGroupingModeChange(option.value),
|
||||
})),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -14,7 +13,6 @@ const defaults: HomeListOptions = {
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
|
||||
describe("home list options", () => {
|
||||
@@ -22,11 +20,10 @@ describe("home list options", () => {
|
||||
expect(hasCustomHomeListOptions(defaults)).toBe(false);
|
||||
});
|
||||
|
||||
it("marks environment filters and grouping changes as customized", () => {
|
||||
it("marks environment filters as customized", () => {
|
||||
expect(
|
||||
hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }),
|
||||
).toBe(true);
|
||||
expect(hasCustomHomeListOptions({ ...defaults, projectGroupingMode: "separate" })).toBe(true);
|
||||
expect(
|
||||
hasCustomHomeListOptions({ ...defaults, selectedProjectKey: "environment-1:project-1" }),
|
||||
).toBe(true);
|
||||
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -26,9 +25,18 @@ export interface HomeListOptions {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
}
|
||||
|
||||
export interface ResolvedHomeListOptions extends HomeListOptions {
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
export function resolveProjectGroupingMode(
|
||||
projectGroupingEnabled: boolean | undefined,
|
||||
): SidebarProjectGroupingMode {
|
||||
return projectGroupingEnabled === false ? "separate" : "repository";
|
||||
}
|
||||
|
||||
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: HomeProjectSortOrder;
|
||||
readonly label: string;
|
||||
@@ -45,28 +53,6 @@ export const THREAD_SORT_OPTIONS: ReadonlyArray<{
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
export const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarProjectGroupingMode;
|
||||
readonly label: string;
|
||||
readonly subtitle: string;
|
||||
}> = [
|
||||
{
|
||||
value: "repository",
|
||||
label: "Group by repository",
|
||||
subtitle: "Combine matching repositories across environments",
|
||||
},
|
||||
{
|
||||
value: "repository_path",
|
||||
label: "Group by repository path",
|
||||
subtitle: "Combine only matching paths within a repository",
|
||||
},
|
||||
{
|
||||
value: "separate",
|
||||
label: "Keep separate",
|
||||
subtitle: "Show every project path separately",
|
||||
},
|
||||
];
|
||||
|
||||
function defaultHomeListOptions(): HomeListOptions {
|
||||
return {
|
||||
selectedEnvironmentId: null,
|
||||
@@ -75,26 +61,34 @@ function defaultHomeListOptions(): HomeListOptions {
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
}
|
||||
|
||||
interface HomeListOptionsContextValue {
|
||||
readonly options: HomeListOptions;
|
||||
readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>(null);
|
||||
|
||||
/** Keeps list preferences stable while the app moves between compact and split shells. */
|
||||
export function HomeListOptionsProvider({ children }: PropsWithChildren) {
|
||||
export function HomeListOptionsProvider({
|
||||
children,
|
||||
projectGroupingMode,
|
||||
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
|
||||
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
|
||||
const value = useMemo(() => ({ options, setOptions }), [options]);
|
||||
const value = useMemo(
|
||||
() => ({ options, setOptions, projectGroupingMode }),
|
||||
[options, projectGroupingMode],
|
||||
);
|
||||
return createElement(HomeListOptionsContext, { value }, children);
|
||||
}
|
||||
|
||||
export function hasCustomHomeListOptions(
|
||||
options: HomeListOptions & { readonly selectedProjectKey?: string | null },
|
||||
options: HomeListOptions & {
|
||||
readonly selectedProjectKey?: string | null;
|
||||
},
|
||||
): boolean {
|
||||
const defaultProjectSortOrder =
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
@@ -104,8 +98,7 @@ export function hasCustomHomeListOptions(
|
||||
options.selectedEnvironmentId !== null ||
|
||||
(options.selectedProjectKey !== null && options.selectedProjectKey !== undefined) ||
|
||||
options.projectSortOrder !== defaultProjectSortOrder ||
|
||||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
|
||||
options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE
|
||||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER
|
||||
);
|
||||
}
|
||||
|
||||
@@ -119,10 +112,14 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
|
||||
availableEnvironmentIds.has(options.selectedEnvironmentId)
|
||||
? options.selectedEnvironmentId
|
||||
: null;
|
||||
const resolvedOptions =
|
||||
const availableOptions =
|
||||
selectedEnvironmentId === options.selectedEnvironmentId
|
||||
? options
|
||||
: { ...options, selectedEnvironmentId };
|
||||
const resolvedOptions: ResolvedHomeListOptions = {
|
||||
...availableOptions,
|
||||
projectGroupingMode: shared?.projectGroupingMode ?? "repository",
|
||||
};
|
||||
|
||||
const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {
|
||||
setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
|
||||
@@ -133,15 +130,10 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
|
||||
const setThreadSortOrder = useCallback((value: SidebarThreadSortOrder) => {
|
||||
setOptions((current) => ({ ...current, threadSortOrder: value }));
|
||||
}, []);
|
||||
const setProjectGroupingMode = useCallback((value: SidebarProjectGroupingMode) => {
|
||||
setOptions((current) => ({ ...current, projectGroupingMode: value }));
|
||||
}, []);
|
||||
|
||||
return {
|
||||
options: resolvedOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
setProjectGroupingMode,
|
||||
} as const;
|
||||
}
|
||||
@@ -5,7 +5,11 @@ import type {
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildHomeThreadGroups } from "./homeThreadList";
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -67,6 +71,346 @@ function buildGroups(
|
||||
}
|
||||
|
||||
describe("buildHomeThreadGroups", () => {
|
||||
it("builds one v2 scope for the same repository across environments", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
];
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.title).toBe("t3code");
|
||||
expect(scopes[0]?.projects).toEqual(projects);
|
||||
expect(scopes[0]?.projectRefs).toEqual(
|
||||
projects.map((project) => ({
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
it("routes stale duplicate project refs through the canonical repository group", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const local = makeProject({
|
||||
id: ProjectId.make("project-local"),
|
||||
environmentId: localEnvironmentId,
|
||||
title: "t3code",
|
||||
workspaceRoot: "/workspaces/t3code",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const stale = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-stale"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
});
|
||||
const canonicalRemote = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-canonical-remote"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code/",
|
||||
repositoryIdentity,
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const projects = [local, stale, canonicalRemote];
|
||||
const staleThread = makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("thread-stale-project-ref"),
|
||||
projectId: stale.id,
|
||||
title: "Still visible",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
const groups = buildGroups(projects, [staleThread]);
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.projects.map((project) => project.id)).toEqual([
|
||||
local.id,
|
||||
canonicalRemote.id,
|
||||
]);
|
||||
expect(scopes[0]?.projectRefs.map((projectRef) => projectRef.projectId)).toEqual([
|
||||
local.id,
|
||||
stale.id,
|
||||
canonicalRemote.id,
|
||||
]);
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.threads.map((thread) => thread.id)).toEqual([staleThread.id]);
|
||||
expect(groups[0]?.newThreadTarget?.id).toBe(canonicalRemote.id);
|
||||
});
|
||||
|
||||
it("keeps repository identity from an older duplicate when the freshness winner lacks it", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote-with-identity"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code",
|
||||
repositoryIdentity,
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote-fresh"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code/",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.representative.id).toBe(ProjectId.make("project-local"));
|
||||
expect(scopes[0]?.projects.map((project) => project.id)).toContain(
|
||||
ProjectId.make("project-remote-fresh"),
|
||||
);
|
||||
expect(scopes[0]?.projectRefs).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("sorts v2 project scopes by their grouped thread activity", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const olderProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-older"),
|
||||
title: "Older project",
|
||||
});
|
||||
const newerProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-newer"),
|
||||
title: "Newer project",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [newerProject, olderProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "separate",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-older-project"),
|
||||
projectId: olderProject.id,
|
||||
title: "Most recently active",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-newer-project"),
|
||||
projectId: newerProject.id,
|
||||
title: "Less recently active",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
}).map((scope) => scope.representative.id),
|
||||
).toEqual([olderProject.id, newerProject.id]);
|
||||
});
|
||||
|
||||
it("sorts invalid project creation timestamps after valid ones", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const invalidProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-invalid"),
|
||||
title: "A invalid timestamp",
|
||||
createdAt: "invalid",
|
||||
});
|
||||
const validProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-valid"),
|
||||
title: "Z valid timestamp",
|
||||
createdAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [invalidProject, validProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "separate",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "created_at",
|
||||
}).map((scope) => scope.representative.id),
|
||||
).toEqual([validProject.id, invalidProject.id]);
|
||||
});
|
||||
|
||||
it("uses the freshest member when a grouped scope has no activity", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const olderMember = makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-older-member"),
|
||||
title: "t3code",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const newerMember = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-newer-member"),
|
||||
title: "t3code",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const otherProject = makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-other"),
|
||||
title: "other",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [olderMember, newerMember, otherProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
})[0]?.key,
|
||||
).toBe(scopes.find((scope) => scope.projects.length === 2)?.key);
|
||||
});
|
||||
|
||||
it("does not merge unrelated repositories that share a title", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const projects = ["one", "two"].map((name) =>
|
||||
makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make(`project-${name}`),
|
||||
title: "app",
|
||||
repositoryIdentity: {
|
||||
canonicalKey: `github.com/example/${name}`,
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: `[email protected]:example/${name}.git`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
}),
|
||||
).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({
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import {
|
||||
deriveLogicalProjectKey,
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupLabel,
|
||||
} from "@t3tools/client-runtime/state/project-grouping";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import {
|
||||
getThreadSortTimestamp,
|
||||
sortThreads,
|
||||
toSortableTimestamp,
|
||||
} from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ScopedProjectRef,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarProjectSortOrder,
|
||||
SidebarThreadSortOrder,
|
||||
@@ -22,6 +28,161 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
|
||||
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
|
||||
|
||||
export interface HomeProjectScope {
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly representative: EnvironmentProject;
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
|
||||
}
|
||||
|
||||
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
|
||||
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
|
||||
}
|
||||
|
||||
function getProjectSortTimestamp(
|
||||
project: EnvironmentProject,
|
||||
sortOrder: HomeProjectSortOrder,
|
||||
): number {
|
||||
return sortOrder === "created_at"
|
||||
? (toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY)
|
||||
: (toSortableTimestamp(project.updatedAt) ??
|
||||
toSortableTimestamp(project.createdAt) ??
|
||||
Number.NEGATIVE_INFINITY);
|
||||
}
|
||||
|
||||
export function buildHomeProjectScopes(input: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}): ReadonlyArray<HomeProjectScope> {
|
||||
const projects = input.projects.filter(
|
||||
(project) => input.environmentId === null || project.environmentId === input.environmentId,
|
||||
);
|
||||
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
|
||||
for (const project of projects) {
|
||||
const physicalKey = derivePhysicalProjectKey(project);
|
||||
const existing = projectsByPhysicalKey.get(physicalKey);
|
||||
if (existing) existing.push(project);
|
||||
else projectsByPhysicalKey.set(physicalKey, [project]);
|
||||
}
|
||||
|
||||
const winnersByPhysicalKey = new Map<
|
||||
string,
|
||||
{ readonly key: string; readonly project: EnvironmentProject }
|
||||
>();
|
||||
for (const [physicalKey, members] of projectsByPhysicalKey) {
|
||||
const project = members.reduce((winner, candidate) => {
|
||||
const freshnessDelta =
|
||||
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
|
||||
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
|
||||
? candidate
|
||||
: winner;
|
||||
});
|
||||
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
|
||||
winnersByPhysicalKey.set(physicalKey, {
|
||||
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
|
||||
project,
|
||||
});
|
||||
}
|
||||
|
||||
const groups = new Map<string, EnvironmentProject[]>();
|
||||
for (const { key, project } of winnersByPhysicalKey.values()) {
|
||||
const existing = groups.get(key);
|
||||
if (existing) existing.push(project);
|
||||
else groups.set(key, [project]);
|
||||
}
|
||||
|
||||
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
|
||||
const seenProjectRefs = new Set<string>();
|
||||
for (const project of projects) {
|
||||
const refKey = scopedProjectKey(project.environmentId, project.id);
|
||||
if (seenProjectRefs.has(refKey)) continue;
|
||||
seenProjectRefs.add(refKey);
|
||||
|
||||
const key =
|
||||
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
|
||||
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
|
||||
const refs = projectRefsByGroup.get(key);
|
||||
const projectRef = { environmentId: project.environmentId, projectId: project.id };
|
||||
if (refs) refs.push(projectRef);
|
||||
else projectRefsByGroup.set(key, [projectRef]);
|
||||
}
|
||||
|
||||
return Array.from(groups, ([key, projects]) => {
|
||||
const representative = projects[0]!;
|
||||
return {
|
||||
key,
|
||||
title: deriveProjectGroupLabel({ representative, members: projects }),
|
||||
representative,
|
||||
projects,
|
||||
projectRefs: projectRefsByGroup.get(key) ?? [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function sortHomeProjectScopes(input: {
|
||||
readonly scopes: ReadonlyArray<HomeProjectScope>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
}): ReadonlyArray<HomeProjectScope> {
|
||||
const scopeKeyByProjectRef = new Map(
|
||||
input.scopes.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.key] as const,
|
||||
),
|
||||
),
|
||||
);
|
||||
const latestActivityByScope = new Map<string, number>();
|
||||
const recordActivity = (scopeKey: string | undefined, timestamp: number) => {
|
||||
if (!scopeKey || !Number.isFinite(timestamp)) return;
|
||||
latestActivityByScope.set(
|
||||
scopeKey,
|
||||
Math.max(latestActivityByScope.get(scopeKey) ?? Number.NEGATIVE_INFINITY, timestamp),
|
||||
);
|
||||
};
|
||||
|
||||
for (const thread of input.threads) {
|
||||
if (thread.archivedAt !== null) continue;
|
||||
recordActivity(
|
||||
scopeKeyByProjectRef.get(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
getThreadSortTimestamp(thread, input.projectSortOrder),
|
||||
);
|
||||
}
|
||||
for (const pendingTask of input.pendingTasks) {
|
||||
recordActivity(
|
||||
scopeKeyByProjectRef.get(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
Date.parse(pendingTask.message.createdAt),
|
||||
);
|
||||
}
|
||||
|
||||
return Arr.sort(
|
||||
input.scopes,
|
||||
Order.mapInput(
|
||||
Order.Struct({
|
||||
timestamp: Order.flip(Order.Number),
|
||||
title: Order.String,
|
||||
key: Order.String,
|
||||
}),
|
||||
(scope: HomeProjectScope) => ({
|
||||
timestamp:
|
||||
latestActivityByScope.get(scope.key) ??
|
||||
Math.max(
|
||||
...scope.projects.map((project) =>
|
||||
getProjectSortTimestamp(project, input.projectSortOrder),
|
||||
),
|
||||
),
|
||||
title: scope.title,
|
||||
key: scope.key,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Default home view only surfaces threads active within this window, to keep the
|
||||
* screen compact while keeping recent work visible.
|
||||
@@ -103,22 +264,18 @@ export function buildHomeThreadGroups(input: {
|
||||
const groups = new Map<string, MutableHomeThreadGroup>();
|
||||
const groupKeyByProjectKey = new Map<string, string>();
|
||||
|
||||
for (const project of input.projects) {
|
||||
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const groupKey = deriveLogicalProjectKey(project, {
|
||||
groupingMode: input.projectGroupingMode,
|
||||
for (const scope of buildHomeProjectScopes(input)) {
|
||||
groups.set(scope.key, {
|
||||
key: scope.key,
|
||||
projects: [...scope.projects],
|
||||
pendingTasks: [],
|
||||
threads: [],
|
||||
});
|
||||
const physicalKey = scopedProjectKey(project.environmentId, project.id);
|
||||
groupKeyByProjectKey.set(physicalKey, groupKey);
|
||||
|
||||
const existing = groups.get(groupKey);
|
||||
if (existing) {
|
||||
existing.projects.push(project);
|
||||
} else {
|
||||
groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
|
||||
for (const projectRef of scope.projectRefs) {
|
||||
groupKeyByProjectKey.set(
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.key,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,10 +343,7 @@ export function buildHomeThreadGroups(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const title =
|
||||
group.projects.length > 1
|
||||
? deriveProjectGroupLabel({ representative, members: group.projects })
|
||||
: representative.title;
|
||||
const title = deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
title.toLocaleLowerCase().includes(query) ||
|
||||
@@ -215,19 +369,21 @@ export function buildHomeThreadGroups(input: {
|
||||
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
|
||||
: sortedThreads;
|
||||
|
||||
// Sorted newest-first, so the first thread whose project is a group member
|
||||
// marks the machine the user last worked on.
|
||||
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
|
||||
group.projects.some(
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
).pipe(
|
||||
// A stale project id still resolves to the canonical member with the same
|
||||
// environment/path, so quick creation follows the machine with the newest activity.
|
||||
const lastActiveProject = Arr.head(sortedThreads).pipe(
|
||||
Option.flatMap((thread) =>
|
||||
Arr.findFirst(
|
||||
input.projects,
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
),
|
||||
Option.flatMap((threadProject) =>
|
||||
Arr.findFirst(
|
||||
group.projects,
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
derivePhysicalProjectKey(project) === derivePhysicalProjectKey(threadProject),
|
||||
),
|
||||
),
|
||||
Option.getOrNull,
|
||||
|
||||
@@ -2,7 +2,8 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useFocusEffect } from "@react-navigation/native";
|
||||
import {
|
||||
NavigationContext,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
} from "react";
|
||||
import { useWindowDimensions, View } from "react-native";
|
||||
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
deriveFileInspectorPaneLayout,
|
||||
@@ -34,11 +36,12 @@ import {
|
||||
} from "../../lib/layout";
|
||||
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import {
|
||||
parseActiveThreadPath,
|
||||
useHardwareKeyboardCommand,
|
||||
} from "../keyboard/hardwareKeyboardCommands";
|
||||
import { HomeListOptionsProvider } from "../home/home-list-options";
|
||||
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
|
||||
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
|
||||
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
|
||||
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
|
||||
@@ -184,6 +187,31 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly pathname: string;
|
||||
}) {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
return AsyncResult.isFailure(preferencesResult) ? (
|
||||
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
|
||||
) : null;
|
||||
}
|
||||
return (
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={resolveProjectGroupingMode(
|
||||
preferencesResult.value.projectGroupingEnabled,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AdaptiveWorkspaceLayoutContent(
|
||||
props: {
|
||||
readonly children: ReactNode;
|
||||
readonly pathname: string;
|
||||
} & {
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
},
|
||||
) {
|
||||
const projectGroupingMode = props.projectGroupingMode;
|
||||
const { width, height } = useWindowDimensions();
|
||||
const pathname = props.pathname;
|
||||
const navigation = useNavigation();
|
||||
@@ -474,7 +502,7 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
);
|
||||
|
||||
return (
|
||||
<HomeListOptionsProvider>
|
||||
<HomeListOptionsProvider projectGroupingMode={projectGroupingMode}>
|
||||
<AdaptiveWorkspaceContext.Provider value={contextValue}>
|
||||
<View testID="adaptive-workspace-layout" className="flex-1 flex-row">
|
||||
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
|
||||
|
||||
@@ -119,6 +119,8 @@ function LocalSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<GeneralSettingsSection />
|
||||
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
@@ -504,6 +506,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<GeneralSettingsSection />
|
||||
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
@@ -518,6 +522,25 @@ function ConfiguredSettingsRouteScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
function GeneralSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.projectGroupingEnabled !== false
|
||||
: true;
|
||||
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsSwitchRow
|
||||
icon="folder"
|
||||
label="Project Grouping"
|
||||
value={projectGroupingEnabled}
|
||||
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Device-local beta toggles. Mobile has no client-settings sync, so this is
|
||||
* the counterpart of web's Settings → Beta backed by mobile preferences.
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
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, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { ActivityIndicator, Pressable, StyleSheet, useColorScheme, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -10,6 +11,9 @@ 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;
|
||||
@@ -45,7 +49,7 @@ export function GitActionProgressOverlay(props: {
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
entering={FadeIn.duration(200)}
|
||||
entering={isLiquidGlassSupported ? undefined : FadeIn.duration(200)}
|
||||
exiting={FadeOut.duration(150)}
|
||||
className="absolute inset-x-3 z-[100]"
|
||||
style={{ top: insets.top + 48 }}
|
||||
@@ -61,16 +65,11 @@ export function GitActionProgressOverlay(props: {
|
||||
function OverlayContent(props: { readonly progress: GitActionProgress }) {
|
||||
const { progress } = props;
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
|
||||
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}`}
|
||||
>
|
||||
const glassBorder = useThemeColor("--color-header-border");
|
||||
const glassTint = useThemeColor("--color-glass-tint");
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const content = (
|
||||
<>
|
||||
<OverlayIcon phase={progress.phase} iconColor={iconColor} />
|
||||
|
||||
<View className="flex-1 gap-0.5">
|
||||
@@ -89,7 +88,56 @@ function OverlayContent(props: { readonly progress: GitActionProgress }) {
|
||||
{progress.prUrl ? (
|
||||
<SymbolView name="arrow.up.right" size={13} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,6 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
useHomeListOptions,
|
||||
@@ -48,7 +47,7 @@ import {
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "../home/homeListItems";
|
||||
import { buildHomeThreadGroups } from "../home/homeThreadList";
|
||||
import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
|
||||
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
|
||||
import { useThreadListActions } from "../home/useThreadListActions";
|
||||
@@ -217,36 +216,47 @@ function ThreadNavigationSidebarPane(
|
||||
() => new Set(environments.map((environment) => environment.environmentId)),
|
||||
[environments],
|
||||
);
|
||||
const {
|
||||
options,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
} = useHomeListOptions(availableEnvironmentIds);
|
||||
const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
|
||||
useHomeListOptions(availableEnvironmentIds);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
}),
|
||||
[options.projectGroupingMode, options.selectedEnvironmentId, projects],
|
||||
);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
projects
|
||||
.filter(
|
||||
(project) =>
|
||||
options.selectedEnvironmentId === null ||
|
||||
project.environmentId === options.selectedEnvironmentId,
|
||||
)
|
||||
.map((project) => ({
|
||||
key: scopedProjectKey(project.environmentId, project.id),
|
||||
label: project.title,
|
||||
})),
|
||||
[options.selectedEnvironmentId, projects],
|
||||
projectScopes.map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[projectScopes],
|
||||
);
|
||||
const selectedProject = useMemo(
|
||||
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
|
||||
? null
|
||||
: (projects.find(
|
||||
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
|
||||
) ?? null),
|
||||
[projects, selectedProjectKey],
|
||||
: (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
|
||||
[projectScopes, selectedProjectKey],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
@@ -256,31 +266,45 @@ function ThreadNavigationSidebarPane(
|
||||
setSelectedProjectKey(null);
|
||||
}
|
||||
}, [projectFilterOptions, selectedProjectKey]);
|
||||
const selectedProjectRefs = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() => (selectedProject === null ? projects : [selectedProject]),
|
||||
[projects, selectedProject],
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
? projects
|
||||
: projects.filter((project) =>
|
||||
selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[projects, selectedProjectRefs],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
selectedProject === null
|
||||
selectedProjectRefs === null
|
||||
? threads
|
||||
: threads.filter(
|
||||
(thread) =>
|
||||
thread.environmentId === selectedProject.environmentId &&
|
||||
thread.projectId === selectedProject.id,
|
||||
: threads.filter((thread) =>
|
||||
selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
),
|
||||
[selectedProject, threads],
|
||||
[selectedProjectRefs, threads],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
selectedProject === null
|
||||
selectedProjectRefs === null
|
||||
? pendingTasks
|
||||
: pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
pendingTask.message.environmentId === selectedProject.environmentId &&
|
||||
pendingTask.creation.projectId === selectedProject.id,
|
||||
: pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefs.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
),
|
||||
[pendingTasks, selectedProject],
|
||||
[pendingTasks, selectedProjectRefs],
|
||||
);
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
@@ -375,6 +399,10 @@ 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
|
||||
@@ -396,35 +424,57 @@ 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 };
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
projectRef:
|
||||
selectedProject === null
|
||||
? null
|
||||
: {
|
||||
environmentId: selectedProject.environmentId,
|
||||
projectId: selectedProject.id,
|
||||
},
|
||||
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
|
||||
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,
|
||||
selectedProject,
|
||||
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
|
||||
@@ -437,9 +487,10 @@ function ThreadNavigationSidebarPane(
|
||||
(pendingTask) =>
|
||||
(options.selectedEnvironmentId === null ||
|
||||
pendingTask.message.environmentId === options.selectedEnvironmentId) &&
|
||||
(selectedProject === null ||
|
||||
(pendingTask.message.environmentId === selectedProject.environmentId &&
|
||||
pendingTask.creation.projectId === selectedProject.id)) &&
|
||||
(selectedProjectRefs === null ||
|
||||
selectedProjectRefs.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
)) &&
|
||||
(v2SearchQuery.length === 0 ||
|
||||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
|
||||
);
|
||||
@@ -469,7 +520,7 @@ function ThreadNavigationSidebarPane(
|
||||
options.selectedEnvironmentId,
|
||||
pendingTasks,
|
||||
props.searchQuery,
|
||||
selectedProject,
|
||||
selectedProjectRefs,
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
@@ -541,16 +592,6 @@ function ThreadNavigationSidebarPane(
|
||||
state: options.threadSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "project-grouping",
|
||||
title: "Group projects",
|
||||
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
id: `project-grouping:${option.value}`,
|
||||
title: option.label,
|
||||
subtitle: option.subtitle,
|
||||
state: options.projectGroupingMode === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
],
|
||||
[environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
|
||||
@@ -594,15 +635,10 @@ function ThreadNavigationSidebarPane(
|
||||
setThreadSortOrder(threadSort.value);
|
||||
return;
|
||||
}
|
||||
const grouping = PROJECT_GROUPING_OPTIONS.find(
|
||||
(option) => `project-grouping:${option.value}` === event,
|
||||
);
|
||||
if (grouping) setProjectGroupingMode(grouping.value);
|
||||
},
|
||||
[
|
||||
environments,
|
||||
projectFilterOptions,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setSelectedEnvironmentId,
|
||||
setThreadSortOrder,
|
||||
@@ -739,6 +775,7 @@ function ThreadNavigationSidebarPane(
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
projectTitle={projectTitleByProjectKey.get(scopeKey)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(thread.environmentId)
|
||||
@@ -868,6 +905,7 @@ function ThreadNavigationSidebarPane(
|
||||
openPendingTask,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
props.onNewThreadInProject,
|
||||
props.selectedThreadKey,
|
||||
props.width,
|
||||
@@ -898,12 +936,10 @@ function ThreadNavigationSidebarPane(
|
||||
selectedProjectKey,
|
||||
projectSortOrder: options.projectSortOrder,
|
||||
threadSortOrder: options.threadSortOrder,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
onEnvironmentChange: setSelectedEnvironmentId,
|
||||
onProjectChange: setSelectedProjectKey,
|
||||
onProjectSortOrderChange: setProjectSortOrder,
|
||||
onThreadSortOrderChange: setThreadSortOrder,
|
||||
onProjectGroupingModeChange: setProjectGroupingMode,
|
||||
listOrganization: !threadListV2Enabled,
|
||||
}),
|
||||
[
|
||||
@@ -911,7 +947,6 @@ function ThreadNavigationSidebarPane(
|
||||
options,
|
||||
projectFilterOptions,
|
||||
selectedProjectKey,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setSelectedEnvironmentId,
|
||||
setThreadSortOrder,
|
||||
@@ -927,15 +962,28 @@ 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
|
||||
? "No matching threads"
|
||||
: selectedProject !== null
|
||||
? `No threads in ${selectedProject.title}`
|
||||
: "No threads yet"}
|
||||
? 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"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@ const STATUS_LABEL_BY_STATUS: Partial<
|
||||
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
|
||||
input: { label: "Input", className: "text-indigo-600 dark:text-indigo-300" },
|
||||
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
|
||||
// Colorless like the web sidebar: parked on background work, not "act now".
|
||||
waiting: { label: "Waiting", className: "text-foreground-tertiary" },
|
||||
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
|
||||
};
|
||||
|
||||
@@ -90,6 +92,7 @@ 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
|
||||
@@ -219,7 +222,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.project.title}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
@@ -230,7 +233,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.project?.title ?? ""}
|
||||
{props.projectTitle ?? props.project?.title ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
@@ -393,7 +396,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.project.title}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -63,6 +63,24 @@ describe("resolveThreadListV2Status", () => {
|
||||
"ready",
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves waiting for an idle session parked on background tasks", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
session: {
|
||||
threadId: ThreadId.make("t"),
|
||||
status: "idle",
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
});
|
||||
expect(resolveThreadListV2Status(thread)).toBe("waiting");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForListV2", () => {
|
||||
@@ -77,6 +95,85 @@ 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: [
|
||||
@@ -166,13 +263,36 @@ describe("buildThreadListV2Items", () => {
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRef: { environmentId, projectId: ProjectId.make("project-1") },
|
||||
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["included"]);
|
||||
});
|
||||
|
||||
it("scopes the flat list to every environment member of a logical project", () => {
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("local"), title: "Local" }),
|
||||
makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("remote"),
|
||||
title: "Remote",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [
|
||||
{ environmentId, projectId: ProjectId.make("project-1") },
|
||||
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
|
||||
],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["local", "remote"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items settled paging", () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
@@ -6,11 +6,12 @@ import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
* Thread List v2 model, ported from the web sidebar v2
|
||||
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
|
||||
*
|
||||
* Four visual states, three colors: color is reserved for "act now"
|
||||
* Six visual states, three colors: color is reserved for "act now"
|
||||
* (approval), "in motion" (working), and "broken" (failed). Ready is the
|
||||
* unlabeled resting state.
|
||||
* unlabeled resting state; waiting (session status "idle") is the agent
|
||||
* parked on open background tasks — grey like working, not a false Done.
|
||||
*/
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
|
||||
|
||||
// Settled-tail paging: recent history is the common lookup; the deep tail
|
||||
// stays behind an explicit Show more. Shared by the compact Home list and
|
||||
@@ -30,6 +31,9 @@ export function resolveThreadListV2Status(
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") {
|
||||
return "working";
|
||||
}
|
||||
if (thread.session?.status === "idle") {
|
||||
return "waiting";
|
||||
}
|
||||
if (thread.session?.status === "error") {
|
||||
return "failed";
|
||||
}
|
||||
@@ -84,6 +88,13 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,10 +106,10 @@ export interface ThreadListV2Layout {
|
||||
export function buildThreadListV2Items(input: {
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly projectRef?: {
|
||||
readonly projectRefs?: ReadonlyArray<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectId: ProjectId;
|
||||
} | null;
|
||||
}> | null;
|
||||
readonly searchQuery: string;
|
||||
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
|
||||
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
|
||||
@@ -106,33 +117,58 @@ 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
|
||||
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
|
||||
: null;
|
||||
|
||||
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.
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
|
||||
if (
|
||||
input.projectRef != null &&
|
||||
(thread.environmentId !== input.projectRef.environmentId ||
|
||||
thread.projectId !== input.projectRef.projectId)
|
||||
) {
|
||||
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
|
||||
continue;
|
||||
}
|
||||
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 })
|
||||
@@ -169,5 +205,10 @@ export function buildThreadListV2Items(input: {
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export interface Preferences {
|
||||
readonly codeWordBreak?: boolean;
|
||||
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
readonly collapsedProjectGroups?: readonly string[];
|
||||
readonly projectGroupingEnabled?: boolean;
|
||||
/**
|
||||
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
|
||||
* client-settings sync, so the flat v2 thread list is opted into per
|
||||
@@ -77,6 +78,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
codeWordBreak?: boolean;
|
||||
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
collapsedProjectGroups?: readonly string[];
|
||||
projectGroupingEnabled?: boolean;
|
||||
threadListV2Enabled?: boolean;
|
||||
} = {};
|
||||
|
||||
@@ -104,6 +106,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
(key): key is string => typeof key === "string",
|
||||
);
|
||||
}
|
||||
if (typeof parsed.projectGroupingEnabled === "boolean") {
|
||||
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
|
||||
}
|
||||
if (typeof parsed.threadListV2Enabled === "boolean") {
|
||||
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
|
||||
}
|
||||
|
||||
@@ -60,6 +60,8 @@ 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,7 +31,8 @@
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0"
|
||||
"node-pty": "^1.1.0",
|
||||
"yaml": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
|
||||
+40
-55
@@ -12,7 +12,8 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
DEVELOPMENT_ICON_OVERRIDES,
|
||||
PUBLISH_ICON_OVERRIDES,
|
||||
resolveWebAssetBrandForPackageVersion,
|
||||
resolveWebIconOverrides,
|
||||
} from "../../../scripts/lib/brand-assets.ts";
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
@@ -81,50 +82,34 @@ const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Stan
|
||||
}
|
||||
});
|
||||
|
||||
interface PublishIconBackup {
|
||||
readonly targetPath: string;
|
||||
readonly backupPath: string;
|
||||
}
|
||||
|
||||
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
|
||||
const preparePublishIcons = Effect.fn("preparePublishIcons")(function* (
|
||||
repoRoot: string,
|
||||
serverDir: string,
|
||||
version: string,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const backups: PublishIconBackup[] = [];
|
||||
const brand = resolveWebAssetBrandForPackageVersion(version);
|
||||
const icons = resolveWebIconOverrides(brand, "dist/client").map((override) => ({
|
||||
sourcePath: path.join(repoRoot, override.sourceRelativePath),
|
||||
targetPath: path.join(serverDir, override.targetRelativePath),
|
||||
}));
|
||||
|
||||
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 });
|
||||
for (const icon of icons) {
|
||||
if (!(yield* fs.exists(icon.sourcePath))) {
|
||||
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath: icon.sourcePath });
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath });
|
||||
if (!(yield* fs.exists(icon.targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath: icon.targetPath });
|
||||
}
|
||||
|
||||
yield* fs.copyFile(targetPath, backupPath);
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
backups.push({ targetPath, backupPath });
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
return yield* Effect.forEach(icons, (icon) =>
|
||||
Effect.all({
|
||||
original: fs.readFile(icon.targetPath),
|
||||
publish: fs.readFile(icon.sourcePath),
|
||||
}).pipe(Effect.map((contents) => ({ ...icon, ...contents }))),
|
||||
);
|
||||
});
|
||||
|
||||
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
|
||||
@@ -236,7 +221,6 @@ 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"]) {
|
||||
@@ -247,7 +231,7 @@ const publishCmd = Command.make(
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
|
||||
// Acquire: resolve publish metadata and read every original before mutation.
|
||||
Effect.gen(function* () {
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const workspaceConfig = yield* readWorkspaceConfig();
|
||||
@@ -273,19 +257,22 @@ const publishCmd = Command.make(
|
||||
),
|
||||
};
|
||||
|
||||
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 };
|
||||
return {
|
||||
packageJsonString: yield* encodePackageJson(pkg),
|
||||
originalPackageJson: yield* fs.readFile(packageJsonPath),
|
||||
icons: yield* preparePublishIcons(repoRoot, serverDir, version),
|
||||
};
|
||||
}),
|
||||
// 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]);
|
||||
|
||||
@@ -299,16 +286,14 @@ const publishCmd = Command.make(
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore
|
||||
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
|
||||
// Release: restore every file even if applying overrides or publishing fails.
|
||||
(resource) =>
|
||||
Effect.gen(function* () {
|
||||
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");
|
||||
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");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -54,7 +54,7 @@ const makeRecordingRunnerLayer = (
|
||||
return {
|
||||
stdout:
|
||||
options?.stdoutFor?.(input.command, input.args) ??
|
||||
(versionFromPath === undefined ? "" : `${versionFromPath}\n`),
|
||||
(versionFromPath === undefined ? "" : `t3 v${versionFromPath}\n`),
|
||||
stderr: failed ? `${input.command} exploded` : "",
|
||||
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
|
||||
timedOut: false,
|
||||
@@ -427,7 +427,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
stdoutFor: (command, args) =>
|
||||
command === NODE_PATH && args[1] === "--version" ? "0.0.28\n" : undefined,
|
||||
command === NODE_PATH && args[1] === "--version" ? "t3 v0.0.28\n" : undefined,
|
||||
});
|
||||
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
|
||||
|
||||
|
||||
@@ -273,8 +273,10 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
|
||||
failWith(`Could not verify the installed t3@${targetVersion}.`, cause),
|
||||
),
|
||||
);
|
||||
const preflightVersion = preflight.stdout.trim();
|
||||
if (preflight.code !== 0 || preflightVersion !== targetVersion) {
|
||||
// Effect CLI's unstable formatVersion currently emits `${name} v${version}`.
|
||||
// Extract the version token so surrounding presentation changes do not break updates.
|
||||
const reportedVersion = /\bv(\S+)\s*$/.exec(preflight.stdout)?.[1];
|
||||
if (preflight.code !== 0 || reportedVersion !== targetVersion) {
|
||||
// A completed npm install can still be unusable under this Node or on
|
||||
// this machine. Remove its sentinel and tree so a retry of the same
|
||||
// version performs a clean install instead of reusing a known-bad one.
|
||||
|
||||
@@ -141,6 +141,7 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewTabId,
|
||||
@@ -58,6 +59,8 @@ 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,6 +10,8 @@ import {
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSetColorSchemeInput,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewAutomationTabTargetInput,
|
||||
@@ -86,6 +88,19 @@ 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:
|
||||
@@ -189,6 +204,7 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSetAppearanceTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -205,6 +221,7 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSetAppearanceTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -609,6 +609,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -679,6 +681,38 @@ 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,6 +310,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -422,6 +424,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
|
||||
@@ -336,6 +336,8 @@ 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",
|
||||
@@ -366,6 +368,8 @@ 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",
|
||||
@@ -398,6 +402,8 @@ 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",
|
||||
@@ -762,6 +768,8 @@ 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",
|
||||
@@ -1196,6 +1204,8 @@ 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) ?? [],
|
||||
@@ -1396,6 +1406,8 @@ 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) ?? [],
|
||||
@@ -1527,6 +1539,8 @@ 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,
|
||||
@@ -1663,6 +1677,8 @@ 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,
|
||||
@@ -1905,6 +1921,8 @@ 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,
|
||||
@@ -2001,6 +2019,8 @@ 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 = {
|
||||
|
||||
@@ -3174,6 +3174,454 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
).toBe("# Plan title");
|
||||
});
|
||||
|
||||
it("parks the session on idle when a turn completes with open tasks", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-waiting-turn-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: now,
|
||||
turnId: asTurnId("turn-waiting-1"),
|
||||
});
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-waiting-task-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-waiting-1"),
|
||||
payload: {
|
||||
taskId: "bg-task-1",
|
||||
description: "Babysit PR checks",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-waiting-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
turnId: asTurnId("turn-waiting-1"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
const waiting = await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.session?.status === "idle" && entry.session?.activeTurnId === null,
|
||||
);
|
||||
expect(waiting.session?.lastError).toBeNull();
|
||||
|
||||
// The wake-up turn flips waiting straight back to running.
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-waiting-wakeup-turn-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
turnId: asTurnId("turn-waiting-2"),
|
||||
});
|
||||
harness.emit({
|
||||
type: "task.completed",
|
||||
eventId: asEventId("evt-waiting-task-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-waiting-2"),
|
||||
payload: {
|
||||
taskId: "bg-task-1",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-waiting-wakeup-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:04.000Z",
|
||||
turnId: asTurnId("turn-waiting-2"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
// With the task closed before this turn ended, the thread is genuinely done.
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "ready");
|
||||
});
|
||||
|
||||
it("keeps a turn completion ready when its tasks already completed", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-closed-task-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "fg-task-1",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "task.completed",
|
||||
eventId: asEventId("evt-closed-task-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "fg-task-1",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-closed-task-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
turnId: asTurnId("turn-closed-task"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.session?.status === "ready" && entry.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
|
||||
it("demotes a ready session to idle when a task start arrives after turn completion", async () => {
|
||||
const harness = await createHarness();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-late-task-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
turnId: asTurnId("turn-late-task"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "ready");
|
||||
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-late-task-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "late-task-1",
|
||||
description: "Monitor deploy",
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "idle");
|
||||
});
|
||||
|
||||
it("returns a waiting thread to ready when its last task is stopped", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-stopped-task-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "stopped-task-1",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-stopped-task-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
turnId: asTurnId("turn-stopped-task"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "idle");
|
||||
|
||||
// A stopped task never wakes the agent, so Waiting must resolve here.
|
||||
harness.emit({
|
||||
type: "task.completed",
|
||||
eventId: asEventId("evt-stopped-task-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "stopped-task-1",
|
||||
status: "stopped",
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "ready");
|
||||
});
|
||||
|
||||
it("keeps a waiting thread waiting when its last task completes (the wake turn follows)", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-wake-task-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "wake-task-1",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-wake-task-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
turnId: asTurnId("turn-wake-task"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "idle");
|
||||
|
||||
// A successful completion wakes the agent; the status must go straight
|
||||
// to running with no intermediate ready flash.
|
||||
harness.emit({
|
||||
type: "task.completed",
|
||||
eventId: asEventId("evt-wake-task-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "wake-task-1",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-wake-task-wake-turn"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
turnId: asTurnId("turn-wake-follow-up"),
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.session?.status === "running",
|
||||
);
|
||||
expect(thread.session?.activeTurnId).toBe("turn-wake-follow-up");
|
||||
});
|
||||
|
||||
it("ignores late task progress for a completed task", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-tombstone-task-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "tombstone-task-1",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "task.completed",
|
||||
eventId: asEventId("evt-tombstone-task-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "tombstone-task-1",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
// Duplicate/late progress must not re-open the finished task…
|
||||
harness.emit({
|
||||
type: "task.progress",
|
||||
eventId: asEventId("evt-tombstone-task-late-progress"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "tombstone-task-1",
|
||||
description: "late duplicate progress",
|
||||
},
|
||||
});
|
||||
// …so a subsequent turn completion settles on ready, not idle.
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-tombstone-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
turnId: asTurnId("turn-tombstone"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "ready");
|
||||
});
|
||||
|
||||
it("re-opens a completed task on an explicit restart (resumed agent)", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-resumed-task-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "resumed-task-1",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "task.completed",
|
||||
eventId: asEventId("evt-resumed-task-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "resumed-task-1",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
// The agent is resumed: the same task id starts again. The tombstone
|
||||
// must yield to the explicit start…
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-resumed-task-restarted"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "resumed-task-1",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-resumed-task-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
turnId: asTurnId("turn-resumed-task"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
// …so the turn parks on Waiting for the resumed agent.
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "idle");
|
||||
});
|
||||
|
||||
it("ignores task events from a stale provider instance", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
// Current instance ("codex", matching the seeded session) opens a task.
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-current-instance-task-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "current-task-1",
|
||||
},
|
||||
});
|
||||
// A delayed start from a replaced instance must not displace it.
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-stale-instance-task-started"),
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "stale-task-1",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-stale-instance-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
turnId: asTurnId("turn-stale-instance"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
// The current instance's open task still parks the thread on Waiting.
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "idle");
|
||||
});
|
||||
|
||||
it("clears open tasks on session exit so they cannot park a later session", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-orphan-task-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
taskId: "orphan-task-1",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "session.exited",
|
||||
eventId: asEventId("evt-orphan-task-session-exited"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
payload: {},
|
||||
});
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "stopped");
|
||||
|
||||
// A fresh session's turn must not inherit the orphaned task.
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-orphan-task-new-turn-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
turnId: asTurnId("turn-after-orphan"),
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-orphan-task-new-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
turnId: asTurnId("turn-after-orphan"),
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.status === "ready");
|
||||
});
|
||||
|
||||
it("titles task activities with the task description, including on completion", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -746,6 +746,102 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
// Open provider-reported tasks per thread. A turn that completes while any
|
||||
// remain open parks the session on "idle" (sidebar "Waiting") instead of
|
||||
// "ready" ("Done"): the agent stopped, but a task completion is expected to
|
||||
// wake it, and flashing Done in between is a lie. Keyed by provider
|
||||
// instance so a replaced session can neither inherit nor close a
|
||||
// predecessor's tasks; closed ids are kept as tombstones so a late or
|
||||
// replayed start/progress cannot resurrect a finished task. Plain mutable
|
||||
// state is safe: ingestion is a single serial worker. Terminal session
|
||||
// statuses sweep the entry.
|
||||
const openTasksByThreadId = new Map<
|
||||
ThreadId,
|
||||
{ instanceKey: string; taskIds: Set<string>; closedTaskIds: Set<string> }
|
||||
>();
|
||||
|
||||
const taskInstanceKey = (event: ProviderRuntimeEvent) =>
|
||||
event.providerInstanceId ?? event.provider;
|
||||
|
||||
const sessionInstanceKeyFor = (session: {
|
||||
providerInstanceId?: string | undefined;
|
||||
providerName: string | null;
|
||||
}): string | null => session.providerInstanceId ?? session.providerName;
|
||||
|
||||
/**
|
||||
* Returns true when this task is the instance's first open task. The
|
||||
* projected session adjudicates cross-instance races: a delayed start from
|
||||
* a replaced instance must neither seed a phantom set nor displace the
|
||||
* current instance's tasks, while a current-instance start may reclaim an
|
||||
* entry a dead instance leaked.
|
||||
*/
|
||||
const trackTaskStarted = (
|
||||
threadId: ThreadId,
|
||||
event: ProviderRuntimeEvent,
|
||||
taskId: string,
|
||||
sessionInstanceKey: string | null,
|
||||
) => {
|
||||
const instanceKey = taskInstanceKey(event);
|
||||
if (sessionInstanceKey !== null && instanceKey !== sessionInstanceKey) {
|
||||
return false;
|
||||
}
|
||||
const entry = openTasksByThreadId.get(threadId);
|
||||
if (!entry || entry.instanceKey !== instanceKey) {
|
||||
openTasksByThreadId.set(threadId, {
|
||||
instanceKey,
|
||||
taskIds: new Set([taskId]),
|
||||
closedTaskIds: new Set(),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (entry.closedTaskIds.has(taskId)) {
|
||||
// task.progress for a finished task is a late duplicate and stays
|
||||
// ignored. task.started is authoritative: providers reuse task ids
|
||||
// when an agent is resumed, so an explicit start re-opens the task.
|
||||
if (event.type !== "task.started") {
|
||||
return false;
|
||||
}
|
||||
entry.closedTaskIds.delete(taskId);
|
||||
}
|
||||
const wasEmpty = entry.taskIds.size === 0;
|
||||
entry.taskIds.add(taskId);
|
||||
return wasEmpty;
|
||||
};
|
||||
|
||||
/** Returns true when this completion closed the instance's last open task. */
|
||||
const trackTaskCompleted = (threadId: ThreadId, event: ProviderRuntimeEvent, taskId: string) => {
|
||||
const instanceKey = taskInstanceKey(event);
|
||||
const entry = openTasksByThreadId.get(threadId);
|
||||
if (!entry) {
|
||||
// Completion outrunning its start: tombstone it anyway, or the late
|
||||
// start would open a phantom task and park the thread on Waiting for
|
||||
// a completion that already happened.
|
||||
openTasksByThreadId.set(threadId, {
|
||||
instanceKey,
|
||||
taskIds: new Set(),
|
||||
closedTaskIds: new Set([taskId]),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
if (entry.instanceKey !== instanceKey) {
|
||||
return false;
|
||||
}
|
||||
const removed = entry.taskIds.delete(taskId);
|
||||
entry.closedTaskIds.add(taskId);
|
||||
return removed && entry.taskIds.size === 0;
|
||||
};
|
||||
|
||||
const hasOpenTasks = (threadId: ThreadId, event: ProviderRuntimeEvent) => {
|
||||
const entry = openTasksByThreadId.get(threadId);
|
||||
return (
|
||||
entry !== undefined && entry.instanceKey === taskInstanceKey(event) && entry.taskIds.size > 0
|
||||
);
|
||||
};
|
||||
|
||||
const clearOpenTasks = (threadId: ThreadId) => {
|
||||
openTasksByThreadId.delete(threadId);
|
||||
};
|
||||
|
||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
@@ -1370,10 +1466,18 @@ const make = Effect.gen(function* () {
|
||||
event.type === "turn.completed"
|
||||
) {
|
||||
const status = (() => {
|
||||
// The agent stopping with provider-reported tasks still open is not
|
||||
// "ready" (Done): a task completion is expected to wake it. Park on
|
||||
// "idle" (Waiting) until real activity or session teardown moves it.
|
||||
const restingStatus = hasOpenTasks(thread.id, event) ? "idle" : "ready";
|
||||
switch (event.type) {
|
||||
case "session.state.changed": {
|
||||
const runtimeStatus = orchestrationSessionStatusFromRuntimeState(event.payload.state);
|
||||
return hasPendingTurnStart && runtimeStatus === "ready" ? "starting" : runtimeStatus;
|
||||
return runtimeStatus === "ready"
|
||||
? hasPendingTurnStart
|
||||
? "starting"
|
||||
: restingStatus
|
||||
: runtimeStatus;
|
||||
}
|
||||
case "turn.started":
|
||||
return "running";
|
||||
@@ -1382,12 +1486,16 @@ const make = Effect.gen(function* () {
|
||||
case "turn.completed":
|
||||
return normalizeRuntimeTurnState(event.payload.state) === "failed"
|
||||
? "error"
|
||||
: "ready";
|
||||
: restingStatus;
|
||||
case "session.started":
|
||||
case "thread.started":
|
||||
// Provider thread/session start notifications can arrive during an
|
||||
// active or pending turn; preserve that lifecycle state.
|
||||
return activeTurnId !== null ? "running" : hasPendingTurnStart ? "starting" : "ready";
|
||||
return activeTurnId !== null
|
||||
? "running"
|
||||
: hasPendingTurnStart
|
||||
? "starting"
|
||||
: restingStatus;
|
||||
}
|
||||
})();
|
||||
const nextActiveTurnId =
|
||||
@@ -1407,11 +1515,18 @@ const make = Effect.gen(function* () {
|
||||
: event.type === "turn.completed" &&
|
||||
normalizeRuntimeTurnState(event.payload.state) === "failed"
|
||||
? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed")
|
||||
: status === "ready"
|
||||
: status === "ready" || status === "idle"
|
||||
? null
|
||||
: (thread.session?.lastError ?? null);
|
||||
|
||||
if (shouldApplyThreadLifecycle) {
|
||||
// A session leaving the resting/running loop can no longer be woken
|
||||
// by its tasks; drop them so a stale set never parks a future
|
||||
// session on Waiting. Gated like the session.set below: a rejected
|
||||
// stale event must not erase the active turn's tasks.
|
||||
if (status === "stopped" || status === "error" || status === "interrupted") {
|
||||
clearOpenTasks(thread.id);
|
||||
}
|
||||
if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) {
|
||||
yield* markSourceProposedPlanImplemented(
|
||||
acceptedTurnStartedSourcePlan.sourceThreadId,
|
||||
@@ -1671,6 +1786,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (event.type === "session.exited") {
|
||||
clearOpenTasks(thread.id);
|
||||
yield* clearTurnStateForSession(thread.id);
|
||||
}
|
||||
|
||||
@@ -1682,6 +1798,7 @@ const make = Effect.gen(function* () {
|
||||
: activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);
|
||||
|
||||
if (shouldApplyRuntimeError) {
|
||||
clearOpenTasks(thread.id);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: yield* providerCommandId(event, "runtime-error-session-set"),
|
||||
@@ -1754,9 +1871,67 @@ const make = Effect.gen(function* () {
|
||||
if (description) {
|
||||
yield* rememberTaskDescription(thread.id, event.payload.taskId, description);
|
||||
}
|
||||
// task.progress tracks too: it re-opens a task the tracker lost
|
||||
// (server restart, missed start event) so the thread still parks on
|
||||
// Waiting instead of a false Done.
|
||||
const firstOpenTask = trackTaskStarted(
|
||||
thread.id,
|
||||
event,
|
||||
event.payload.taskId,
|
||||
thread.session ? sessionInstanceKeyFor(thread.session) : null,
|
||||
);
|
||||
// A task can outlive its turn: when its start (or surviving progress)
|
||||
// lands after the turn already settled the session on "ready", demote
|
||||
// to "idle" now — the turn-completion path never saw the task.
|
||||
if (
|
||||
firstOpenTask &&
|
||||
thread.session?.status === "ready" &&
|
||||
thread.session.activeTurnId === null &&
|
||||
sessionInstanceKeyFor(thread.session) === taskInstanceKey(event)
|
||||
) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: yield* providerCommandId(event, "open-task-session-idle"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
...thread.session,
|
||||
status: "idle",
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
let taskTitle: string | undefined;
|
||||
if (event.type === "task.completed") {
|
||||
const closedLastTask = trackTaskCompleted(thread.id, event, event.payload.taskId);
|
||||
// A completed/failed final task wakes the agent — its notification is
|
||||
// the wake signal — so the thread goes Waiting → Working directly and
|
||||
// flipping to ready here would flash the very Done this feature
|
||||
// removes. A STOPPED final task is the opposite: someone killed it,
|
||||
// no wake follows, and a live session would sit on Waiting forever.
|
||||
// Only that case flips back to ready.
|
||||
if (
|
||||
closedLastTask &&
|
||||
event.payload.status === "stopped" &&
|
||||
thread.session?.status === "idle" &&
|
||||
thread.session.activeTurnId === null &&
|
||||
sessionInstanceKeyFor(thread.session) === taskInstanceKey(event)
|
||||
) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: yield* providerCommandId(event, "last-task-session-ready"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
...thread.session,
|
||||
status: "ready",
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId);
|
||||
if (!taskTitle) {
|
||||
const threadDetail = yield* getLoadedThreadDetail();
|
||||
|
||||
@@ -11,6 +11,8 @@ 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,
|
||||
@@ -38,6 +40,8 @@ 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;
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
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,6 +53,13 @@ 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 {
|
||||
@@ -79,6 +86,62 @@ 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"];
|
||||
@@ -411,46 +474,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
);
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
// 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) {
|
||||
// Settling inside the adoption window would hide just-requested work.
|
||||
if (threadHasQueuedTurnStart(thread, occurredAt)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
@@ -508,6 +533,103 @@ 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,
|
||||
@@ -663,24 +785,42 @@ 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.
|
||||
if (targetThread.settledOverride === null) {
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
// 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,
|
||||
},
|
||||
});
|
||||
}
|
||||
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];
|
||||
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];
|
||||
}
|
||||
|
||||
case "thread.turn.interrupt": {
|
||||
@@ -822,7 +962,12 @@ 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.
|
||||
// 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.
|
||||
const isSessionActivity =
|
||||
command.session.status === "starting" || command.session.status === "running";
|
||||
// Real activity resets ANY override (settled wakes, active unpins).
|
||||
|
||||
@@ -91,6 +91,8 @@ describe("orchestration projector", () => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -23,8 +23,10 @@ import {
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadSnoozedPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadUnsnoozedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -290,6 +292,8 @@ export function projectEvent(
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -365,6 +369,30 @@ 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,6 +93,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -153,6 +155,8 @@ 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,
|
||||
@@ -169,12 +173,17 @@ 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 confirm the flip persists.
|
||||
// Un-settle to the keep-active pin and wake the snooze; confirm the
|
||||
// flips persist.
|
||||
yield* threads.upsert({
|
||||
...row,
|
||||
settledOverride: "active",
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
});
|
||||
const repersisted = yield* threads.getById({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
@@ -182,6 +191,8 @@ 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,6 +45,8 @@ 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,
|
||||
@@ -66,6 +68,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.archivedAt},
|
||||
${row.settledOverride},
|
||||
${row.settledAt},
|
||||
${row.snoozedUntil},
|
||||
${row.snoozedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -87,6 +91,8 @@ 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,
|
||||
@@ -115,6 +121,8 @@ 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",
|
||||
@@ -145,6 +153,8 @@ 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,6 +46,7 @@ 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.
|
||||
@@ -91,6 +92,7 @@ export const migrationEntries = [
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
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,6 +38,8 @@ 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,6 +118,7 @@ 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;
|
||||
@@ -165,9 +166,11 @@ 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),
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
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, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* 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,6 +7,7 @@ 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";
|
||||
@@ -40,6 +41,7 @@ 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: [],
|
||||
@@ -732,10 +734,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings: ClaudeSettings,
|
||||
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Path.Path
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
@@ -845,6 +848,7 @@ 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);
|
||||
|
||||
@@ -855,6 +859,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -876,6 +881,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolveLocalCheckoutBranchMismatch,
|
||||
resolvePreviousWorktreeLabel,
|
||||
resolvePreviousWorktreeSeed,
|
||||
shouldIncludeBranchPickerItem,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
@@ -19,6 +21,91 @@ 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("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
|
||||
expect(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { toSortableTimestamp } from "../lib/threadSort";
|
||||
export {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
@@ -65,6 +66,53 @@ 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,12 +6,13 @@ import {
|
||||
FolderGit2Icon,
|
||||
FolderGitIcon,
|
||||
FolderIcon,
|
||||
HistoryIcon,
|
||||
MonitorIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useMemo } from "react";
|
||||
import { memo, useCallback, useMemo } from "react";
|
||||
|
||||
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
|
||||
import { useIsMobile } from "../hooks/useMediaQuery";
|
||||
import {
|
||||
type EnvMode,
|
||||
@@ -20,6 +21,8 @@ import {
|
||||
resolveEnvModeLabel,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolvePreviousWorktreeLabel,
|
||||
resolvePreviousWorktreeSeed,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
@@ -66,6 +69,8 @@ interface MobileRunContextSelectorProps {
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
previousWorktreeLabel: string | null;
|
||||
onUsePreviousWorktree: () => void;
|
||||
}
|
||||
|
||||
const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
@@ -79,6 +84,8 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
onEnvModeChange,
|
||||
previousWorktreeLabel,
|
||||
onUsePreviousWorktree,
|
||||
}: MobileRunContextSelectorProps) {
|
||||
const activeEnvironment = useMemo(
|
||||
() => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null,
|
||||
@@ -166,7 +173,13 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<MenuGroupLabel>Workspace</MenuGroupLabel>
|
||||
<MenuRadioGroup
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
onValueChange={(value) => {
|
||||
if (value === "previous-worktree") {
|
||||
onUsePreviousWorktree();
|
||||
return;
|
||||
}
|
||||
onEnvModeChange(value as EnvMode);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem disabled={envModeLocked} value="local">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
@@ -186,6 +199,14 @@ 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>
|
||||
@@ -217,6 +238,7 @@ 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
|
||||
@@ -234,6 +256,40 @@ 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,
|
||||
);
|
||||
@@ -248,7 +304,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
if (!hasActiveThread || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<div className="flex w-full items-center gap-2 border-t border-border/60 px-3 py-2">
|
||||
<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">
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
@@ -261,6 +317,8 @@ 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">
|
||||
@@ -280,6 +338,8 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
previousWorktreeLabel={previousWorktreeLabel}
|
||||
onUsePreviousWorktree={onUsePreviousWorktree}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -731,7 +731,7 @@ export function BranchToolbarBranchSelector({
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="min-w-0 text-muted-foreground/70 hover:text-foreground/80"
|
||||
className="min-w-0 max-w-full text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={isInitialBranchesLoadPending || isBranchActionPending}
|
||||
>
|
||||
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon } from "lucide-react";
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon, HistoryIcon } from "lucide-react";
|
||||
import { memo, useMemo } from "react";
|
||||
|
||||
import {
|
||||
@@ -17,11 +17,15 @@ 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;
|
||||
previousWorktreeLabel?: string | null;
|
||||
onUsePreviousWorktree?: () => void;
|
||||
}
|
||||
|
||||
export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({
|
||||
@@ -29,13 +33,19 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
onEnvModeChange,
|
||||
previousWorktreeLabel,
|
||||
onUsePreviousWorktree,
|
||||
}: BranchToolbarEnvModeSelectorProps) {
|
||||
const showPreviousWorktree = Boolean(previousWorktreeLabel && onUsePreviousWorktree);
|
||||
const envModeItems = useMemo(
|
||||
() => [
|
||||
{ value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) },
|
||||
{ value: "worktree", label: resolveEnvModeLabel("worktree") },
|
||||
...(showPreviousWorktree && previousWorktreeLabel
|
||||
? [{ value: PREVIOUS_WORKTREE_SELECT_VALUE, label: previousWorktreeLabel }]
|
||||
: []),
|
||||
],
|
||||
[activeWorktreePath],
|
||||
[activeWorktreePath, previousWorktreeLabel, showPreviousWorktree],
|
||||
);
|
||||
|
||||
if (envLocked) {
|
||||
@@ -60,7 +70,13 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
<Select
|
||||
modal={false}
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
onValueChange={(value: string | null) => {
|
||||
if (value === PREVIOUS_WORKTREE_SELECT_VALUE) {
|
||||
onUsePreviousWorktree?.();
|
||||
return;
|
||||
}
|
||||
onEnvModeChange(value as EnvMode);
|
||||
}}
|
||||
items={envModeItems}
|
||||
>
|
||||
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Workspace">
|
||||
@@ -92,6 +108,14 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
{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>
|
||||
</Select>
|
||||
|
||||
@@ -12,16 +12,20 @@ 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";
|
||||
|
||||
@@ -292,6 +296,61 @@ 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,6 +289,46 @@ 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),
|
||||
|
||||
@@ -22,9 +22,10 @@ import {
|
||||
TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
connectionStatusText,
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
@@ -138,7 +139,14 @@ import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
|
||||
import {
|
||||
AlarmClockIcon,
|
||||
CheckCircle2Icon,
|
||||
ChevronDownIcon,
|
||||
GitBranchIcon,
|
||||
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";
|
||||
@@ -153,7 +161,8 @@ import {
|
||||
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
|
||||
import { useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { useNowMinute } from "../hooks/useNowMinute";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { getTerminalFocusOwner } from "../lib/terminalFocus";
|
||||
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
|
||||
@@ -202,6 +211,7 @@ import {
|
||||
useThread,
|
||||
useThreadProposedPlans,
|
||||
useThreadRefs,
|
||||
useThreadShell,
|
||||
} from "../state/entities";
|
||||
import { environmentShell } from "../state/shell";
|
||||
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
|
||||
@@ -220,6 +230,7 @@ import {
|
||||
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,
|
||||
@@ -231,13 +242,17 @@ 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,
|
||||
@@ -260,6 +275,16 @@ 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,
|
||||
@@ -1815,7 +1840,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
|
||||
variant: connection.phase === "error" ? "error" : "warning",
|
||||
icon: <WifiOffIcon />,
|
||||
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusText(connection)}`,
|
||||
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusTitle(connection)}`,
|
||||
description:
|
||||
connection.error ??
|
||||
"Reconnect this environment before sending messages or running actions.",
|
||||
@@ -2352,6 +2377,7 @@ 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";
|
||||
@@ -3808,52 +3834,159 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: null,
|
||||
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
|
||||
);
|
||||
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,
|
||||
},
|
||||
// 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,
|
||||
});
|
||||
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();
|
||||
}, [
|
||||
activeThread,
|
||||
branchRepairAction,
|
||||
environmentId,
|
||||
localCheckoutBranchMismatch,
|
||||
scheduleComposerFocus,
|
||||
updateThreadMetadata,
|
||||
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,
|
||||
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]);
|
||||
const handleSwitchCheckoutToThread = useCallback(async () => {
|
||||
if (
|
||||
!activeProjectCwd ||
|
||||
!activeThread ||
|
||||
!localCheckoutBranchMismatch ||
|
||||
branchRepairAction !== null
|
||||
isRestoringThreadBranch
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setBranchRepairAction("switch-checkout");
|
||||
setIsRestoringThreadBranch(true);
|
||||
const checkoutResult = await switchGitRef({
|
||||
environmentId,
|
||||
input: {
|
||||
@@ -3862,7 +3995,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
},
|
||||
});
|
||||
if (checkoutResult._tag === "Failure") {
|
||||
setBranchRepairAction(null);
|
||||
setIsRestoringThreadBranch(false);
|
||||
if (!isAtomCommandInterrupted(checkoutResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
@@ -3882,7 +4015,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
|
||||
});
|
||||
if (updateResult._tag === "Failure") {
|
||||
setBranchRepairAction(null);
|
||||
setIsRestoringThreadBranch(false);
|
||||
if (!isAtomCommandInterrupted(updateResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
@@ -3897,76 +4030,125 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
}
|
||||
gitStatusQuery.refresh();
|
||||
setBranchRepairAction(null);
|
||||
setIsRestoringThreadBranch(false);
|
||||
scheduleComposerFocus();
|
||||
}, [
|
||||
activeProjectCwd,
|
||||
activeThread,
|
||||
branchRepairAction,
|
||||
environmentId,
|
||||
gitStatusQuery,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
scheduleComposerFocus,
|
||||
switchGitRef,
|
||||
updateThreadMetadata,
|
||||
]);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
if (!localCheckoutBranchMismatch) {
|
||||
return systemComposerBannerItems;
|
||||
// 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];
|
||||
}
|
||||
const isRepairingBranch = branchRepairAction !== null;
|
||||
return [
|
||||
...systemComposerBannerItems,
|
||||
{
|
||||
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>
|
||||
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>
|
||||
),
|
||||
className: "dark:shadow-none",
|
||||
actions: (
|
||||
<>
|
||||
<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>
|
||||
</>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={isRestoringThreadBranch}
|
||||
onClick={handleRestoreThreadBranch}
|
||||
>
|
||||
{isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
|
||||
</Button>
|
||||
),
|
||||
dismissLabel: "Dismiss branch change notice",
|
||||
onDismiss: () => {
|
||||
dismissBranchMismatchForSession(activeBranchMismatchKey);
|
||||
setBranchMismatchDismissTick((tick) => tick + 1);
|
||||
},
|
||||
},
|
||||
...parkedThreadItems,
|
||||
];
|
||||
}, [
|
||||
activeThread?.id,
|
||||
branchRepairAction,
|
||||
handleSwitchCheckoutToThread,
|
||||
handleUpdateThreadToCheckout,
|
||||
activeBranchMismatchKey,
|
||||
handleRestoreThreadBranch,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
parkedThreadBannerItem,
|
||||
showBranchMismatchBanner,
|
||||
systemComposerBannerItems,
|
||||
]);
|
||||
|
||||
@@ -5592,90 +5774,99 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div className="chat-composer-glass-host 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
|
||||
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>
|
||||
<div className="min-h-0">
|
||||
<div
|
||||
data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
|
||||
className="relative z-0"
|
||||
>
|
||||
{isGitRepo && (
|
||||
{showComposerContextStrip && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
@@ -5716,6 +5907,36 @@ 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}
|
||||
|
||||
@@ -111,12 +111,13 @@ export function buildProjectActionItems(input: {
|
||||
valuePrefix: string;
|
||||
icon: (project: Project) => ReactNode;
|
||||
runProject: (project: Project) => Promise<void>;
|
||||
searchTerms?: (project: Project) => ReadonlyArray<string>;
|
||||
shortcutCommand?: KeybindingCommand;
|
||||
}): CommandPaletteActionItem[] {
|
||||
return input.projects.map((project) => ({
|
||||
kind: "action",
|
||||
value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
|
||||
searchTerms: [project.title, project.workspaceRoot],
|
||||
searchTerms: [project.title, project.workspaceRoot, ...(input.searchTerms?.(project) ?? [])],
|
||||
title: project.title,
|
||||
description: project.workspaceRoot,
|
||||
icon: input.icon(project),
|
||||
|
||||
@@ -56,12 +56,9 @@ import { useEnvironmentQuery } from "../state/query";
|
||||
import { sourceControlEnvironment } from "../state/sourceControl";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
|
||||
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
|
||||
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
import {
|
||||
startNewThreadInProjectFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import {
|
||||
appendBrowsePathSegment,
|
||||
canNavigateUp,
|
||||
@@ -79,7 +76,7 @@ import {
|
||||
} from "../lib/projectPaths";
|
||||
import { onOpenCommandPalette } from "../commandPaletteBus";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";
|
||||
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
@@ -106,6 +103,7 @@ import {
|
||||
ITEM_ICON_CLASS,
|
||||
RECENT_THREAD_LIMIT,
|
||||
} from "./CommandPalette.logic";
|
||||
import { orderItemsByPreferredIds, sortLogicalProjectsForSidebar } from "./Sidebar.logic";
|
||||
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
|
||||
import { CommandPaletteResults } from "./CommandPaletteResults";
|
||||
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
|
||||
@@ -128,6 +126,12 @@ import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";
|
||||
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
buildSidebarProjectPickerEntries,
|
||||
buildSidebarProjectSnapshots,
|
||||
} from "../sidebarProjectGrouping";
|
||||
|
||||
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
|
||||
|
||||
@@ -487,10 +491,11 @@ function OpenCommandPaletteDialog(props: {
|
||||
});
|
||||
const { environments } = useEnvironments();
|
||||
const desktopLocalBootstraps = useDesktopLocalBootstraps();
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
|
||||
useHandleNewThread();
|
||||
const projects = useProjects();
|
||||
const projectOrder = useUiStateStore((store) => store.projectOrder);
|
||||
const threads = useThreadShells();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const providers = useAtomValue(primaryServerProvidersAtom);
|
||||
@@ -504,7 +509,93 @@ function OpenCommandPaletteDialog(props: {
|
||||
const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null);
|
||||
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
|
||||
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
|
||||
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
|
||||
const projectGroupingSettings = useMemo(
|
||||
() => selectProjectGroupingSettings(clientSettings),
|
||||
[clientSettings],
|
||||
);
|
||||
|
||||
const environmentLabelById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
environments.map((environment) => [environment.environmentId, environment.label] as const),
|
||||
),
|
||||
[environments],
|
||||
);
|
||||
const orderedProjects = useMemo(
|
||||
() =>
|
||||
orderItemsByPreferredIds({
|
||||
items: projects,
|
||||
preferredIds: projectOrder,
|
||||
getId: getProjectOrderKey,
|
||||
getPreferenceIds: (project) => [
|
||||
getProjectOrderKey(project),
|
||||
legacyProjectCwdPreferenceKey(project.workspaceRoot),
|
||||
],
|
||||
}),
|
||||
[projectOrder, projects],
|
||||
);
|
||||
const unsortedProjectGroups = useMemo(
|
||||
() =>
|
||||
buildSidebarProjectSnapshots({
|
||||
projects: clientSettings.sidebarProjectSortOrder === "manual" ? orderedProjects : projects,
|
||||
settings: projectGroupingSettings,
|
||||
primaryEnvironmentId,
|
||||
resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
|
||||
}),
|
||||
[
|
||||
clientSettings.sidebarProjectSortOrder,
|
||||
environmentLabelById,
|
||||
orderedProjects,
|
||||
primaryEnvironmentId,
|
||||
projectGroupingSettings,
|
||||
projects,
|
||||
],
|
||||
);
|
||||
const projectGroups = useMemo(
|
||||
() =>
|
||||
sortLogicalProjectsForSidebar(
|
||||
unsortedProjectGroups,
|
||||
threads,
|
||||
clientSettings.sidebarProjectSortOrder,
|
||||
),
|
||||
[clientSettings.sidebarProjectSortOrder, threads, unsortedProjectGroups],
|
||||
);
|
||||
const contextualProjectRef = useMemo(
|
||||
() =>
|
||||
resolveThreadActionProjectRef({
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
}),
|
||||
[activeDraftThread, activeThread, defaultProjectRef, handleNewThread],
|
||||
);
|
||||
const projectPickerEntries = useMemo(
|
||||
() =>
|
||||
buildSidebarProjectPickerEntries({
|
||||
groups: projectGroups,
|
||||
preferredProjectRef: contextualProjectRef,
|
||||
}),
|
||||
[contextualProjectRef, projectGroups],
|
||||
);
|
||||
const pickerProjects = useMemo(
|
||||
() =>
|
||||
projectPickerEntries.map(({ group, targetProject }) => ({
|
||||
...targetProject,
|
||||
title: group.displayName,
|
||||
})),
|
||||
[projectPickerEntries],
|
||||
);
|
||||
const projectGroupByTargetKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
projectPickerEntries.map(({ group, targetProject }) => [
|
||||
`${targetProject.environmentId}:${targetProject.id}`,
|
||||
group,
|
||||
]),
|
||||
),
|
||||
[projectPickerEntries],
|
||||
);
|
||||
|
||||
const addProjectEnvironmentOptions = useMemo(() => {
|
||||
const options = environments.map((environment): AddProjectEnvironmentOption => {
|
||||
@@ -648,11 +739,28 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
() => async (project: (typeof projects)[number]) => {
|
||||
const latestThread = getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === project.environmentId),
|
||||
project.id,
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
);
|
||||
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
|
||||
const groupedProjectKeys = group
|
||||
? new Set(
|
||||
group.memberProjectRefs.map(
|
||||
(projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const latestThread = groupedProjectKeys
|
||||
? (sortThreads(
|
||||
threads.filter(
|
||||
(thread) =>
|
||||
thread.archivedAt === null &&
|
||||
groupedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`),
|
||||
),
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
)[0] ?? null)
|
||||
: getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === project.environmentId),
|
||||
project.id,
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
);
|
||||
if (latestThread) {
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
@@ -665,14 +773,26 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
await handleNewThread(scopeProjectRef(project.environmentId, project.id));
|
||||
},
|
||||
[handleNewThread, navigate, clientSettings.sidebarThreadSortOrder, threads],
|
||||
[
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
handleNewThread,
|
||||
navigate,
|
||||
projectGroupByTargetKey,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
const projectSearchItems = useMemo(
|
||||
() =>
|
||||
buildProjectActionItems({
|
||||
projects,
|
||||
projects: pickerProjects,
|
||||
valuePrefix: "project",
|
||||
searchTerms: (project) => {
|
||||
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
|
||||
return (
|
||||
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
|
||||
);
|
||||
},
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
@@ -682,15 +802,21 @@ function OpenCommandPaletteDialog(props: {
|
||||
),
|
||||
runProject: openProjectFromSearch,
|
||||
}),
|
||||
[openProjectFromSearch, projects],
|
||||
[openProjectFromSearch, pickerProjects, projectGroupByTargetKey],
|
||||
);
|
||||
|
||||
const projectThreadItems = useMemo(
|
||||
() =>
|
||||
enumerateCommandPaletteItems(
|
||||
buildProjectActionItems({
|
||||
projects,
|
||||
projects: pickerProjects,
|
||||
valuePrefix: "new-thread-in",
|
||||
searchTerms: (project) => {
|
||||
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
|
||||
return (
|
||||
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
|
||||
);
|
||||
},
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
@@ -699,19 +825,23 @@ function OpenCommandPaletteDialog(props: {
|
||||
/>
|
||||
),
|
||||
runProject: async (project) => {
|
||||
await startNewThreadInProjectFromContext(
|
||||
{
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
},
|
||||
scopeProjectRef(project.environmentId, project.id),
|
||||
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
|
||||
const contextualRefBelongsToGroup =
|
||||
contextualProjectRef !== null &&
|
||||
group?.memberProjectRefs.some(
|
||||
(projectRef) =>
|
||||
projectRef.environmentId === contextualProjectRef.environmentId &&
|
||||
projectRef.projectId === contextualProjectRef.projectId,
|
||||
);
|
||||
await handleNewThread(
|
||||
contextualRefBelongsToGroup
|
||||
? contextualProjectRef
|
||||
: scopeProjectRef(project.environmentId, project.id),
|
||||
);
|
||||
},
|
||||
}),
|
||||
),
|
||||
[activeDraftThread, activeThread, defaultProjectRef, handleNewThread, projects],
|
||||
[contextualProjectRef, handleNewThread, pickerProjects, projectGroupByTargetKey],
|
||||
);
|
||||
|
||||
const allThreadItems = useMemo(
|
||||
@@ -1018,9 +1148,9 @@ function OpenCommandPaletteDialog(props: {
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (projects.length > 0) {
|
||||
const activeProjectTitle = currentProjectId
|
||||
? (projectTitleById.get(currentProjectId) ?? null)
|
||||
: null;
|
||||
const activeProjectTitle =
|
||||
projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ??
|
||||
(currentProjectId ? (projectTitleById.get(currentProjectId) ?? null) : null);
|
||||
|
||||
if (activeProjectTitle) {
|
||||
actionItems.push({
|
||||
|
||||
@@ -14,15 +14,16 @@ import {
|
||||
isTrailingDoubleClick,
|
||||
orderItemsByPreferredIds,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveSidebarV2Status,
|
||||
resolveThreadStatusPill,
|
||||
resolveWorkingStartedAt,
|
||||
formatWorkingDurationLabel,
|
||||
shouldNavigateAfterProjectRemoval,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortLogicalProjectsForSidebar,
|
||||
sortSettledThreadsForSidebarV2,
|
||||
sortThreadsForSidebarV2,
|
||||
sortProjectsForSidebar,
|
||||
sortScopedProjectsForSidebar,
|
||||
@@ -35,6 +36,7 @@ import {
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
@@ -208,8 +210,10 @@ function makeLatestTurn(overrides?: {
|
||||
state: "completed",
|
||||
assistantMessageId: null,
|
||||
requestedAt: "2026-03-09T10:00:00.000Z",
|
||||
startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
|
||||
completedAt: overrides?.completedAt ?? "2026-03-09T10:05: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",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -365,112 +369,6 @@ 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({
|
||||
@@ -730,6 +628,22 @@ describe("resolveSidebarV2Status", () => {
|
||||
).toBe("working");
|
||||
});
|
||||
|
||||
it("reports waiting for an idle session, below approval and input", () => {
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
...idle,
|
||||
session: { ...session, status: "idle" as const, activeTurnId: null },
|
||||
}),
|
||||
).toBe("waiting");
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
...idle,
|
||||
hasPendingApprovals: true,
|
||||
session: { ...session, status: "idle" as const, activeTurnId: null },
|
||||
}),
|
||||
).toBe("approval");
|
||||
});
|
||||
|
||||
it("reports failed only while the session status is error", () => {
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
@@ -782,6 +696,141 @@ 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,7 +18,6 @@ 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;
|
||||
@@ -246,62 +245,6 @@ 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[];
|
||||
@@ -452,13 +395,16 @@ export function resolveThreadRowClassName(input: {
|
||||
}
|
||||
|
||||
// ── Sidebar v2 status model ─────────────────────────────────────────
|
||||
// Five visual states, three colors: color is reserved for "act now"
|
||||
// Six visual states, three colors: color is reserved for "act now"
|
||||
// (approval), "in motion" (working), and "broken" (failed). Ready is the
|
||||
// unlabeled resting state — the agent stopped and is waiting on the user,
|
||||
// whether it finished, asked a question, or proposed a plan.
|
||||
// whether it finished, asked a question, or proposed a plan. Waiting
|
||||
// (session status "idle") is the agent stopped with background tasks still
|
||||
// open: not the user's turn yet, so it renders grey like working, not as a
|
||||
// false Done.
|
||||
// Unread completion is tracked separately: it describes whether a ready
|
||||
// thread needs attention, not what the thread is currently doing.
|
||||
export type SidebarV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
export type SidebarV2Status = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
|
||||
|
||||
type SidebarV2StatusInput = Pick<
|
||||
SidebarThreadSummary,
|
||||
@@ -475,6 +421,9 @@ export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2S
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") {
|
||||
return "working";
|
||||
}
|
||||
if (thread.session?.status === "idle") {
|
||||
return "waiting";
|
||||
}
|
||||
if (thread.session?.status === "error") {
|
||||
return "failed";
|
||||
}
|
||||
@@ -502,6 +451,18 @@ 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
|
||||
@@ -516,6 +477,73 @@ 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 {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
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/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* 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}`;
|
||||
}
|
||||
@@ -145,15 +145,7 @@ import {
|
||||
DialogTitle,
|
||||
} from "./ui/dialog";
|
||||
import { Input } from "./ui/input";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from "./ui/menu";
|
||||
import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldDecrement,
|
||||
@@ -185,8 +177,6 @@ import {
|
||||
isContextMenuPointerDown,
|
||||
isTrailingDoubleClick,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
orderItemsByPreferredIds,
|
||||
@@ -201,7 +191,7 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useIsMobile } from "~/hooks/useMediaQuery";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
|
||||
import { primaryServerKeybindingsAtom, primaryServerSettingsAtom } from "../state/server";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import {
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupingOverrideKey,
|
||||
@@ -1111,7 +1101,6 @@ 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,
|
||||
});
|
||||
@@ -1883,61 +1872,14 @@ 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), {
|
||||
...(seedContext.branch !== undefined ? { branch: seedContext.branch } : {}),
|
||||
...(seedContext.worktreePath !== undefined
|
||||
? { worktreePath: seedContext.worktreePath }
|
||||
: {}),
|
||||
envMode: seedContext.envMode,
|
||||
...(seedContext.startFromOrigin !== undefined
|
||||
? { startFromOrigin: seedContext.startFromOrigin }
|
||||
: {}),
|
||||
}),
|
||||
handleNewThread(scopeProjectRef(member.environmentId, member.id)),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
@@ -1951,7 +1893,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}
|
||||
})();
|
||||
},
|
||||
[handleNewThread, isMobile, primaryServerSettings.defaultThreadEnvMode, router, setOpenMobile],
|
||||
[handleNewThread, isMobile, setOpenMobile],
|
||||
);
|
||||
|
||||
const handleCreateThreadClick = useCallback(
|
||||
@@ -2172,6 +2114,9 @@ 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" },
|
||||
@@ -2181,6 +2126,30 @@ 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;
|
||||
@@ -2237,6 +2206,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
copyPathToClipboard,
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
handleNewThread,
|
||||
markThreadUnread,
|
||||
memberProjectByScopedKey,
|
||||
project.workspaceRoot,
|
||||
@@ -2601,20 +2571,16 @@ type SortableProjectHandleProps = Pick<
|
||||
function ProjectSortMenu({
|
||||
projectSortOrder,
|
||||
threadSortOrder,
|
||||
projectGroupingMode,
|
||||
threadPreviewCount,
|
||||
onProjectSortOrderChange,
|
||||
onThreadSortOrderChange,
|
||||
onProjectGroupingModeChange,
|
||||
onThreadPreviewCountChange,
|
||||
}: {
|
||||
projectSortOrder: SidebarProjectSortOrder;
|
||||
threadSortOrder: SidebarThreadSortOrder;
|
||||
projectGroupingMode: SidebarProjectGroupingMode;
|
||||
threadPreviewCount: SidebarThreadPreviewCount;
|
||||
onProjectSortOrderChange: (sortOrder: SidebarProjectSortOrder) => void;
|
||||
onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
onThreadPreviewCountChange: (count: SidebarThreadPreviewCount) => void;
|
||||
}) {
|
||||
const handleThreadPreviewCountChange = useCallback(
|
||||
@@ -2718,30 +2684,6 @@ function ProjectSortMenu({
|
||||
</NumberField>
|
||||
</div>
|
||||
</MenuGroup>
|
||||
<MenuSeparator />
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-2 pb-1 font-medium text-muted-foreground sm:text-xs">
|
||||
Group projects
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={projectGroupingMode}
|
||||
onValueChange={(value) => {
|
||||
if (value === "repository" || value === "repository_path" || value === "separate") {
|
||||
onProjectGroupingModeChange(value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{(
|
||||
Object.entries(PROJECT_GROUPING_MODE_LABELS) as Array<
|
||||
[SidebarProjectGroupingMode, string]
|
||||
>
|
||||
).map(([value, label]) => (
|
||||
<MenuRadioItem key={value} value={value} className="min-h-7 py-1 sm:text-xs">
|
||||
{label}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
@@ -2792,7 +2734,6 @@ interface SidebarProjectsContentProps {
|
||||
handleDesktopUpdateButtonClick: () => void;
|
||||
projectSortOrder: SidebarProjectSortOrder;
|
||||
threadSortOrder: SidebarThreadSortOrder;
|
||||
projectGroupingMode: SidebarProjectGroupingMode;
|
||||
threadPreviewCount: SidebarThreadPreviewCount;
|
||||
updateSettings: ReturnType<typeof useUpdateClientSettings>;
|
||||
openAddProject: () => void;
|
||||
@@ -2833,7 +2774,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
handleDesktopUpdateButtonClick,
|
||||
projectSortOrder,
|
||||
threadSortOrder,
|
||||
projectGroupingMode,
|
||||
threadPreviewCount,
|
||||
updateSettings,
|
||||
openAddProject,
|
||||
@@ -2875,12 +2815,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
},
|
||||
[updateSettings],
|
||||
);
|
||||
const handleProjectGroupingModeChange = useCallback(
|
||||
(groupingMode: SidebarProjectGroupingMode) => {
|
||||
updateSettings({ sidebarProjectGroupingMode: groupingMode });
|
||||
},
|
||||
[updateSettings],
|
||||
);
|
||||
const handleThreadPreviewCountChange = useCallback(
|
||||
(count: SidebarThreadPreviewCount) => {
|
||||
updateSettings({ sidebarThreadPreviewCount: count });
|
||||
@@ -2944,11 +2878,9 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
<ProjectSortMenu
|
||||
projectSortOrder={projectSortOrder}
|
||||
threadSortOrder={threadSortOrder}
|
||||
projectGroupingMode={projectGroupingMode}
|
||||
threadPreviewCount={threadPreviewCount}
|
||||
onProjectSortOrderChange={handleProjectSortOrderChange}
|
||||
onThreadSortOrderChange={handleThreadSortOrderChange}
|
||||
onProjectGroupingModeChange={handleProjectGroupingModeChange}
|
||||
onThreadPreviewCountChange={handleThreadPreviewCountChange}
|
||||
/>
|
||||
<Tooltip>
|
||||
@@ -3064,7 +2996,6 @@ export default function Sidebar() {
|
||||
const isOnSettings = pathname.startsWith("/settings");
|
||||
const sidebarThreadSortOrder = useClientSettings((s) => s.sidebarThreadSortOrder);
|
||||
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
|
||||
const sidebarProjectGroupingMode = useClientSettings((s) => s.sidebarProjectGroupingMode);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const sidebarThreadPreviewCount = useClientSettings((s) => s.sidebarThreadPreviewCount);
|
||||
const updateSettings = useUpdateClientSettings();
|
||||
@@ -3608,7 +3539,7 @@ export default function Sidebar() {
|
||||
|
||||
if (desktopUpdateButtonAction === "install") {
|
||||
const confirmed = window.confirm(
|
||||
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState),
|
||||
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState, navigator.platform),
|
||||
);
|
||||
if (!confirmed) return;
|
||||
void bridge
|
||||
@@ -3674,7 +3605,6 @@ export default function Sidebar() {
|
||||
handleDesktopUpdateButtonClick={handleDesktopUpdateButtonClick}
|
||||
projectSortOrder={sidebarProjectSortOrder}
|
||||
threadSortOrder={sidebarThreadSortOrder}
|
||||
projectGroupingMode={sidebarProjectGroupingMode}
|
||||
threadPreviewCount={sidebarThreadPreviewCount}
|
||||
updateSettings={updateSettings}
|
||||
openAddProject={openAddProjectCommandPalette}
|
||||
|
||||
+1101
-218
File diff suppressed because it is too large.
Load diff
@@ -10,23 +10,86 @@ 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('class="sticky top-0 z-10');
|
||||
expect(markup).not.toContain("self-start");
|
||||
expect(markup).toContain('data-changed-files-state="expanded"');
|
||||
expect(markup).toContain('aria-expanded="true"');
|
||||
expect(markup).toContain("whitespace-nowrap");
|
||||
expect(markup).toContain("!size-[22px]");
|
||||
expect(markup).toContain("size-3");
|
||||
expect(markup).toContain('aria-label="Collapse all"');
|
||||
expect(markup).toContain('aria-label="View diff"');
|
||||
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("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,95 +19,184 @@ 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 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"}
|
||||
<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"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
<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>
|
||||
<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="icon-xs"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
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"
|
||||
aria-label="Open diff"
|
||||
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
<span className="hidden sm:inline">Open diff</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">View diff</TooltipPopup>
|
||||
<TooltipPopup side="top">Open the full diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
{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}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -18,10 +18,7 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
connectionStatusText,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
|
||||
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
|
||||
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import {
|
||||
@@ -2577,15 +2574,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
? "Add feedback to refine the plan, or leave this blank to implement it"
|
||||
: projectSelectionRequired
|
||||
? "Choose a project above to start a thread"
|
||||
: environmentUnavailable
|
||||
? `${environmentUnavailable.label}: ${connectionStatusText(
|
||||
environmentUnavailable.connection,
|
||||
)}`
|
||||
: noProviderAvailable
|
||||
? "Enable a provider in Settings to send a message"
|
||||
: phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
: noProviderAvailable
|
||||
? "Enable a provider in Settings to send a message"
|
||||
: phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
}
|
||||
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
|
||||
/>
|
||||
|
||||
@@ -31,6 +31,8 @@ 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"
|
||||
@@ -38,8 +40,12 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span className="font-mono text-success">+{formatCompactDiffCount(additions)}</span>
|
||||
<span className="font-mono text-destructive">-{formatCompactDiffCount(deletions)}</span>
|
||||
<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>
|
||||
{showParentheses && <span className="text-muted-foreground/70">)</span>}
|
||||
</>
|
||||
|
||||
@@ -5,8 +5,15 @@ import { useCallback, useMemo } from "react";
|
||||
|
||||
import { openCommandPalette } from "~/commandPaletteBus";
|
||||
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
|
||||
import { useClientSettings } from "~/hooks/useSettings";
|
||||
import { selectProjectGroupingSettings } from "~/logicalProject";
|
||||
import {
|
||||
buildSidebarProjectPickerEntries,
|
||||
buildSidebarProjectSnapshots,
|
||||
} from "~/sidebarProjectGrouping";
|
||||
import { useProjects, useThreadShells } from "~/state/entities";
|
||||
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
|
||||
import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
|
||||
import { sortLogicalProjectsForSidebar } from "../Sidebar.logic";
|
||||
import {
|
||||
Menu,
|
||||
MenuItem,
|
||||
@@ -28,29 +35,66 @@ export function DraftHeroHeadline({
|
||||
}: DraftHeroHeadlineProps) {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { environments } = useEnvironments();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const projectSortOrder = useClientSettings((settings) => settings.sidebarProjectSortOrder);
|
||||
const handleNewThread = useNewThreadHandler();
|
||||
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
|
||||
|
||||
const orderedProjects = useMemo(
|
||||
() => sortScopedProjectsForSidebar(projects, threads, "updated_at"),
|
||||
[projects, threads],
|
||||
);
|
||||
const projectByKey = useMemo(
|
||||
const environmentLabelById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
orderedProjects.map(
|
||||
(project) =>
|
||||
[
|
||||
scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
|
||||
project,
|
||||
] as const,
|
||||
),
|
||||
environments.map((environment) => [environment.environmentId, environment.label] as const),
|
||||
),
|
||||
[orderedProjects],
|
||||
[environments],
|
||||
);
|
||||
const activeProjectKey = activeProjectRef === null ? "" : scopedProjectKey(activeProjectRef);
|
||||
const projectGroups = useMemo(
|
||||
() =>
|
||||
sortLogicalProjectsForSidebar(
|
||||
buildSidebarProjectSnapshots({
|
||||
projects,
|
||||
settings: projectGroupingSettings,
|
||||
primaryEnvironmentId,
|
||||
resolveEnvironmentLabel: (environmentId) =>
|
||||
environmentLabelById.get(environmentId) ?? null,
|
||||
}),
|
||||
threads,
|
||||
projectSortOrder,
|
||||
),
|
||||
[
|
||||
environmentLabelById,
|
||||
primaryEnvironmentId,
|
||||
projectGroupingSettings,
|
||||
projectSortOrder,
|
||||
projects,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
const projectPickerEntries = useMemo(
|
||||
() =>
|
||||
buildSidebarProjectPickerEntries({
|
||||
groups: projectGroups,
|
||||
preferredProjectRef: activeProjectRef,
|
||||
}),
|
||||
[activeProjectRef, projectGroups],
|
||||
);
|
||||
const projectEntryByKey = useMemo(
|
||||
() => new Map(projectPickerEntries.map((entry) => [entry.group.projectKey, entry] as const)),
|
||||
[projectPickerEntries],
|
||||
);
|
||||
const activeProjectGroup =
|
||||
activeProjectRef === null
|
||||
? null
|
||||
: (projectGroups.find((group) =>
|
||||
group.memberProjectRefs.some(
|
||||
(projectRef) => scopedProjectKey(projectRef) === scopedProjectKey(activeProjectRef),
|
||||
),
|
||||
) ?? null);
|
||||
const activeProjectKey = activeProjectGroup?.projectKey ?? "";
|
||||
const activeProjectDisplayName = activeProjectGroup?.displayName ?? activeProjectTitle;
|
||||
const hasResolvedProject = activeProjectTitle !== null;
|
||||
const canChooseProject = orderedProjects.length > 0;
|
||||
const canChooseProject = projectPickerEntries.length > 0;
|
||||
const shouldShowProjectMenu = canChooseProject;
|
||||
|
||||
const projectSelector = shouldShowProjectMenu ? (
|
||||
@@ -59,26 +103,26 @@ export function DraftHeroHeadline({
|
||||
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
|
||||
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-foreground underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{activeProjectTitle ?? "Choose a project"}
|
||||
{activeProjectDisplayName ?? "Choose a project"}
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">
|
||||
<MenuRadioGroup
|
||||
value={activeProjectKey}
|
||||
onValueChange={(value) => {
|
||||
const project = projectByKey.get(value as string);
|
||||
if (!project || value === activeProjectKey) {
|
||||
const entry = projectEntryByKey.get(value as string);
|
||||
if (!entry || value === activeProjectKey) {
|
||||
return;
|
||||
}
|
||||
const project = entry.targetProject;
|
||||
void handleNewThread(scopeProjectRef(project.environmentId, project.id), {
|
||||
replace: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
{orderedProjects.map((project) => {
|
||||
const key = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
|
||||
{projectPickerEntries.map(({ group }) => {
|
||||
return (
|
||||
<MenuRadioItem key={key} value={key} closeOnClick>
|
||||
<span className="min-w-0 truncate">{project.title}</span>
|
||||
<MenuRadioItem key={group.projectKey} value={group.projectKey} closeOnClick>
|
||||
<span className="min-w-0 truncate">{group.displayName}</span>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -245,6 +245,12 @@ 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",
|
||||
@@ -280,13 +286,13 @@ describe("MessagesTimeline", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('class="sticky top-2 z-10');
|
||||
expect(markup).toContain("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"');
|
||||
expect(markup).toContain('aria-label="View diff"');
|
||||
expect(markup).toContain('aria-label="Collapse all folders"');
|
||||
expect(markup).toContain('aria-label="Open diff"');
|
||||
expect(markup).toContain("1 changed file");
|
||||
});
|
||||
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
workLogEntryIsToolLike,
|
||||
} from "../../session-logic";
|
||||
import { type TurnDiffSummary } from "../../types";
|
||||
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
|
||||
import {
|
||||
getRenderablePatch,
|
||||
resolveDiffThemeName,
|
||||
@@ -44,11 +43,8 @@ import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsDownUpIcon,
|
||||
ChevronsUpDownIcon,
|
||||
CircleAlertIcon,
|
||||
EyeIcon,
|
||||
FileDiffIcon,
|
||||
GlobeIcon,
|
||||
HammerIcon,
|
||||
MessageCircleIcon,
|
||||
@@ -65,8 +61,8 @@ import {
|
||||
import { Button } from "../ui/button";
|
||||
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { ProposedPlanCard } from "./ProposedPlanCard";
|
||||
import { ChangedFilesTree } from "./ChangedFilesTree";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { ChangedFilesCard } from "./ChangedFilesTree";
|
||||
import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation";
|
||||
import { MessageCopyButton } from "./MessageCopyButton";
|
||||
import {
|
||||
computeStableMessagesTimelineRows,
|
||||
@@ -145,6 +141,7 @@ interface TimelineRowActivityState {
|
||||
isWorking: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
activeTurnInProgress: boolean;
|
||||
latestTurnId: TurnId | null;
|
||||
}
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
@@ -454,8 +451,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
isWorking,
|
||||
isRevertingCheckpoint,
|
||||
activeTurnInProgress,
|
||||
latestTurnId: latestTurn?.turnId ?? null,
|
||||
}),
|
||||
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
|
||||
[activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId],
|
||||
);
|
||||
|
||||
// Stable renderItem — no closure deps. Row components read shared state
|
||||
@@ -1278,83 +1276,32 @@ function AssistantChangedFilesSectionInner({
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const allDirectoriesExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const isLatestTurn = activity.latestTurnId === turnSummary.turnId;
|
||||
const persistedExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId],
|
||||
);
|
||||
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
const [autoExpanded] = useState(() =>
|
||||
shouldAutoExpandChangedFiles(checkpointFiles, isLatestTurn),
|
||||
);
|
||||
const [allDirectoriesExpanded, setAllDirectoriesExpanded] = useState(autoExpanded);
|
||||
const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded);
|
||||
|
||||
return (
|
||||
<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-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>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.turnId}`}
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
<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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
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;
|
||||
}
|
||||
@@ -225,6 +225,32 @@ describe("desktop update UI helpers", () => {
|
||||
}),
|
||||
).toContain("Install update and restart T3 Code?");
|
||||
});
|
||||
|
||||
it("warns Windows users that a silent installation can take several minutes", () => {
|
||||
const message = getDesktopUpdateInstallConfirmationMessage(
|
||||
{
|
||||
availableVersion: "1.1.0",
|
||||
downloadedVersion: "1.1.0",
|
||||
},
|
||||
"Win32",
|
||||
);
|
||||
|
||||
expect(message).toContain("may remain closed for several minutes");
|
||||
expect(message).toContain("no installer window may appear");
|
||||
expect(message).toContain("will reopen automatically");
|
||||
});
|
||||
|
||||
it("keeps the additional silent installation warning Windows-specific", () => {
|
||||
const message = getDesktopUpdateInstallConfirmationMessage(
|
||||
{
|
||||
availableVersion: "1.1.0",
|
||||
downloadedVersion: "1.1.0",
|
||||
},
|
||||
"MacIntel",
|
||||
);
|
||||
|
||||
expect(message).not.toContain("may remain closed for several minutes");
|
||||
});
|
||||
});
|
||||
|
||||
describe("canCheckForUpdate", () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
|
||||
import { isWindowsPlatform } from "../lib/utils";
|
||||
|
||||
export type DesktopUpdateButtonAction = "download" | "install" | "none";
|
||||
|
||||
@@ -78,9 +79,13 @@ export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string
|
||||
|
||||
export function getDesktopUpdateInstallConfirmationMessage(
|
||||
state: Pick<DesktopUpdateState, "availableVersion" | "downloadedVersion">,
|
||||
platform = "",
|
||||
): string {
|
||||
const version = state.downloadedVersion ?? state.availableVersion;
|
||||
return `Install update${version ? ` ${version}` : ""} and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.`;
|
||||
const windowsInstallWarning = isWindowsPlatform(platform)
|
||||
? "\n\nOn Windows, T3 Code may remain closed for several minutes while the update installs, and no installer window may appear. T3 Code will reopen automatically when installation finishes."
|
||||
: "";
|
||||
return `Install update${version ? ` ${version}` : ""} and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.${windowsInstallWarning}`;
|
||||
}
|
||||
|
||||
export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): string | null {
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
type PreviewAutomationOpenInput,
|
||||
type PreviewAutomationResizeInput,
|
||||
type PreviewAutomationResizeResult,
|
||||
type PreviewAutomationSetColorSchemeInput,
|
||||
type PreviewAutomationSetColorSchemeResult,
|
||||
type PreviewAutomationHost as PreviewAutomationHostState,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationStatus,
|
||||
@@ -451,6 +453,15 @@ 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,13 +1,34 @@
|
||||
"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, MenuSeparator, MenuTrigger } from "~/components/ui/menu";
|
||||
import {
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator,
|
||||
MenuSub,
|
||||
MenuSubPopup,
|
||||
MenuSubTrigger,
|
||||
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;
|
||||
@@ -19,6 +40,8 @@ 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. */
|
||||
@@ -34,6 +57,7 @@ export function PreviewMoreMenu({
|
||||
tabId,
|
||||
hasWebContents,
|
||||
zoomFactor,
|
||||
colorScheme,
|
||||
deviceToolbarVisible,
|
||||
onToggleDeviceToolbar,
|
||||
}: Props) {
|
||||
@@ -72,6 +96,26 @@ 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,6 +40,7 @@ vi.mock("~/previewStateStore", () => ({
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -610,6 +610,7 @@ 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,6 +77,7 @@ function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverl
|
||||
canGoForward: state.canGoForward,
|
||||
loading: state.navStatus.kind === "Loading",
|
||||
zoomFactor: state.zoomFactor,
|
||||
colorScheme: state.colorScheme,
|
||||
controller: state.controller,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,8 +8,25 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
buildProviderInstanceUpdatePatch,
|
||||
formatDiagnosticsDescription,
|
||||
isProjectGroupingEnabled,
|
||||
projectGroupingModeFromToggle,
|
||||
} from "./SettingsPanels.logic";
|
||||
|
||||
describe("project grouping toggle", () => {
|
||||
it("enables repository grouping and disables into separate projects", () => {
|
||||
expect(isProjectGroupingEnabled("repository")).toBe(true);
|
||||
expect(isProjectGroupingEnabled("repository_path")).toBe(true);
|
||||
expect(isProjectGroupingEnabled("separate")).toBe(false);
|
||||
expect(projectGroupingModeFromToggle(true)).toBe("repository");
|
||||
expect(projectGroupingModeFromToggle(false)).toBe("separate");
|
||||
});
|
||||
|
||||
it("restores repository path grouping when the toggle is cycled", () => {
|
||||
expect(projectGroupingModeFromToggle(false, "repository_path")).toBe("separate");
|
||||
expect(projectGroupingModeFromToggle(true, "repository_path")).toBe("repository_path");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatDiagnosticsDescription", () => {
|
||||
it("collapses trace and metric URLs that share the same OTEL base path", () => {
|
||||
expect(
|
||||
|
||||
@@ -3,10 +3,44 @@ import type {
|
||||
ProviderInstanceConfig,
|
||||
ProviderInstanceId,
|
||||
ServerSettings,
|
||||
SidebarProjectGroupingMode,
|
||||
UnifiedSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
|
||||
export function isProjectGroupingEnabled(mode: SidebarProjectGroupingMode): boolean {
|
||||
return mode !== "separate";
|
||||
}
|
||||
|
||||
export function projectGroupingModeFromToggle(
|
||||
enabled: boolean,
|
||||
lastEnabledMode: SidebarProjectGroupingMode = "repository",
|
||||
): SidebarProjectGroupingMode {
|
||||
if (!enabled) return "separate";
|
||||
return lastEnabledMode === "repository_path" ? "repository_path" : "repository";
|
||||
}
|
||||
|
||||
const LAST_ENABLED_PROJECT_GROUPING_MODE_KEY = "t3code:last-enabled-project-grouping-mode";
|
||||
|
||||
export function readLastEnabledProjectGroupingMode(): SidebarProjectGroupingMode {
|
||||
try {
|
||||
return localStorage.getItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY) === "repository_path"
|
||||
? "repository_path"
|
||||
: "repository";
|
||||
} catch {
|
||||
return "repository";
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberEnabledProjectGroupingMode(mode: SidebarProjectGroupingMode): void {
|
||||
if (mode === "separate") return;
|
||||
try {
|
||||
localStorage.setItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY, mode);
|
||||
} catch {
|
||||
// Storage can be unavailable in restricted browser contexts.
|
||||
}
|
||||
}
|
||||
|
||||
function collapseOtelSignalsUrl(input: {
|
||||
readonly tracesUrl: string;
|
||||
readonly metricsUrl: string;
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceId,
|
||||
type ScopedThreadRef,
|
||||
type SidebarProjectGroupingMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
@@ -83,6 +84,10 @@ import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
|
||||
import {
|
||||
buildProviderInstanceUpdatePatch,
|
||||
formatDiagnosticsDescription,
|
||||
isProjectGroupingEnabled,
|
||||
projectGroupingModeFromToggle,
|
||||
readLastEnabledProjectGroupingMode,
|
||||
rememberEnabledProjectGroupingMode,
|
||||
} from "./SettingsPanels.logic";
|
||||
import {
|
||||
SettingResetButton,
|
||||
@@ -233,6 +238,7 @@ function AboutVersionSection() {
|
||||
const confirmed = window.confirm(
|
||||
getDesktopUpdateInstallConfirmationMessage(
|
||||
updateState ?? { availableVersion: null, downloadedVersion: null },
|
||||
navigator.platform,
|
||||
),
|
||||
);
|
||||
if (!confirmed) return;
|
||||
@@ -401,6 +407,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.sidebarThreadPreviewCount !== DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount
|
||||
? ["Visible threads"]
|
||||
: []),
|
||||
...(settings.sidebarProjectGroupingMode !==
|
||||
DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode
|
||||
? ["Project Grouping"]
|
||||
: []),
|
||||
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
|
||||
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
|
||||
? ["Diff whitespace changes"]
|
||||
@@ -450,6 +460,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.automaticGitFetchInterval,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.enableProviderUpdateChecks,
|
||||
settings.sidebarProjectGroupingMode,
|
||||
settings.sidebarThreadPreviewCount,
|
||||
settings.timestampFormat,
|
||||
settings.wordWrap,
|
||||
@@ -474,6 +485,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
|
||||
glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity,
|
||||
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
|
||||
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
|
||||
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
|
||||
@@ -498,6 +510,9 @@ export function GeneralSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const lastEnabledProjectGroupingMode = useRef<SidebarProjectGroupingMode>(
|
||||
readLastEnabledProjectGroupingMode(),
|
||||
);
|
||||
const observability = useAtomValue(primaryServerObservabilityAtom);
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const glassOpacityRatio =
|
||||
@@ -619,6 +634,42 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Project Grouping"
|
||||
description="Combine matching repositories across environments."
|
||||
resetAction={
|
||||
settings.sidebarProjectGroupingMode !==
|
||||
DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode ? (
|
||||
<SettingResetButton
|
||||
label="project grouping"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={isProjectGroupingEnabled(settings.sidebarProjectGroupingMode)}
|
||||
onCheckedChange={(checked) => {
|
||||
if (!checked && settings.sidebarProjectGroupingMode !== "separate") {
|
||||
lastEnabledProjectGroupingMode.current = settings.sidebarProjectGroupingMode;
|
||||
rememberEnabledProjectGroupingMode(settings.sidebarProjectGroupingMode);
|
||||
}
|
||||
updateSettings({
|
||||
sidebarProjectGroupingMode: projectGroupingModeFromToggle(
|
||||
checked,
|
||||
lastEnabledProjectGroupingMode.current,
|
||||
),
|
||||
});
|
||||
}}
|
||||
aria-label="Project Grouping"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Time format"
|
||||
description="System default follows your browser or OS clock preference."
|
||||
|
||||
@@ -110,7 +110,9 @@ export function SidebarUpdatePill() {
|
||||
}
|
||||
|
||||
if (action === "install") {
|
||||
const confirmed = window.confirm(getDesktopUpdateInstallConfirmationMessage(state));
|
||||
const confirmed = window.confirm(
|
||||
getDesktopUpdateInstallConfirmationMessage(state, navigator.platform),
|
||||
);
|
||||
if (!confirmed) return;
|
||||
void bridge
|
||||
.installUpdate()
|
||||
|
||||
@@ -406,6 +406,15 @@ 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: (
|
||||
@@ -2594,7 +2603,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadKey: nextDraftsByThreadKey };
|
||||
});
|
||||
},
|
||||
setModelSelection: (threadRef, modelSelection) => {
|
||||
setModelSelection: (threadRef, modelSelection, opts) => {
|
||||
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
||||
if (threadKey.length === 0) {
|
||||
return;
|
||||
@@ -2609,8 +2618,10 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
if (normalized) {
|
||||
const current = nextMap[normalized.instanceId];
|
||||
if (normalized.options !== undefined) {
|
||||
// Explicit options provided → use them
|
||||
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.
|
||||
nextMap[normalized.instanceId] = normalized as ModelSelection;
|
||||
} else {
|
||||
// No options in selection → preserve existing options, update provider+model
|
||||
|
||||
@@ -54,14 +54,52 @@ 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 &&
|
||||
@@ -92,25 +130,70 @@ export function useNewThreadHandler() {
|
||||
: null;
|
||||
if (reusableStoredDraftThread) {
|
||||
return (async () => {
|
||||
if (
|
||||
const isDraftAlreadyOpen =
|
||||
currentRouteTarget?.kind === "draft" &&
|
||||
currentRouteTarget.draftId === reusableStoredDraftThread.draftId;
|
||||
const hasExplicitWorkspaceOption =
|
||||
hasBranchOption ||
|
||||
hasWorktreePathOption ||
|
||||
hasEnvModeOption ||
|
||||
hasStartFromOriginOption
|
||||
) {
|
||||
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) {
|
||||
setDraftThreadContext(reusableStoredDraftThread.draftId, {
|
||||
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
|
||||
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
|
||||
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
|
||||
...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
|
||||
...workspaceContext,
|
||||
...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
|
||||
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
|
||||
});
|
||||
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 (
|
||||
@@ -176,9 +259,18 @@ export function useNewThreadHandler() {
|
||||
envMode: initialEnvMode,
|
||||
newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
|
||||
}),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
runtimeMode: carryRuntimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
|
||||
});
|
||||
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",
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
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 } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { canSettle, canSnooze } 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,6 +22,7 @@ import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsStat
|
||||
import { readLocalApi } from "../localApi";
|
||||
import {
|
||||
readEnvironmentSupportsSettlement,
|
||||
readEnvironmentSupportsSnooze,
|
||||
readEnvironmentThreadRefs,
|
||||
readProject,
|
||||
readThreadShell,
|
||||
@@ -69,6 +70,30 @@ 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, {
|
||||
@@ -86,6 +111,12 @@ 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,
|
||||
@@ -441,6 +472,61 @@ 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();
|
||||
@@ -477,14 +563,18 @@ export function useThreadActions() {
|
||||
confirmAndDeleteThread,
|
||||
settleThread,
|
||||
unsettleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
}),
|
||||
[
|
||||
archiveThread,
|
||||
confirmAndDeleteThread,
|
||||
deleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
],
|
||||
);
|
||||
}
|
||||
+147
-10
@@ -377,21 +377,20 @@ 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-host {
|
||||
.chat-composer-glass-shell {
|
||||
--chat-composer-glass-surface: var(--card);
|
||||
--chat-composer-outline: rgb(0 0 0 / 8%);
|
||||
|
||||
position: relative;
|
||||
box-shadow:
|
||||
0 0 0 1px rgb(0 0 0 / 8%),
|
||||
0 12px 28px -18px rgb(0 0 0 / 40%);
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
.chat-composer-glass-host::before {
|
||||
.chat-composer-glass-shell::before {
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
z-index: 0;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
border-radius: 22px;
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--chat-composer-glass-surface) var(--glass-opacity),
|
||||
@@ -402,10 +401,148 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
content: "";
|
||||
}
|
||||
|
||||
.dark .chat-composer-glass-host {
|
||||
--chat-composer-glass-surface: color-mix(in srgb, var(--background) 84%, var(--color-white));
|
||||
.chat-composer-glass-shell-with-context {
|
||||
--chat-composer-context-extension: 2.25rem;
|
||||
}
|
||||
|
||||
box-shadow: 0 0 0 1px rgb(255 255 255 / 10%);
|
||||
.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 {
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
.chat-composer-context-strip::before {
|
||||
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. */
|
||||
-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%);
|
||||
}
|
||||
|
||||
.dark .chat-composer-glass-host {
|
||||
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 {
|
||||
@@ -612,7 +749,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
background: var(--background) !important;
|
||||
}
|
||||
|
||||
.chat-composer-glass-host::before {
|
||||
.chat-composer-glass-shell::before {
|
||||
background: var(--chat-composer-glass-surface);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
resolveThreadActionProjectRef,
|
||||
resolveNewDraftStartFromOrigin,
|
||||
startNewLocalThreadFromContext,
|
||||
startNewThreadFromContext,
|
||||
startNewThreadInProjectFromContext,
|
||||
type ChatThreadActionContext,
|
||||
} from "./chatThreadActions";
|
||||
|
||||
@@ -40,16 +38,25 @@ describe("chatThreadActions", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("prefers the active draft thread project when resolving thread actions", () => {
|
||||
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", () => {
|
||||
const projectRef = resolveThreadActionProjectRef(
|
||||
createContext({
|
||||
activeDraftThread: {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -67,85 +74,17 @@ describe("chatThreadActions", () => {
|
||||
expect(projectRef).toEqual(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID));
|
||||
});
|
||||
|
||||
it("starts a contextual new thread from the active draft thread", async () => {
|
||||
it("inherits only the project from context, never branch or worktree state", 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,13 +5,6 @@ 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 {
|
||||
@@ -26,10 +19,8 @@ interface NewThreadHandler {
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
type NewThreadOptions = NonNullable<Parameters<NewThreadHandler>[1]>;
|
||||
|
||||
export interface ChatThreadActionContext {
|
||||
readonly activeDraftThread: DraftThreadContextLike | null;
|
||||
readonly activeDraftThread: ThreadContextLike | null;
|
||||
readonly activeThread: ThreadContextLike | undefined;
|
||||
readonly defaultProjectRef: ScopedProjectRef | null;
|
||||
readonly handleNewThread: NewThreadHandler;
|
||||
@@ -57,35 +48,12 @@ export function resolveThreadActionProjectRef(
|
||||
return context.defaultProjectRef;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
// 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.
|
||||
export async function startNewThreadFromContext(
|
||||
context: ChatThreadActionContext,
|
||||
): Promise<boolean> {
|
||||
@@ -94,18 +62,6 @@ 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;
|
||||
}
|
||||
@@ -295,6 +295,7 @@ describe("previewStateStore (single-tab)", () => {
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
});
|
||||
const state = readThreadPreviewState(ref);
|
||||
@@ -312,6 +313,7 @@ describe("previewStateStore (single-tab)", () => {
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
});
|
||||
setActivePreviewTab(ref, first.tabId);
|
||||
@@ -357,6 +359,7 @@ describe("previewStateStore (single-tab)", () => {
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
});
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import {
|
||||
type DesktopPreviewColorScheme,
|
||||
type PreviewEvent,
|
||||
type PreviewSessionSnapshot,
|
||||
type ScopedThreadRef,
|
||||
@@ -22,6 +23,7 @@ export interface DesktopPreviewOverlay {
|
||||
canGoForward: boolean;
|
||||
loading: boolean;
|
||||
zoomFactor: number;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,14 @@ import { useEffect } from "react";
|
||||
import ChatView from "../components/ChatView";
|
||||
import { threadHasStarted } from "../components/ChatView.logic";
|
||||
import { finalizePromotedDraftThreadByRef, useComposerDraftStore } from "../composerDraftStore";
|
||||
import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { resolveThreadRouteRef, resolveThreadRouteRenderState } from "../threadRoutes";
|
||||
import { SidebarInset } from "~/components/ui/sidebar";
|
||||
import { useEnvironmentThreadRefs, useThreadDetail, useThreadShell } from "../state/entities";
|
||||
import {
|
||||
useEnvironmentThreadRefs,
|
||||
useThreadDetail,
|
||||
useThreadShell,
|
||||
useThreadStatus,
|
||||
} from "../state/entities";
|
||||
import { useEnvironmentQuery } from "../state/query";
|
||||
import { environmentShell } from "../state/shell";
|
||||
|
||||
@@ -20,9 +25,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,
|
||||
@@ -36,7 +41,13 @@ function ChatThreadRouteView() {
|
||||
}
|
||||
return store.hasDraftThreadsInEnvironment(threadRef.environmentId);
|
||||
});
|
||||
const routeThreadExists = threadExists || draftThreadExists;
|
||||
const renderState = resolveThreadRouteRenderState({
|
||||
bootstrapComplete,
|
||||
serverThreadShellExists: serverThreadShell !== null,
|
||||
serverThreadDetailExists: serverThreadDetail !== null,
|
||||
serverThreadDetailDeleted: serverThreadStatus === "deleted",
|
||||
draftThreadExists,
|
||||
});
|
||||
const serverThreadStarted = threadHasStarted(serverThreadDetail);
|
||||
const environmentHasAnyThreads = environmentHasServerThreads || environmentHasDraftThreads;
|
||||
|
||||
@@ -45,10 +56,10 @@ function ChatThreadRouteView() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!routeThreadExists && environmentHasAnyThreads) {
|
||||
if (renderState === "missing" && environmentHasAnyThreads) {
|
||||
void navigate({ to: "/", replace: true });
|
||||
}
|
||||
}, [bootstrapComplete, environmentHasAnyThreads, navigate, routeThreadExists, threadRef]);
|
||||
}, [bootstrapComplete, environmentHasAnyThreads, navigate, renderState, threadRef]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!threadRef || !serverThreadStarted || !draftThread) {
|
||||
@@ -57,7 +68,7 @@ function ChatThreadRouteView() {
|
||||
finalizePromotedDraftThreadByRef(threadRef);
|
||||
}, [draftThread, serverThreadStarted, threadRef]);
|
||||
|
||||
if (!threadRef || !bootstrapComplete || !routeThreadExists) {
|
||||
if (!threadRef || renderState !== "ready") {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { isCommandPaletteOpen } from "../commandPaletteBus";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { openCommandPalette } from "../commandPaletteBus";
|
||||
import { useProjects } from "../state/entities";
|
||||
import { usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { selectProjectGroupingSettings } from "../logicalProject";
|
||||
import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
|
||||
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import {
|
||||
startNewLocalThreadFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import { startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import { isPreviewFocused } from "../lib/previewFocus";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
@@ -29,7 +29,19 @@ function ChatRouteGlobalShortcuts() {
|
||||
useHandleNewThread();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const projectCount = useProjects().length;
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const projects = useProjects();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const projectGroupCount = useMemo(
|
||||
() =>
|
||||
buildSidebarProjectSnapshots({
|
||||
projects,
|
||||
settings: projectGroupingSettings,
|
||||
primaryEnvironmentId,
|
||||
resolveEnvironmentLabel: () => null,
|
||||
}).length,
|
||||
[primaryEnvironmentId, projectGroupingSettings, projects],
|
||||
);
|
||||
const terminalOpen = useTerminalUiStateStore((state) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
|
||||
@@ -68,7 +80,7 @@ function ChatRouteGlobalShortcuts() {
|
||||
if (command === "chat.newLocal") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void startNewLocalThreadFromContext({
|
||||
void startNewThreadFromContext({
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
@@ -83,7 +95,7 @@ function ChatRouteGlobalShortcuts() {
|
||||
// Sidebar v2 routes creation through the command palette whenever
|
||||
// there is a real choice to make; v1 (and single-project setups)
|
||||
// keep the immediate contextual create.
|
||||
if (sidebarV2Enabled && projectCount > 1) {
|
||||
if (sidebarV2Enabled && projectGroupCount > 1) {
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
return;
|
||||
}
|
||||
@@ -152,7 +164,7 @@ function ChatRouteGlobalShortcuts() {
|
||||
keybindings,
|
||||
defaultProjectRef,
|
||||
previewOpen,
|
||||
projectCount,
|
||||
projectGroupCount,
|
||||
routeThreadRef,
|
||||
selectedThreadKeysSize,
|
||||
sidebarV2Enabled,
|
||||
|
||||
@@ -4,7 +4,10 @@ import type {
|
||||
EnvironmentThread,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { mergeEnvironmentThread } from "@t3tools/client-runtime/state/threads";
|
||||
import {
|
||||
type EnvironmentThreadStatus,
|
||||
mergeEnvironmentThread,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import type {
|
||||
OrchestrationMessage,
|
||||
OrchestrationProposedPlan,
|
||||
@@ -44,6 +47,9 @@ const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).p
|
||||
const EMPTY_THREAD_DETAIL_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
|
||||
Atom.withLabel("web-thread-detail:empty"),
|
||||
);
|
||||
const EMPTY_THREAD_STATUS_ATOM = Atom.make<EnvironmentThreadStatus>("empty").pipe(
|
||||
Atom.withLabel("web-thread-status:empty"),
|
||||
);
|
||||
const EMPTY_MESSAGES_ATOM = Atom.make(EMPTY_MESSAGES).pipe(
|
||||
Atom.withLabel("web-thread-messages:empty"),
|
||||
);
|
||||
@@ -140,6 +146,12 @@ export function useThreadDetail(ref: ScopedThreadRef | null): EnvironmentThread
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
/** Detail collections composed with shell-authoritative thread/workspace metadata. */
|
||||
export function useThread(ref: ScopedThreadRef | null): EnvironmentThread | null {
|
||||
const shell = useThreadShell(ref);
|
||||
@@ -195,6 +207,15 @@ export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId):
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the environment's server understands thread.snooze/unsnooze.
|
||||
Same version-skew contract as settlement. */
|
||||
export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSnooze === true
|
||||
);
|
||||
}
|
||||
|
||||
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
|
||||
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
buildDraftThreadRouteParams,
|
||||
buildThreadRouteParams,
|
||||
resolveActiveThreadRouteRef,
|
||||
resolveThreadRouteRenderState,
|
||||
resolveThreadRouteRef,
|
||||
resolveThreadRouteTarget,
|
||||
} from "./threadRoutes";
|
||||
@@ -92,4 +93,70 @@ describe("threadRoutes", () => {
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps shell-only server threads in the loading state", () => {
|
||||
expect(
|
||||
resolveThreadRouteRenderState({
|
||||
bootstrapComplete: true,
|
||||
serverThreadShellExists: true,
|
||||
serverThreadDetailExists: false,
|
||||
serverThreadDetailDeleted: false,
|
||||
draftThreadExists: false,
|
||||
}),
|
||||
).toBe("loading");
|
||||
});
|
||||
|
||||
it("renders server details and local drafts when they are ready", () => {
|
||||
expect(
|
||||
resolveThreadRouteRenderState({
|
||||
bootstrapComplete: true,
|
||||
serverThreadShellExists: true,
|
||||
serverThreadDetailExists: true,
|
||||
serverThreadDetailDeleted: false,
|
||||
draftThreadExists: false,
|
||||
}),
|
||||
).toBe("ready");
|
||||
expect(
|
||||
resolveThreadRouteRenderState({
|
||||
bootstrapComplete: true,
|
||||
serverThreadShellExists: false,
|
||||
serverThreadDetailExists: false,
|
||||
serverThreadDetailDeleted: false,
|
||||
draftThreadExists: true,
|
||||
}),
|
||||
).toBe("ready");
|
||||
});
|
||||
|
||||
it("distinguishes bootstrap loading from a missing thread", () => {
|
||||
expect(
|
||||
resolveThreadRouteRenderState({
|
||||
bootstrapComplete: false,
|
||||
serverThreadShellExists: false,
|
||||
serverThreadDetailExists: false,
|
||||
serverThreadDetailDeleted: false,
|
||||
draftThreadExists: false,
|
||||
}),
|
||||
).toBe("loading");
|
||||
expect(
|
||||
resolveThreadRouteRenderState({
|
||||
bootstrapComplete: true,
|
||||
serverThreadShellExists: false,
|
||||
serverThreadDetailExists: false,
|
||||
serverThreadDetailDeleted: false,
|
||||
draftThreadExists: false,
|
||||
}),
|
||||
).toBe("missing");
|
||||
});
|
||||
|
||||
it("redirects deleted shell-only threads", () => {
|
||||
expect(
|
||||
resolveThreadRouteRenderState({
|
||||
bootstrapComplete: true,
|
||||
serverThreadShellExists: true,
|
||||
serverThreadDetailExists: false,
|
||||
serverThreadDetailDeleted: true,
|
||||
draftThreadExists: false,
|
||||
}),
|
||||
).toBe("missing");
|
||||
});
|
||||
});
|
||||
@@ -18,6 +18,27 @@ type DraftThreadRouteState = {
|
||||
promotedTo?: ScopedThreadRef | null;
|
||||
};
|
||||
|
||||
export type ThreadRouteRenderState = "loading" | "ready" | "missing";
|
||||
|
||||
export function resolveThreadRouteRenderState(input: {
|
||||
bootstrapComplete: boolean;
|
||||
serverThreadShellExists: boolean;
|
||||
serverThreadDetailExists: boolean;
|
||||
serverThreadDetailDeleted: boolean;
|
||||
draftThreadExists: boolean;
|
||||
}): ThreadRouteRenderState {
|
||||
if (!input.bootstrapComplete) {
|
||||
return "loading";
|
||||
}
|
||||
if (input.serverThreadDetailExists || input.draftThreadExists) {
|
||||
return "ready";
|
||||
}
|
||||
if (input.serverThreadDetailDeleted) {
|
||||
return "missing";
|
||||
}
|
||||
return input.serverThreadShellExists ? "loading" : "missing";
|
||||
}
|
||||
|
||||
export function buildThreadRouteParams(ref: ScopedThreadRef): {
|
||||
environmentId: EnvironmentId;
|
||||
threadId: ThreadId;
|
||||
|
||||
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user