Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0aed107dc | ||
|
|
b5281f994e | ||
|
|
5c8504d602 | ||
|
|
d3d096c6f7 | ||
|
|
c9b07d665d | ||
|
|
2e42f3fdf6 | ||
|
|
008ac5c3e5 | ||
|
|
9dcea68bce | ||
|
|
5f7ec73a22 | ||
|
|
569fea87a9 | ||
|
|
33dadb5aec | ||
|
|
d18e43b674 | ||
|
|
6f699346e4 | ||
|
|
f5ecca4480 | ||
|
|
cadd708646 | ||
|
|
5f7becf386 | ||
|
|
9b29be916b | ||
|
|
047a0a697c | ||
|
|
77fcad3586 | ||
|
|
801b83e937 | ||
|
|
f2205bdc42 | ||
|
|
1bf048eb8b | ||
|
|
f7fa62aaf9 | ||
|
|
57d7746a5d | ||
|
|
850c912556 | ||
|
|
dff8784aef | ||
|
|
96c9306dbd | ||
|
|
94d13a2b75 | ||
|
|
7a008461fc | ||
|
|
f59ee36bf1 | ||
|
|
2fce84a1d4 | ||
|
|
f9019cd63f | ||
|
|
f9372a4c3d | ||
|
|
934037cb66 |
No files matched your search
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
@@ -50,6 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `commandPalette.toggle`: open or close the global command palette
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
|
||||
@@ -49,6 +49,14 @@ Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Before local development, prepare the environment and install dependencies:
|
||||
|
||||
```bash
|
||||
# Optional: only needed if you use mise for dev tool management.
|
||||
mise install
|
||||
bun install .
|
||||
```
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
} from "./backendReadiness";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend reports a successful session endpoint", async () => {
|
||||
it("returns once the backend serves the requested readiness path", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
@@ -20,6 +20,11 @@ describe("waitForHttpReady", () => {
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("retries after a readiness request stalls past the per-request timeout", async () => {
|
||||
@@ -80,4 +85,30 @@ describe("waitForHttpReady", () => {
|
||||
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
|
||||
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
|
||||
});
|
||||
|
||||
it("supports custom readiness predicates", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
path: "/api/healthz",
|
||||
isReady: (response) => response.status === 204,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,11 @@ export interface WaitForHttpReadyOptions {
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly fetchImpl?: typeof fetch;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly path?: string;
|
||||
readonly isReady?: (response: Response) => boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_INTERVAL_MS = 100;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
|
||||
|
||||
@@ -57,6 +59,8 @@ export async function waitForHttpReady(
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
|
||||
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
const readinessPath = options?.path ?? "/";
|
||||
const isReady = options?.isReady ?? ((response: Response) => response.ok);
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
for (;;) {
|
||||
@@ -74,11 +78,11 @@ export async function waitForHttpReady(
|
||||
signal?.addEventListener("abort", abortRequest, { once: true });
|
||||
|
||||
try {
|
||||
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
|
||||
const response = await fetchImpl(new URL(readinessPath, baseUrl).toString(), {
|
||||
redirect: "manual",
|
||||
signal: requestController.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
if (isReady(response)) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
+188
-35
@@ -7,6 +7,7 @@ import * as Path from "node:path";
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
type BrowserWindowConstructorOptions,
|
||||
clipboard,
|
||||
dialog,
|
||||
ipcMain,
|
||||
@@ -54,6 +55,7 @@ import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
@@ -100,7 +102,7 @@ const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
||||
@@ -118,6 +120,15 @@ const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
BrowserWindowConstructorOptions,
|
||||
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
|
||||
>;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
type LinuxDesktopNamedApp = Electron.App & {
|
||||
@@ -134,6 +145,8 @@ let backendWsUrl = "";
|
||||
let backendEndpointUrl: string | null = null;
|
||||
let backendAdvertisedHost: string | null = null;
|
||||
let backendReadinessAbortController: AbortController | null = null;
|
||||
let backendInitialWindowOpenInFlight: Promise<void> | null = null;
|
||||
let backendListeningDetector: ServerListeningDetector | null = null;
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
@@ -352,13 +365,17 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
|
||||
async function waitForBackendHttpReady(
|
||||
baseUrl: string,
|
||||
options?: Parameters<typeof waitForHttpReady>[1],
|
||||
): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
const controller = new AbortController();
|
||||
backendReadinessAbortController = controller;
|
||||
|
||||
try {
|
||||
await waitForHttpReady(baseUrl, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
@@ -373,6 +390,88 @@ function cancelBackendReadinessWait(): void {
|
||||
backendReadinessAbortController = null;
|
||||
}
|
||||
|
||||
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
const listeningPromise = backendListeningDetector?.promise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
cancelBackendReadinessWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function ensureInitialBackendWindowOpen(): void {
|
||||
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0] ?? null;
|
||||
if (isDevelopment || existingWindow !== null || backendInitialWindowOpenInFlight !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextOpen = waitForBackendWindowReady(backendHttpUrl)
|
||||
.then((source) => {
|
||||
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
|
||||
if (mainWindow ?? BrowserWindow.getAllWindows()[0]) {
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
|
||||
);
|
||||
console.warn("[desktop] backend readiness check timed out during packaged bootstrap", error);
|
||||
})
|
||||
.finally(() => {
|
||||
if (backendInitialWindowOpenInFlight === nextOpen) {
|
||||
backendInitialWindowOpenInFlight = null;
|
||||
}
|
||||
});
|
||||
|
||||
backendInitialWindowOpenInFlight = nextOpen;
|
||||
}
|
||||
|
||||
function writeDesktopStreamChunk(
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: unknown,
|
||||
@@ -450,14 +549,16 @@ function initializePackagedLogging(): void {
|
||||
}
|
||||
|
||||
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
if (!app.isPackaged || backendLogSink === null) return;
|
||||
const writeChunk = (chunk: unknown): void => {
|
||||
if (!backendLogSink) return;
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink.write(buffer);
|
||||
const attachStream = (stream: NodeJS.ReadableStream | null | undefined): void => {
|
||||
stream?.on("data", (chunk: unknown) => {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink?.write(buffer);
|
||||
backendListeningDetector?.push(buffer);
|
||||
});
|
||||
};
|
||||
child.stdout?.on("data", writeChunk);
|
||||
child.stderr?.on("data", writeChunk);
|
||||
|
||||
attachStream(child.stdout);
|
||||
attachStream(child.stderr);
|
||||
}
|
||||
|
||||
initializePackagedLogging();
|
||||
@@ -1212,7 +1313,7 @@ function startBackend(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const captureBackendLogs = !isDevelopment;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
@@ -1249,6 +1350,8 @@ function startBackend(): void {
|
||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
||||
return;
|
||||
}
|
||||
const listeningDetector = new ServerListeningDetector();
|
||||
backendListeningDetector = listeningDetector;
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
@@ -1267,6 +1370,10 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(error);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1279,6 +1386,14 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(
|
||||
new Error(
|
||||
`backend exited before logging readiness (code=${code ?? "null"} signal=${signal ?? "null"})`,
|
||||
),
|
||||
);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1290,10 +1405,13 @@ function startBackend(): void {
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
});
|
||||
|
||||
ensureInitialBackendWindowOpen();
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
cancelBackendReadinessWait();
|
||||
backendListeningDetector = null;
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1649,19 +1767,58 @@ function getInitialWindowBackgroundColor(): string {
|
||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
titleBarStyle: "hidden",
|
||||
titleBarOverlay: {
|
||||
color: TITLEBAR_COLOR,
|
||||
height: TITLEBAR_HEIGHT,
|
||||
symbolColor: nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function syncWindowAppearance(window: BrowserWindow): void {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor());
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions();
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
}
|
||||
|
||||
function syncAllWindowAppearance(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
syncWindowAppearance(window);
|
||||
}
|
||||
}
|
||||
|
||||
nativeTheme.on("updated", syncAllWindowAppearance);
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: isDevelopment,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
...getWindowTitleBarOptions(),
|
||||
webPreferences: {
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
@@ -1730,20 +1887,23 @@ function createWindow(): BrowserWindow {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
if (!isDevelopment) {
|
||||
window.once("ready-to-show", () => {
|
||||
revealWindow(window);
|
||||
});
|
||||
}
|
||||
|
||||
let initialRevealScheduled = false;
|
||||
const revealInitialWindow = () => {
|
||||
if (initialRevealScheduled) {
|
||||
return;
|
||||
}
|
||||
initialRevealScheduled = true;
|
||||
revealWindow(window);
|
||||
};
|
||||
|
||||
window.once("ready-to-show", revealInitialWindow);
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
setImmediate(() => {
|
||||
revealWindow(window);
|
||||
});
|
||||
} else {
|
||||
void window.loadURL(resolveDesktopWindowUrl());
|
||||
void window.loadURL(backendHttpUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -1755,14 +1915,6 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
function resolveDesktopWindowUrl(): string {
|
||||
if (backendHttpUrl) {
|
||||
return backendHttpUrl;
|
||||
}
|
||||
|
||||
return `${DESKTOP_SCHEME}://app`;
|
||||
}
|
||||
|
||||
// Override Electron's userData path before the `ready` event so that
|
||||
// Chromium session data uses a filesystem-friendly directory name.
|
||||
// Must be called synchronously at the top level — before `app.whenReady()`.
|
||||
@@ -1836,10 +1988,7 @@ async function bootstrap(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
await waitForBackendHttpReady(backendHttpUrl);
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
ensureInitialBackendWindowOpen();
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
@@ -1873,7 +2022,11 @@ app
|
||||
revealWindow(existingWindow);
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
return;
|
||||
}
|
||||
ensureInitialBackendWindowOpen();
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
|
||||
describe("ServerListeningDetector", () => {
|
||||
it("resolves when the server logs the listening line", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listening on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves when the listening line arrives across multiple chunks", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listen");
|
||||
detector.push("ing on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects when the server exits before logging readiness", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
const error = new Error("server exited");
|
||||
|
||||
detector.fail(error);
|
||||
|
||||
await expect(detector.promise).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
const LISTENING_LOG_FRAGMENT = "Listening on http://";
|
||||
const MAX_BUFFER_CHARS = 8_192;
|
||||
|
||||
export class ServerListeningDetector {
|
||||
private buffer = "";
|
||||
private settled = false;
|
||||
private readonly resolvePromise: () => void;
|
||||
private readonly rejectPromise: (error: unknown) => void;
|
||||
readonly promise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
let resolvePromise: (() => void) | null = null;
|
||||
let rejectPromise: ((error: unknown) => void) | null = null;
|
||||
|
||||
this.promise = new Promise<void>((resolve, reject) => {
|
||||
resolvePromise = resolve;
|
||||
rejectPromise = reject;
|
||||
});
|
||||
|
||||
this.resolvePromise = () => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
resolvePromise?.();
|
||||
};
|
||||
this.rejectPromise = (error) => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
rejectPromise?.(error);
|
||||
};
|
||||
}
|
||||
|
||||
push(chunk: unknown): void {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
|
||||
this.buffer = `${this.buffer}${text.replace(/\r/g, "")}`;
|
||||
if (this.buffer.includes(LISTENING_LOG_FRAGMENT)) {
|
||||
this.resolvePromise();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.buffer.length > MAX_BUFFER_CHARS) {
|
||||
this.buffer = this.buffer.slice(-MAX_BUFFER_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
fail(error: unknown): void {
|
||||
this.rejectPromise(error);
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,12 @@ describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
HOMEBREW_PREFIX: "/opt/homebrew",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
@@ -18,9 +19,18 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
expect(env.HOMEBREW_PREFIX).toBe("/opt/homebrew");
|
||||
});
|
||||
|
||||
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
||||
@@ -77,11 +87,67 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing does not return one", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => ({}));
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "darwin",
|
||||
readEnvironment,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(2, "/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read login shell environment from /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
|
||||
@@ -1,36 +1,79 @@
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const;
|
||||
|
||||
function logShellEnvironmentWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[desktop] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
options: {
|
||||
platform?: NodeJS.Platform;
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
|
||||
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
|
||||
const shellEnvironment: Partial<Record<string, string>> = {};
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
|
||||
if (shellEnvironment.PATH) {
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read login shell environment from ${shell}.`, error);
|
||||
}
|
||||
}
|
||||
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
]);
|
||||
|
||||
if (shellEnvironment.PATH) {
|
||||
env.PATH = shellEnvironment.PATH;
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellEnvironment.PATH
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellEnvironment.PATH ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
|
||||
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
||||
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
} catch {
|
||||
// Keep inherited environment if shell lookup fails.
|
||||
|
||||
for (const name of [
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const) {
|
||||
if (!env[name] && shellEnvironment[name]) {
|
||||
env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to synchronize the desktop shell environment.", error);
|
||||
}
|
||||
}
|
||||
@@ -82,10 +82,15 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -136,10 +141,15 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -24,6 +24,7 @@ export interface ServerDerivedPaths {
|
||||
readonly dbPath: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly settingsPath: string;
|
||||
readonly providerStatusCacheDir: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly logsDir: string;
|
||||
@@ -76,11 +77,13 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
const providerLogsDir = join(logsDir, "provider");
|
||||
const providerStatusCacheDir = join(baseDir, "caches");
|
||||
return {
|
||||
stateDir,
|
||||
dbPath,
|
||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||
settingsPath: join(stateDir, "settings.json"),
|
||||
providerStatusCacheDir,
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
@@ -110,6 +113,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
|
||||
],
|
||||
|
||||
@@ -826,7 +826,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
|
||||
it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
@@ -845,7 +845,9 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
@@ -856,10 +858,22 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
expect(input.cwd).toBe("/repo");
|
||||
expect(input.args).toEqual([
|
||||
"--git-dir",
|
||||
"/repo/.git",
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
]);
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
@@ -886,70 +900,80 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
it.effect(
|
||||
"briefly backs off failed upstream refreshes across sibling worktrees on one remote",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "origin/feature/pr-123\n"
|
||||
: "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when branch does not exist", () =>
|
||||
@@ -1047,7 +1071,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
remoteName,
|
||||
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -78,11 +78,9 @@ type TraceTailState = {
|
||||
remainder: string;
|
||||
};
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
class StatusRemoteRefreshCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
upstreamRef: string;
|
||||
remoteName: string;
|
||||
upstreamBranch: string;
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
@@ -919,17 +917,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
);
|
||||
});
|
||||
|
||||
const fetchUpstreamRefForStatus = (
|
||||
const fetchRemoteForStatus = (
|
||||
gitCommonDir: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
remoteName: string,
|
||||
): Effect.Effect<void, GitCommandError> => {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
const fetchCwd =
|
||||
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
|
||||
return executeGit(
|
||||
"GitCore.fetchUpstreamRefForStatus",
|
||||
"GitCore.fetchRemoteForStatus",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
@@ -945,18 +942,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
|
||||
});
|
||||
|
||||
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
|
||||
cacheKey: StatusUpstreamRefreshCacheKey,
|
||||
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
|
||||
cacheKey: StatusRemoteRefreshCacheKey,
|
||||
) {
|
||||
yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
|
||||
upstreamRef: cacheKey.upstreamRef,
|
||||
remoteName: cacheKey.remoteName,
|
||||
upstreamBranch: cacheKey.upstreamBranch,
|
||||
});
|
||||
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
|
||||
return true as const;
|
||||
});
|
||||
|
||||
const statusUpstreamRefreshCache = yield* Cache.makeWith(refreshStatusUpstreamCacheEntry, {
|
||||
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
|
||||
timeToLive: (exit) =>
|
||||
@@ -972,12 +965,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
if (!upstream) return;
|
||||
const gitCommonDir = yield* resolveGitCommonDir(cwd);
|
||||
yield* Cache.get(
|
||||
statusUpstreamRefreshCache,
|
||||
new StatusUpstreamRefreshCacheKey({
|
||||
statusRemoteRefreshCache,
|
||||
new StatusRemoteRefreshCacheKey({
|
||||
gitCommonDir,
|
||||
upstreamRef: upstream.upstreamRef,
|
||||
remoteName: upstream.remoteName,
|
||||
upstreamBranch: upstream.upstreamBranch,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -226,6 +226,7 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
@@ -188,6 +188,21 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const),
|
||||
);
|
||||
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.splitRight"), "mod+d");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.splitDown"), "mod+shift+d");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.close"), "mod+w");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.previous"), "mod+[");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.next"), "mod+]");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.left"), "mod+alt+arrowleft");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.right"), "mod+alt+arrowright");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.up"), "mod+alt+arrowup");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.down"), "mod+alt+arrowdown");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.toggleZoom"), "mod+shift+enter");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.resizeLeft"), "mod+ctrl+arrowleft");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.resizeRight"), "mod+ctrl+arrowright");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.resizeUp"), "mod+ctrl+arrowup");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.resizeDown"), "mod+ctrl+arrowdown");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.equalize"), "mod+ctrl+=");
|
||||
assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+[");
|
||||
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
|
||||
@@ -60,7 +60,23 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+d", command: "workspace.pane.splitRight", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+d", command: "workspace.pane.splitDown", when: "!terminalFocus" },
|
||||
{ key: "mod+w", command: "workspace.pane.close", when: "!terminalFocus" },
|
||||
{ key: "mod+[", command: "workspace.focus.previous" },
|
||||
{ key: "mod+]", command: "workspace.focus.next" },
|
||||
{ key: "mod+alt+arrowup", command: "workspace.focus.up" },
|
||||
{ key: "mod+alt+arrowdown", command: "workspace.focus.down" },
|
||||
{ key: "mod+alt+arrowleft", command: "workspace.focus.left" },
|
||||
{ key: "mod+alt+arrowright", command: "workspace.focus.right" },
|
||||
{ key: "mod+shift+enter", command: "workspace.pane.toggleZoom" },
|
||||
{ key: "mod+ctrl+arrowup", command: "workspace.pane.resizeUp" },
|
||||
{ key: "mod+ctrl+arrowdown", command: "workspace.pane.resizeDown" },
|
||||
{ key: "mod+ctrl+arrowleft", command: "workspace.pane.resizeLeft" },
|
||||
{ key: "mod+ctrl+arrowright", command: "workspace.pane.resizeRight" },
|
||||
{ key: "mod+ctrl+=", command: "workspace.pane.equalize" },
|
||||
{ key: "mod+alt+d", command: "diff.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
|
||||
@@ -42,6 +42,16 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const kiroLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLaunch, {
|
||||
command: "kiro",
|
||||
args: ["ide", "/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -122,6 +132,16 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const kiroLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLineAndColumn, {
|
||||
command: "kiro",
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -354,6 +374,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "kiro.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
@@ -361,7 +382,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, ["trae", "kiro", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
+19
-6
@@ -75,6 +75,14 @@ function resolveCommandEditorArgs(
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
@@ -273,7 +281,7 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
|
||||
return {
|
||||
command,
|
||||
args: resolveCommandEditorArgs(editorDef, input.cwd),
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -293,11 +301,16 @@ export const launchDetached = (launch: EditorLaunch) =>
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const isWin32 = process.platform === "win32";
|
||||
child = spawn(
|
||||
launch.command,
|
||||
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
|
||||
{
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: isWin32,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
|
||||
@@ -144,10 +144,20 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.succeed(projectionSnapshot),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: projectionSnapshot.snapshotSequence,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: projectionSnapshot.updatedAt,
|
||||
}),
|
||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
|
||||
@@ -1505,6 +1505,329 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears stale pending approvals from projected shell summaries", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-stale-approval-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:00.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-stale-approval"),
|
||||
title: "Project Stale Approval",
|
||||
workspaceRoot: "/tmp/project-stale-approval",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:30:00.000Z",
|
||||
updatedAt: "2026-02-26T12:30:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-stale-approval-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:01.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-approval"),
|
||||
projectId: ProjectId.make("project-stale-approval"),
|
||||
title: "Thread Stale Approval",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:30:01.000Z",
|
||||
updatedAt: "2026-02-26T12:30:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-approval-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:02.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-approval-requested"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: {
|
||||
requestId: "approval-request-stale-1",
|
||||
requestKind: "command",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:30:02.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-approval-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:03.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-approval-failed"),
|
||||
tone: "error",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
payload: {
|
||||
requestId: "approval-request-stale-1",
|
||||
detail: "Unknown pending permission request: approval-request-stale-1",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:30:03.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly requestId: string;
|
||||
readonly status: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
request_id AS "requestId",
|
||||
status,
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id = 'approval-request-stale-1'
|
||||
`;
|
||||
assert.deepEqual(approvalRows, [
|
||||
{
|
||||
requestId: "approval-request-stale-1",
|
||||
status: "resolved",
|
||||
resolvedAt: "2026-02-26T12:30:03.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly pendingApprovalCount: number;
|
||||
}>`
|
||||
SELECT pending_approval_count AS "pendingApprovalCount"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-stale-approval'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [{ pendingApprovalCount: 0 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores non-stale provider approval response failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-nonstale-approval-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:00.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-nonstale-approval"),
|
||||
title: "Project Non-Stale Approval",
|
||||
workspaceRoot: "/tmp/project-nonstale-approval",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:45:00.000Z",
|
||||
updatedAt: "2026-02-26T12:45:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-nonstale-approval-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:01.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
projectId: ProjectId.make("project-nonstale-approval"),
|
||||
title: "Thread Non-Stale Approval",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:45:01.000Z",
|
||||
updatedAt: "2026-02-26T12:45:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-nonstale-approval-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:02.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-nonstale-approval-requested"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: {
|
||||
requestId: "approval-request-nonstale-existing",
|
||||
requestKind: "command",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:45:02.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-nonstale-approval-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:03.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-nonstale-approval-failed-existing"),
|
||||
tone: "error",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
payload: {
|
||||
requestId: "approval-request-nonstale-existing",
|
||||
detail: "Provider timed out while responding to approval request",
|
||||
},
|
||||
turnId: TurnId.make("turn-nonstale-failure"),
|
||||
createdAt: "2026-02-26T12:45:03.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-nonstale-approval-5"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:04.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-5"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-5"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-nonstale-approval-failed-missing"),
|
||||
tone: "error",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
payload: {
|
||||
requestId: "approval-request-nonstale-missing",
|
||||
detail: "Provider timed out while responding to approval request",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:45:04.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly requestId: string;
|
||||
readonly status: string;
|
||||
readonly turnId: string | null;
|
||||
readonly createdAt: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
request_id AS "requestId",
|
||||
status,
|
||||
turn_id AS "turnId",
|
||||
created_at AS "createdAt",
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id IN (
|
||||
'approval-request-nonstale-existing',
|
||||
'approval-request-nonstale-missing'
|
||||
)
|
||||
ORDER BY request_id
|
||||
`;
|
||||
assert.deepEqual(approvalRows, [
|
||||
{
|
||||
requestId: "approval-request-nonstale-existing",
|
||||
status: "pending",
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:45:02.000Z",
|
||||
resolvedAt: null,
|
||||
},
|
||||
]);
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly pendingApprovalCount: number;
|
||||
}>`
|
||||
SELECT pending_approval_count AS "pendingApprovalCount"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-nonstale-approval'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [{ pendingApprovalCount: 1 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not fallback-retain messages whose turnId is removed by revert", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -89,6 +90,88 @@ function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||
return typeof requestId === "string" ? ApprovalRequestId.make(requestId) : null;
|
||||
}
|
||||
|
||||
function isStalePendingApprovalFailureDetail(detail: string | null): boolean {
|
||||
if (detail === null) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
detail.includes("stale pending approval request") ||
|
||||
detail.includes("unknown pending approval request") ||
|
||||
detail.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
|
||||
function derivePendingUserInputCountFromActivities(
|
||||
activities: ReadonlyArray<ProjectionThreadActivity>,
|
||||
): number {
|
||||
const openRequestIds = new Set<string>();
|
||||
const ordered = [...activities].toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.activityId.localeCompare(right.activityId),
|
||||
);
|
||||
|
||||
for (const activity of ordered) {
|
||||
const requestId = extractActivityRequestId(activity.payload);
|
||||
if (requestId === null) {
|
||||
continue;
|
||||
}
|
||||
const payload =
|
||||
typeof activity.payload === "object" && activity.payload !== null
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
|
||||
if (activity.kind === "user-input.requested") {
|
||||
openRequestIds.add(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (activity.kind === "user-input.resolved") {
|
||||
openRequestIds.delete(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
activity.kind === "provider.user-input.respond.failed" &&
|
||||
detail !== null &&
|
||||
(detail.includes("stale pending user-input request") ||
|
||||
detail.includes("unknown pending user-input request"))
|
||||
) {
|
||||
openRequestIds.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
return openRequestIds.size;
|
||||
}
|
||||
|
||||
function deriveHasActionableProposedPlan(input: {
|
||||
readonly latestTurnId: string | null;
|
||||
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
|
||||
}): boolean {
|
||||
const sorted = [...input.proposedPlans].toSorted(
|
||||
(left, right) =>
|
||||
left.updatedAt.localeCompare(right.updatedAt) || left.planId.localeCompare(right.planId),
|
||||
);
|
||||
|
||||
let latestForTurn: ProjectionThreadProposedPlan | null = null;
|
||||
if (input.latestTurnId !== null) {
|
||||
for (let index = sorted.length - 1; index >= 0; index -= 1) {
|
||||
const plan = sorted[index];
|
||||
if (plan?.turnId === input.latestTurnId) {
|
||||
latestForTurn = plan;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (latestForTurn !== null) {
|
||||
return latestForTurn.implementedAt === null;
|
||||
}
|
||||
|
||||
const latestPlan = sorted.at(-1) ?? null;
|
||||
return latestPlan !== null && latestPlan.implementedAt === null;
|
||||
}
|
||||
|
||||
function retainProjectionMessagesAfterRevert(
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
turns: ReadonlyArray<ProjectionTurn>,
|
||||
@@ -432,6 +515,48 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const refreshThreadShellSummary = Effect.fn("refreshThreadShellSummary")(function* (
|
||||
threadId: ThreadId,
|
||||
) {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [messages, proposedPlans, activities, pendingApprovals] = yield* Effect.all([
|
||||
projectionThreadMessageRepository.listByThreadId({ threadId }),
|
||||
projectionThreadProposedPlanRepository.listByThreadId({ threadId }),
|
||||
projectionThreadActivityRepository.listByThreadId({ threadId }),
|
||||
projectionPendingApprovalRepository.listByThreadId({ threadId }),
|
||||
]);
|
||||
|
||||
const latestUserMessageAt =
|
||||
messages
|
||||
.filter((message) => message.role === "user")
|
||||
.map((message) => message.createdAt)
|
||||
.toSorted()
|
||||
.at(-1) ?? null;
|
||||
|
||||
const pendingApprovalCount = pendingApprovals.filter(
|
||||
(approval) => approval.status === "pending",
|
||||
).length;
|
||||
const pendingUserInputCount = derivePendingUserInputCountFromActivities(activities);
|
||||
const hasActionableProposedPlan = deriveHasActionableProposedPlan({
|
||||
latestTurnId: existingRow.value.latestTurnId,
|
||||
proposedPlans,
|
||||
});
|
||||
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestUserMessageAt,
|
||||
pendingApprovalCount,
|
||||
pendingUserInputCount,
|
||||
hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0,
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadsProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
@@ -450,6 +575,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
return;
|
||||
@@ -554,7 +683,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.activity-appended": {
|
||||
case "thread.activity-appended":
|
||||
case "thread.approval-response-requested":
|
||||
case "thread.user-input-response-requested": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
@@ -565,6 +696,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
...existingRow.value,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -580,6 +712,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.session.activeTurnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -595,6 +728,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.turnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -610,6 +744,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: null,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1121,6 +1256,34 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.payload.activity.kind === "provider.approval.respond.failed") {
|
||||
const payload =
|
||||
typeof event.payload.activity.payload === "object" &&
|
||||
event.payload.activity.payload !== null
|
||||
? (event.payload.activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail =
|
||||
typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
if (isStalePendingApprovalFailureDetail(detail)) {
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
if (existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
yield* projectionPendingApprovalRepository.upsert({
|
||||
requestId,
|
||||
threadId: existingRow.value.threadId,
|
||||
turnId: existingRow.value.turnId,
|
||||
status: "resolved",
|
||||
decision: null,
|
||||
createdAt: existingRow.value.createdAt,
|
||||
resolvedAt: event.payload.activity.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -62,9 +62,15 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
@@ -74,9 +80,15 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:04.000Z',
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
'2026-02-24T00:00:02.000Z',
|
||||
'2026-02-24T00:00:03.000Z',
|
||||
NULL
|
||||
@@ -341,6 +353,81 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.equal(shellSnapshot.snapshotSequence, 5);
|
||||
assert.deepEqual(shellSnapshot.projects, [
|
||||
{
|
||||
id: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
name: "Build",
|
||||
command: "bun run build",
|
||||
icon: "build",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
updatedAt: "2026-02-24T00:00:01.000Z",
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(shellSnapshot.threads, [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
turnId: asTurnId("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-24T00:00:08.000Z",
|
||||
startedAt: "2026-02-24T00:00:08.000Z",
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
assistantMessageId: asMessageId("message-1"),
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
planId: "plan-1",
|
||||
},
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||
},
|
||||
latestUserMessageAt: "2026-02-24T00:00:04.000Z",
|
||||
hasPendingApprovals: true,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -629,4 +716,309 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps thread detail activity ordering consistent with shell snapshot ordering", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_thread_activities`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-01T00:00:00.000Z',
|
||||
'2026-04-01T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-01T00:00:02.000Z',
|
||||
'2026-04-01T00:00:03.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'activity-unsequenced',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'unsequenced first',
|
||||
'{"source":"unsequenced"}',
|
||||
NULL,
|
||||
'2026-04-01T00:00:06.000Z'
|
||||
),
|
||||
(
|
||||
'activity-sequence-2',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'sequence two',
|
||||
'{"source":"sequence-2"}',
|
||||
2,
|
||||
'2026-04-01T00:00:04.000Z'
|
||||
),
|
||||
(
|
||||
'activity-sequence-1',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'sequence one',
|
||||
'{"source":"sequence-1"}',
|
||||
1,
|
||||
'2026-04-01T00:00:05.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
const snapshot = yield* snapshotQuery.getSnapshot();
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.deepEqual(threadDetail.value.activities, snapshot.threads[0]?.activities ?? []);
|
||||
}
|
||||
|
||||
assert.deepEqual(snapshot.threads[0]?.activities ?? [], [
|
||||
{
|
||||
id: asEventId("activity-unsequenced"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "unsequenced first",
|
||||
payload: { source: "unsequenced" },
|
||||
turnId: null,
|
||||
createdAt: "2026-04-01T00:00:06.000Z",
|
||||
},
|
||||
{
|
||||
id: asEventId("activity-sequence-1"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "sequence one",
|
||||
payload: { source: "sequence-1" },
|
||||
turnId: null,
|
||||
sequence: 1,
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
},
|
||||
{
|
||||
id: asEventId("activity-sequence-2"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "sequence two",
|
||||
payload: { source: "sequence-2" },
|
||||
turnId: null,
|
||||
sequence: 2,
|
||||
createdAt: "2026-04-01T00:00:04.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses projection_threads.latest_turn_id for targeted thread latest turn queries", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-02T00:00:00.000Z',
|
||||
'2026-04-02T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-running',
|
||||
'2026-04-02T00:00:04.000Z',
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-02T00:00:02.000Z',
|
||||
'2026-04-02T00:00:03.000Z',
|
||||
NULL,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_turns (
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
started_at,
|
||||
completed_at,
|
||||
checkpoint_turn_count,
|
||||
checkpoint_ref,
|
||||
checkpoint_status,
|
||||
checkpoint_files_json
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'thread-1',
|
||||
'turn-completed',
|
||||
'message-user-1',
|
||||
NULL,
|
||||
NULL,
|
||||
'message-assistant-1',
|
||||
'completed',
|
||||
'2026-04-02T00:00:05.000Z',
|
||||
'2026-04-02T00:00:06.000Z',
|
||||
'2026-04-02T00:00:20.000Z',
|
||||
5,
|
||||
'checkpoint-5',
|
||||
'ready',
|
||||
'[]'
|
||||
),
|
||||
(
|
||||
'thread-1',
|
||||
'turn-running',
|
||||
'message-user-2',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'running',
|
||||
'2026-04-02T00:00:30.000Z',
|
||||
'2026-04-02T00:00:30.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
)
|
||||
`;
|
||||
|
||||
const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadShell._tag, "Some");
|
||||
if (threadShell._tag === "Some") {
|
||||
assert.equal(threadShell.value.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(threadShell.value.latestTurn?.state, "running");
|
||||
assert.equal(threadShell.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z");
|
||||
}
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.equal(threadDetail.value.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(threadDetail.value.latestTurn?.state, "running");
|
||||
assert.equal(threadDetail.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -6,16 +6,19 @@ import {
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
ProjectScript,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type OrchestrationThreadShell,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -48,6 +51,8 @@ import {
|
||||
} from "../Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const decodeShellSnapshot = Schema.decodeUnknownEffect(OrchestrationShellSnapshot);
|
||||
const decodeThread = Schema.decodeUnknownEffect(OrchestrationThread);
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
@@ -155,6 +160,64 @@ function computeSnapshotSequence(
|
||||
return Number.isFinite(minSequence) ? minSequence : 0;
|
||||
}
|
||||
|
||||
function mapLatestTurn(
|
||||
row: Schema.Schema.Type<typeof ProjectionLatestTurnDbRowSchema>,
|
||||
): OrchestrationLatestTurn {
|
||||
return {
|
||||
turnId: row.turnId,
|
||||
state:
|
||||
row.state === "error"
|
||||
? "error"
|
||||
: row.state === "interrupted"
|
||||
? "interrupted"
|
||||
: row.state === "completed"
|
||||
? "completed"
|
||||
: "running",
|
||||
requestedAt: row.requestedAt,
|
||||
startedAt: row.startedAt,
|
||||
completedAt: row.completedAt,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
|
||||
? {
|
||||
sourceProposedPlan: {
|
||||
threadId: row.sourceProposedPlanThreadId,
|
||||
planId: row.sourceProposedPlanId,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function mapSessionRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadSessionDbRowSchema>,
|
||||
): OrchestrationSession {
|
||||
return {
|
||||
threadId: row.threadId,
|
||||
status: row.status,
|
||||
providerName: row.providerName,
|
||||
runtimeMode: row.runtimeMode,
|
||||
activeTurnId: row.activeTurnId,
|
||||
lastError: row.lastError,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function mapProjectShellRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>,
|
||||
repositoryIdentity: OrchestrationProject["repositoryIdentity"],
|
||||
): OrchestrationProjectShell {
|
||||
return {
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
repositoryIdentity,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -204,6 +267,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
ORDER BY created_at ASC, thread_id ASC
|
||||
@@ -381,6 +448,27 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getActiveProjectRowById = SqlSchema.findOneOption({
|
||||
Request: ProjectIdLookupInput,
|
||||
Result: ProjectionProjectLookupRowSchema,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_projects
|
||||
WHERE project_id = ${projectId}
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({
|
||||
Request: ProjectIdLookupInput,
|
||||
Result: ProjectionThreadIdLookupRowSchema,
|
||||
@@ -415,6 +503,146 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getActiveThreadRowById = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadMessageRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadMessageDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
role,
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
is_streaming AS "isStreaming",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_messages
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, message_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadProposedPlanRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadProposedPlanDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
plan_id AS "planId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
implemented_at AS "implementedAt",
|
||||
implementation_thread_id AS "implementationThreadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, plan_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const getThreadSessionRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadSessionDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
status,
|
||||
provider_name AS "providerName",
|
||||
runtime_mode AS "runtimeMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_sessions
|
||||
WHERE thread_id = ${threadId}
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const getLatestTurnRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionLatestTurnDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
turns.thread_id AS "threadId",
|
||||
turns.turn_id AS "turnId",
|
||||
turns.state,
|
||||
turns.requested_at AS "requestedAt",
|
||||
turns.started_at AS "startedAt",
|
||||
turns.completed_at AS "completedAt",
|
||||
turns.assistant_message_id AS "assistantMessageId",
|
||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_threads threads
|
||||
JOIN projection_turns turns
|
||||
ON turns.thread_id = threads.thread_id
|
||||
AND turns.turn_id = threads.latest_turn_id
|
||||
WHERE threads.thread_id = ${threadId}
|
||||
AND threads.deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listCheckpointRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionCheckpointDbRowSchema,
|
||||
@@ -724,6 +952,145 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
Effect.all([
|
||||
listProjectRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjects:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjects:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
|
||||
Effect.gen(function* () {
|
||||
let updatedAt: string | null = null;
|
||||
for (const row of projectRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of threadRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of sessionRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of latestTurnRows) {
|
||||
updatedAt = maxIso(updatedAt, row.requestedAt);
|
||||
if (row.startedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.startedAt);
|
||||
}
|
||||
if (row.completedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
}
|
||||
}
|
||||
for (const row of stateRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
|
||||
const repositoryIdentities = new Map(
|
||||
yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(row.workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
);
|
||||
const latestTurnByThread = new Map(
|
||||
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
|
||||
);
|
||||
const sessionByThread = new Map(
|
||||
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
|
||||
);
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects: projectRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map((row) =>
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
),
|
||||
threads: threadRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map(
|
||||
(row): OrchestrationThreadShell => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: row.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
|
||||
}),
|
||||
),
|
||||
updatedAt: updatedAt ?? new Date(0).toISOString(),
|
||||
};
|
||||
|
||||
return yield* decodeShellSnapshot(snapshot).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot",
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
Effect.mapError((error) => {
|
||||
if (isPersistenceError(error)) {
|
||||
return error;
|
||||
}
|
||||
return toPersistenceSqlError("ProjectionSnapshotQuery.getShellSnapshot:query")(error);
|
||||
}),
|
||||
);
|
||||
|
||||
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
|
||||
readProjectionCounts(undefined).pipe(
|
||||
Effect.mapError(
|
||||
@@ -770,6 +1137,27 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const getProjectShellById: ProjectionSnapshotQueryShape["getProjectShellById"] = (projectId) =>
|
||||
getActiveProjectRowById({ projectId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getProjectShellById:query",
|
||||
"ProjectionSnapshotQuery.getProjectShellById:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((option) =>
|
||||
Option.isNone(option)
|
||||
? Effect.succeed(Option.none<OrchestrationProjectShell>())
|
||||
: repositoryIdentityResolver
|
||||
.resolve(option.value.workspaceRoot)
|
||||
.pipe(
|
||||
Effect.map((repositoryIdentity) =>
|
||||
Option.some(mapProjectShellRow(option.value, repositoryIdentity)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] =
|
||||
(projectId) =>
|
||||
getFirstActiveThreadIdByProject({ projectId }).pipe(
|
||||
@@ -826,12 +1214,217 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThreadShell>();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
|
||||
} satisfies OrchestrationThreadShell);
|
||||
});
|
||||
|
||||
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [
|
||||
threadRow,
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
checkpointRows,
|
||||
latestTurnRow,
|
||||
sessionRow,
|
||||
] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getThread:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadMessageRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadProposedPlanRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPlans:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPlans:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadActivityRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listCheckpointRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThread>();
|
||||
}
|
||||
|
||||
const thread = {
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
id: row.messageId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
turnId: row.turnId,
|
||||
streaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
if (row.attachments !== null) {
|
||||
return Object.assign(message, { attachments: row.attachments });
|
||||
}
|
||||
return message;
|
||||
}),
|
||||
proposedPlans: proposedPlanRows.map((row) => ({
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
implementedAt: row.implementedAt,
|
||||
implementationThreadId: row.implementationThreadId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
})),
|
||||
activities: activityRows.map((row) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
if (row.sequence !== null) {
|
||||
return Object.assign(activity, { sequence: row.sequence });
|
||||
}
|
||||
return activity;
|
||||
}),
|
||||
checkpoints: checkpointRows.map((row) => ({
|
||||
turnId: row.turnId,
|
||||
checkpointTurnCount: row.checkpointTurnCount,
|
||||
checkpointRef: row.checkpointRef,
|
||||
status: row.status,
|
||||
files: row.files,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
completedAt: row.completedAt,
|
||||
})),
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
};
|
||||
|
||||
return Option.some(
|
||||
yield* decodeThread(thread).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("ProjectionSnapshotQuery.getThreadDetailById:decodeThread"),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
getSnapshot,
|
||||
getShellSnapshot,
|
||||
getCounts,
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
getProjectShellById,
|
||||
getFirstActiveThreadIdByProjectId,
|
||||
getThreadCheckpointContext,
|
||||
getThreadShellById,
|
||||
getThreadDetailById,
|
||||
} satisfies ProjectionSnapshotQueryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -27,6 +27,10 @@ import {
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
@@ -177,6 +181,24 @@ describe("ProviderCommandReactor", () => {
|
||||
: "renamed-branch",
|
||||
}),
|
||||
);
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "renamed-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
);
|
||||
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>((_) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
@@ -225,6 +247,15 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(GitStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||
refreshStatus,
|
||||
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
|
||||
} satisfies GitStatusBroadcasterShape),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(TextGeneration, {
|
||||
generateBranchName,
|
||||
@@ -279,6 +310,7 @@ describe("ProviderCommandReactor", () => {
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
renameBranch,
|
||||
refreshStatus,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
stateDir,
|
||||
@@ -513,9 +545,11 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await waitFor(() => harness.refreshStatus.mock.calls.length === 1);
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({
|
||||
message: "Add a safer reconnect backoff.",
|
||||
});
|
||||
expect(harness.refreshStatus.mock.calls[0]?.[0]).toBe("/tmp/provider-project-worktree");
|
||||
});
|
||||
|
||||
it("forwards codex model options through session start and turn send", async () => {
|
||||
@@ -1241,6 +1275,61 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("starts a fresh session when only projected session state exists", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-stale"),
|
||||
role: "user",
|
||||
text: "resume codex",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
});
|
||||
|
||||
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -11,11 +11,13 @@ import {
|
||||
type RuntimeMode,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";
|
||||
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
||||
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||
@@ -72,8 +74,6 @@ const serverCommandId = (tag: string): CommandId =>
|
||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
const DEFAULT_THREAD_TITLE = "New thread";
|
||||
|
||||
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
|
||||
@@ -119,10 +119,6 @@ function stalePendingRequestDetail(
|
||||
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
|
||||
}
|
||||
|
||||
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
}
|
||||
|
||||
function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
@@ -150,6 +146,7 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const git = yield* GitCore;
|
||||
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||
@@ -290,14 +287,14 @@ const make = Effect.gen(function* () {
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const activeSession = yield* resolveActiveSession(threadId);
|
||||
const existingSessionThreadId =
|
||||
thread.session && thread.session.status !== "stopped" ? thread.id : null;
|
||||
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
@@ -452,6 +449,7 @@ const make = Effect.gen(function* () {
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||
|
||||
@@ -9,7 +9,11 @@
|
||||
import type {
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationProject,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadShell,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -44,6 +48,17 @@ export interface ProjectionSnapshotQueryShape {
|
||||
*/
|
||||
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read the latest orchestration shell snapshot.
|
||||
*
|
||||
* Returns only projects and thread shell summaries so clients can bootstrap
|
||||
* lightweight navigation state without hydrating every thread body.
|
||||
*/
|
||||
readonly getShellSnapshot: () => Effect.Effect<
|
||||
OrchestrationShellSnapshot,
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read aggregate projection counts without hydrating the full read model.
|
||||
*/
|
||||
@@ -56,6 +71,13 @@ export interface ProjectionSnapshotQueryShape {
|
||||
workspaceRoot: string,
|
||||
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active project shell row by id.
|
||||
*/
|
||||
readonly getProjectShellById: (
|
||||
projectId: ProjectId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read the earliest active thread for a project.
|
||||
*/
|
||||
@@ -69,6 +91,20 @@ export interface ProjectionSnapshotQueryShape {
|
||||
readonly getThreadCheckpointContext: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread shell row by id.
|
||||
*/
|
||||
readonly getThreadShellById: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThreadShell>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread detail snapshot by id.
|
||||
*/
|
||||
readonly getThreadDetailById: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,7 @@ describe("fixPath", () => {
|
||||
it("hydrates PATH on linux using the resolved login shell", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
};
|
||||
const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
|
||||
@@ -17,6 +17,39 @@ describe("fixPath", () => {
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenCalledWith("/bin/zsh");
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing fails", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readPath = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => undefined);
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
fixPath({
|
||||
env,
|
||||
platform: "darwin",
|
||||
readPath,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu");
|
||||
expect(readPath).toHaveBeenNthCalledWith(2, "/bin/zsh");
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read PATH from login shell /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,28 +1,57 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell";
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readPathFromLoginShell,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
function logPathHydrationWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[server] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function fixPath(
|
||||
options: {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
platform?: NodeJS.Platform;
|
||||
readPath?: typeof readPathFromLoginShell;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const env = options.env ?? process.env;
|
||||
const logWarning = options.logWarning ?? logPathHydrationWarning;
|
||||
const readPath = options.readPath ?? readPathFromLoginShell;
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
const result = (options.readPath ?? readPathFromLoginShell)(shell);
|
||||
if (result) {
|
||||
env.PATH = result;
|
||||
let shellPath: string | undefined;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
shellPath = readPath(shell);
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read PATH from login shell ${shell}.`, error);
|
||||
}
|
||||
|
||||
if (shellPath) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellPath
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to hydrate PATH from the user environment.", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,6 +88,10 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
@@ -55,6 +59,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
${row.hasActionableProposedPlan},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
@@ -70,6 +78,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
archived_at = excluded.archived_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,
|
||||
has_actionable_proposed_plan = excluded.has_actionable_proposed_plan,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
});
|
||||
@@ -92,6 +104,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
@@ -116,6 +132,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE project_id = ${projectId}
|
||||
|
||||
@@ -35,6 +35,8 @@ import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
|
||||
import Migration0020 from "./Migrations/020_AuthAccessManagement.ts";
|
||||
import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts";
|
||||
import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
|
||||
import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
|
||||
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -69,6 +71,8 @@ export const migrationEntries = [
|
||||
[20, "AuthAccessManagement", Migration0020],
|
||||
[21, "AuthSessionClientMetadata", Migration0021],
|
||||
[22, "AuthSessionLastConnectedAt", Migration0022],
|
||||
[23, "ProjectionThreadShellSummary", Migration0023],
|
||||
[24, "BackfillProjectionThreadShellSummary", Migration0024],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN latest_user_message_at TEXT
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN pending_approval_count INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN pending_user_input_count INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN has_actionable_proposed_plan INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
});
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("024_BackfillProjectionThreadShellSummary", (it) => {
|
||||
it.effect("backfills thread shell summary fields and clears stale projected approvals", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 23 });
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'approval-required',
|
||||
'plan',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'message-user-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'user',
|
||||
'Need help',
|
||||
NULL,
|
||||
0,
|
||||
'2026-02-24T00:01:00.000Z',
|
||||
'2026-02-24T00:01:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'activity-approval-requested',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'approval',
|
||||
'approval.requested',
|
||||
'Command approval requested',
|
||||
'{"requestId":"approval-1","requestKind":"command"}',
|
||||
NULL,
|
||||
'2026-02-24T00:02:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-approval-stale',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'error',
|
||||
'provider.approval.respond.failed',
|
||||
'Provider approval response failed',
|
||||
'{"requestId":"approval-1","detail":"Unknown pending permission request: approval-1"}',
|
||||
NULL,
|
||||
'2026-02-24T00:03:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-user-input-requested',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'info',
|
||||
'user-input.requested',
|
||||
'User input requested',
|
||||
'{"requestId":"input-1","questions":[{"id":"area","header":"Area","question":"Which repo area should I inspect next?","options":[{"label":"Server","description":"Server orchestration."}]}]}',
|
||||
NULL,
|
||||
'2026-02-24T00:04:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_proposed_plans (
|
||||
plan_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
implemented_at,
|
||||
implementation_thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'plan-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'# Do the thing',
|
||||
NULL,
|
||||
NULL,
|
||||
'2026-02-24T00:05:00.000Z',
|
||||
'2026-02-24T00:05:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_pending_approvals (
|
||||
request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
status,
|
||||
decision,
|
||||
created_at,
|
||||
resolved_at
|
||||
)
|
||||
VALUES (
|
||||
'approval-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'pending',
|
||||
NULL,
|
||||
'2026-02-24T00:02:00.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 24 });
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly latestUserMessageAt: string | null;
|
||||
readonly pendingApprovalCount: number;
|
||||
readonly pendingUserInputCount: number;
|
||||
readonly hasActionableProposedPlan: number;
|
||||
}>`
|
||||
SELECT
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-1'
|
||||
`;
|
||||
assert.deepStrictEqual(threadRows, [
|
||||
{
|
||||
latestUserMessageAt: "2026-02-24T00:01:00.000Z",
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 1,
|
||||
hasActionableProposedPlan: 1,
|
||||
},
|
||||
]);
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly status: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
status,
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id = 'approval-1'
|
||||
`;
|
||||
assert.deepStrictEqual(approvalRows, [
|
||||
{
|
||||
status: "resolved",
|
||||
resolvedAt: "2026-02-24T00:03:00.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
INSERT OR IGNORE INTO projection_pending_approvals (
|
||||
request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
status,
|
||||
decision,
|
||||
created_at,
|
||||
resolved_at
|
||||
)
|
||||
SELECT
|
||||
requested.request_id,
|
||||
requested.thread_id,
|
||||
requested.turn_id,
|
||||
'pending',
|
||||
NULL,
|
||||
requested.created_at,
|
||||
NULL
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
created_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at ASC, activity_id ASC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'approval.requested'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS requested
|
||||
WHERE requested.row_number = 1
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_resolutions AS (
|
||||
SELECT
|
||||
resolved.request_id,
|
||||
resolved.resolved_at,
|
||||
resolved.decision
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
created_at AS resolved_at,
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.decision') IN (
|
||||
'accept',
|
||||
'acceptForSession',
|
||||
'decline',
|
||||
'cancel'
|
||||
)
|
||||
THEN json_extract(payload_json, '$.decision')
|
||||
ELSE NULL
|
||||
END AS decision,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at DESC, activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'approval.resolved'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS resolved
|
||||
WHERE resolved.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = (
|
||||
SELECT latest_resolutions.decision
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
),
|
||||
resolved_at = (
|
||||
SELECT latest_resolutions.resolved_at
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_response_events AS (
|
||||
SELECT
|
||||
response.request_id,
|
||||
response.resolved_at,
|
||||
response.decision
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
occurred_at AS resolved_at,
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.decision') IN (
|
||||
'accept',
|
||||
'acceptForSession',
|
||||
'decline',
|
||||
'cancel'
|
||||
)
|
||||
THEN json_extract(payload_json, '$.decision')
|
||||
ELSE NULL
|
||||
END AS decision,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY occurred_at DESC, sequence DESC
|
||||
) AS row_number
|
||||
FROM orchestration_events
|
||||
WHERE event_type = 'thread.approval-response-requested'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS response
|
||||
WHERE response.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = (
|
||||
SELECT latest_response_events.decision
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
),
|
||||
resolved_at = (
|
||||
SELECT latest_response_events.resolved_at
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_stale_failures AS (
|
||||
SELECT
|
||||
failure.request_id,
|
||||
failure.resolved_at
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
created_at AS resolved_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at DESC, activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'provider.approval.respond.failed'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
AND (
|
||||
lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%stale pending approval request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending approval request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending permission request%'
|
||||
)
|
||||
) AS failure
|
||||
WHERE failure.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = NULL,
|
||||
resolved_at = (
|
||||
SELECT latest_stale_failures.resolved_at
|
||||
FROM latest_stale_failures
|
||||
WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE status = 'pending'
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_stale_failures
|
||||
WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET
|
||||
latest_user_message_at = (
|
||||
SELECT MAX(message.created_at)
|
||||
FROM projection_thread_messages AS message
|
||||
WHERE message.thread_id = projection_threads.thread_id
|
||||
AND message.role = 'user'
|
||||
),
|
||||
pending_approval_count = COALESCE((
|
||||
SELECT COUNT(*)
|
||||
FROM projection_pending_approvals
|
||||
WHERE projection_pending_approvals.thread_id = projection_threads.thread_id
|
||||
AND projection_pending_approvals.status = 'pending'
|
||||
), 0),
|
||||
pending_user_input_count = COALESCE((
|
||||
WITH latest_user_input_states AS (
|
||||
SELECT
|
||||
latest.request_id,
|
||||
latest.kind,
|
||||
latest.detail
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(activity.payload_json, '$.requestId') AS request_id,
|
||||
activity.kind,
|
||||
lower(COALESCE(json_extract(activity.payload_json, '$.detail'), '')) AS detail,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(activity.payload_json, '$.requestId')
|
||||
ORDER BY activity.created_at DESC, activity.activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities AS activity
|
||||
WHERE activity.thread_id = projection_threads.thread_id
|
||||
AND json_extract(activity.payload_json, '$.requestId') IS NOT NULL
|
||||
AND activity.kind IN (
|
||||
'user-input.requested',
|
||||
'user-input.resolved',
|
||||
'provider.user-input.respond.failed'
|
||||
)
|
||||
) AS latest
|
||||
WHERE latest.row_number = 1
|
||||
)
|
||||
SELECT COUNT(*)
|
||||
FROM latest_user_input_states
|
||||
WHERE latest_user_input_states.kind = 'user-input.requested'
|
||||
OR (
|
||||
latest_user_input_states.kind = 'provider.user-input.respond.failed'
|
||||
AND latest_user_input_states.detail NOT LIKE '%stale pending user-input request%'
|
||||
AND latest_user_input_states.detail NOT LIKE '%unknown pending user-input request%'
|
||||
)
|
||||
), 0),
|
||||
has_actionable_proposed_plan = COALESCE((
|
||||
SELECT CASE
|
||||
WHEN projection_threads.latest_turn_id IS NOT NULL
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_proposed_plans AS latest_turn_plan_exists
|
||||
WHERE latest_turn_plan_exists.thread_id = projection_threads.thread_id
|
||||
AND latest_turn_plan_exists.turn_id = projection_threads.latest_turn_id
|
||||
)
|
||||
THEN CASE
|
||||
WHEN (
|
||||
SELECT latest_turn_plan.implemented_at
|
||||
FROM projection_thread_proposed_plans AS latest_turn_plan
|
||||
WHERE latest_turn_plan.thread_id = projection_threads.thread_id
|
||||
AND latest_turn_plan.turn_id = projection_threads.latest_turn_id
|
||||
ORDER BY latest_turn_plan.updated_at DESC, latest_turn_plan.plan_id DESC
|
||||
LIMIT 1
|
||||
) IS NULL
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END
|
||||
WHEN EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_proposed_plans AS any_plan
|
||||
WHERE any_plan.thread_id = projection_threads.thread_id
|
||||
)
|
||||
THEN CASE
|
||||
WHEN (
|
||||
SELECT latest_plan.implemented_at
|
||||
FROM projection_thread_proposed_plans AS latest_plan
|
||||
WHERE latest_plan.thread_id = projection_threads.thread_id
|
||||
ORDER BY latest_plan.updated_at DESC, latest_plan.plan_id DESC
|
||||
LIMIT 1
|
||||
) IS NULL
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END
|
||||
ELSE 0
|
||||
END
|
||||
), 0)
|
||||
`;
|
||||
});
|
||||
@@ -9,6 +9,7 @@
|
||||
import {
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
NonNegativeInt,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
@@ -33,6 +34,10 @@ export const ProjectionThread = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
hasActionableProposedPlan: NonNegativeInt,
|
||||
deletedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type ProjectionThread = typeof ProjectionThread.Type;
|
||||
|
||||
@@ -1408,6 +1408,150 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("clamps oversized Claude usage to the reported context window", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 1234,
|
||||
duration_api_ms: 1200,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-result-usage-clamped",
|
||||
usage: {
|
||||
total_tokens: 535000,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.finish();
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
|
||||
assert.equal(usageEvent?.type, "thread.token-usage.updated");
|
||||
if (usageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(usageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 200000,
|
||||
lastUsedTokens: 200000,
|
||||
totalProcessedTokens: 535000,
|
||||
maxTokens: 200000,
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"preserves oversized Claude result totals after task progress snapshots are recorded",
|
||||
() => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_progress",
|
||||
task_id: "task-usage-clamped",
|
||||
description: "Thinking through the patch",
|
||||
usage: {
|
||||
total_tokens: 190000,
|
||||
},
|
||||
session_id: "sdk-session-task-usage-clamped",
|
||||
uuid: "task-usage-progress-clamped",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 1234,
|
||||
duration_api_ms: 1200,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-result-usage-clamped-after-progress",
|
||||
usage: {
|
||||
total_tokens: 535000,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.finish();
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvents = runtimeEvents.filter(
|
||||
(event) => event.type === "thread.token-usage.updated",
|
||||
);
|
||||
const finalUsageEvent = usageEvents.at(-1);
|
||||
assert.equal(finalUsageEvent?.type, "thread.token-usage.updated");
|
||||
if (finalUsageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(finalUsageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 190000,
|
||||
lastUsedTokens: 190000,
|
||||
totalProcessedTokens: 535000,
|
||||
maxTokens: 200000,
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"emits completion only after turn result when assistant frames arrive before deltas",
|
||||
() => {
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
type SDKResultMessage,
|
||||
type SettingSource,
|
||||
type SDKUserMessage,
|
||||
ModelUsage,
|
||||
NonNullableUsage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -272,24 +274,14 @@ function asRuntimeItemId(value: string): RuntimeItemId {
|
||||
return RuntimeItemId.make(value);
|
||||
}
|
||||
|
||||
function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined {
|
||||
if (!modelUsage || typeof modelUsage !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
function maxClaudeContextWindowFromModelUsage(
|
||||
modelUsage: Record<string, ModelUsage> | undefined,
|
||||
): number | undefined {
|
||||
if (!modelUsage) return undefined;
|
||||
|
||||
let maxContextWindow: number | undefined;
|
||||
for (const value of Object.values(modelUsage as Record<string, unknown>)) {
|
||||
if (!value || typeof value !== "object") {
|
||||
continue;
|
||||
}
|
||||
const contextWindow = (value as { contextWindow?: unknown }).contextWindow;
|
||||
if (
|
||||
typeof contextWindow !== "number" ||
|
||||
!Number.isFinite(contextWindow) ||
|
||||
contextWindow <= 0
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
for (const value of Object.values(modelUsage)) {
|
||||
const contextWindow = value.contextWindow;
|
||||
maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow);
|
||||
}
|
||||
|
||||
@@ -297,53 +289,58 @@ function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | und
|
||||
}
|
||||
|
||||
function normalizeClaudeTokenUsage(
|
||||
usage: unknown,
|
||||
value: NonNullableUsage | undefined,
|
||||
contextWindow?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
if (!usage || typeof usage !== "object") {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const record = usage as Record<string, unknown>;
|
||||
const directUsedTokens =
|
||||
typeof record.total_tokens === "number" && Number.isFinite(record.total_tokens)
|
||||
? record.total_tokens
|
||||
: undefined;
|
||||
const usage = value as Record<string, unknown>;
|
||||
const inputTokens =
|
||||
(typeof record.input_tokens === "number" && Number.isFinite(record.input_tokens)
|
||||
? record.input_tokens
|
||||
(typeof usage.input_tokens === "number" && Number.isFinite(usage.input_tokens)
|
||||
? usage.input_tokens
|
||||
: 0) +
|
||||
(typeof record.cache_creation_input_tokens === "number" &&
|
||||
Number.isFinite(record.cache_creation_input_tokens)
|
||||
? record.cache_creation_input_tokens
|
||||
(typeof usage.cache_creation_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_creation_input_tokens)
|
||||
? usage.cache_creation_input_tokens
|
||||
: 0) +
|
||||
(typeof record.cache_read_input_tokens === "number" &&
|
||||
Number.isFinite(record.cache_read_input_tokens)
|
||||
? record.cache_read_input_tokens
|
||||
(typeof usage.cache_read_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_read_input_tokens)
|
||||
? usage.cache_read_input_tokens
|
||||
: 0);
|
||||
const outputTokens =
|
||||
typeof record.output_tokens === "number" && Number.isFinite(record.output_tokens)
|
||||
? record.output_tokens
|
||||
typeof usage.output_tokens === "number" && Number.isFinite(usage.output_tokens)
|
||||
? usage.output_tokens
|
||||
: 0;
|
||||
const derivedUsedTokens = inputTokens + outputTokens;
|
||||
const usedTokens = directUsedTokens ?? (derivedUsedTokens > 0 ? derivedUsedTokens : undefined);
|
||||
if (usedTokens === undefined || usedTokens <= 0) {
|
||||
const derivedTotalProcessedTokens = inputTokens + outputTokens;
|
||||
const totalProcessedTokens =
|
||||
(typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens)
|
||||
? usage.total_tokens
|
||||
: undefined) ?? (derivedTotalProcessedTokens > 0 ? derivedTotalProcessedTokens : undefined);
|
||||
if (totalProcessedTokens === undefined || totalProcessedTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens =
|
||||
typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
|
||||
? contextWindow
|
||||
: undefined;
|
||||
const usedTokens =
|
||||
maxTokens !== undefined ? Math.min(totalProcessedTokens, maxTokens) : totalProcessedTokens;
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
lastUsedTokens: usedTokens,
|
||||
...(totalProcessedTokens > usedTokens ? { totalProcessedTokens } : {}),
|
||||
...(inputTokens > 0 ? { inputTokens } : {}),
|
||||
...(outputTokens > 0 ? { outputTokens } : {}),
|
||||
...(typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
|
||||
? { maxTokens: contextWindow }
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(typeof usage.tool_uses === "number" && Number.isFinite(usage.tool_uses)
|
||||
? { toolUses: usage.tool_uses }
|
||||
: {}),
|
||||
...(typeof record.tool_uses === "number" && Number.isFinite(record.tool_uses)
|
||||
? { toolUses: record.tool_uses }
|
||||
: {}),
|
||||
...(typeof record.duration_ms === "number" && Number.isFinite(record.duration_ms)
|
||||
? { durationMs: record.duration_ms }
|
||||
...(typeof usage.duration_ms === "number" && Number.isFinite(usage.duration_ms)
|
||||
? { durationMs: usage.duration_ms }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -1328,8 +1325,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
errorMessage?: string,
|
||||
result?: SDKResultMessage,
|
||||
) {
|
||||
const resultUsage =
|
||||
result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
|
||||
const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
|
||||
if (resultContextWindow !== undefined) {
|
||||
context.lastKnownContextWindow = resultContextWindow;
|
||||
@@ -1341,9 +1336,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
// Instead, use the last known context-window-accurate usage from task_progress
|
||||
// events and treat the accumulated total as totalProcessedTokens.
|
||||
const accumulatedSnapshot = normalizeClaudeTokenUsage(
|
||||
resultUsage,
|
||||
result?.usage,
|
||||
resultContextWindow ?? context.lastKnownContextWindow,
|
||||
);
|
||||
const accumulatedTotalProcessedTokens =
|
||||
accumulatedSnapshot?.totalProcessedTokens ?? accumulatedSnapshot?.usedTokens;
|
||||
const lastGoodUsage = context.lastKnownTokenUsage;
|
||||
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
|
||||
const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
|
||||
@@ -1352,8 +1349,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens
|
||||
? { totalProcessedTokens: accumulatedSnapshot.usedTokens }
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? { totalProcessedTokens: accumulatedTotalProcessedTokens }
|
||||
: {}),
|
||||
}
|
||||
: accumulatedSnapshot;
|
||||
|
||||
@@ -663,6 +663,46 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
});
|
||||
});
|
||||
|
||||
const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvider => {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Claude provider status has not been checked in this session yet.",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const ClaudeProviderLive = Layer.effect(
|
||||
ClaudeProvider,
|
||||
Effect.gen(function* () {
|
||||
@@ -698,6 +738,7 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
Stream.map((settings) => settings.providers.claudeAgent),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingClaudeProvider,
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -552,6 +552,46 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
});
|
||||
});
|
||||
|
||||
const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
codexSettings.customModels,
|
||||
DEFAULT_CODEX_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex provider status has not been checked in this session yet.",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const CodexProviderLive = Layer.effect(
|
||||
CodexProvider,
|
||||
Effect.gen(function* () {
|
||||
@@ -602,6 +642,7 @@ export const CodexProviderLive = Layer.effect(
|
||||
Stream.map((settings) => settings.providers.codex),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingCodexProvider,
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from "./CodexProvider";
|
||||
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider";
|
||||
import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry";
|
||||
import { ServerConfig } from "../../config";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry";
|
||||
|
||||
@@ -562,6 +563,61 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
|
||||
});
|
||||
|
||||
it.effect("does not probe provider health during registry startup", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnCount = 0;
|
||||
const serverSettings = yield* makeMutableServerSettingsService();
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
spawnCount += 1;
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") {
|
||||
if (command === "codex") {
|
||||
return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
}
|
||||
return { stdout: "claude 1.0.0\n", stderr: "", code: 0 };
|
||||
}
|
||||
if (joined === "login status") {
|
||||
return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
}
|
||||
if (joined === "auth status") {
|
||||
return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${command} ${joined}`);
|
||||
}),
|
||||
),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ServerSettingsService, serverSettings),
|
||||
providerRegistryLayer,
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
assert.deepStrictEqual(yield* registry.getProviders, []);
|
||||
assert.strictEqual(spawnCount, 0);
|
||||
|
||||
const refreshed = yield* registry.refresh("codex");
|
||||
assert.strictEqual(spawnCount > 0, true);
|
||||
assert.strictEqual(
|
||||
refreshed.find((provider) => provider.provider === "codex")?.status,
|
||||
"ready",
|
||||
);
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reruns codex health when codex provider settings change", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* makeMutableServerSettingsService();
|
||||
@@ -569,6 +625,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
const joined = args.join(" ");
|
||||
@@ -596,8 +657,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
const registry = yield* ProviderRegistry;
|
||||
|
||||
const initial = yield* registry.getProviders;
|
||||
assert.deepStrictEqual(initial, []);
|
||||
|
||||
const refreshed = yield* registry.refresh("codex");
|
||||
assert.strictEqual(
|
||||
initial.find((status) => status.provider === "codex")?.status,
|
||||
refreshed.find((status) => status.provider === "codex")?.status,
|
||||
"ready",
|
||||
);
|
||||
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
* @module ProviderRegistryLive
|
||||
*/
|
||||
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
|
||||
import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config";
|
||||
import { ClaudeProviderLive } from "./ClaudeProvider";
|
||||
import { CodexProviderLive } from "./CodexProvider";
|
||||
import type { ClaudeProviderShape } from "../Services/ClaudeProvider";
|
||||
@@ -13,6 +14,14 @@ import { ClaudeProvider } from "../Services/ClaudeProvider";
|
||||
import type { CodexProviderShape } from "../Services/CodexProvider";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry";
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
PROVIDER_CACHE_IDS,
|
||||
orderProviderSnapshots,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache";
|
||||
|
||||
const loadProviders = (
|
||||
codexProvider: CodexProviderShape,
|
||||
@@ -32,61 +41,152 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
Effect.gen(function* () {
|
||||
const codexProvider = yield* CodexProvider;
|
||||
const claudeProvider = yield* ClaudeProvider;
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
yield* loadProviders(codexProvider, claudeProvider),
|
||||
const fallbackProviders = yield* loadProviders(codexProvider, claudeProvider);
|
||||
const cachePathByProvider = new Map(
|
||||
PROVIDER_CACHE_IDS.map(
|
||||
(provider) =>
|
||||
[
|
||||
provider,
|
||||
resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
provider,
|
||||
}),
|
||||
] as const,
|
||||
),
|
||||
);
|
||||
const fallbackByProvider = new Map(
|
||||
fallbackProviders.map((provider) => [provider.provider, provider] as const),
|
||||
);
|
||||
const cachedProviders = yield* Effect.forEach(
|
||||
PROVIDER_CACHE_IDS,
|
||||
(provider) => {
|
||||
const filePath = cachePathByProvider.get(provider)!;
|
||||
const fallbackProvider = fallbackByProvider.get(provider)!;
|
||||
return readProviderStatusCache(filePath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.map((cachedProvider) =>
|
||||
cachedProvider === undefined
|
||||
? undefined
|
||||
: hydrateCachedProvider({
|
||||
cachedProvider,
|
||||
fallbackProvider,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.map((providers) =>
|
||||
orderProviderSnapshots(
|
||||
providers.filter((provider): provider is ServerProvider => provider !== undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
|
||||
const syncProviders = Effect.fn("syncProviders")(function* (options?: {
|
||||
readonly publish?: boolean;
|
||||
}) {
|
||||
const previousProviders = yield* Ref.get(providersRef);
|
||||
const providers = yield* loadProviders(codexProvider, claudeProvider);
|
||||
yield* Ref.set(providersRef, providers);
|
||||
const persistProvider = (provider: ServerProvider) =>
|
||||
writeProviderStatusCache({
|
||||
filePath: cachePathByProvider.get(provider.provider)!,
|
||||
provider,
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.ignore,
|
||||
);
|
||||
|
||||
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [provider.provider, provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(provider.provider, provider);
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* Effect.forEach(nextProviders, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
if (options?.publish !== false) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
const syncProvider = Effect.fn("syncProvider")(function* (
|
||||
provider: ServerProvider,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
|
||||
switch (provider) {
|
||||
case "codex":
|
||||
yield* codexProvider.refresh;
|
||||
break;
|
||||
return yield* codexProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
case "claudeAgent":
|
||||
yield* claudeProvider.refresh;
|
||||
break;
|
||||
return yield* claudeProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
default:
|
||||
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
break;
|
||||
return yield* Effect.all(
|
||||
[
|
||||
codexProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
),
|
||||
claudeProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
),
|
||||
],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.andThen(Ref.get(providersRef)));
|
||||
}
|
||||
return yield* syncProviders();
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, (provider) =>
|
||||
syncProvider(provider),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, (provider) =>
|
||||
syncProvider(provider),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return {
|
||||
getProviders: syncProviders({ publish: false }).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (provider?: ProviderKind) =>
|
||||
refresh(provider).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
Effect.orElseSucceed(() => [] as ReadonlyArray<ServerProvider>),
|
||||
),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
|
||||
@@ -11,6 +11,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
readonly initialSnapshot: (settings: Settings) => ServerProvider;
|
||||
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
@@ -20,7 +21,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const initialSettings = yield* input.getSettings;
|
||||
const initialSnapshot = yield* input.checkProvider;
|
||||
const initialSnapshot = input.initialSnapshot(initialSettings);
|
||||
const snapshotRef = yield* Ref.make(initialSnapshot);
|
||||
const settingsRef = yield* Ref.make(initialSettings);
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem } from "effect";
|
||||
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "./providerStatusCache";
|
||||
|
||||
const makeProvider = (
|
||||
provider: ServerProvider["provider"],
|
||||
overrides?: Partial<ServerProvider>,
|
||||
): ServerProvider => ({
|
||||
provider,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-11T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
it.effect("writes and reads provider status snapshots", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-" });
|
||||
const codexProvider = makeProvider("codex");
|
||||
const claudeProvider = makeProvider("claudeAgent", {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
});
|
||||
const codexPath = resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
provider: "codex",
|
||||
});
|
||||
const claudePath = resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
yield* writeProviderStatusCache({
|
||||
filePath: codexPath,
|
||||
provider: codexProvider,
|
||||
});
|
||||
yield* writeProviderStatusCache({
|
||||
filePath: claudePath,
|
||||
provider: claudeProvider,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(codexPath), codexProvider);
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(claudePath), claudeProvider);
|
||||
}),
|
||||
);
|
||||
|
||||
it("hydrates cached provider status onto current settings-derived models", () => {
|
||||
const cachedCodex = makeProvider("codex", {
|
||||
checkedAt: "2026-04-10T12:00:00.000Z",
|
||||
models: [],
|
||||
message: "Cached message",
|
||||
skills: [
|
||||
{
|
||||
name: "github:gh-fix-ci",
|
||||
path: "/tmp/skills/gh-fix-ci/SKILL.md",
|
||||
enabled: true,
|
||||
displayName: "CI Debug",
|
||||
},
|
||||
],
|
||||
});
|
||||
const fallbackCodex = makeProvider("codex", {
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
message: "Pending refresh",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(
|
||||
hydrateCachedProvider({
|
||||
cachedProvider: cachedCodex,
|
||||
fallbackProvider: fallbackCodex,
|
||||
}),
|
||||
{
|
||||
...fallbackCodex,
|
||||
installed: cachedCodex.installed,
|
||||
version: cachedCodex.version,
|
||||
status: cachedCodex.status,
|
||||
auth: cachedCodex.auth,
|
||||
checkedAt: cachedCodex.checkedAt,
|
||||
slashCommands: cachedCodex.slashCommands,
|
||||
skills: cachedCodex.skills,
|
||||
message: cachedCodex.message,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores stale cached enabled state when the provider is now disabled", () => {
|
||||
const cachedCodex = makeProvider("codex", {
|
||||
checkedAt: "2026-04-10T12:00:00.000Z",
|
||||
message: "Cached ready status",
|
||||
});
|
||||
const disabledFallback = makeProvider("codex", {
|
||||
enabled: false,
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "disabled",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(
|
||||
hydrateCachedProvider({
|
||||
cachedProvider: cachedCodex,
|
||||
fallbackProvider: disabledFallback,
|
||||
}),
|
||||
disabledFallback,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import * as nodePath from "node:path";
|
||||
import { type ServerProvider, ServerProvider as ServerProviderSchema } from "@t3tools/contracts";
|
||||
import { Cause, Effect, FileSystem, Path, Schema } from "effect";
|
||||
|
||||
export const PROVIDER_CACHE_IDS = ["codex", "claudeAgent"] as const satisfies ReadonlyArray<
|
||||
ServerProvider["provider"]
|
||||
>;
|
||||
|
||||
const decodeProviderStatusCache = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(ServerProviderSchema),
|
||||
);
|
||||
|
||||
const providerOrderRank = (provider: ServerProvider["provider"]): number => {
|
||||
const rank = PROVIDER_CACHE_IDS.indexOf(provider);
|
||||
return rank === -1 ? Number.MAX_SAFE_INTEGER : rank;
|
||||
};
|
||||
|
||||
export const orderProviderSnapshots = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
[...providers].toSorted(
|
||||
(left, right) => providerOrderRank(left.provider) - providerOrderRank(right.provider),
|
||||
);
|
||||
|
||||
export const hydrateCachedProvider = (input: {
|
||||
readonly cachedProvider: ServerProvider;
|
||||
readonly fallbackProvider: ServerProvider;
|
||||
}): ServerProvider => {
|
||||
if (
|
||||
!input.fallbackProvider.enabled ||
|
||||
input.cachedProvider.enabled !== input.fallbackProvider.enabled
|
||||
) {
|
||||
return input.fallbackProvider;
|
||||
}
|
||||
|
||||
const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
|
||||
const hydratedProvider: ServerProvider = {
|
||||
...fallbackWithoutMessage,
|
||||
installed: input.cachedProvider.installed,
|
||||
version: input.cachedProvider.version,
|
||||
status: input.cachedProvider.status,
|
||||
auth: input.cachedProvider.auth,
|
||||
checkedAt: input.cachedProvider.checkedAt,
|
||||
slashCommands: input.cachedProvider.slashCommands,
|
||||
skills: input.cachedProvider.skills,
|
||||
};
|
||||
|
||||
return input.cachedProvider.message
|
||||
? { ...hydratedProvider, message: input.cachedProvider.message }
|
||||
: hydratedProvider;
|
||||
};
|
||||
|
||||
export const resolveProviderStatusCachePath = (input: {
|
||||
readonly cacheDir: string;
|
||||
readonly provider: ServerProvider["provider"];
|
||||
}) => nodePath.join(input.cacheDir, `${input.provider}.json`);
|
||||
|
||||
export const readProviderStatusCache = (filePath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return yield* decodeProviderStatusCache(trimmed).pipe(
|
||||
Effect.matchCauseEffect({
|
||||
onFailure: (cause) =>
|
||||
Effect.logWarning("failed to parse provider status cache, ignoring", {
|
||||
path: filePath,
|
||||
issues: Cause.pretty(cause),
|
||||
}).pipe(Effect.as(undefined)),
|
||||
onSuccess: Effect.succeed,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const writeProviderStatusCache = (input: {
|
||||
readonly filePath: string;
|
||||
readonly provider: ServerProvider;
|
||||
}) => {
|
||||
const tempPath = `${input.filePath}.${process.pid}.${Date.now()}.tmp`;
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const encoded = `${JSON.stringify(input.provider, null, 2)}\n`;
|
||||
|
||||
yield* fs.makeDirectory(path.dirname(input.filePath), { recursive: true });
|
||||
yield* fs.writeFileString(tempPath, encoded);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }));
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
+80
-239
@@ -31,6 +31,7 @@ import {
|
||||
FileSystem,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Option,
|
||||
Path,
|
||||
Stream,
|
||||
} from "effect";
|
||||
@@ -57,6 +58,10 @@ import {
|
||||
import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "./git/Services/GitStatusBroadcaster.ts";
|
||||
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
|
||||
import { Open, type OpenShape } from "./open.ts";
|
||||
import {
|
||||
@@ -68,7 +73,6 @@ import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionSnapshotQueryShape,
|
||||
} from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { PersistenceSqlError } from "./persistence/Errors.ts";
|
||||
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
ProviderRegistry,
|
||||
@@ -293,6 +297,7 @@ const buildAppUnderTest = (options?: {
|
||||
open?: Partial<OpenShape>;
|
||||
gitCore?: Partial<GitCoreShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
gitStatusBroadcaster?: Partial<GitStatusBroadcasterShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
orchestrationEngine?: Partial<OrchestrationEngineShape>;
|
||||
@@ -341,7 +346,11 @@ const buildAppUnderTest = (options?: {
|
||||
const gitManagerLayer = Layer.mock(GitManager)({
|
||||
...options?.layers?.gitManager,
|
||||
});
|
||||
const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
|
||||
const gitStatusBroadcasterLayer = options?.layers?.gitStatusBroadcaster
|
||||
? Layer.mock(GitStatusBroadcaster)({
|
||||
...options.layers.gitStatusBroadcaster,
|
||||
})
|
||||
: GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
|
||||
|
||||
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
|
||||
disableListenLog: true,
|
||||
@@ -410,6 +419,20 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery)({
|
||||
getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
}),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
...options?.layers?.projectionSnapshotQuery,
|
||||
}),
|
||||
),
|
||||
@@ -1767,7 +1790,20 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () =>
|
||||
Effect.gen(function* () {
|
||||
const providers = [] as const;
|
||||
const providers = [
|
||||
{
|
||||
provider: "codex" as const,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready" as const,
|
||||
auth: { status: "authenticated" as const },
|
||||
checkedAt: "2026-04-11T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const;
|
||||
const changeEvent = {
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
@@ -1824,7 +1860,20 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const providers = [] as const;
|
||||
const nextProviders = [
|
||||
{
|
||||
provider: "codex" as const,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready" as const,
|
||||
auth: { status: "authenticated" as const },
|
||||
checkedAt: "2026-04-11T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
@@ -1837,7 +1886,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
},
|
||||
providerRegistry: {
|
||||
getProviders: Effect.succeed([]),
|
||||
streamChanges: Stream.succeed(providers),
|
||||
streamChanges: Stream.succeed(nextProviders),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1851,10 +1900,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
const [first, second] = Array.from(events);
|
||||
assert.equal(first?.type, "snapshot");
|
||||
if (first?.type === "snapshot") {
|
||||
assert.deepEqual(first.config.providers, []);
|
||||
}
|
||||
assert.deepEqual(second, {
|
||||
version: 1,
|
||||
type: "providerStatuses",
|
||||
payload: { providers },
|
||||
payload: { providers: nextProviders },
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
@@ -2748,11 +2800,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const snapshotResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})),
|
||||
);
|
||||
assert.equal(snapshotResult.snapshotSequence, 1);
|
||||
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
@@ -2904,6 +2951,24 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "t3code/bootstrap-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
);
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
@@ -2928,6 +2993,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
gitStatusBroadcaster: {
|
||||
refreshStatus,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
@@ -3005,6 +3073,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
projectCwd: "/tmp/project",
|
||||
worktreePath: "/tmp/bootstrap-worktree",
|
||||
});
|
||||
assert.deepEqual(refreshStatus.mock.calls[0]?.[0], "/tmp/bootstrap-worktree");
|
||||
|
||||
const setupActivities = dispatchedCommands.filter(
|
||||
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
|
||||
@@ -3306,234 +3375,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const now = new Date().toISOString();
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
let replayCursor: number | null = null;
|
||||
const makeEvent = (sequence: number): OrchestrationEvent =>
|
||||
({
|
||||
sequence,
|
||||
eventId: `event-${sequence}`,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "thread.reverted",
|
||||
payload: {
|
||||
threadId,
|
||||
turnCount: sequence,
|
||||
},
|
||||
}) as OrchestrationEvent;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
getReadModel: () =>
|
||||
Effect.succeed({
|
||||
...makeDefaultOrchestrationReadModel(),
|
||||
snapshotSequence: 1,
|
||||
}),
|
||||
readEvents: (fromSequenceExclusive) => {
|
||||
replayCursor = fromSequenceExclusive;
|
||||
return Stream.make(makeEvent(2), makeEvent(3));
|
||||
},
|
||||
streamDomainEvents: Stream.make(makeEvent(3), makeEvent(4)),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
|
||||
Stream.take(3),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(replayCursor, 1);
|
||||
assert.deepEqual(
|
||||
Array.from(events).map((event) => event.sequence),
|
||||
[2, 3, 4],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("enriches replayed project events only once before streaming them to subscribers", () =>
|
||||
Effect.gen(function* () {
|
||||
let resolveCalls = 0;
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/t3tools/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:t3tools/t3code.git",
|
||||
},
|
||||
displayName: "t3tools/t3code",
|
||||
provider: "github" as const,
|
||||
owner: "t3tools",
|
||||
name: "t3code",
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
getReadModel: () =>
|
||||
Effect.succeed({
|
||||
...makeDefaultOrchestrationReadModel(),
|
||||
snapshotSequence: 0,
|
||||
}),
|
||||
readEvents: () =>
|
||||
Stream.make({
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: defaultProjectId,
|
||||
occurredAt: "2026-04-06T00:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "project.meta-updated",
|
||||
payload: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Replayed Project",
|
||||
updatedAt: "2026-04-06T00:00:00.000Z",
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "project.meta-updated" }>),
|
||||
streamDomainEvents: Stream.empty,
|
||||
},
|
||||
repositoryIdentityResolver: {
|
||||
resolve: () => {
|
||||
resolveCalls += 1;
|
||||
return Effect.succeed(repositoryIdentity);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
|
||||
Stream.take(1),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const event = Array.from(events)[0];
|
||||
assert.equal(resolveCalls, 1);
|
||||
assert.equal(event?.type, "project.meta-updated");
|
||||
assert.deepEqual(
|
||||
event && event.type === "project.meta-updated" ? event.payload.repositoryIdentity : null,
|
||||
repositoryIdentity,
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("enriches subscribed project meta updates with repository identity metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/t3tools/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "upstream",
|
||||
remoteUrl: "[email protected]:T3Tools/t3code.git",
|
||||
},
|
||||
displayName: "T3Tools/t3code",
|
||||
provider: "github",
|
||||
owner: "T3Tools",
|
||||
name: "t3code",
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
getReadModel: () =>
|
||||
Effect.succeed({
|
||||
...makeDefaultOrchestrationReadModel(),
|
||||
snapshotSequence: 0,
|
||||
}),
|
||||
streamDomainEvents: Stream.make({
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: defaultProjectId,
|
||||
occurredAt: "2026-04-05T00:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "project.meta-updated",
|
||||
payload: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Renamed Project",
|
||||
updatedAt: "2026-04-05T00:00:00.000Z",
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "project.meta-updated" }>),
|
||||
},
|
||||
repositoryIdentityResolver: {
|
||||
resolve: () => Effect.succeed(repositoryIdentity),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
|
||||
Stream.take(1),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const event = Array.from(events)[0];
|
||||
assert.equal(event?.type, "project.meta-updated");
|
||||
assert.deepEqual(
|
||||
event && event.type === "project.meta-updated" ? event.payload.repositoryIdentity : null,
|
||||
repositoryIdentity,
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc orchestration.getSnapshot errors", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
projectionSnapshotQuery: {
|
||||
getSnapshot: () =>
|
||||
Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
operation: "ProjectionSnapshotQuery.getSnapshot",
|
||||
detail: "projection unavailable",
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const result = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})).pipe(
|
||||
Effect.result,
|
||||
),
|
||||
);
|
||||
|
||||
assertTrue(result._tag === "Failure");
|
||||
assertTrue(result.failure._tag === "OrchestrationGetSnapshotError");
|
||||
assertInclude(result.failure.message, "Failed to load orchestration snapshot");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc terminal methods", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = {
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
import { DEFAULT_MODEL_BY_PROVIDER } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { DEFAULT_MODEL_BY_PROVIDER, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Deferred, Effect, Fiber, Option, Ref } from "effect";
|
||||
import { Deferred, Effect, Fiber, Option, Ref, Stream } from "effect";
|
||||
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import {
|
||||
getAutoBootstrapDefaultModelSelection,
|
||||
launchStartupHeartbeat,
|
||||
makeCommandGate,
|
||||
resolveAutoBootstrapWelcomeTargets,
|
||||
resolveWelcomeBase,
|
||||
ServerRuntimeStartupError,
|
||||
} from "./serverRuntimeStartup.ts";
|
||||
|
||||
@@ -70,6 +78,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
yield* launchStartupHeartbeat.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getCounts: () =>
|
||||
Deferred.await(releaseCounts).pipe(
|
||||
Effect.as({
|
||||
@@ -78,8 +87,11 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
}),
|
||||
),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
Effect.provideService(AnalyticsService, {
|
||||
record: () => Effect.void,
|
||||
@@ -89,3 +101,109 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolveWelcomeBase derives cwd and project name from server config", () =>
|
||||
Effect.gen(function* () {
|
||||
const welcome = yield* resolveWelcomeBase.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
} as never),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(welcome, {
|
||||
cwd: "/tmp/startup-project",
|
||||
projectName: "startup-project",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and thread ids", () => {
|
||||
const bootstrapProjectId = ProjectId.make("project-startup-bootstrap");
|
||||
const bootstrapThreadId = ThreadId.make("thread-startup-bootstrap");
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const targets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () =>
|
||||
Effect.succeed(
|
||||
Option.some({
|
||||
id: bootstrapProjectId,
|
||||
title: "Startup Project",
|
||||
workspaceRoot: "/tmp/startup-project",
|
||||
defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
}),
|
||||
),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(targets, {
|
||||
bootstrapProjectId,
|
||||
bootstrapThreadId,
|
||||
});
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const targets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
assert.equal(typeof targets.bootstrapProjectId, "string");
|
||||
assert.equal(typeof targets.bootstrapThreadId, "string");
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), ["project.create", "thread.create"]);
|
||||
}),
|
||||
);
|
||||
@@ -157,7 +157,18 @@ export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
});
|
||||
|
||||
const autoBootstrapWelcome = Effect.gen(function* () {
|
||||
export const resolveWelcomeBase = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
return {
|
||||
cwd: serverConfig.cwd,
|
||||
projectName,
|
||||
} as const;
|
||||
});
|
||||
|
||||
export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
@@ -221,12 +232,7 @@ const autoBootstrapWelcome = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
return {
|
||||
cwd: serverConfig.cwd,
|
||||
projectName,
|
||||
...(bootstrapProjectId ? { bootstrapProjectId } : {}),
|
||||
...(bootstrapThreadId ? { bootstrapThreadId } : {}),
|
||||
} as const;
|
||||
@@ -271,7 +277,7 @@ const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>)
|
||||
Effect.withSpan(`server.startup.${phase}`),
|
||||
);
|
||||
|
||||
const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
export const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const keybindings = yield* Keybindings;
|
||||
const orchestrationReactor = yield* OrchestrationReactor;
|
||||
@@ -322,15 +328,13 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
|
||||
);
|
||||
|
||||
yield* Effect.logDebug("startup phase: preparing welcome payload");
|
||||
const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome);
|
||||
const welcomeBase = yield* resolveWelcomeBase;
|
||||
const environment = yield* serverEnvironment.getDescriptor;
|
||||
yield* Effect.logDebug("startup phase: preparing welcome payload");
|
||||
yield* Effect.logDebug("startup phase: publishing welcome event", {
|
||||
environmentId: environment.environmentId,
|
||||
cwd: welcome.cwd,
|
||||
projectName: welcome.projectName,
|
||||
bootstrapProjectId: welcome.bootstrapProjectId,
|
||||
bootstrapThreadId: welcome.bootstrapThreadId,
|
||||
cwd: welcomeBase.cwd,
|
||||
projectName: welcomeBase.projectName,
|
||||
});
|
||||
yield* runStartupPhase(
|
||||
"welcome.publish",
|
||||
@@ -339,10 +343,47 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
type: "welcome",
|
||||
payload: {
|
||||
environment,
|
||||
...welcome,
|
||||
...welcomeBase,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
if (serverConfig.autoBootstrapProjectFromCwd) {
|
||||
yield* Effect.forkScoped(
|
||||
runStartupPhase(
|
||||
"welcome.autobootstrap",
|
||||
Effect.gen(function* () {
|
||||
const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets;
|
||||
if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.logDebug("startup phase: publishing bootstrapped welcome event", {
|
||||
environmentId: environment.environmentId,
|
||||
cwd: welcomeBase.cwd,
|
||||
projectName: welcomeBase.projectName,
|
||||
bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
|
||||
bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
|
||||
});
|
||||
yield* lifecycleEvents.publish({
|
||||
version: 1,
|
||||
type: "welcome",
|
||||
payload: {
|
||||
environment,
|
||||
...welcomeBase,
|
||||
...bootstrapTargets,
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("startup auto-bootstrap welcome failed", {
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.annotateSpans({
|
||||
"server.mode": serverConfig.mode,
|
||||
|
||||
+164
-67
@@ -1,4 +1,4 @@
|
||||
import { Cause, Effect, Layer, Queue, Ref, Schema, Stream } from "effect";
|
||||
import { Cause, Duration, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import {
|
||||
type AuthAccessStreamEvent,
|
||||
AuthSessionId,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type GitManagerServiceError,
|
||||
OrchestrationDispatchCommandError,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationShellStreamEvent,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
@@ -62,6 +63,30 @@ import {
|
||||
} from "./auth/Services/SessionCredentialService";
|
||||
import { respondToAuthError } from "./auth/http";
|
||||
|
||||
function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
OrchestrationEvent,
|
||||
{
|
||||
type:
|
||||
| "thread.message-sent"
|
||||
| "thread.proposed-plan-upserted"
|
||||
| "thread.activity-appended"
|
||||
| "thread.turn-diff-completed"
|
||||
| "thread.reverted"
|
||||
| "thread.session-set";
|
||||
}
|
||||
> {
|
||||
return (
|
||||
event.type === "thread.message-sent" ||
|
||||
event.type === "thread.proposed-plan-upserted" ||
|
||||
event.type === "thread.activity-appended" ||
|
||||
event.type === "thread.turn-diff-completed" ||
|
||||
event.type === "thread.reverted" ||
|
||||
event.type === "thread.session-set"
|
||||
);
|
||||
}
|
||||
|
||||
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
|
||||
|
||||
function toAuthAccessStreamEvent(
|
||||
change: BootstrapCredentialChange | SessionCredentialChange,
|
||||
revision: number,
|
||||
@@ -222,6 +247,57 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const enrichOrchestrationEvents = (events: ReadonlyArray<OrchestrationEvent>) =>
|
||||
Effect.forEach(events, enrichProjectEvent, { concurrency: 4 });
|
||||
|
||||
const toShellStreamEvent = (
|
||||
event: OrchestrationEvent,
|
||||
): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
case "project.meta-updated":
|
||||
return projectionSnapshotQuery.getProjectShellById(event.payload.projectId).pipe(
|
||||
Effect.map((project) =>
|
||||
Option.map(project, (nextProject) => ({
|
||||
kind: "project-upserted" as const,
|
||||
sequence: event.sequence,
|
||||
project: nextProject,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
case "project.deleted":
|
||||
return Effect.succeed(
|
||||
Option.some({
|
||||
kind: "project-removed" as const,
|
||||
sequence: event.sequence,
|
||||
projectId: event.payload.projectId,
|
||||
}),
|
||||
);
|
||||
case "thread.deleted":
|
||||
return Effect.succeed(
|
||||
Option.some({
|
||||
kind: "thread-removed" as const,
|
||||
sequence: event.sequence,
|
||||
threadId: event.payload.threadId,
|
||||
}),
|
||||
);
|
||||
default:
|
||||
if (event.aggregateKind !== "thread") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return projectionSnapshotQuery
|
||||
.getThreadShellById(ThreadId.make(event.aggregateId))
|
||||
.pipe(
|
||||
Effect.map((thread) =>
|
||||
Option.map(thread, (nextThread) => ({
|
||||
kind: "thread-upserted" as const,
|
||||
sequence: event.sequence,
|
||||
thread: nextThread,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const dispatchBootstrapTurnStart = (
|
||||
command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
|
||||
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
|
||||
@@ -390,6 +466,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
branch: worktree.worktree.branch,
|
||||
worktreePath: targetWorktreePath,
|
||||
});
|
||||
yield* refreshGitStatus(targetWorktreePath);
|
||||
}
|
||||
|
||||
yield* runSetupProgram();
|
||||
@@ -467,20 +544,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
|
||||
|
||||
return WsRpcGroup.of({
|
||||
[ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_WS_METHODS.getSnapshot,
|
||||
projectionSnapshotQuery.getSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_WS_METHODS.dispatchCommand,
|
||||
@@ -561,65 +624,85 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
|
||||
[ORCHESTRATION_WS_METHODS.subscribeShell]: (_input) =>
|
||||
observeRpcStreamEffect(
|
||||
WS_METHODS.subscribeOrchestrationDomainEvents,
|
||||
ORCHESTRATION_WS_METHODS.subscribeShell,
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* orchestrationEngine.getReadModel();
|
||||
const fromSequenceExclusive = snapshot.snapshotSequence;
|
||||
const replayEvents: Array<OrchestrationEvent> = yield* Stream.runCollect(
|
||||
orchestrationEngine.readEvents(fromSequenceExclusive),
|
||||
).pipe(
|
||||
Effect.map((events) => Array.from(events)),
|
||||
Effect.flatMap(enrichOrchestrationEvents),
|
||||
Effect.catch(() => Effect.succeed([] as Array<OrchestrationEvent>)),
|
||||
const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration shell snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const replayStream = Stream.fromIterable(replayEvents);
|
||||
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.mapEffect(enrichProjectEvent),
|
||||
Stream.mapEffect(toShellStreamEvent),
|
||||
Stream.flatMap((event) =>
|
||||
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
|
||||
),
|
||||
);
|
||||
const source = Stream.merge(replayStream, liveStream);
|
||||
type SequenceState = {
|
||||
readonly nextSequence: number;
|
||||
readonly pendingBySequence: Map<number, OrchestrationEvent>;
|
||||
};
|
||||
const state = yield* Ref.make<SequenceState>({
|
||||
nextSequence: fromSequenceExclusive + 1,
|
||||
pendingBySequence: new Map<number, OrchestrationEvent>(),
|
||||
});
|
||||
|
||||
return source.pipe(
|
||||
Stream.mapEffect((event) =>
|
||||
Ref.modify(
|
||||
state,
|
||||
({
|
||||
nextSequence,
|
||||
pendingBySequence,
|
||||
}): [Array<OrchestrationEvent>, SequenceState] => {
|
||||
if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) {
|
||||
return [[], { nextSequence, pendingBySequence }];
|
||||
}
|
||||
|
||||
const updatedPending = new Map(pendingBySequence);
|
||||
updatedPending.set(event.sequence, event);
|
||||
|
||||
const emit: Array<OrchestrationEvent> = [];
|
||||
let expected = nextSequence;
|
||||
for (;;) {
|
||||
const expectedEvent = updatedPending.get(expected);
|
||||
if (!expectedEvent) {
|
||||
break;
|
||||
}
|
||||
emit.push(expectedEvent);
|
||||
updatedPending.delete(expected);
|
||||
expected += 1;
|
||||
}
|
||||
|
||||
return [emit, { nextSequence: expected, pendingBySequence: updatedPending }];
|
||||
},
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot,
|
||||
}),
|
||||
liveStream,
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>
|
||||
observeRpcStreamEffect(
|
||||
ORCHESTRATION_WS_METHODS.subscribeThread,
|
||||
Effect.gen(function* () {
|
||||
const [threadDetail, snapshotSequence] = yield* Effect.all([
|
||||
projectionSnapshotQuery.getThreadDetailById(input.threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: `Failed to load thread ${input.threadId}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Stream.flatMap((events) => Stream.fromIterable(events)),
|
||||
orchestrationEngine
|
||||
.getReadModel()
|
||||
.pipe(Effect.map((readModel) => readModel.snapshotSequence)),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadDetail)) {
|
||||
return yield* new OrchestrationGetSnapshotError({
|
||||
message: `Thread ${input.threadId} was not found`,
|
||||
cause: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.filter(
|
||||
(event) =>
|
||||
event.aggregateKind === "thread" &&
|
||||
event.aggregateId === input.threadId &&
|
||||
isThreadDetailEvent(event),
|
||||
),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event,
|
||||
})),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot: {
|
||||
snapshotSequence,
|
||||
thread: threadDetail.value,
|
||||
},
|
||||
}),
|
||||
liveStream,
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
@@ -838,6 +921,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
type: "providerStatuses" as const,
|
||||
payload: { providers },
|
||||
})),
|
||||
Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)),
|
||||
);
|
||||
const settingsUpdates = serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => ({
|
||||
@@ -847,13 +931,26 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
})),
|
||||
);
|
||||
|
||||
yield* Effect.all(
|
||||
[providerRegistry.refresh("codex"), providerRegistry.refresh("claudeAgent")],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
|
||||
|
||||
const liveUpdates = Stream.merge(
|
||||
keybindingsUpdates,
|
||||
Stream.merge(providerStatuses, settingsUpdates),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
version: 1 as const,
|
||||
type: "snapshot" as const,
|
||||
config: yield* loadServerConfig,
|
||||
}),
|
||||
Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
|
||||
liveUpdates,
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
@@ -29,7 +30,6 @@
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
|
||||
@@ -424,7 +424,7 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3773/api/auth/session");
|
||||
});
|
||||
|
||||
it("revalidates the server session state after a previous authenticated result", async () => {
|
||||
it("memoizes the authenticated gate state after the first successful read", async () => {
|
||||
const fetchMock = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(
|
||||
@@ -459,15 +459,9 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
status: "authenticated",
|
||||
});
|
||||
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
|
||||
status: "requires-auth",
|
||||
auth: {
|
||||
policy: "loopback-browser",
|
||||
bootstrapMethods: ["one-time-token"],
|
||||
sessionMethods: ["browser-session-cookie"],
|
||||
sessionCookieName: "t3_session",
|
||||
},
|
||||
status: "authenticated",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("creates a pairing credential from the authenticated auth endpoint", async () => {
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
|
||||
|
||||
describe("isScrollContainerNearBottom", () => {
|
||||
it("returns true when already at bottom", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 600,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true when within the auto-scroll threshold", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 540,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when the user is meaningfully above the bottom", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 520,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("clamps negative thresholds to zero", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom(
|
||||
{
|
||||
scrollTop: 539,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
},
|
||||
-1,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the default threshold for non-finite values", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom(
|
||||
{
|
||||
scrollTop: 540,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
},
|
||||
Number.NaN,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(AUTO_SCROLL_BOTTOM_THRESHOLD_PX).toBe(64);
|
||||
});
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
export const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 64;
|
||||
|
||||
interface ScrollPosition {
|
||||
scrollTop: number;
|
||||
clientHeight: number;
|
||||
scrollHeight: number;
|
||||
}
|
||||
|
||||
export function isScrollContainerNearBottom(
|
||||
position: ScrollPosition,
|
||||
thresholdPx = AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
|
||||
): boolean {
|
||||
const threshold = Number.isFinite(thresholdPx)
|
||||
? Math.max(0, thresholdPx)
|
||||
: AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
|
||||
|
||||
const { scrollTop, clientHeight, scrollHeight } = position;
|
||||
if (![scrollTop, clientHeight, scrollHeight].every(Number.isFinite)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const distanceFromBottom = scrollHeight - clientHeight - scrollTop;
|
||||
return distanceFromBottom <= threshold;
|
||||
}
|
||||
@@ -77,4 +77,53 @@ describe("clientPersistenceStorage", () => {
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reads and writes workspace documents as JSON blobs", async () => {
|
||||
const testWindow = getTestWindow();
|
||||
const {
|
||||
WORKSPACE_DOCUMENT_STORAGE_KEY,
|
||||
readBrowserWorkspaceDocument,
|
||||
writeBrowserWorkspaceDocument,
|
||||
} = await import("./clientPersistenceStorage");
|
||||
const workspaceDocument = {
|
||||
version: 1 as const,
|
||||
layoutEngine: "split" as const,
|
||||
rootNodeId: "node-1",
|
||||
nodesById: {
|
||||
"node-1": {
|
||||
id: "node-1",
|
||||
kind: "window" as const,
|
||||
windowId: "window-1",
|
||||
},
|
||||
},
|
||||
windowsById: {
|
||||
"window-1": {
|
||||
id: "window-1",
|
||||
surfaceId: "surface-1",
|
||||
},
|
||||
},
|
||||
surfacesById: {
|
||||
"surface-1": {
|
||||
id: "surface-1",
|
||||
kind: "thread" as const,
|
||||
input: {
|
||||
scope: "server" as const,
|
||||
threadRef: {
|
||||
environmentId: testEnvironmentId,
|
||||
threadId: "thread-1",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
focusedWindowId: "window-1",
|
||||
mobileActiveWindowId: "window-1",
|
||||
};
|
||||
|
||||
writeBrowserWorkspaceDocument(workspaceDocument);
|
||||
|
||||
expect(readBrowserWorkspaceDocument<typeof workspaceDocument>()).toEqual(workspaceDocument);
|
||||
expect(JSON.parse(testWindow.localStorage.getItem(WORKSPACE_DOCUMENT_STORAGE_KEY)!)).toEqual(
|
||||
workspaceDocument,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorag
|
||||
|
||||
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
|
||||
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
|
||||
export const WORKSPACE_DOCUMENT_STORAGE_KEY = "t3code:workspace-document:v1";
|
||||
|
||||
const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
@@ -34,6 +35,34 @@ function hasWindow(): boolean {
|
||||
return typeof window !== "undefined";
|
||||
}
|
||||
|
||||
function readBrowserJsonDocument<T>(storageKey: string): T | null {
|
||||
if (!hasWindow()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeBrowserJsonDocument<T>(storageKey: string, document: T): void {
|
||||
if (!hasWindow()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(storageKey, JSON.stringify(document));
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking the app.
|
||||
}
|
||||
}
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
record: PersistedSavedEnvironmentRecord,
|
||||
): PersistedSavedEnvironmentRecord {
|
||||
@@ -192,3 +221,11 @@ export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentId
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export function readBrowserWorkspaceDocument<T>(): T | null {
|
||||
return readBrowserJsonDocument<T>(WORKSPACE_DOCUMENT_STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function writeBrowserWorkspaceDocument<T>(document: T): void {
|
||||
writeBrowserJsonDocument(WORKSPACE_DOCUMENT_STORAGE_KEY, document);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
export interface CommandPaletteWorkspaceTarget {
|
||||
disposition: "split-right" | "split-down";
|
||||
}
|
||||
|
||||
interface CommandPaletteStore {
|
||||
open: boolean;
|
||||
workspaceTarget: CommandPaletteWorkspaceTarget | null;
|
||||
setOpen: (open: boolean) => void;
|
||||
toggleOpen: () => void;
|
||||
openWorkspaceTarget: (target: CommandPaletteWorkspaceTarget) => void;
|
||||
clearWorkspaceTarget: () => void;
|
||||
}
|
||||
|
||||
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
|
||||
open: false,
|
||||
workspaceTarget: null,
|
||||
setOpen: (open) => set({ open, ...(open ? {} : { workspaceTarget: null }) }),
|
||||
toggleOpen: () =>
|
||||
set((state) => {
|
||||
const next = !state.open;
|
||||
return { open: next, ...(next ? {} : { workspaceTarget: null }) };
|
||||
}),
|
||||
openWorkspaceTarget: (target) => set({ open: true, workspaceTarget: target }),
|
||||
clearWorkspaceTarget: () => set({ workspaceTarget: null }),
|
||||
}));
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
resolveEffectiveEnvMode,
|
||||
resolveEnvModeLabel,
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
@@ -157,6 +158,16 @@ describe("resolveCurrentWorkspaceLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveLockedWorkspaceLabel", () => {
|
||||
it("uses a shorter label for the main repo checkout", () => {
|
||||
expect(resolveLockedWorkspaceLabel(null)).toBe("Local checkout");
|
||||
});
|
||||
|
||||
it("uses a shorter label for an attached worktree", () => {
|
||||
expect(resolveLockedWorkspaceLabel("/repo/.t3/worktrees/feature-a")).toBe("Worktree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
it("strips the remote prefix from a remote ref", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
|
||||
|
||||
@@ -50,6 +50,10 @@ export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null):
|
||||
return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
|
||||
}
|
||||
|
||||
export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): string {
|
||||
return activeWorktreePath ? "Worktree" : "Local checkout";
|
||||
}
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
hasServerThread: boolean;
|
||||
|
||||
@@ -20,6 +20,9 @@ interface BranchToolbarProps {
|
||||
threadId: ThreadId;
|
||||
draftId?: DraftId;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
effectiveEnvModeOverride?: EnvMode;
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
envLocked: boolean;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
@@ -32,6 +35,9 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
threadId,
|
||||
draftId,
|
||||
onEnvModeChange,
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
envLocked,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
@@ -59,11 +65,13 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
const activeProject = useStore(activeProjectSelector);
|
||||
const hasActiveThread = serverThread !== undefined || draftThread !== null;
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: serverThread !== undefined,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const effectiveEnvMode =
|
||||
effectiveEnvModeOverride ??
|
||||
resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: serverThread !== undefined,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const envModeLocked = envLocked || (serverThread !== undefined && activeWorktreePath !== null);
|
||||
|
||||
const showEnvironmentPicker =
|
||||
@@ -98,6 +106,9 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
threadId={threadId}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
envLocked={envLocked}
|
||||
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
|
||||
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
|
||||
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
|
||||
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import {
|
||||
type CSSProperties,
|
||||
useCallback,
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
@@ -38,6 +37,7 @@ import {
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxListVirtualized,
|
||||
ComboboxPopup,
|
||||
ComboboxStatus,
|
||||
ComboboxTrigger,
|
||||
@@ -49,6 +49,9 @@ interface BranchToolbarBranchSelectorProps {
|
||||
threadId: ThreadId;
|
||||
draftId?: DraftId;
|
||||
envLocked: boolean;
|
||||
effectiveEnvModeOverride?: "local" | "worktree";
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
@@ -77,6 +80,9 @@ export function BranchToolbarBranchSelector({
|
||||
threadId,
|
||||
draftId,
|
||||
envLocked,
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
@@ -108,16 +114,21 @@ export function BranchToolbarBranchSelector({
|
||||
const activeProject = useStore(activeProjectSelector);
|
||||
|
||||
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
|
||||
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
|
||||
const activeThreadBranch =
|
||||
activeThreadBranchOverride !== undefined
|
||||
? activeThreadBranchOverride
|
||||
: (serverThread?.branch ?? draftThread?.branch ?? null);
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const branchCwd = activeWorktreePath ?? activeProjectCwd;
|
||||
const hasServerThread = serverThread !== undefined;
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const effectiveEnvMode =
|
||||
effectiveEnvModeOverride ??
|
||||
resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread branch mutation (colocated — only this component calls it)
|
||||
@@ -146,6 +157,7 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
onActiveThreadBranchOverrideChange?.(branch);
|
||||
setThreadBranchAction(threadRef, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
@@ -167,6 +179,7 @@ export function BranchToolbarBranchSelector({
|
||||
serverSession,
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
setThreadBranchAction,
|
||||
setDraftThreadContext,
|
||||
draftId,
|
||||
@@ -390,7 +403,7 @@ export function BranchToolbarBranchSelector({
|
||||
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combobox / virtualizer plumbing
|
||||
// Combobox / list plumbing
|
||||
// ---------------------------------------------------------------------------
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
@@ -425,49 +438,22 @@ export function BranchToolbarBranchSelector({
|
||||
|
||||
void fetchNextPage().catch(() => undefined);
|
||||
}, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
|
||||
const branchListVirtualizer = useVirtualizer({
|
||||
count: filteredBranchPickerItems.length,
|
||||
estimateSize: (index) =>
|
||||
filteredBranchPickerItems[index] === checkoutPullRequestItemValue ? 44 : 28,
|
||||
getScrollElement: () => branchListScrollElementRef.current,
|
||||
overscan: 12,
|
||||
enabled: isBranchMenuOpen && shouldVirtualizeBranchList,
|
||||
initialRect: {
|
||||
height: 224,
|
||||
width: 0,
|
||||
},
|
||||
});
|
||||
const virtualBranchRows = branchListVirtualizer.getVirtualItems();
|
||||
const setBranchListRef = useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
branchListScrollElementRef.current =
|
||||
(element?.parentElement as HTMLDivElement | null) ?? null;
|
||||
if (element) {
|
||||
branchListVirtualizer.measure();
|
||||
}
|
||||
},
|
||||
[branchListVirtualizer],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isBranchMenuOpen || !shouldVirtualizeBranchList) return;
|
||||
queueMicrotask(() => {
|
||||
branchListVirtualizer.measure();
|
||||
});
|
||||
}, [
|
||||
branchListVirtualizer,
|
||||
filteredBranchPickerItems.length,
|
||||
isBranchMenuOpen,
|
||||
shouldVirtualizeBranchList,
|
||||
]);
|
||||
const branchListRef = useRef<LegendListRef | null>(null);
|
||||
const setBranchListRef = useCallback((element: HTMLDivElement | null) => {
|
||||
branchListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isBranchMenuOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
branchListScrollElementRef.current?.scrollTo({ top: 0 });
|
||||
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
|
||||
if (shouldVirtualizeBranchList) {
|
||||
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
|
||||
} else {
|
||||
branchListScrollElementRef.current?.scrollTo({ top: 0 });
|
||||
}
|
||||
}, [deferredTrimmedBranchQuery, isBranchMenuOpen, shouldVirtualizeBranchList]);
|
||||
|
||||
useEffect(() => {
|
||||
const scrollElement = branchListScrollElementRef.current;
|
||||
@@ -487,8 +473,9 @@ export function BranchToolbarBranchSelector({
|
||||
}, [isBranchMenuOpen, maybeFetchNextBranchPage]);
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldVirtualizeBranchList) return;
|
||||
maybeFetchNextBranchPage();
|
||||
}, [branches.length, maybeFetchNextBranchPage]);
|
||||
}, [branches.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
|
||||
|
||||
const triggerLabel = getBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
@@ -496,7 +483,7 @@ export function BranchToolbarBranchSelector({
|
||||
resolvedActiveBranch,
|
||||
});
|
||||
|
||||
function renderPickerItem(itemValue: string, index: number, style?: CSSProperties) {
|
||||
function renderPickerItem(itemValue: string, index: number) {
|
||||
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
|
||||
return (
|
||||
<ComboboxItem
|
||||
@@ -504,7 +491,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
style={style}
|
||||
onClick={() => {
|
||||
if (!prReference || !onCheckoutPullRequestRequest) {
|
||||
return;
|
||||
@@ -529,7 +515,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
style={style}
|
||||
onClick={() => createBranch(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||
@@ -557,7 +542,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
style={style}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
@@ -575,8 +559,13 @@ export function BranchToolbarBranchSelector({
|
||||
autoHighlight
|
||||
virtualized={shouldVirtualizeBranchList}
|
||||
onItemHighlighted={(_value, eventDetails) => {
|
||||
if (!isBranchMenuOpen || eventDetails.index < 0) return;
|
||||
branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
|
||||
if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
|
||||
return;
|
||||
}
|
||||
branchListRef.current?.scrollIndexIntoView?.({
|
||||
index: eventDetails.index,
|
||||
animated: false,
|
||||
});
|
||||
}}
|
||||
onOpenChange={handleOpenChange}
|
||||
open={isBranchMenuOpen}
|
||||
@@ -604,30 +593,30 @@ export function BranchToolbarBranchSelector({
|
||||
</div>
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
<ComboboxList ref={setBranchListRef} className="max-h-56">
|
||||
{shouldVirtualizeBranchList ? (
|
||||
<div
|
||||
className="relative"
|
||||
style={{
|
||||
height: `${branchListVirtualizer.getTotalSize()}px`,
|
||||
{shouldVirtualizeBranchList ? (
|
||||
<ComboboxListVirtualized>
|
||||
<LegendList<string>
|
||||
ref={branchListRef}
|
||||
data={filteredBranchPickerItems}
|
||||
keyExtractor={(item) => item}
|
||||
renderItem={({ item, index }) => renderPickerItem(item, index)}
|
||||
estimatedItemSize={28}
|
||||
drawDistance={336}
|
||||
onEndReached={() => {
|
||||
if (hasNextPage && !isFetchingNextPage) {
|
||||
void fetchNextPage().catch(() => undefined);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{virtualBranchRows.map((virtualRow) => {
|
||||
const itemValue = filteredBranchPickerItems[virtualRow.index];
|
||||
if (!itemValue) return null;
|
||||
return renderPickerItem(itemValue, virtualRow.index, {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
});
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))
|
||||
)}
|
||||
</ComboboxList>
|
||||
style={{ maxHeight: "14rem" }}
|
||||
/>
|
||||
</ComboboxListVirtualized>
|
||||
) : (
|
||||
<ComboboxList ref={setBranchListRef} className="max-h-56">
|
||||
{filteredBranchPickerItems.map((itemValue, index) =>
|
||||
renderPickerItem(itemValue, index),
|
||||
)}
|
||||
</ComboboxList>
|
||||
)}
|
||||
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
|
||||
</ComboboxPopup>
|
||||
</Combobox>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { memo, useMemo } from "react";
|
||||
import {
|
||||
resolveCurrentWorkspaceLabel,
|
||||
resolveEnvModeLabel,
|
||||
resolveLockedWorkspaceLabel,
|
||||
type EnvMode,
|
||||
} from "./BranchToolbar.logic";
|
||||
import {
|
||||
@@ -43,12 +44,12 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
{activeWorktreePath ? (
|
||||
<>
|
||||
<FolderGitIcon className="size-3" />
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FolderIcon className="size-3" />
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,7 @@ import {
|
||||
deriveComposerSendState,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
resolveSendEnvMode,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
waitForStartedServerThread,
|
||||
} from "./ChatView.logic";
|
||||
@@ -82,6 +83,17 @@ describe("buildExpiredTerminalContextToastCopy", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSendEnvMode", () => {
|
||||
it("keeps worktree mode for git repositories", () => {
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");
|
||||
});
|
||||
|
||||
it("forces local mode for non-git repositories", () => {
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: false })).toBe("local");
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "local", isGitRepo: false })).toBe("local");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileMountedTerminalThreadIds", () => {
|
||||
it("keeps previously mounted open threads and adds the active open thread", () => {
|
||||
expect(
|
||||
@@ -530,6 +542,142 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not clear local dispatch while the session is running a newer turn than latestTurn", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: previousLatestTurn,
|
||||
session: {
|
||||
...previousSession,
|
||||
status: "running",
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.make("turn-2"),
|
||||
updatedAt: "2026-03-29T00:01:00.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not clear local dispatch while the session is running but latestTurn has not advanced yet", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: previousLatestTurn,
|
||||
session: {
|
||||
...previousSession,
|
||||
status: "running",
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: undefined,
|
||||
updatedAt: "2026-03-29T00:01:00.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("clears local dispatch once the running latestTurn matches the active session turn", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: {
|
||||
...previousLatestTurn,
|
||||
turnId: TurnId.make("turn-2"),
|
||||
state: "running",
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: null,
|
||||
},
|
||||
session: {
|
||||
...previousSession,
|
||||
status: "running",
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.make("turn-2"),
|
||||
updatedAt: "2026-03-29T00:01:01.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("clears local dispatch when the session changes without an observed running phase", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import { Schema } from "effect";
|
||||
import { selectThreadByRef, useStore } from "../store";
|
||||
@@ -17,10 +16,10 @@ import {
|
||||
stripInlineTerminalContextPlaceholders,
|
||||
type TerminalContextDraft,
|
||||
} from "../lib/terminalContext";
|
||||
import type { DraftThreadEnvMode } from "../composerDraftStore";
|
||||
|
||||
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
|
||||
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
|
||||
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
|
||||
|
||||
@@ -157,10 +156,11 @@ export function readFileAsDataUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
export function buildTemporaryWorktreeBranchName(): string {
|
||||
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||
const token = randomUUID().slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
export function resolveSendEnvMode(input: {
|
||||
requestedEnvMode: DraftThreadEnvMode;
|
||||
isGitRepo: boolean;
|
||||
}): DraftThreadEnvMode {
|
||||
return input.isGitRepo ? input.requestedEnvMode : "local";
|
||||
}
|
||||
|
||||
export function cloneComposerImageForRetry(
|
||||
@@ -322,23 +322,37 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
if (!input.localDispatch) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
input.phase === "running" ||
|
||||
input.hasPendingApproval ||
|
||||
input.hasPendingUserInput ||
|
||||
Boolean(input.threadError)
|
||||
) {
|
||||
if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const latestTurn = input.latestTurn ?? null;
|
||||
const session = input.session ?? null;
|
||||
|
||||
return (
|
||||
const latestTurnChanged =
|
||||
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
|
||||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
|
||||
|
||||
if (input.phase === "running") {
|
||||
if (!latestTurnChanged) {
|
||||
return false;
|
||||
}
|
||||
if (latestTurn?.startedAt === null || latestTurn === null) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
session?.activeTurnId !== undefined &&
|
||||
session.activeTurnId !== null &&
|
||||
latestTurn?.turnId !== session.activeTurnId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
latestTurnChanged ||
|
||||
input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) ||
|
||||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,166 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import type { Thread } from "../types";
|
||||
import {
|
||||
buildThreadActionItems,
|
||||
filterCommandPaletteGroups,
|
||||
type CommandPaletteGroup,
|
||||
} from "./CommandPalette.logic";
|
||||
|
||||
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
codexThreadId: null,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadActionItems", () => {
|
||||
it("orders threads by most recent activity and formats timestamps from updatedAt", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-03-25T12:00:00.000Z"));
|
||||
|
||||
try {
|
||||
const items = buildThreadActionItems({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-older"),
|
||||
title: "Older thread",
|
||||
updatedAt: "2026-03-24T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-newer"),
|
||||
title: "Newer thread",
|
||||
createdAt: "2026-03-20T00:00:00.000Z",
|
||||
updatedAt: "2026-03-20T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
projectTitleById: new Map([[PROJECT_ID, "Project"]]),
|
||||
sortOrder: "updated_at",
|
||||
icon: null,
|
||||
runThread: async (_thread) => undefined,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.value)).toEqual([
|
||||
"thread:thread-older",
|
||||
"thread:thread-newer",
|
||||
]);
|
||||
expect(items[0]?.timestamp).toBe("1d ago");
|
||||
expect(items[1]?.timestamp).toBe("5d ago");
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("ranks thread title matches ahead of contextual project-name matches", () => {
|
||||
const threadItems = buildThreadActionItems({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-context-match"),
|
||||
title: "Fix navbar spacing",
|
||||
updatedAt: "2026-03-20T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-title-match"),
|
||||
title: "Project kickoff notes",
|
||||
createdAt: "2026-03-02T00:00:00.000Z",
|
||||
updatedAt: "2026-03-19T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
projectTitleById: new Map([[PROJECT_ID, "Project"]]),
|
||||
sortOrder: "updated_at",
|
||||
icon: null,
|
||||
runThread: async (_thread) => undefined,
|
||||
});
|
||||
|
||||
const groups = filterCommandPaletteGroups({
|
||||
activeGroups: [],
|
||||
query: "project",
|
||||
isInSubmenu: false,
|
||||
projectSearchItems: [],
|
||||
threadSearchItems: threadItems,
|
||||
});
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.value).toBe("threads-search");
|
||||
expect(groups[0]?.items.map((item) => item.value)).toEqual([
|
||||
"thread:thread-title-match",
|
||||
"thread:thread-context-match",
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves thread project-name matches when there is no stronger title match", () => {
|
||||
const group: CommandPaletteGroup = {
|
||||
value: "threads-search",
|
||||
label: "Threads",
|
||||
items: [
|
||||
{
|
||||
kind: "action",
|
||||
value: "thread:project-context-only",
|
||||
searchTerms: ["Fix navbar spacing", "Project"],
|
||||
title: "Fix navbar spacing",
|
||||
description: "Project",
|
||||
icon: null,
|
||||
run: async () => undefined,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const groups = filterCommandPaletteGroups({
|
||||
activeGroups: [group],
|
||||
query: "project",
|
||||
isInSubmenu: false,
|
||||
projectSearchItems: [],
|
||||
threadSearchItems: [],
|
||||
});
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.items.map((item) => item.value)).toEqual(["thread:project-context-only"]);
|
||||
});
|
||||
|
||||
it("filters archived threads out of thread search items", () => {
|
||||
const items = buildThreadActionItems({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-active"),
|
||||
title: "Active thread",
|
||||
createdAt: "2026-03-02T00:00:00.000Z",
|
||||
updatedAt: "2026-03-19T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-archived"),
|
||||
title: "Archived thread",
|
||||
archivedAt: "2026-03-20T00:00:00.000Z",
|
||||
updatedAt: "2026-03-20T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
projectTitleById: new Map([[PROJECT_ID, "Project"]]),
|
||||
sortOrder: "updated_at",
|
||||
icon: null,
|
||||
runThread: async (_thread) => undefined,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.value)).toEqual(["thread:thread-active"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import { type KeybindingCommand } from "@t3tools/contracts";
|
||||
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import { type ReactNode } from "react";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
import { type Project, type SidebarThreadSummary, type Thread } from "../types";
|
||||
|
||||
export const RECENT_THREAD_LIMIT = 12;
|
||||
export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80";
|
||||
export const ADDON_ICON_CLASS = "size-4";
|
||||
|
||||
export interface CommandPaletteItem {
|
||||
readonly kind: "action" | "submenu";
|
||||
readonly value: string;
|
||||
readonly searchTerms: ReadonlyArray<string>;
|
||||
readonly title: ReactNode;
|
||||
readonly description?: string;
|
||||
readonly timestamp?: string;
|
||||
readonly icon: ReactNode;
|
||||
readonly shortcutCommand?: KeybindingCommand;
|
||||
}
|
||||
|
||||
export interface CommandPaletteActionItem extends CommandPaletteItem {
|
||||
readonly kind: "action";
|
||||
readonly keepOpen?: boolean;
|
||||
readonly run: () => Promise<void>;
|
||||
}
|
||||
|
||||
export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
|
||||
readonly kind: "submenu";
|
||||
readonly addonIcon: ReactNode;
|
||||
readonly groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
readonly initialQuery?: string;
|
||||
}
|
||||
|
||||
export interface CommandPaletteGroup {
|
||||
readonly value: string;
|
||||
readonly label: string;
|
||||
readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
|
||||
}
|
||||
|
||||
export interface CommandPaletteView {
|
||||
readonly addonIcon: ReactNode;
|
||||
readonly groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
readonly initialQuery?: string;
|
||||
}
|
||||
|
||||
export type CommandPaletteMode = "root" | "submenu";
|
||||
|
||||
export function normalizeSearchText(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
export function buildProjectActionItems(input: {
|
||||
projects: ReadonlyArray<Project>;
|
||||
valuePrefix: string;
|
||||
icon: (project: Project) => ReactNode;
|
||||
runProject: (project: Project) => Promise<void>;
|
||||
}): CommandPaletteActionItem[] {
|
||||
return input.projects.map((project) => ({
|
||||
kind: "action",
|
||||
value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
|
||||
searchTerms: [project.name, project.cwd],
|
||||
title: project.name,
|
||||
description: project.cwd,
|
||||
icon: input.icon(project),
|
||||
run: async () => {
|
||||
await input.runProject(project);
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildThreadActionItems(input: {
|
||||
threads: ReadonlyArray<
|
||||
Pick<
|
||||
SidebarThreadSummary,
|
||||
"archivedAt" | "branch" | "createdAt" | "environmentId" | "id" | "projectId" | "title"
|
||||
> & {
|
||||
updatedAt?: string | undefined;
|
||||
latestUserMessageAt?: string | null;
|
||||
}
|
||||
>;
|
||||
activeThreadId?: Thread["id"];
|
||||
projectTitleById: ReadonlyMap<Project["id"], string>;
|
||||
sortOrder: SidebarThreadSortOrder;
|
||||
icon: ReactNode;
|
||||
runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
|
||||
limit?: number;
|
||||
}): CommandPaletteActionItem[] {
|
||||
const sortedThreads = sortThreads(
|
||||
input.threads.filter((thread) => thread.archivedAt === null),
|
||||
input.sortOrder,
|
||||
);
|
||||
const visibleThreads =
|
||||
input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
|
||||
|
||||
return visibleThreads.map((thread) => {
|
||||
const projectTitle = input.projectTitleById.get(thread.projectId);
|
||||
const descriptionParts: string[] = [];
|
||||
|
||||
if (projectTitle) {
|
||||
descriptionParts.push(projectTitle);
|
||||
}
|
||||
if (thread.branch) {
|
||||
descriptionParts.push(`#${thread.branch}`);
|
||||
}
|
||||
if (thread.id === input.activeThreadId) {
|
||||
descriptionParts.push("Current thread");
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "action",
|
||||
value: `thread:${thread.id}`,
|
||||
searchTerms: [thread.title, projectTitle ?? "", thread.branch ?? ""],
|
||||
title: thread.title,
|
||||
description: descriptionParts.join(" · "),
|
||||
timestamp: formatRelativeTimeLabel(
|
||||
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
|
||||
),
|
||||
icon: input.icon,
|
||||
run: async () => {
|
||||
await input.runThread(thread);
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
|
||||
const normalizedField = normalizeSearchText(field);
|
||||
if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
|
||||
return Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
if (normalizedField === normalizedQuery) {
|
||||
return 3;
|
||||
}
|
||||
if (normalizedField.startsWith(normalizedQuery)) {
|
||||
return 2;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function rankCommandPaletteItemMatch(
|
||||
item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
|
||||
normalizedQuery: string,
|
||||
): number {
|
||||
const terms = item.searchTerms.filter((term) => term.length > 0);
|
||||
if (terms.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (const [index, field] of terms.entries()) {
|
||||
const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
|
||||
if (fieldRank !== Number.NEGATIVE_INFINITY) {
|
||||
return 1_000 - index * 100 + fieldRank;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function filterCommandPaletteGroups(input: {
|
||||
activeGroups: ReadonlyArray<CommandPaletteGroup>;
|
||||
query: string;
|
||||
isInSubmenu: boolean;
|
||||
projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
|
||||
threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
|
||||
}): CommandPaletteGroup[] {
|
||||
const isActionsFilter = input.query.startsWith(">");
|
||||
const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
|
||||
const normalizedQuery = normalizeSearchText(searchQuery);
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
if (isActionsFilter) {
|
||||
return input.activeGroups.filter((group) => group.value === "actions");
|
||||
}
|
||||
return [...input.activeGroups];
|
||||
}
|
||||
|
||||
let baseGroups = [...input.activeGroups];
|
||||
if (isActionsFilter) {
|
||||
baseGroups = baseGroups.filter((group) => group.value === "actions");
|
||||
} else if (!input.isInSubmenu) {
|
||||
baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
|
||||
}
|
||||
|
||||
const searchableGroups = [...baseGroups];
|
||||
if (!input.isInSubmenu && !isActionsFilter) {
|
||||
if (input.projectSearchItems.length > 0) {
|
||||
searchableGroups.push({
|
||||
value: "projects-search",
|
||||
label: "Projects",
|
||||
items: input.projectSearchItems,
|
||||
});
|
||||
}
|
||||
if (input.threadSearchItems.length > 0) {
|
||||
searchableGroups.push({
|
||||
value: "threads-search",
|
||||
label: "Threads",
|
||||
items: input.threadSearchItems,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return searchableGroups.flatMap((group) => {
|
||||
const items = group.items
|
||||
.map((item, index) => {
|
||||
const haystack = normalizeSearchText(item.searchTerms.join(" "));
|
||||
if (!haystack.includes(normalizedQuery)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
item,
|
||||
index,
|
||||
rank: rankCommandPaletteItemMatch(item, normalizedQuery),
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(entry): entry is { item: (typeof group.items)[number]; index: number; rank: number } =>
|
||||
entry !== null,
|
||||
)
|
||||
.toSorted((left, right) => right.rank - left.rank || left.index - right.index)
|
||||
.map((entry) => entry.item);
|
||||
|
||||
if (items.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [{ value: group.value, label: group.label, items }];
|
||||
});
|
||||
}
|
||||
|
||||
export function getCommandPaletteMode(input: {
|
||||
currentView: CommandPaletteView | null;
|
||||
}): CommandPaletteMode {
|
||||
return input.currentView ? "submenu" : "root";
|
||||
}
|
||||
|
||||
export function buildRootGroups(input: {
|
||||
actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
|
||||
recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
|
||||
}): CommandPaletteGroup[] {
|
||||
const groups: CommandPaletteGroup[] = [];
|
||||
if (input.actionItems.length > 0) {
|
||||
groups.push({ value: "actions", label: "Actions", items: input.actionItems });
|
||||
}
|
||||
if (input.recentThreadItems.length > 0) {
|
||||
groups.push({
|
||||
value: "recent-threads",
|
||||
label: "Recent Threads",
|
||||
items: input.recentThreadItems,
|
||||
});
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
|
||||
switch (mode) {
|
||||
case "root":
|
||||
return "Search commands, projects, and threads...";
|
||||
case "submenu":
|
||||
return "Search...";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,799 @@
|
||||
"use client";
|
||||
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { ProjectId } from "@t3tools/contracts";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
ArrowDownIcon,
|
||||
ArrowLeftIcon,
|
||||
ArrowRightIcon,
|
||||
ArrowUpIcon,
|
||||
Columns2Icon,
|
||||
MessageSquareIcon,
|
||||
Rows2Icon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
TerminalSquareIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import {
|
||||
WORKSPACE_COMMAND_METADATA,
|
||||
useWorkspaceCommandExecutor,
|
||||
} from "../hooks/useWorkspaceCommandExecutor";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
startNewThreadInProjectFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { cn } from "../lib/utils";
|
||||
import {
|
||||
selectProjectsAcrossEnvironments,
|
||||
selectSidebarThreadsAcrossEnvironments,
|
||||
useStore,
|
||||
} from "../store";
|
||||
import { useThreadTerminalOpen } from "../terminalStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import { useWorkspaceStore } from "../workspace/store";
|
||||
import { serverThreadSurfaceInput } from "../workspace/types";
|
||||
import {
|
||||
ADDON_ICON_CLASS,
|
||||
buildProjectActionItems,
|
||||
buildRootGroups,
|
||||
buildThreadActionItems,
|
||||
type CommandPaletteActionItem,
|
||||
type CommandPaletteSubmenuItem,
|
||||
type CommandPaletteView,
|
||||
filterCommandPaletteGroups,
|
||||
getCommandPaletteInputPlaceholder,
|
||||
getCommandPaletteMode,
|
||||
ITEM_ICON_CLASS,
|
||||
RECENT_THREAD_LIMIT,
|
||||
} from "./CommandPalette.logic";
|
||||
import { CommandPaletteResults } from "./CommandPaletteResults";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandDialogPopup,
|
||||
CommandFooter,
|
||||
CommandInput,
|
||||
CommandPanel,
|
||||
} from "./ui/command";
|
||||
import { Kbd, KbdGroup } from "./ui/kbd";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
|
||||
export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
const toggleOpen = useCommandPaletteStore((store) => store.toggleOpen);
|
||||
const keybindings = useServerKeybindings();
|
||||
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
|
||||
const routeTarget = useParams({
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
|
||||
const terminalOpen = useThreadTerminalOpen(routeThreadRef);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
context: {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen,
|
||||
},
|
||||
});
|
||||
if (command !== "commandPalette.toggle") {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleOpen();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
return (
|
||||
<ComposerHandleContext.Provider value={composerHandleRef}>
|
||||
{children}
|
||||
<CommandDialog open={open} onOpenChange={setOpen}>
|
||||
<CommandPaletteDialog />
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandPaletteDialog() {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setOpen(false);
|
||||
};
|
||||
}, [setOpen]);
|
||||
|
||||
if (!open) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <OpenCommandPaletteDialog />;
|
||||
}
|
||||
|
||||
function OpenCommandPaletteDialog() {
|
||||
const navigate = useNavigate();
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
const workspaceTarget = useCommandPaletteStore((store) => store.workspaceTarget);
|
||||
const clearWorkspaceTarget = useCommandPaletteStore((store) => store.clearWorkspaceTarget);
|
||||
const composerHandleRef = useComposerHandleContext();
|
||||
const [query, setQuery] = useState("");
|
||||
const deferredQuery = useDeferredValue(query);
|
||||
const isActionsOnly = deferredQuery.startsWith(">");
|
||||
const settings = useSettings();
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
|
||||
useHandleNewThread();
|
||||
const projects = useStore(useShallow(selectProjectsAcrossEnvironments));
|
||||
const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments));
|
||||
const keybindings = useServerKeybindings();
|
||||
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
|
||||
const currentView = viewStack.at(-1) ?? null;
|
||||
const paletteMode = getCommandPaletteMode({ currentView });
|
||||
const { canOpenTerminalSurface, canSplitFocusedPane, executeWorkspaceCommand } =
|
||||
useWorkspaceCommandExecutor();
|
||||
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
|
||||
const workspaceWindowCount = useWorkspaceStore(
|
||||
(state) => Object.keys(state.document.windowsById).length,
|
||||
);
|
||||
const canUseSpatialWorkspaceCommands = workspaceWindowCount > 1;
|
||||
|
||||
const projectTitleById = useMemo(
|
||||
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.name])),
|
||||
[projects],
|
||||
);
|
||||
|
||||
const activeThreadId = activeThread?.id;
|
||||
const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null;
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
() => async (project: (typeof projects)[number]) => {
|
||||
const latestThread = getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === project.environmentId),
|
||||
project.id,
|
||||
settings.sidebarThreadSortOrder,
|
||||
);
|
||||
if (latestThread) {
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(
|
||||
scopeThreadRef(latestThread.environmentId, latestThread.id),
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await handleNewThread(scopeProjectRef(project.environmentId, project.id), {
|
||||
envMode: settings.defaultThreadEnvMode,
|
||||
});
|
||||
},
|
||||
[
|
||||
handleNewThread,
|
||||
navigate,
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.sidebarThreadSortOrder,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
const projectSearchItems = useMemo(
|
||||
() =>
|
||||
buildProjectActionItems({
|
||||
projects,
|
||||
valuePrefix: "project",
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.cwd}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
),
|
||||
runProject: openProjectFromSearch,
|
||||
}),
|
||||
[openProjectFromSearch, projects],
|
||||
);
|
||||
|
||||
const projectThreadItems = useMemo(
|
||||
() =>
|
||||
buildProjectActionItems({
|
||||
projects,
|
||||
valuePrefix: "new-thread-in",
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.cwd}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
),
|
||||
runProject: async (project) => {
|
||||
await startNewThreadInProjectFromContext(
|
||||
{
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
defaultThreadEnvMode: settings.defaultThreadEnvMode,
|
||||
handleNewThread,
|
||||
},
|
||||
scopeProjectRef(project.environmentId, project.id),
|
||||
);
|
||||
},
|
||||
}),
|
||||
[
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
projects,
|
||||
settings.defaultThreadEnvMode,
|
||||
],
|
||||
);
|
||||
|
||||
const allThreadItems = useMemo(
|
||||
() =>
|
||||
buildThreadActionItems({
|
||||
threads,
|
||||
...(activeThreadId ? { activeThreadId } : {}),
|
||||
projectTitleById,
|
||||
sortOrder: settings.sidebarThreadSortOrder,
|
||||
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
runThread: async (thread) => {
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
|
||||
});
|
||||
},
|
||||
}),
|
||||
[activeThreadId, navigate, projectTitleById, settings.sidebarThreadSortOrder, threads],
|
||||
);
|
||||
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
|
||||
const workspaceTargetThreadItems = useMemo(() => {
|
||||
if (!workspaceTarget) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return buildThreadActionItems({
|
||||
threads,
|
||||
...(activeThreadId ? { activeThreadId } : {}),
|
||||
projectTitleById,
|
||||
sortOrder: settings.sidebarThreadSortOrder,
|
||||
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
runThread: async (thread) => {
|
||||
openThreadSurface(
|
||||
serverThreadSurfaceInput(scopeThreadRef(thread.environmentId, thread.id)),
|
||||
workspaceTarget.disposition,
|
||||
);
|
||||
},
|
||||
});
|
||||
}, [
|
||||
activeThreadId,
|
||||
openThreadSurface,
|
||||
projectTitleById,
|
||||
settings.sidebarThreadSortOrder,
|
||||
threads,
|
||||
workspaceTarget,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!workspaceTarget) {
|
||||
return;
|
||||
}
|
||||
setViewStack([]);
|
||||
setQuery("");
|
||||
}, [workspaceTarget]);
|
||||
|
||||
function pushView(item: CommandPaletteSubmenuItem): void {
|
||||
setViewStack((previousViews) => [
|
||||
...previousViews,
|
||||
{
|
||||
addonIcon: item.addonIcon,
|
||||
groups: item.groups,
|
||||
...(item.initialQuery ? { initialQuery: item.initialQuery } : {}),
|
||||
},
|
||||
]);
|
||||
setQuery(item.initialQuery ?? "");
|
||||
}
|
||||
|
||||
function popView(): void {
|
||||
setViewStack((previousViews) => previousViews.slice(0, -1));
|
||||
setQuery("");
|
||||
}
|
||||
|
||||
function leaveSubmenu(): void {
|
||||
if (currentView) {
|
||||
popView();
|
||||
return;
|
||||
}
|
||||
clearWorkspaceTarget();
|
||||
setQuery("");
|
||||
}
|
||||
|
||||
function handleQueryChange(nextQuery: string): void {
|
||||
setQuery(nextQuery);
|
||||
if (nextQuery === "" && currentView?.initialQuery) {
|
||||
popView();
|
||||
}
|
||||
}
|
||||
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (projects.length > 0) {
|
||||
const activeProjectTitle = currentProjectId
|
||||
? (projectTitleById.get(currentProjectId) ?? null)
|
||||
: null;
|
||||
|
||||
if (activeProjectTitle) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:new-thread",
|
||||
searchTerms: ["new thread", "chat", "create", "draft"],
|
||||
title: (
|
||||
<>
|
||||
New thread in <span className="font-semibold">{activeProjectTitle}</span>
|
||||
</>
|
||||
),
|
||||
icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "chat.new",
|
||||
run: async () => {
|
||||
await startNewThreadFromContext({
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
defaultThreadEnvMode: settings.defaultThreadEnvMode,
|
||||
handleNewThread,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
actionItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:new-thread-in",
|
||||
searchTerms: ["new thread", "project", "pick", "choose", "select"],
|
||||
title: "New thread in...",
|
||||
icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
|
||||
});
|
||||
}
|
||||
|
||||
if (canOpenTerminalSurface) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-terminal-split-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitRight"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitRight"].title,
|
||||
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.terminal.splitRight",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.terminal.splitRight");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-terminal-split-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitDown"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitDown"].title,
|
||||
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.terminal.splitDown",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.terminal.splitDown");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (canSplitFocusedPane) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-split-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.splitRight"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.splitRight"].title,
|
||||
icon: <Columns2Icon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.splitRight",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.splitRight");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-split-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.splitDown"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.splitDown"].title,
|
||||
icon: <Rows2Icon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.splitDown",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.splitDown");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-close",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.close"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.close"].title,
|
||||
icon: <XIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.close",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.close");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-toggle-zoom",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.toggleZoom"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.toggleZoom"].title,
|
||||
icon: <Columns2Icon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.toggleZoom",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.toggleZoom");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (canUseSpatialWorkspaceCommands) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-previous",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.previous"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.previous"].title,
|
||||
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.previous",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.previous");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-next",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.next"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.next"].title,
|
||||
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.next",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.next");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-left",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.left"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.left"].title,
|
||||
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.left",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.left");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.right"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.right"].title,
|
||||
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.right",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.right");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-up",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.up"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.up"].title,
|
||||
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.up",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.up");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.down"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.down"].title,
|
||||
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.down",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.down");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-resize-left",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeLeft"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeLeft"].title,
|
||||
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.resizeLeft",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.resizeLeft");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-resize-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeRight"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeRight"].title,
|
||||
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.resizeRight",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.resizeRight");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-resize-up",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeUp"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeUp"].title,
|
||||
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.resizeUp",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.resizeUp");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-resize-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeDown"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeDown"].title,
|
||||
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.resizeDown",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.resizeDown");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-equalize",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.equalize"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.equalize"].title,
|
||||
icon: <Rows2Icon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.equalize",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.equalize");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-move-left",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveLeft"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveLeft"].title,
|
||||
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.moveLeft",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.moveLeft");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-move-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveRight"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveRight"].title,
|
||||
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.moveRight",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.moveRight");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-move-up",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveUp"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveUp"].title,
|
||||
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.moveUp",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.moveUp");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-move-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveDown"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveDown"].title,
|
||||
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.moveDown",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.moveDown");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:settings",
|
||||
searchTerms: ["settings", "preferences", "configuration", "keybindings"],
|
||||
title: "Open settings",
|
||||
icon: <SettingsIcon className={ITEM_ICON_CLASS} />,
|
||||
run: async () => {
|
||||
await navigate({ to: "/settings" });
|
||||
},
|
||||
});
|
||||
|
||||
const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
|
||||
const workspaceTargetGroups = useMemo(() => {
|
||||
if (!workspaceTarget) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const items: CommandPaletteActionItem[] = [];
|
||||
if (canOpenTerminalSurface) {
|
||||
const targetCommand =
|
||||
workspaceTarget.disposition === "split-right"
|
||||
? "workspace.terminal.splitRight"
|
||||
: "workspace.terminal.splitDown";
|
||||
items.push({
|
||||
kind: "action",
|
||||
value: `action:workspace-target:${targetCommand}`,
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA[targetCommand].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA[targetCommand].title,
|
||||
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: targetCommand,
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand(targetCommand);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return [
|
||||
...(items.length > 0 ? [{ value: "actions", label: "Actions", items }] : []),
|
||||
...(workspaceTargetThreadItems.length > 0
|
||||
? [{ value: "threads", label: "Threads", items: workspaceTargetThreadItems }]
|
||||
: []),
|
||||
];
|
||||
}, [
|
||||
canOpenTerminalSurface,
|
||||
executeWorkspaceCommand,
|
||||
workspaceTarget,
|
||||
workspaceTargetThreadItems,
|
||||
]);
|
||||
const activeGroups = currentView
|
||||
? currentView.groups
|
||||
: workspaceTarget
|
||||
? workspaceTargetGroups
|
||||
: rootGroups;
|
||||
|
||||
const displayedGroups = filterCommandPaletteGroups({
|
||||
activeGroups,
|
||||
query: deferredQuery,
|
||||
isInSubmenu: currentView !== null || workspaceTarget !== null,
|
||||
projectSearchItems: projectSearchItems,
|
||||
threadSearchItems: allThreadItems,
|
||||
});
|
||||
|
||||
const isSubmenu = paletteMode === "submenu" || workspaceTarget !== null;
|
||||
const inputPlaceholder = workspaceTarget
|
||||
? "Open in split..."
|
||||
: getCommandPaletteInputPlaceholder(paletteMode);
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
|
||||
if (event.key === "Backspace" && query === "" && isSubmenu) {
|
||||
event.preventDefault();
|
||||
leaveSubmenu();
|
||||
}
|
||||
}
|
||||
|
||||
function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void {
|
||||
if (item.kind === "submenu") {
|
||||
pushView(item);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!item.keepOpen) {
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
void item.run().catch((error: unknown) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to run command",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<CommandDialogPopup
|
||||
aria-label="Command palette"
|
||||
className="overflow-hidden p-0"
|
||||
data-testid="command-palette"
|
||||
finalFocus={() => {
|
||||
composerHandleRef?.current?.focusAtEnd();
|
||||
return false;
|
||||
}}
|
||||
>
|
||||
<Command
|
||||
key={`${viewStack.length}-${workspaceTarget?.disposition ?? "root"}`}
|
||||
aria-label="Command palette"
|
||||
autoHighlight="always"
|
||||
mode="none"
|
||||
onValueChange={handleQueryChange}
|
||||
value={query}
|
||||
>
|
||||
<CommandInput
|
||||
placeholder={inputPlaceholder}
|
||||
wrapperClassName={
|
||||
isSubmenu
|
||||
? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto [&_[data-slot=autocomplete-start-addon]]:cursor-pointer"
|
||||
: undefined
|
||||
}
|
||||
{...(isSubmenu
|
||||
? {
|
||||
startAddon: (
|
||||
<button
|
||||
type="button"
|
||||
className="flex cursor-pointer items-center"
|
||||
aria-label="Back"
|
||||
onClick={leaveSubmenu}
|
||||
>
|
||||
<ArrowLeftIcon />
|
||||
</button>
|
||||
),
|
||||
}
|
||||
: {})}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
<CommandPanel className="max-h-[min(28rem,70vh)]">
|
||||
<CommandPaletteResults
|
||||
groups={displayedGroups}
|
||||
isActionsOnly={isActionsOnly}
|
||||
keybindings={keybindings}
|
||||
onExecuteItem={executeItem}
|
||||
/>
|
||||
</CommandPanel>
|
||||
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
|
||||
<div className="flex items-center gap-3">
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>
|
||||
<ArrowUpIcon />
|
||||
</Kbd>
|
||||
<Kbd>
|
||||
<ArrowDownIcon />
|
||||
</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Navigate</span>
|
||||
</KbdGroup>
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Select</span>
|
||||
</KbdGroup>
|
||||
{isSubmenu ? (
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Backspace</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Back</span>
|
||||
</KbdGroup>
|
||||
) : null}
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Esc</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Close</span>
|
||||
</KbdGroup>
|
||||
</div>
|
||||
</CommandFooter>
|
||||
</Command>
|
||||
</CommandDialogPopup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { type ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { ChevronRightIcon } from "lucide-react";
|
||||
import { shortcutLabelForCommand } from "../keybindings";
|
||||
import {
|
||||
type CommandPaletteActionItem,
|
||||
type CommandPaletteGroup,
|
||||
type CommandPaletteSubmenuItem,
|
||||
} from "./CommandPalette.logic";
|
||||
import {
|
||||
CommandCollection,
|
||||
CommandGroup,
|
||||
CommandGroupLabel,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandShortcut,
|
||||
} from "./ui/command";
|
||||
|
||||
interface CommandPaletteResultsProps {
|
||||
emptyStateMessage?: string;
|
||||
groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
isActionsOnly: boolean;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
|
||||
}
|
||||
|
||||
export function CommandPaletteResults(props: CommandPaletteResultsProps) {
|
||||
if (props.groups.length === 0) {
|
||||
return (
|
||||
<div className="py-10 text-center text-sm text-muted-foreground">
|
||||
{props.emptyStateMessage ??
|
||||
(props.isActionsOnly
|
||||
? "No matching actions."
|
||||
: "No matching commands, projects, or threads.")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CommandList>
|
||||
{props.groups.map((group) => (
|
||||
<CommandGroup items={group.items} key={group.value}>
|
||||
<CommandGroupLabel>{group.label}</CommandGroupLabel>
|
||||
<CommandCollection>
|
||||
{(item) => (
|
||||
<CommandPaletteResultRow
|
||||
item={item}
|
||||
key={item.value}
|
||||
keybindings={props.keybindings}
|
||||
onExecuteItem={props.onExecuteItem}
|
||||
/>
|
||||
)}
|
||||
</CommandCollection>
|
||||
</CommandGroup>
|
||||
))}
|
||||
</CommandList>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandPaletteResultRow(props: {
|
||||
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
|
||||
}) {
|
||||
const shortcutLabel = props.item.shortcutCommand
|
||||
? shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
value={props.item.value}
|
||||
className="cursor-pointer gap-2"
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
props.onExecuteItem(props.item);
|
||||
}}
|
||||
>
|
||||
{props.item.icon}
|
||||
{props.item.description ? (
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-sm text-foreground">{props.item.title}</span>
|
||||
<span className="truncate text-muted-foreground/70 text-xs">
|
||||
{props.item.description}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex min-w-0 items-center gap-1.5 truncate text-sm text-foreground">
|
||||
<span className="truncate">{props.item.title}</span>
|
||||
</span>
|
||||
)}
|
||||
{props.item.timestamp ? (
|
||||
<span className="min-w-12 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground/70">
|
||||
{props.item.timestamp}
|
||||
</span>
|
||||
) : null}
|
||||
{shortcutLabel ? <CommandShortcut>{shortcutLabel}</CommandShortcut> : null}
|
||||
{props.item.kind === "submenu" ? (
|
||||
<ChevronRightIcon className="ml-auto size-4 shrink-0 text-muted-foreground/50" />
|
||||
) : null}
|
||||
</CommandItem>
|
||||
);
|
||||
}
|
||||
@@ -890,6 +890,7 @@ export interface ComposerPromptEditorHandle {
|
||||
focus: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
focusAtEnd: () => void;
|
||||
isFocused: () => boolean;
|
||||
readSnapshot: () => {
|
||||
value: string;
|
||||
cursor: number;
|
||||
@@ -1383,7 +1384,6 @@ function ComposerSurroundSelectionPlugin(props: {
|
||||
const onCompositionEnd = () => {
|
||||
tryApplyDeadKeyBacktickSurround({ finalAttempt: true });
|
||||
};
|
||||
|
||||
let activeRootElement: HTMLElement | null = null;
|
||||
const unregisterRootListener = editor.registerRootListener((rootElement, prevRootElement) => {
|
||||
prevRootElement?.removeEventListener("keydown", onKeyDown);
|
||||
@@ -1493,7 +1493,7 @@ function ComposerPromptEditorInner({
|
||||
if (shouldRewriteEditorState) {
|
||||
$setComposerEditorPrompt(value, terminalContexts, skillMetadataRef.current);
|
||||
}
|
||||
if (shouldRewriteEditorState || isFocused) {
|
||||
if (isFocused) {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
}
|
||||
});
|
||||
@@ -1508,22 +1508,19 @@ function ComposerPromptEditorInner({
|
||||
if (!rootElement) return;
|
||||
const boundedCursor = clampCollapsedComposerCursor(snapshotRef.current.value, nextCursor);
|
||||
rootElement.focus();
|
||||
isApplyingControlledUpdateRef.current = true;
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(boundedCursor);
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
isApplyingControlledUpdateRef.current = false;
|
||||
});
|
||||
snapshotRef.current = {
|
||||
value: snapshotRef.current.value,
|
||||
cursor: boundedCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
|
||||
terminalContextIds: snapshotRef.current.terminalContextIds,
|
||||
};
|
||||
onChangeRef.current(
|
||||
snapshotRef.current.value,
|
||||
boundedCursor,
|
||||
snapshotRef.current.expandedCursor,
|
||||
false,
|
||||
snapshotRef.current.terminalContextIds,
|
||||
);
|
||||
},
|
||||
[editor],
|
||||
);
|
||||
@@ -1577,9 +1574,13 @@ function ComposerPromptEditorInner({
|
||||
),
|
||||
);
|
||||
},
|
||||
isFocused: () => {
|
||||
const rootElement = editor.getRootElement();
|
||||
return Boolean(rootElement && document.activeElement === rootElement);
|
||||
},
|
||||
readSnapshot,
|
||||
}),
|
||||
[focusAt, readSnapshot],
|
||||
[editor, focusAt, readSnapshot],
|
||||
);
|
||||
|
||||
const handleEditorChange = useCallback((editorState: EditorState) => {
|
||||
|
||||
@@ -429,12 +429,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const headerRow = (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
|
||||
{canScrollTurnStripLeft && (
|
||||
<div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-linear-to-r from-card to-transparent" />
|
||||
)}
|
||||
{canScrollTurnStripRight && (
|
||||
<div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-linear-to-l from-card to-transparent" />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
@@ -466,6 +460,13 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div
|
||||
ref={turnStripRef}
|
||||
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
|
||||
style={
|
||||
canScrollTurnStripLeft || canScrollTurnStripRight
|
||||
? {
|
||||
maskImage: `linear-gradient(to right, ${canScrollTurnStripLeft ? "transparent 24px, black 72px" : "black"}, ${canScrollTurnStripRight ? "black calc(100% - 72px), transparent calc(100% - 24px)" : "black"})`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onWheel={onTurnStripWheel}
|
||||
>
|
||||
<button
|
||||
|
||||
@@ -10,8 +10,10 @@ export type DiffPanelMode = "inline" | "sheet" | "sidebar";
|
||||
function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) {
|
||||
const shouldUseDragRegion = isElectron && mode !== "sheet";
|
||||
return cn(
|
||||
"flex items-center justify-between gap-2 px-4",
|
||||
shouldUseDragRegion ? "drag-region h-[52px] border-b border-border" : "h-12",
|
||||
"flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
|
||||
shouldUseDragRegion
|
||||
? "drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]"
|
||||
: "h-12 wco:max-h-[env(titlebar-area-height)]",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1020,6 +1020,15 @@ describe("resolveLiveThreadBranchUpdate", () => {
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
|
||||
it("does not regress a semantic thread branch back to a temporary worktree branch", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "t3code/github-query-rate-limit",
|
||||
gitStatus: status({ branch: "t3code/bda76797" }),
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAutoFeatureBranchName", () => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
GitStackedAction,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
|
||||
export type GitActionIconName = "commit" | "push" | "pr";
|
||||
|
||||
@@ -354,6 +355,15 @@ export function resolveLiveThreadBranchUpdate(input: {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
input.threadBranch !== null &&
|
||||
input.gitStatus.branch !== null &&
|
||||
!isTemporaryWorktreeBranch(input.threadBranch) &&
|
||||
isTemporaryWorktreeBranch(input.gitStatus.branch)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
branch: input.gitStatus.branch,
|
||||
};
|
||||
|
||||
@@ -34,6 +34,24 @@ export const TraeIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const KiroIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 1200 1200" fill="none">
|
||||
<rect width="1200" height="1200" rx="260" fill="#9046FF" />
|
||||
<path
|
||||
d="M398.554 818.914C316.315 1001.03 491.477 1046.74 620.672 940.156C658.687 1059.66 801.052 970.473 852.234 877.795C964.787 673.567 919.318 465.357 907.64 422.374C827.637 129.443 427.623 128.946 358.8 423.865C342.651 475.544 342.402 534.18 333.458 595.051C328.986 625.86 325.507 645.488 313.83 677.785C306.873 696.424 297.68 712.819 282.773 740.645C259.915 783.881 269.604 867.113 387.87 823.883L399.051 818.914H398.554Z"
|
||||
fill="#fff"
|
||||
/>
|
||||
<path
|
||||
d="M636.123 549.353C603.328 549.353 598.359 510.097 598.359 486.742C598.359 465.623 602.086 448.977 609.293 438.293C615.504 428.852 624.697 424.131 636.123 424.131C647.555 424.131 657.492 428.852 664.447 438.541C672.398 449.474 676.623 466.12 676.623 486.742C676.623 525.998 661.471 549.353 636.375 549.353H636.123Z"
|
||||
fill="#000"
|
||||
/>
|
||||
<path
|
||||
d="M771.24 549.353C738.445 549.353 733.477 510.097 733.477 486.742C733.477 465.623 737.203 448.977 744.41 438.293C750.621 428.852 759.814 424.131 771.24 424.131C782.672 424.131 792.609 428.852 799.564 438.541C807.516 449.474 811.74 466.12 811.74 486.742C811.74 525.998 796.588 549.353 771.492 549.353H771.24Z"
|
||||
fill="#000"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const VisualStudioCode: Icon = (props) => {
|
||||
const id = useId();
|
||||
const maskId = `${id}-vscode-a`;
|
||||
|
||||
@@ -169,6 +169,43 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
};
|
||||
}
|
||||
|
||||
function toShellSnapshot(snapshot: OrchestrationReadModel) {
|
||||
return {
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
projects: snapshot.projects.map((project) => ({
|
||||
id: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
repositoryIdentity: project.repositoryIdentity ?? null,
|
||||
defaultModelSelection: project.defaultModelSelection,
|
||||
scripts: project.scripts,
|
||||
createdAt: project.createdAt,
|
||||
updatedAt: project.updatedAt,
|
||||
})),
|
||||
threads: snapshot.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: thread.modelSelection,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
latestTurn: thread.latestTurn,
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
session: thread.session,
|
||||
latestUserMessageAt:
|
||||
thread.messages.findLast((message) => message.role === "user")?.createdAt ?? null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
})),
|
||||
updatedAt: snapshot.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFixture(): TestFixture {
|
||||
return {
|
||||
snapshot: createMinimalSnapshot(),
|
||||
@@ -190,9 +227,6 @@ function buildFixture(): TestFixture {
|
||||
}
|
||||
|
||||
function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
}
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
@@ -429,6 +463,28 @@ describe("Keybindings update toast", () => {
|
||||
},
|
||||
];
|
||||
}
|
||||
if (request._tag === ORCHESTRATION_WS_METHODS.subscribeShell) {
|
||||
return [
|
||||
{
|
||||
kind: "snapshot",
|
||||
snapshot: toShellSnapshot(fixture.snapshot),
|
||||
},
|
||||
];
|
||||
}
|
||||
if (
|
||||
request._tag === ORCHESTRATION_WS_METHODS.subscribeThread &&
|
||||
request.threadId === THREAD_ID
|
||||
) {
|
||||
return [
|
||||
{
|
||||
kind: "snapshot",
|
||||
snapshot: {
|
||||
snapshotSequence: fixture.snapshot.snapshotSequence,
|
||||
thread: fixture.snapshot.threads[0],
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
});
|
||||
|
||||
@@ -10,11 +10,15 @@ export function NoActiveThreadState() {
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border px-3 sm:px-5",
|
||||
isElectron ? "drag-region flex h-[52px] items-center" : "py-2 sm:py-3",
|
||||
isElectron
|
||||
? "drag-region flex h-[52px] items-center wco:h-[env(titlebar-area-height)]"
|
||||
: "py-2 sm:py-3",
|
||||
)}
|
||||
>
|
||||
{isElectron ? (
|
||||
<span className="text-xs text-muted-foreground/50">No active thread</span>
|
||||
<span className="text-xs text-muted-foreground/50 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]">
|
||||
No active thread
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createThreadJumpHintVisibilityController,
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
getVisibleSidebarThreadIds,
|
||||
resolveAdjacentThreadId,
|
||||
getFallbackThreadIdAfterDelete,
|
||||
@@ -17,7 +18,6 @@ import {
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import { EnvironmentId, OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
@@ -122,6 +122,20 @@ describe("createThreadJumpHintVisibilityController", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSidebarThreadIdsToPrewarm", () => {
|
||||
it("returns only the first visible thread ids up to the prewarm limit", () => {
|
||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2", "t3"], 2)).toEqual(["t1", "t2"]);
|
||||
});
|
||||
|
||||
it("returns all visible thread ids when they fit within the limit", () => {
|
||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 10)).toEqual(["t1", "t2"]);
|
||||
});
|
||||
|
||||
it("returns no thread ids when the limit is zero", () => {
|
||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 0)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldClearThreadSelectionOnMouseDown", () => {
|
||||
it("preserves selection for thread items", () => {
|
||||
const child = {
|
||||
@@ -170,6 +184,28 @@ describe("resolveSidebarNewThreadEnvMode", () => {
|
||||
});
|
||||
|
||||
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",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
|
||||
it("inherits the active server thread context when creating a new thread in the same project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
@@ -667,133 +703,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
};
|
||||
}
|
||||
|
||||
describe("sortThreadsForSidebar", () => {
|
||||
it("sorts threads by the latest user message in recency mode", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older",
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:01:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer",
|
||||
createdAt: "2026-03-09T10:06:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:06:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-2"),
|
||||
ThreadId.make("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to thread timestamps when there is no user message", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "assistant",
|
||||
text: "assistant only",
|
||||
createdAt: "2026-03-09T10:02:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:02:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-2"),
|
||||
ThreadId.make("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to id ordering when threads have no sortable timestamps", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "" as never,
|
||||
updatedAt: undefined,
|
||||
messages: [],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "" as never,
|
||||
updatedAt: undefined,
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-2"),
|
||||
ThreadId.make("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("can sort threads by createdAt when configured", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
}),
|
||||
],
|
||||
"created_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-1"),
|
||||
ThreadId.make("thread-2"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFallbackThreadIdAfterDelete", () => {
|
||||
it("returns the top remaining thread in the deleted thread's project sidebar order", () => {
|
||||
const fallbackThreadId = getFallbackThreadIdAfterDelete({
|
||||
@@ -860,7 +769,6 @@ describe("getFallbackThreadIdAfterDelete", () => {
|
||||
expect(fallbackThreadId).toBe(ThreadId.make("thread-next"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortProjectsForSidebar", () => {
|
||||
it("sorts projects by the most recent user message across their threads", () => {
|
||||
const projects = [
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import * as React from "react";
|
||||
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import {
|
||||
getThreadSortTimestamp,
|
||||
sortThreads,
|
||||
toSortableTimestamp,
|
||||
type ThreadSortInput,
|
||||
} from "../lib/threadSort";
|
||||
import type { SidebarThreadSummary, Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
import { isLatestTurnSettled } from "../session-logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
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;
|
||||
@@ -13,10 +22,6 @@ type SidebarProject = {
|
||||
createdAt?: string | undefined;
|
||||
updatedAt?: string | undefined;
|
||||
};
|
||||
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
|
||||
latestUserMessageAt?: string | null;
|
||||
messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
|
||||
};
|
||||
|
||||
export type ThreadTraversalDirection = "previous" | "next";
|
||||
|
||||
@@ -181,6 +186,12 @@ export function resolveSidebarNewThreadSeedContext(input: {
|
||||
worktreePath?: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
} {
|
||||
if (input.defaultEnvMode === "worktree") {
|
||||
return {
|
||||
envMode: "worktree",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeDraftThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeDraftThread.branch,
|
||||
@@ -241,6 +252,13 @@ export function getVisibleSidebarThreadIds<TThreadId>(
|
||||
);
|
||||
}
|
||||
|
||||
export function getSidebarThreadIdsToPrewarm<TThreadId>(
|
||||
visibleThreadIds: readonly TThreadId[],
|
||||
limit = SIDEBAR_THREAD_PREWARM_LIMIT,
|
||||
): TThreadId[] {
|
||||
return visibleThreadIds.slice(0, Math.max(0, limit));
|
||||
}
|
||||
|
||||
export function resolveAdjacentThreadId<T>(input: {
|
||||
threadIds: readonly T[];
|
||||
currentThreadId: T | null;
|
||||
@@ -441,61 +459,8 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
|
||||
};
|
||||
}
|
||||
|
||||
function toSortableTimestamp(iso: string | undefined): number | null {
|
||||
if (!iso) return null;
|
||||
const ms = Date.parse(iso);
|
||||
return Number.isFinite(ms) ? ms : null;
|
||||
}
|
||||
|
||||
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
|
||||
if (thread.latestUserMessageAt) {
|
||||
return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
let latestUserMessageTimestamp: number | null = null;
|
||||
|
||||
for (const message of thread.messages ?? []) {
|
||||
if (message.role !== "user") continue;
|
||||
const messageTimestamp = toSortableTimestamp(message.createdAt);
|
||||
if (messageTimestamp === null) continue;
|
||||
latestUserMessageTimestamp =
|
||||
latestUserMessageTimestamp === null
|
||||
? messageTimestamp
|
||||
: Math.max(latestUserMessageTimestamp, messageTimestamp);
|
||||
}
|
||||
|
||||
if (latestUserMessageTimestamp !== null) {
|
||||
return latestUserMessageTimestamp;
|
||||
}
|
||||
|
||||
return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
function getThreadSortTimestamp(
|
||||
thread: SidebarThreadSortInput,
|
||||
sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
|
||||
): number {
|
||||
if (sortOrder === "created_at") {
|
||||
return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
return getLatestUserMessageTimestamp(thread);
|
||||
}
|
||||
|
||||
export function sortThreadsForSidebar<
|
||||
T extends Pick<Thread, "id" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
|
||||
return threads.toSorted((left, right) => {
|
||||
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
|
||||
const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
|
||||
const byTimestamp =
|
||||
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
|
||||
if (byTimestamp !== 0) return byTimestamp;
|
||||
return right.id.localeCompare(left.id);
|
||||
});
|
||||
}
|
||||
|
||||
export function getFallbackThreadIdAfterDelete<
|
||||
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
|
||||
>(input: {
|
||||
threads: readonly T[];
|
||||
deletedThreadId: T["id"];
|
||||
@@ -509,7 +474,7 @@ export function getFallbackThreadIdAfterDelete<
|
||||
}
|
||||
|
||||
return (
|
||||
sortThreadsForSidebar(
|
||||
sortThreads(
|
||||
threads.filter(
|
||||
(thread) =>
|
||||
thread.projectId === deletedThread.projectId &&
|
||||
@@ -520,10 +485,9 @@ export function getFallbackThreadIdAfterDelete<
|
||||
)[0]?.id ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function getProjectSortTimestamp(
|
||||
project: SidebarProject,
|
||||
projectThreads: readonly SidebarThreadSortInput[],
|
||||
projectThreads: readonly ThreadSortInput[],
|
||||
sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
|
||||
): number {
|
||||
if (projectThreads.length > 0) {
|
||||
@@ -541,7 +505,7 @@ export function getProjectSortTimestamp(
|
||||
|
||||
export function sortProjectsForSidebar<
|
||||
TProject extends SidebarProject,
|
||||
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
|
||||
>(
|
||||
projects: readonly TProject[],
|
||||
threads: readonly TThread[],
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
PlusIcon,
|
||||
SearchIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
@@ -42,6 +43,7 @@ import {
|
||||
type GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedProjectKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
@@ -66,7 +68,11 @@ import {
|
||||
selectThreadByRef,
|
||||
useStore,
|
||||
} from "../store";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import {
|
||||
selectThreadTerminalState,
|
||||
useTerminalStateStore,
|
||||
useThreadTerminalOpen,
|
||||
} from "../terminalStateStore";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
resolveShortcutCommand,
|
||||
@@ -80,6 +86,7 @@ import { useGitStatus } from "../lib/gitStatusState";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
|
||||
import { retainThreadDetailSubscription } from "../environments/runtime/service";
|
||||
|
||||
import { useThreadActions } from "../hooks/useThreadActions";
|
||||
import {
|
||||
@@ -90,6 +97,7 @@ import {
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
import { Kbd } from "./ui/kbd";
|
||||
import {
|
||||
getArm64IntelBuildWarningDescription,
|
||||
getDesktopUpdateActionError,
|
||||
@@ -120,6 +128,7 @@ import {
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
import {
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
resolveAdjacentThreadId,
|
||||
isContextMenuPointerDown,
|
||||
resolveProjectStatusIndicator,
|
||||
@@ -130,20 +139,24 @@ import {
|
||||
orderItemsByPreferredIds,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
useThreadJumpHintVisibility,
|
||||
ThreadStatusPill,
|
||||
} from "./Sidebar.logic";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { readEnvironmentApi } from "../environmentApi";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
import { deriveLogicalProjectKey } from "../logicalProject";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import {
|
||||
useSavedEnvironmentRegistryStore,
|
||||
useSavedEnvironmentRuntimeStore,
|
||||
} from "../environments/runtime";
|
||||
import { serverThreadSurfaceInput, type WorkspaceLayoutEngine } from "../workspace/types";
|
||||
import { useWorkspaceDragStore } from "../workspace/dragStore";
|
||||
import { useWorkspaceLayoutEngine, useWorkspaceStore } from "../workspace/store";
|
||||
import type { Project, SidebarThreadSummary } from "../types";
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
|
||||
@@ -564,6 +577,24 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleDragStart = useCallback(
|
||||
(event: React.DragEvent<HTMLElement>) => {
|
||||
if (renamingThreadKey === threadKey) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
event.dataTransfer.setData("text/plain", thread.id);
|
||||
useWorkspaceDragStore.getState().setItem({
|
||||
kind: "thread",
|
||||
input: serverThreadSurfaceInput(threadRef),
|
||||
});
|
||||
},
|
||||
[renamingThreadKey, thread.id, threadKey, threadRef],
|
||||
);
|
||||
const handleDragEnd = useCallback(() => {
|
||||
useWorkspaceDragStore.getState().clearItem();
|
||||
}, []);
|
||||
const handleConfirmArchiveClick = useCallback(
|
||||
(event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
event.preventDefault();
|
||||
@@ -610,7 +641,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
isActive,
|
||||
isSelected,
|
||||
})} relative isolate`}
|
||||
draggable={renamingThreadKey !== threadKey}
|
||||
onClick={handleRowClick}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragStart={handleDragStart}
|
||||
onKeyDown={handleRowKeyDown}
|
||||
onContextMenu={handleRowContextMenu}
|
||||
>
|
||||
@@ -644,7 +678,21 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
onClick={handleRenameInputClick}
|
||||
/>
|
||||
) : (
|
||||
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
className="min-w-0 flex-1 truncate text-xs"
|
||||
data-testid={`thread-title-${thread.id}`}
|
||||
>
|
||||
{thread.title}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-80 whitespace-normal leading-tight">
|
||||
{thread.title}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
@@ -742,7 +790,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
: "text-muted-foreground/40"
|
||||
}`}
|
||||
>
|
||||
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
|
||||
{formatRelativeTimeLabel(
|
||||
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
@@ -986,6 +1036,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const removeFromSelection = useThreadSelectionStore((state) => state.removeFromSelection);
|
||||
const setSelectionAnchor = useThreadSelectionStore((state) => state.setAnchor);
|
||||
const selectedThreadCount = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
|
||||
const openThreadInSplit = useWorkspaceStore((state) => state.openThreadInSplit);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((state) => state.clearDraftThread);
|
||||
const getDraftThreadByProjectRef = useComposerDraftStore(
|
||||
(state) => state.getDraftThreadByProjectRef,
|
||||
@@ -1098,6 +1149,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
),
|
||||
[allSidebarThreads],
|
||||
);
|
||||
// Keep a ref so callbacks can read the latest map without appearing in
|
||||
// dependency arrays (avoids invalidating every thread-row memo on each
|
||||
// thread-list change).
|
||||
const sidebarThreadByKeyRef = useRef(sidebarThreadByKey);
|
||||
sidebarThreadByKeyRef.current = sidebarThreadByKey;
|
||||
// All threads from the representative + other member environments are
|
||||
// already fetched into allSidebarThreads, so we can use them directly.
|
||||
const projectThreads = allSidebarThreads;
|
||||
@@ -1139,7 +1195,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
},
|
||||
});
|
||||
};
|
||||
const visibleProjectThreads = sortThreadsForSidebar(
|
||||
const visibleProjectThreads = sortThreads(
|
||||
projectThreads.filter((thread) => thread.archivedAt === null),
|
||||
threadSortOrder,
|
||||
);
|
||||
@@ -1441,7 +1497,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = sidebarThreadByKey.get(threadKey);
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey);
|
||||
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
|
||||
}
|
||||
clearSelection();
|
||||
@@ -1462,7 +1518,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
const deletedThreadKeys = new Set(threadKeys);
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = sidebarThreadByKey.get(threadKey);
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey);
|
||||
if (!thread) continue;
|
||||
await deleteThread(scopeThreadRef(thread.environmentId, thread.id), {
|
||||
deletedThreadKeys,
|
||||
@@ -1476,7 +1532,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
deleteThread,
|
||||
markThreadUnread,
|
||||
removeFromSelection,
|
||||
sidebarThreadByKey,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1605,16 +1660,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const api = readLocalApi();
|
||||
if (!api) return;
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const thread =
|
||||
projectThreads.find(
|
||||
(projectThread) =>
|
||||
projectThread.environmentId === threadRef.environmentId &&
|
||||
projectThread.id === threadRef.threadId,
|
||||
) ?? null;
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null;
|
||||
if (!thread) return;
|
||||
const threadWorkspacePath = thread.worktreePath ?? project.cwd ?? null;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "open-split-right", label: "Open in split right" },
|
||||
{ id: "open-split-down", label: "Open in split down" },
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-path", label: "Copy Path" },
|
||||
@@ -1624,6 +1676,24 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
position,
|
||||
);
|
||||
|
||||
if (clicked === "open-split-right") {
|
||||
openThreadInSplit(serverThreadSurfaceInput(threadRef), "x");
|
||||
void router.navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(threadRef),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "open-split-down") {
|
||||
openThreadInSplit(serverThreadSurfaceInput(threadRef), "y");
|
||||
void router.navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(threadRef),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "rename") {
|
||||
setRenamingThreadKey(threadKey);
|
||||
setRenamingTitle(thread.title);
|
||||
@@ -1671,8 +1741,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
markThreadUnread,
|
||||
openThreadInSplit,
|
||||
project.cwd,
|
||||
projectThreads,
|
||||
router,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1971,7 +2042,7 @@ const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
);
|
||||
|
||||
return isElectron ? (
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px]">
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px] wco:h-[env(titlebar-area-height)] wco:pl-[calc(env(titlebar-area-x)+1em)]">
|
||||
{wordmark}
|
||||
</SidebarHeader>
|
||||
) : (
|
||||
@@ -1981,6 +2052,8 @@ const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
|
||||
const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
const navigate = useNavigate();
|
||||
const layoutEngine = useWorkspaceLayoutEngine();
|
||||
const setLayoutEngine = useWorkspaceStore((state) => state.setLayoutEngine);
|
||||
const handleSettingsClick = useCallback(() => {
|
||||
void navigate({ to: "/settings" });
|
||||
}, [navigate]);
|
||||
@@ -2000,10 +2073,41 @@ const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
<div className="mt-2 flex items-center gap-1 px-2">
|
||||
<span className="text-[11px] text-muted-foreground/70">Layout</span>
|
||||
<WorkspaceLayoutToggle
|
||||
layoutEngine={layoutEngine}
|
||||
onSelect={(engine) => setLayoutEngine(engine)}
|
||||
/>
|
||||
</div>
|
||||
</SidebarFooter>
|
||||
);
|
||||
});
|
||||
|
||||
const WorkspaceLayoutToggle = memo(function WorkspaceLayoutToggle(props: {
|
||||
layoutEngine: WorkspaceLayoutEngine;
|
||||
onSelect: (engine: WorkspaceLayoutEngine) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
{(["split", "paper"] as const).map((engine) => (
|
||||
<button
|
||||
key={engine}
|
||||
type="button"
|
||||
className={
|
||||
props.layoutEngine === engine
|
||||
? "rounded-md border border-border bg-accent px-2 py-1 text-[11px] text-foreground"
|
||||
: "rounded-md border border-border/60 px-2 py-1 text-[11px] text-muted-foreground transition hover:bg-accent hover:text-foreground"
|
||||
}
|
||||
onClick={() => props.onSelect(engine)}
|
||||
>
|
||||
{engine === "split" ? "Split" : "Paper"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
interface SidebarProjectsContentProps {
|
||||
showArm64IntelBuildWarning: boolean;
|
||||
arm64IntelBuildWarningDescription: string | null;
|
||||
@@ -2041,6 +2145,8 @@ interface SidebarProjectsContentProps {
|
||||
activeRouteProjectKey: string | null;
|
||||
routeThreadKey: string | null;
|
||||
newThreadShortcutLabel: string | null;
|
||||
commandPaletteShortcutLabel: string | null;
|
||||
onOpenCommandPalette: () => void;
|
||||
threadJumpLabelByKey: ReadonlyMap<string, string>;
|
||||
attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void;
|
||||
expandThreadListForProject: (projectKey: string) => void;
|
||||
@@ -2092,6 +2198,8 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
activeRouteProjectKey,
|
||||
routeThreadKey,
|
||||
newThreadShortcutLabel,
|
||||
commandPaletteShortcutLabel,
|
||||
onOpenCommandPalette,
|
||||
threadJumpLabelByKey,
|
||||
attachThreadListAutoAnimateRef,
|
||||
expandThreadListForProject,
|
||||
@@ -2138,6 +2246,27 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
|
||||
return (
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 pt-2 pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
type="button"
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground focus-visible:ring-0"
|
||||
data-testid="command-palette-trigger"
|
||||
onClick={onOpenCommandPalette}
|
||||
>
|
||||
<SearchIcon className="size-3.5" />
|
||||
<span className="flex-1 truncate text-left text-xs">Search</span>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
{showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? (
|
||||
<SidebarGroup className="px-2 pt-2 pb-0">
|
||||
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
|
||||
@@ -2345,7 +2474,9 @@ export default function Sidebar() {
|
||||
select: (params) => resolveThreadRouteRef(params),
|
||||
});
|
||||
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
|
||||
const routeThreadTerminalOpen = useThreadTerminalOpen(routeThreadRef);
|
||||
const keybindings = useServerKeybindings();
|
||||
const setCommandPaletteOpen = useCommandPaletteStore((state) => state.setOpen);
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
@@ -2507,14 +2638,9 @@ export default function Sidebar() {
|
||||
const getCurrentSidebarShortcutContext = useCallback(
|
||||
() => ({
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen: routeThreadRef
|
||||
? selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
routeThreadRef,
|
||||
).terminalOpen
|
||||
: false,
|
||||
terminalOpen: routeThreadTerminalOpen,
|
||||
}),
|
||||
[routeThreadRef],
|
||||
[routeThreadTerminalOpen],
|
||||
);
|
||||
const newThreadShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
@@ -2535,7 +2661,7 @@ export default function Sidebar() {
|
||||
scopeProjectRef(projectRef.environmentId, projectRef.projectId),
|
||||
);
|
||||
const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey;
|
||||
const latestThread = sortThreadsForSidebar(
|
||||
const latestThread = sortThreads(
|
||||
(threadsByProjectKey.get(logicalKey) ?? []).filter((thread) => thread.archivedAt === null),
|
||||
sidebarThreadSortOrder,
|
||||
)[0];
|
||||
@@ -2549,7 +2675,7 @@ export default function Sidebar() {
|
||||
[sidebarThreadSortOrder, navigate, threadsByProjectKey, physicalToLogicalKey],
|
||||
);
|
||||
|
||||
const addProjectFromPath = useCallback(
|
||||
const addProjectFromInput = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
const cwd = rawCwd.trim();
|
||||
if (!cwd || isAddingProject) return;
|
||||
@@ -2575,7 +2701,6 @@ export default function Sidebar() {
|
||||
}
|
||||
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
try {
|
||||
await api.orchestration.dispatchCommand({
|
||||
@@ -2588,7 +2713,7 @@ export default function Sidebar() {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
createdAt,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
if (activeEnvironmentId !== null) {
|
||||
await handleNewThread(scopeProjectRef(activeEnvironmentId, projectId), {
|
||||
@@ -2624,7 +2749,7 @@ export default function Sidebar() {
|
||||
);
|
||||
|
||||
const handleAddProject = () => {
|
||||
void addProjectFromPath(newCwd);
|
||||
void addProjectFromInput(newCwd);
|
||||
};
|
||||
|
||||
const canAddProject = newCwd.trim().length > 0 && !isAddingProject;
|
||||
@@ -2640,7 +2765,7 @@ export default function Sidebar() {
|
||||
// Ignore picker failures and leave the current thread selection unchanged.
|
||||
}
|
||||
if (pickedPath) {
|
||||
await addProjectFromPath(pickedPath);
|
||||
await addProjectFromInput(pickedPath);
|
||||
} else if (!shouldBrowseForProjectImmediately) {
|
||||
addProjectInputRef.current?.focus();
|
||||
}
|
||||
@@ -2771,7 +2896,7 @@ export default function Sidebar() {
|
||||
const visibleSidebarThreadKeys = useMemo(
|
||||
() =>
|
||||
sortedProjects.flatMap((project) => {
|
||||
const projectThreads = sortThreadsForSidebar(
|
||||
const projectThreads = sortThreads(
|
||||
(threadsByProjectKey.get(project.projectKey) ?? []).filter(
|
||||
(thread) => thread.archivedAt === null,
|
||||
),
|
||||
@@ -2837,6 +2962,30 @@ export default function Sidebar() {
|
||||
? threadJumpLabelByKey
|
||||
: EMPTY_THREAD_JUMP_LABELS;
|
||||
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
|
||||
const prewarmedSidebarThreadKeys = useMemo(
|
||||
() => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys),
|
||||
[visibleSidebarThreadKeys],
|
||||
);
|
||||
const prewarmedSidebarThreadRefs = useMemo(
|
||||
() =>
|
||||
prewarmedSidebarThreadKeys.flatMap((threadKey) => {
|
||||
const ref = parseScopedThreadKey(threadKey);
|
||||
return ref ? [ref] : [];
|
||||
}),
|
||||
[prewarmedSidebarThreadKeys],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const releases = prewarmedSidebarThreadRefs.map((ref) =>
|
||||
retainThreadDetailSubscription(ref.environmentId, ref.threadId),
|
||||
);
|
||||
|
||||
return () => {
|
||||
for (const release of releases) {
|
||||
release();
|
||||
}
|
||||
};
|
||||
}, [prewarmedSidebarThreadRefs]);
|
||||
|
||||
useEffect(() => {
|
||||
const clearThreadJumpHints = () => {
|
||||
@@ -3042,6 +3191,11 @@ export default function Sidebar() {
|
||||
desktopUpdateState && showArm64IntelBuildWarning
|
||||
? getArm64IntelBuildWarningDescription(desktopUpdateState)
|
||||
: null;
|
||||
const commandPaletteShortcutLabel = shortcutLabelForCommand(
|
||||
keybindings,
|
||||
"commandPalette.toggle",
|
||||
newThreadShortcutLabelOptions,
|
||||
);
|
||||
const handleDesktopUpdateButtonClick = useCallback(() => {
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || !desktopUpdateState) return;
|
||||
@@ -3167,6 +3321,8 @@ export default function Sidebar() {
|
||||
activeRouteProjectKey={activeRouteProjectKey}
|
||||
routeThreadKey={routeThreadKey}
|
||||
newThreadShortcutLabel={newThreadShortcutLabel}
|
||||
commandPaletteShortcutLabel={commandPaletteShortcutLabel}
|
||||
onOpenCommandPalette={() => setCommandPaletteOpen(true)}
|
||||
threadJumpLabelByKey={visibleThreadJumpLabelByKey}
|
||||
attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef}
|
||||
expandThreadListForProject={expandThreadListForProject}
|
||||
|
||||
@@ -783,6 +783,7 @@ interface ThreadTerminalDrawerProps {
|
||||
onCloseTerminal: (terminalId: string) => void;
|
||||
onHeightChange: (height: number) => void;
|
||||
onAddTerminalContext: (selection: TerminalContextSelection) => void;
|
||||
showResizeHandle?: boolean;
|
||||
}
|
||||
|
||||
interface TerminalActionButtonProps {
|
||||
@@ -836,6 +837,7 @@ export default function ThreadTerminalDrawer({
|
||||
onCloseTerminal,
|
||||
onHeightChange,
|
||||
onAddTerminalContext,
|
||||
showResizeHandle = true,
|
||||
}: ThreadTerminalDrawerProps) {
|
||||
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
|
||||
const [resizeEpoch, setResizeEpoch] = useState(0);
|
||||
@@ -1072,16 +1074,20 @@ export default function ThreadTerminalDrawer({
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
className={`thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden bg-background ${
|
||||
showResizeHandle ? "border-t border-border/80" : ""
|
||||
}`}
|
||||
style={{ height: `${drawerHeight}px` }}
|
||||
>
|
||||
<div
|
||||
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
|
||||
onPointerDown={handleResizePointerDown}
|
||||
onPointerMove={handleResizePointerMove}
|
||||
onPointerUp={handleResizePointerEnd}
|
||||
onPointerCancel={handleResizePointerEnd}
|
||||
/>
|
||||
{showResizeHandle ? (
|
||||
<div
|
||||
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
|
||||
onPointerDown={handleResizePointerDown}
|
||||
onPointerMove={handleResizePointerMove}
|
||||
onPointerUp={handleResizePointerEnd}
|
||||
onPointerCancel={handleResizePointerEnd}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!hasTerminalSidebar && (
|
||||
<div className="pointer-events-none absolute right-2 top-2 z-20">
|
||||
|
||||
@@ -339,6 +339,7 @@ export interface ChatComposerHandle {
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export interface ChatComposerProps {
|
||||
activationFocusRequestId?: number;
|
||||
composerDraftTarget: ScopedThreadRef | DraftId;
|
||||
environmentId: EnvironmentId;
|
||||
routeKind: "server" | "draft";
|
||||
@@ -447,6 +448,7 @@ export interface ChatComposerProps {
|
||||
export const ChatComposer = memo(
|
||||
forwardRef<ChatComposerHandle, ChatComposerProps>(function ChatComposer(props, ref) {
|
||||
const {
|
||||
activationFocusRequestId,
|
||||
composerDraftTarget,
|
||||
environmentId,
|
||||
routeKind,
|
||||
@@ -653,6 +655,7 @@ export const ChatComposer = memo(
|
||||
// Refs
|
||||
// ------------------------------------------------------------------
|
||||
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
|
||||
const pendingActivationFocusRepairRef = useRef(false);
|
||||
const composerFormRef = useRef<HTMLFormElement>(null);
|
||||
const composerFormHeightRef = useRef(0);
|
||||
const composerSelectLockRef = useRef(false);
|
||||
@@ -661,6 +664,13 @@ export const ChatComposer = memo(
|
||||
const activeComposerMenuItemRef = useRef<ComposerCommandItem | null>(null);
|
||||
const dragDepthRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (activationFocusRequestId === undefined) {
|
||||
return;
|
||||
}
|
||||
pendingActivationFocusRepairRef.current = true;
|
||||
}, [activationFocusRequestId]);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Derived: composer send state
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1227,8 +1237,11 @@ export const ChatComposer = memo(
|
||||
);
|
||||
return;
|
||||
}
|
||||
const previousPrompt = promptRef.current;
|
||||
promptRef.current = nextPrompt;
|
||||
setPrompt(nextPrompt);
|
||||
if (previousPrompt !== nextPrompt) {
|
||||
setPrompt(nextPrompt);
|
||||
}
|
||||
if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) {
|
||||
setComposerDraftTerminalContexts(
|
||||
composerDraftTarget,
|
||||
@@ -1239,6 +1252,20 @@ export const ChatComposer = memo(
|
||||
setComposerTrigger(
|
||||
cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
|
||||
);
|
||||
if (pendingActivationFocusRepairRef.current) {
|
||||
const repairCursor = nextCursor;
|
||||
window.requestAnimationFrame(() => {
|
||||
const composerEditor = composerEditorRef.current;
|
||||
if (!composerEditor) {
|
||||
pendingActivationFocusRepairRef.current = false;
|
||||
return;
|
||||
}
|
||||
if (!composerEditor.isFocused()) {
|
||||
composerEditor.focusAt(repairCursor);
|
||||
}
|
||||
pendingActivationFocusRepairRef.current = false;
|
||||
});
|
||||
}
|
||||
},
|
||||
[
|
||||
activePendingProgress?.activeQuestion,
|
||||
@@ -1902,7 +1929,7 @@ export const ChatComposer = memo(
|
||||
isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0",
|
||||
)}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<div className="-m-1 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<ProviderModelPicker
|
||||
compact={isComposerFooterCompact}
|
||||
provider={selectedProvider}
|
||||
|
||||
@@ -122,7 +122,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
className="shrink-0"
|
||||
pressed={terminalOpen}
|
||||
onPressedChange={onToggleTerminal}
|
||||
aria-label="Toggle terminal drawer"
|
||||
aria-label="Toggle terminal split"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!terminalAvailable}
|
||||
@@ -135,8 +135,8 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
{!terminalAvailable
|
||||
? "Terminal is unavailable until this thread has an active project."
|
||||
: terminalToggleShortcutLabel
|
||||
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
|
||||
: "Toggle terminal drawer"}
|
||||
? `Toggle terminal split (${terminalToggleShortcutLabel})`
|
||||
: "Toggle terminal split"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { createRef } from "react";
|
||||
import type { LegendListRef } from "@legendapp/list/react";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
const scrollToEndSpy = vi.fn();
|
||||
const getStateSpy = vi.fn(() => ({ isAtEnd: true }));
|
||||
|
||||
vi.mock("@legendapp/list/react", async () => {
|
||||
const React = await import("react");
|
||||
|
||||
const LegendList = React.forwardRef(function MockLegendList(
|
||||
props: {
|
||||
data: Array<{ id: string }>;
|
||||
keyExtractor: (item: { id: string }) => string;
|
||||
renderItem: (args: { item: { id: string } }) => React.ReactNode;
|
||||
ListHeaderComponent?: React.ReactNode;
|
||||
ListFooterComponent?: React.ReactNode;
|
||||
},
|
||||
ref: React.ForwardedRef<LegendListRef>,
|
||||
) {
|
||||
React.useImperativeHandle(
|
||||
ref,
|
||||
() =>
|
||||
({
|
||||
scrollToEnd: scrollToEndSpy,
|
||||
getState: getStateSpy,
|
||||
}) as unknown as LegendListRef,
|
||||
);
|
||||
|
||||
return (
|
||||
<div data-testid="legend-list">
|
||||
{props.ListHeaderComponent}
|
||||
{props.data.map((item) => (
|
||||
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
|
||||
))}
|
||||
{props.ListFooterComponent}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
return { LegendList };
|
||||
});
|
||||
|
||||
import { MessagesTimeline } from "./MessagesTimeline";
|
||||
|
||||
function buildProps() {
|
||||
return {
|
||||
isWorking: false,
|
||||
activeTurnInProgress: false,
|
||||
activeTurnId: null,
|
||||
activeTurnStartedAt: null,
|
||||
listRef: createRef<LegendListRef | null>(),
|
||||
completionDividerBeforeEntryId: null,
|
||||
completionSummary: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
routeThreadKey: "environment-local:thread-1",
|
||||
onOpenTurnDiff: vi.fn(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
onRevertUserMessage: vi.fn(),
|
||||
isRevertingCheckpoint: false,
|
||||
onImageExpand: vi.fn(),
|
||||
activeThreadEnvironmentId: EnvironmentId.make("environment-local"),
|
||||
markdownCwd: undefined,
|
||||
resolvedTheme: "dark" as const,
|
||||
timestampFormat: "24-hour" as const,
|
||||
workspaceRoot: undefined,
|
||||
onIsAtEndChange: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("MessagesTimeline", () => {
|
||||
afterEach(() => {
|
||||
scrollToEndSpy.mockReset();
|
||||
getStateSpy.mockClear();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("renders activity rows instead of the empty placeholder when a thread has non-message timeline data", async () => {
|
||||
const screen = await render(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "work-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-04-13T12:00:00.000Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-04-13T12:00:00.000Z",
|
||||
label: "thinking",
|
||||
detail: "Inspecting repository state",
|
||||
tone: "thinking",
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
await expect
|
||||
.element(page.getByText("Send a message to start the conversation."))
|
||||
.not.toBeInTheDocument();
|
||||
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("snaps to the bottom when timeline rows appear after an initially empty render", async () => {
|
||||
const requestAnimationFrameSpy = vi
|
||||
.spyOn(window, "requestAnimationFrame")
|
||||
.mockImplementation((callback: FrameRequestCallback) => {
|
||||
callback(0);
|
||||
return 1;
|
||||
});
|
||||
vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => undefined);
|
||||
|
||||
const props = buildProps();
|
||||
const screen = await render(<MessagesTimeline {...props} timelineEntries={[]} />);
|
||||
|
||||
try {
|
||||
await expect
|
||||
.element(page.getByText("Send a message to start the conversation."))
|
||||
.toBeVisible();
|
||||
|
||||
await screen.rerender(
|
||||
<MessagesTimeline
|
||||
{...props}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "work-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-04-13T12:00:00.000Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-04-13T12:00:00.000Z",
|
||||
label: "thinking",
|
||||
detail: "Inspecting repository state",
|
||||
tone: "thinking",
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
|
||||
expect(props.onIsAtEndChange).toHaveBeenCalledWith(true);
|
||||
expect(scrollToEndSpy).toHaveBeenCalledWith({ animated: false });
|
||||
expect(requestAnimationFrameSpy).toHaveBeenCalled();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
computeStableMessagesTimelineRows,
|
||||
computeMessageDurationStart,
|
||||
deriveMessagesTimelineRows,
|
||||
normalizeCompactToolLabel,
|
||||
@@ -252,6 +253,8 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
completionDividerBeforeEntryId: "assistant-final-entry",
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const assistantRows = rows.filter(
|
||||
@@ -264,4 +267,169 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(assistantRows[1]?.showAssistantCopyButton).toBe(true);
|
||||
expect(assistantRows[1]?.showCompletionDivider).toBe(true);
|
||||
});
|
||||
|
||||
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
|
||||
const assistantTurnDiffSummary = {
|
||||
turnId: "turn-1" as never,
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
assistantMessageId: "assistant-1" as never,
|
||||
checkpointTurnCount: 2,
|
||||
files: [{ path: "src/index.ts", additions: 3, deletions: 1 }],
|
||||
};
|
||||
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "user-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
message: {
|
||||
id: "user-1" as never,
|
||||
role: "user",
|
||||
text: "Do the thing",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-1" as never,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map([
|
||||
["assistant-1" as never, assistantTurnDiffSummary],
|
||||
]),
|
||||
revertTurnCountByUserMessageId: new Map([["user-1" as never, 1]]),
|
||||
});
|
||||
|
||||
const userRow = rows.find(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
|
||||
row.kind === "message" && row.message.role === "user",
|
||||
);
|
||||
const assistantRow = rows.find(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
|
||||
row.kind === "message" && row.message.role === "assistant",
|
||||
);
|
||||
|
||||
expect(userRow?.revertTurnCount).toBe(1);
|
||||
expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeStableMessagesTimelineRows", () => {
|
||||
it("returns the previous result when row order and content are unchanged", () => {
|
||||
const firstUserMessage = {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "First",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
};
|
||||
const secondUserMessage = {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "Second",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
streaming: false,
|
||||
};
|
||||
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "entry-user-1",
|
||||
kind: "message",
|
||||
createdAt: firstUserMessage.createdAt,
|
||||
message: firstUserMessage,
|
||||
},
|
||||
{
|
||||
id: "entry-user-2",
|
||||
kind: "message",
|
||||
createdAt: secondUserMessage.createdAt,
|
||||
message: secondUserMessage,
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const initial = computeStableMessagesTimelineRows(rows, {
|
||||
byId: new Map(),
|
||||
result: [],
|
||||
});
|
||||
|
||||
const repeated = computeStableMessagesTimelineRows(rows, initial);
|
||||
|
||||
expect(repeated).toBe(initial);
|
||||
expect(repeated.result).toBe(initial.result);
|
||||
});
|
||||
|
||||
it("returns a new result when row order changes without content changes", () => {
|
||||
const firstUserMessage = {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "First",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
};
|
||||
const secondUserMessage = {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "Second",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
streaming: false,
|
||||
};
|
||||
|
||||
const firstRows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "entry-user-1",
|
||||
kind: "message",
|
||||
createdAt: firstUserMessage.createdAt,
|
||||
message: firstUserMessage,
|
||||
},
|
||||
{
|
||||
id: "entry-user-2",
|
||||
kind: "message",
|
||||
createdAt: secondUserMessage.createdAt,
|
||||
message: secondUserMessage,
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const initial = computeStableMessagesTimelineRows(firstRows, {
|
||||
byId: new Map(),
|
||||
result: [],
|
||||
});
|
||||
|
||||
const reordered = computeStableMessagesTimelineRows([firstRows[1]!, firstRows[0]!], initial);
|
||||
|
||||
expect(reordered).not.toBe(initial);
|
||||
expect(reordered.result).toEqual([initial.result[1], initial.result[0]]);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,6 @@
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
|
||||
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
|
||||
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
|
||||
import { estimateTimelineMessageHeight } from "../timelineHeight";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
|
||||
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
|
||||
@@ -28,6 +26,8 @@ export type MessagesTimelineRow =
|
||||
durationStart: string;
|
||||
showCompletionDivider: boolean;
|
||||
showAssistantCopyButton: boolean;
|
||||
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
|
||||
revertTurnCount?: number | undefined;
|
||||
}
|
||||
| {
|
||||
kind: "proposed-plan";
|
||||
@@ -37,6 +37,11 @@ export type MessagesTimelineRow =
|
||||
}
|
||||
| { kind: "working"; id: string; createdAt: string | null };
|
||||
|
||||
export interface StableMessagesTimelineRowsState {
|
||||
byId: Map<string, MessagesTimelineRow>;
|
||||
result: MessagesTimelineRow[];
|
||||
}
|
||||
|
||||
export function computeMessageDurationStart(
|
||||
messages: ReadonlyArray<TimelineDurationMessage>,
|
||||
): Map<string, string> {
|
||||
@@ -107,6 +112,8 @@ export function deriveMessagesTimelineRows(input: {
|
||||
completionDividerBeforeEntryId: string | null;
|
||||
isWorking: boolean;
|
||||
activeTurnStartedAt: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
|
||||
}): MessagesTimelineRow[] {
|
||||
const nextRows: MessagesTimelineRow[] = [];
|
||||
const durationStartByMessageId = computeMessageDurationStart(
|
||||
@@ -162,6 +169,14 @@ export function deriveMessagesTimelineRows(input: {
|
||||
showAssistantCopyButton:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
terminalAssistantMessageIds.has(timelineEntry.message.id),
|
||||
assistantTurnDiffSummary:
|
||||
timelineEntry.message.role === "assistant"
|
||||
? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
|
||||
: undefined,
|
||||
revertTurnCount:
|
||||
timelineEntry.message.role === "user"
|
||||
? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -176,71 +191,50 @@ export function deriveMessagesTimelineRows(input: {
|
||||
return nextRows;
|
||||
}
|
||||
|
||||
export function estimateMessagesTimelineRowHeight(
|
||||
row: MessagesTimelineRow,
|
||||
input: {
|
||||
timelineWidthPx: number | null;
|
||||
expandedWorkGroups?: Readonly<Record<string, boolean>>;
|
||||
turnDiffSummaryByAssistantMessageId?: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
},
|
||||
): number {
|
||||
switch (row.kind) {
|
||||
case "work":
|
||||
return estimateWorkRowHeight(row, input);
|
||||
case "proposed-plan":
|
||||
return estimateTimelineProposedPlanHeight(row.proposedPlan);
|
||||
export function computeStableMessagesTimelineRows(
|
||||
rows: MessagesTimelineRow[],
|
||||
previous: StableMessagesTimelineRowsState,
|
||||
): StableMessagesTimelineRowsState {
|
||||
const next = new Map<string, MessagesTimelineRow>();
|
||||
let anyChanged = rows.length !== previous.byId.size;
|
||||
|
||||
const result = rows.map((row, index) => {
|
||||
const prevRow = previous.byId.get(row.id);
|
||||
const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
|
||||
next.set(row.id, nextRow);
|
||||
if (!anyChanged && previous.result[index] !== nextRow) {
|
||||
anyChanged = true;
|
||||
}
|
||||
return nextRow;
|
||||
});
|
||||
|
||||
return anyChanged ? { byId: next, result } : previous;
|
||||
}
|
||||
|
||||
/** Shallow field comparison per row variant — avoids deep equality cost. */
|
||||
function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
|
||||
if (a.kind !== b.kind || a.id !== b.id) return false;
|
||||
|
||||
switch (a.kind) {
|
||||
case "working":
|
||||
return 40;
|
||||
return a.createdAt === (b as typeof a).createdAt;
|
||||
|
||||
case "proposed-plan":
|
||||
return a.proposedPlan === (b as typeof a).proposedPlan;
|
||||
|
||||
case "work":
|
||||
return a.groupedEntries === (b as typeof a).groupedEntries;
|
||||
|
||||
case "message": {
|
||||
let estimate = estimateTimelineMessageHeight(row.message, {
|
||||
timelineWidthPx: input.timelineWidthPx,
|
||||
});
|
||||
const turnDiffSummary = input.turnDiffSummaryByAssistantMessageId?.get(row.message.id);
|
||||
if (turnDiffSummary && turnDiffSummary.files.length > 0) {
|
||||
estimate += estimateChangedFilesCardHeight(turnDiffSummary);
|
||||
}
|
||||
return estimate;
|
||||
const bm = b as typeof a;
|
||||
return (
|
||||
a.message === bm.message &&
|
||||
a.durationStart === bm.durationStart &&
|
||||
a.showCompletionDivider === bm.showCompletionDivider &&
|
||||
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
|
||||
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
|
||||
a.revertTurnCount === bm.revertTurnCount
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function estimateWorkRowHeight(
|
||||
row: Extract<MessagesTimelineRow, { kind: "work" }>,
|
||||
input: {
|
||||
expandedWorkGroups?: Readonly<Record<string, boolean>>;
|
||||
},
|
||||
): number {
|
||||
const isExpanded = input.expandedWorkGroups?.[row.id] ?? false;
|
||||
const hasOverflow = row.groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleEntries =
|
||||
hasOverflow && !isExpanded ? MAX_VISIBLE_WORK_LOG_ENTRIES : row.groupedEntries.length;
|
||||
const onlyToolEntries = row.groupedEntries.every((entry) => entry.tone === "tool");
|
||||
const showHeader = hasOverflow || !onlyToolEntries;
|
||||
|
||||
// Card chrome, optional header, and one compact work-entry row per visible entry.
|
||||
return 28 + (showHeader ? 26 : 0) + visibleEntries * 32;
|
||||
}
|
||||
|
||||
function estimateTimelineProposedPlanHeight(proposedPlan: ProposedPlan): number {
|
||||
const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
|
||||
return 120 + Math.min(estimatedLines * 22, 880);
|
||||
}
|
||||
|
||||
function estimateChangedFilesCardHeight(turnDiffSummary: TurnDiffSummary): number {
|
||||
const treeNodes = buildTurnDiffTree(turnDiffSummary.files);
|
||||
const visibleNodeCount = countTurnDiffTreeNodes(treeNodes);
|
||||
|
||||
// Card chrome: top/bottom padding, header row, and tree spacing.
|
||||
return 60 + visibleNodeCount * 25;
|
||||
}
|
||||
|
||||
function countTurnDiffTreeNodes(nodes: ReadonlyArray<TurnDiffTreeNode>): number {
|
||||
let count = 0;
|
||||
for (const node of nodes) {
|
||||
count += 1;
|
||||
if (node.kind === "directory") {
|
||||
count += countTurnDiffTreeNodes(node.children);
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import { MessageId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
function matchMedia() {
|
||||
return {
|
||||
matches: false,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
const classList = {
|
||||
add: () => {},
|
||||
remove: () => {},
|
||||
toggle: () => {},
|
||||
contains: () => false,
|
||||
};
|
||||
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: () => null,
|
||||
setItem: () => {},
|
||||
removeItem: () => {},
|
||||
clear: () => {},
|
||||
});
|
||||
vi.stubGlobal("window", {
|
||||
matchMedia,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
desktopBridge: undefined,
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: {
|
||||
classList,
|
||||
offsetHeight: 0,
|
||||
},
|
||||
});
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
|
||||
callback(0);
|
||||
return 0;
|
||||
});
|
||||
});
|
||||
|
||||
const ACTIVE_THREAD_ENVIRONMENT_ID = "environment-local" as never;
|
||||
|
||||
describe("MessagesTimeline", () => {
|
||||
it("renders inline terminal labels with the composer chip UI", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
hasMessages
|
||||
isWorking={false}
|
||||
activeTurnInProgress={false}
|
||||
activeTurnStartedAt={null}
|
||||
scrollContainer={null}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "message",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
message: {
|
||||
id: MessageId.make("message-2"),
|
||||
role: "user",
|
||||
text: [
|
||||
"yoo what's @terminal-1:1-5 mean",
|
||||
"",
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 1-5:",
|
||||
" 1 | julius@mac effect-http-ws-cli % bun i",
|
||||
" 2 | bun install v1.3.9 (cf6cdbbb)",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
]}
|
||||
completionDividerBeforeEntryId={null}
|
||||
completionSummary={null}
|
||||
turnDiffSummaryByAssistantMessageId={new Map()}
|
||||
nowIso="2026-03-17T19:12:30.000Z"
|
||||
expandedWorkGroups={{}}
|
||||
onToggleWorkGroup={() => {}}
|
||||
changedFilesExpandedByTurnId={{}}
|
||||
onSetChangedFilesExpanded={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
revertTurnCountByUserMessageId={new Map()}
|
||||
onRevertUserMessage={() => {}}
|
||||
isRevertingCheckpoint={false}
|
||||
onImageExpand={() => {}}
|
||||
activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
|
||||
markdownCwd={undefined}
|
||||
resolvedTheme="light"
|
||||
timestampFormat="locale"
|
||||
workspaceRoot={undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Terminal 1 lines 1-5");
|
||||
expect(markup).toContain("lucide-terminal");
|
||||
expect(markup).toContain("yoo what's ");
|
||||
}, 10_000);
|
||||
|
||||
it("renders context compaction entries in the normal work log", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
hasMessages
|
||||
isWorking={false}
|
||||
activeTurnInProgress={false}
|
||||
activeTurnStartedAt={null}
|
||||
scrollContainer={null}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
label: "Context compacted",
|
||||
tone: "info",
|
||||
},
|
||||
},
|
||||
]}
|
||||
completionDividerBeforeEntryId={null}
|
||||
completionSummary={null}
|
||||
turnDiffSummaryByAssistantMessageId={new Map()}
|
||||
nowIso="2026-03-17T19:12:30.000Z"
|
||||
expandedWorkGroups={{}}
|
||||
onToggleWorkGroup={() => {}}
|
||||
changedFilesExpandedByTurnId={{}}
|
||||
onSetChangedFilesExpanded={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
revertTurnCountByUserMessageId={new Map()}
|
||||
onRevertUserMessage={() => {}}
|
||||
isRevertingCheckpoint={false}
|
||||
onImageExpand={() => {}}
|
||||
activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
|
||||
markdownCwd={undefined}
|
||||
resolvedTheme="light"
|
||||
timestampFormat="locale"
|
||||
workspaceRoot={undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Context compacted");
|
||||
expect(markup).toContain("Work log");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -10,6 +10,7 @@ import {
|
||||
AntigravityIcon,
|
||||
CursorIcon,
|
||||
Icon,
|
||||
KiroIcon,
|
||||
TraeIcon,
|
||||
IntelliJIdeaIcon,
|
||||
VisualStudioCode,
|
||||
@@ -32,6 +33,11 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
Icon: TraeIcon,
|
||||
value: "trae",
|
||||
},
|
||||
{
|
||||
label: "Kiro",
|
||||
Icon: KiroIcon,
|
||||
value: "kiro",
|
||||
},
|
||||
{
|
||||
label: "VS Code",
|
||||
Icon: VisualStudioCode,
|
||||
|
||||
@@ -1,151 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { appendTerminalContextsToPrompt } from "../lib/terminalContext";
|
||||
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
describe("estimateTimelineMessageHeight", () => {
|
||||
it("uses assistant sizing rules for assistant messages", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "assistant",
|
||||
text: "a".repeat(144),
|
||||
}),
|
||||
).toBe(86.5);
|
||||
});
|
||||
|
||||
it("uses assistant sizing rules for system messages", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "system",
|
||||
text: "a".repeat(144),
|
||||
}),
|
||||
).toBe(86.5);
|
||||
});
|
||||
|
||||
it("adds one attachment row for one or two user attachments", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }],
|
||||
}),
|
||||
).toBe(234);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }],
|
||||
}),
|
||||
).toBe(234);
|
||||
});
|
||||
|
||||
it("adds a second attachment row for three or four user attachments", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }],
|
||||
}),
|
||||
).toBe(350);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }],
|
||||
}),
|
||||
).toBe(350);
|
||||
});
|
||||
|
||||
it("does not cap long user message estimates", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "a".repeat(56 * 120),
|
||||
}),
|
||||
).toBe(2736);
|
||||
});
|
||||
|
||||
it("counts explicit newlines for user message estimates", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "first\nsecond\nthird",
|
||||
}),
|
||||
).toBe(162);
|
||||
});
|
||||
|
||||
it("adds terminal context chrome without counting the hidden block as message text", () => {
|
||||
const prompt = appendTerminalContextsToPrompt("Investigate this", [
|
||||
{
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 40,
|
||||
lineEnd: 43,
|
||||
text: [
|
||||
"git status",
|
||||
"M apps/web/src/components/chat/MessagesTimeline.tsx",
|
||||
"?? tmp",
|
||||
"",
|
||||
].join("\n"),
|
||||
},
|
||||
]);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: prompt,
|
||||
}),
|
||||
).toBe(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: `${buildInlineTerminalContextText([{ header: "Terminal 1 lines 40-43" }])} Investigate this`,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase user line wrapping", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
text: "a".repeat(52),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(140);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(118);
|
||||
});
|
||||
|
||||
it("does not clamp user wrapping too aggressively on very narrow layouts", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
text: "a".repeat(20),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 100 })).toBe(184);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(118);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase assistant line wrapping", () => {
|
||||
const message = {
|
||||
role: "assistant" as const,
|
||||
text: "a".repeat(200),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(154.75);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(86.5);
|
||||
});
|
||||
|
||||
it("treats inline code as wider when estimating assistant markdown wrapping", () => {
|
||||
const message = {
|
||||
role: "assistant" as const,
|
||||
text: [
|
||||
"Typecheck found one exact-optional-property issue in the browser harness:",
|
||||
"I was always passing `onVirtualizerSnapshot`, including `undefined`.",
|
||||
"I'm tightening that object construction and rerunning the checks.",
|
||||
].join(" "),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(109.25);
|
||||
});
|
||||
});
|
||||
@@ -1,131 +0,0 @@
|
||||
import { deriveDisplayedUserMessageState } from "../lib/terminalContext";
|
||||
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
|
||||
|
||||
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
|
||||
const USER_CHARS_PER_LINE_FALLBACK = 56;
|
||||
const USER_LINE_HEIGHT_PX = 22;
|
||||
const ASSISTANT_LINE_HEIGHT_PX = 22.75;
|
||||
// Assistant rows render as markdown content plus a compact timestamp meta line.
|
||||
// The DOM baseline is much smaller than the user bubble chrome, so model it
|
||||
// separately instead of reusing the old shared constant.
|
||||
const ASSISTANT_BASE_HEIGHT_PX = 41;
|
||||
const USER_BASE_HEIGHT_PX = 96;
|
||||
const ATTACHMENTS_PER_ROW = 2;
|
||||
// Full-app browser measurements land closer to a ~116px attachment row once
|
||||
// the bubble shrinks to content width, so calibrate the estimate to that DOM.
|
||||
const USER_ATTACHMENT_ROW_HEIGHT_PX = 116;
|
||||
const USER_BUBBLE_WIDTH_RATIO = 0.8;
|
||||
const USER_BUBBLE_HORIZONTAL_PADDING_PX = 32;
|
||||
const ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX = 8;
|
||||
const USER_MONO_AVG_CHAR_WIDTH_PX = 8.4;
|
||||
const ASSISTANT_AVG_CHAR_WIDTH_PX = 7.2;
|
||||
const MIN_USER_CHARS_PER_LINE = 4;
|
||||
const MIN_ASSISTANT_CHARS_PER_LINE = 20;
|
||||
const ASSISTANT_INLINE_CODE_WIDTH_MULTIPLIER = 1.2;
|
||||
const ASSISTANT_INLINE_CODE_WRAP_OVERHEAD_CHARS = 2;
|
||||
const INLINE_CODE_SPAN_REGEX = /`([^`\n]+)`/g;
|
||||
|
||||
interface TimelineMessageHeightInput {
|
||||
role: "user" | "assistant" | "system";
|
||||
text: string;
|
||||
attachments?: ReadonlyArray<{ id: string }>;
|
||||
}
|
||||
|
||||
interface TimelineHeightEstimateLayout {
|
||||
timelineWidthPx: number | null;
|
||||
}
|
||||
|
||||
function estimateWrappedLineCount(text: string, charsPerLine: number): number {
|
||||
if (text.length === 0) return 1;
|
||||
|
||||
// Avoid allocating via split for long logs; iterate once and count wrapped lines.
|
||||
let lines = 0;
|
||||
let currentLineLength = 0;
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
if (text.charCodeAt(index) === 10) {
|
||||
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
|
||||
currentLineLength = 0;
|
||||
continue;
|
||||
}
|
||||
currentLineLength += 1;
|
||||
}
|
||||
|
||||
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
|
||||
return lines;
|
||||
}
|
||||
|
||||
function isFinitePositiveNumber(value: number | null | undefined): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
||||
}
|
||||
|
||||
function estimateCharsPerLineForUser(timelineWidthPx: number | null): number {
|
||||
if (!isFinitePositiveNumber(timelineWidthPx)) return USER_CHARS_PER_LINE_FALLBACK;
|
||||
const bubbleWidthPx = timelineWidthPx * USER_BUBBLE_WIDTH_RATIO;
|
||||
const textWidthPx = Math.max(bubbleWidthPx - USER_BUBBLE_HORIZONTAL_PADDING_PX, 0);
|
||||
return Math.max(MIN_USER_CHARS_PER_LINE, Math.floor(textWidthPx / USER_MONO_AVG_CHAR_WIDTH_PX));
|
||||
}
|
||||
|
||||
function estimateCharsPerLineForAssistant(timelineWidthPx: number | null): number {
|
||||
if (!isFinitePositiveNumber(timelineWidthPx)) return ASSISTANT_CHARS_PER_LINE_FALLBACK;
|
||||
const textWidthPx = Math.max(timelineWidthPx - ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX, 0);
|
||||
return Math.max(
|
||||
MIN_ASSISTANT_CHARS_PER_LINE,
|
||||
Math.floor(textWidthPx / ASSISTANT_AVG_CHAR_WIDTH_PX),
|
||||
);
|
||||
}
|
||||
|
||||
function expandAssistantInlineCodeForEstimate(text: string) {
|
||||
return text.replace(INLINE_CODE_SPAN_REGEX, (_match, code: string) =>
|
||||
"x".repeat(
|
||||
Math.max(
|
||||
code.length + 2,
|
||||
Math.ceil(
|
||||
code.length * ASSISTANT_INLINE_CODE_WIDTH_MULTIPLIER +
|
||||
ASSISTANT_INLINE_CODE_WRAP_OVERHEAD_CHARS,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function estimateTimelineMessageHeight(
|
||||
message: TimelineMessageHeightInput,
|
||||
layout: TimelineHeightEstimateLayout = { timelineWidthPx: null },
|
||||
): number {
|
||||
if (message.role === "assistant") {
|
||||
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(
|
||||
expandAssistantInlineCodeForEstimate(message.text),
|
||||
charsPerLine,
|
||||
);
|
||||
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * ASSISTANT_LINE_HEIGHT_PX;
|
||||
}
|
||||
|
||||
if (message.role === "user") {
|
||||
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
|
||||
const displayedUserMessage = deriveDisplayedUserMessageState(message.text);
|
||||
const renderedText =
|
||||
displayedUserMessage.contexts.length > 0
|
||||
? [
|
||||
buildInlineTerminalContextText(displayedUserMessage.contexts),
|
||||
displayedUserMessage.visibleText,
|
||||
]
|
||||
.filter((part) => part.length > 0)
|
||||
.join(" ")
|
||||
: displayedUserMessage.visibleText;
|
||||
const estimatedLines = estimateWrappedLineCount(renderedText, charsPerLine);
|
||||
const attachmentCount = message.attachments?.length ?? 0;
|
||||
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
|
||||
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
|
||||
return USER_BASE_HEIGHT_PX + estimatedLines * USER_LINE_HEIGHT_PX + attachmentHeight;
|
||||
}
|
||||
|
||||
// `system` messages are not rendered in the chat timeline, but keep a stable
|
||||
// explicit branch in case they are present in timeline data.
|
||||
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(
|
||||
expandAssistantInlineCodeForEstimate(message.text),
|
||||
charsPerLine,
|
||||
);
|
||||
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * ASSISTANT_LINE_HEIGHT_PX;
|
||||
}
|
||||
@@ -275,6 +275,20 @@ function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A variant of `ComboboxList` without `ScrollArea`, for use when
|
||||
* an external virtualizer (e.g. LegendList) owns the scroll container.
|
||||
*/
|
||||
function ComboboxListVirtualized({ className, ...props }: ComboboxPrimitive.List.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.List
|
||||
className={cn("not-empty:px-1 not-empty:py-1", className)}
|
||||
data-slot="combobox-list"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
|
||||
return <ComboboxPrimitive.Clear className={className} data-slot="combobox-clear" {...props} />;
|
||||
}
|
||||
@@ -371,6 +385,7 @@ export {
|
||||
ComboboxEmpty,
|
||||
ComboboxValue,
|
||||
ComboboxList,
|
||||
ComboboxListVirtualized,
|
||||
ComboboxClear,
|
||||
ComboboxStatus,
|
||||
ComboboxRow,
|
||||
|
||||
@@ -30,7 +30,7 @@ function CommandDialogBackdrop({ className, ...props }: CommandDialogPrimitive.B
|
||||
return (
|
||||
<CommandDialogPrimitive.Backdrop
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
|
||||
"fixed inset-0 z-50 bg-background/60 transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
|
||||
className,
|
||||
)}
|
||||
data-slot="command-dialog-backdrop"
|
||||
@@ -90,11 +90,14 @@ function Command({
|
||||
|
||||
function CommandInput({
|
||||
className,
|
||||
wrapperClassName,
|
||||
placeholder = undefined,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AutocompleteInput>) {
|
||||
}: React.ComponentProps<typeof AutocompleteInput> & {
|
||||
wrapperClassName?: string | undefined;
|
||||
}) {
|
||||
return (
|
||||
<div className="px-2.5 py-1.5">
|
||||
<div className={cn("px-2.5 py-1.5", wrapperClassName)}>
|
||||
<AutocompleteInput
|
||||
autoFocus
|
||||
className={cn(
|
||||
|
||||
@@ -12,7 +12,7 @@ import { cn } from "~/lib/utils";
|
||||
const Select = SelectPrimitive.Root;
|
||||
|
||||
const selectTriggerVariants = cva(
|
||||
"relative inline-flex select-none items-center justify-between gap-2 border rounded-lg text-left text-base outline-none transition-[color,box-shadow,background-color] data-disabled:pointer-events-none data-disabled:opacity-64 sm:text-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4",
|
||||
"relative inline-flex cursor-pointer select-none items-center justify-between gap-2 border rounded-lg text-left text-base outline-none transition-[color,box-shadow,background-color] data-disabled:pointer-events-none data-disabled:opacity-64 sm:text-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
|
||||
@@ -209,7 +209,7 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
<Toast.Portal data-slot="toast-portal">
|
||||
<Toast.Viewport
|
||||
className={cn(
|
||||
"fixed z-50 mx-auto flex w-[calc(100%-var(--toast-inset)*2)] max-w-90 [--toast-header-offset:52px] [--toast-inset:--spacing(4)] sm:[--toast-inset:--spacing(8)]",
|
||||
"fixed z-100 mx-auto flex w-[calc(100%-var(--toast-inset)*2)] max-w-90 [--toast-header-offset:52px] [--toast-inset:--spacing(4)] sm:[--toast-inset:--spacing(8)]",
|
||||
// Vertical positioning
|
||||
"data-[position*=top]:top-[calc(var(--toast-inset)+var(--toast-header-offset))]",
|
||||
"data-[position*=bottom]:bottom-(--toast-inset)",
|
||||
@@ -381,7 +381,7 @@ function AnchoredToasts() {
|
||||
|
||||
return (
|
||||
<Toast.Positioner
|
||||
className="z-50 max-w-[min(--spacing(64),var(--available-width))]"
|
||||
className="z-100 max-w-[min(--spacing(64),var(--available-width))]"
|
||||
data-slot="toast-positioner"
|
||||
key={toast.id}
|
||||
sideOffset={positionerProps.sideOffset ?? 4}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime";
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../../storeSelectors";
|
||||
import { useStore } from "../../store";
|
||||
import { useTerminalStateStore } from "../../terminalStateStore";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { TerminalViewport } from "../ThreadTerminalDrawer";
|
||||
import { useWorkspaceStore } from "../../workspace/store";
|
||||
|
||||
export function ThreadTerminalSurface(props: {
|
||||
surfaceId: string;
|
||||
terminalId: string;
|
||||
threadRef: ScopedThreadRef;
|
||||
activationFocusRequestId?: number;
|
||||
}) {
|
||||
const { activationFocusRequestId, surfaceId, terminalId, threadRef } = props;
|
||||
const thread = useStore(useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]));
|
||||
const projectRef = thread ? scopeProjectRef(thread.environmentId, thread.projectId) : null;
|
||||
const project = useStore(useMemo(() => createProjectSelectorByRef(projectRef), [projectRef]));
|
||||
const closeTerminal = useTerminalStateStore((state) => state.closeTerminal);
|
||||
const terminalLaunchContext = useTerminalStateStore(
|
||||
(state) => state.terminalLaunchContextByThreadKey[scopedThreadKey(threadRef)] ?? null,
|
||||
);
|
||||
const [containerHeight, setContainerHeight] = useState(320);
|
||||
const [focusRequestId, setFocusRequestId] = useState(1);
|
||||
const closeSurface = useWorkspaceStore((state) => state.closeSurface);
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const worktreePath = terminalLaunchContext?.worktreePath ?? thread?.worktreePath ?? null;
|
||||
const cwd = useMemo(
|
||||
() =>
|
||||
terminalLaunchContext?.cwd ??
|
||||
(project
|
||||
? projectScriptCwd({
|
||||
project: { cwd: project.cwd },
|
||||
worktreePath,
|
||||
})
|
||||
: null),
|
||||
[project, terminalLaunchContext?.cwd, worktreePath],
|
||||
);
|
||||
const runtimeEnv = useMemo(
|
||||
() =>
|
||||
project
|
||||
? projectScriptRuntimeEnv({
|
||||
project: { cwd: project.cwd },
|
||||
worktreePath,
|
||||
})
|
||||
: {},
|
||||
[project, worktreePath],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const element = containerRef.current;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const nextHeight = Math.max(180, Math.floor(entries[0]?.contentRect.height ?? 0));
|
||||
setContainerHeight((current) => (current === nextHeight ? current : nextHeight));
|
||||
});
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (activationFocusRequestId === undefined) {
|
||||
return;
|
||||
}
|
||||
setFocusRequestId((current) => current + 1);
|
||||
}, [activationFocusRequestId]);
|
||||
|
||||
if (!thread || !project || !cwd) {
|
||||
return <div ref={containerRef} className="min-h-0 flex-1 bg-background" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="min-h-0 flex-1 overflow-hidden bg-background">
|
||||
<TerminalViewport
|
||||
threadRef={threadRef}
|
||||
threadId={thread.id}
|
||||
terminalId={terminalId}
|
||||
terminalLabel={thread.title}
|
||||
cwd={cwd}
|
||||
worktreePath={worktreePath}
|
||||
runtimeEnv={runtimeEnv}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus
|
||||
resizeEpoch={0}
|
||||
drawerHeight={containerHeight}
|
||||
onAddTerminalContext={() => undefined}
|
||||
onSessionExited={() => {
|
||||
closeTerminal(threadRef, terminalId);
|
||||
closeSurface(surfaceId);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
import { resolveThreadRouteTarget } from "../../threadRoutes";
|
||||
import { useFocusedWorkspaceRouteTarget, useWorkspaceStore } from "../../workspace/store";
|
||||
import type { ThreadSurfaceInput } from "../../workspace/types";
|
||||
|
||||
function sameRouteTarget(
|
||||
left: ReturnType<typeof resolveThreadRouteTarget>,
|
||||
right: ReturnType<typeof resolveThreadRouteTarget>,
|
||||
): boolean {
|
||||
if (!left && !right) {
|
||||
return true;
|
||||
}
|
||||
if (!left || !right || left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
if (left.kind === "server" && right.kind === "server") {
|
||||
return (
|
||||
left.threadRef.environmentId === right.threadRef.environmentId &&
|
||||
left.threadRef.threadId === right.threadRef.threadId
|
||||
);
|
||||
}
|
||||
if (left.kind === "draft" && right.kind === "draft") {
|
||||
return left.draftId === right.draftId;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function WorkspaceRouteSync() {
|
||||
const navigate = useNavigate();
|
||||
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
|
||||
const currentRouteTarget = useParams({
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const focusedRouteTarget = useFocusedWorkspaceRouteTarget();
|
||||
const pathname = useLocation({
|
||||
select: (location) => location.pathname,
|
||||
});
|
||||
const previousPathnameRef = useRef(pathname);
|
||||
const draftSession = useComposerDraftStore((store) =>
|
||||
currentRouteTarget?.kind === "draft" ? store.getDraftSession(currentRouteTarget.draftId) : null,
|
||||
);
|
||||
const currentRouteSurfaceInput = useMemo<ThreadSurfaceInput | null>(() => {
|
||||
if (!currentRouteTarget) {
|
||||
return null;
|
||||
}
|
||||
if (currentRouteTarget.kind === "server") {
|
||||
return {
|
||||
scope: "server",
|
||||
threadRef: currentRouteTarget.threadRef,
|
||||
};
|
||||
}
|
||||
if (!draftSession) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
scope: "draft",
|
||||
draftId: currentRouteTarget.draftId,
|
||||
environmentId: draftSession.environmentId,
|
||||
threadId: draftSession.threadId,
|
||||
};
|
||||
}, [currentRouteTarget, draftSession]);
|
||||
|
||||
useEffect(() => {
|
||||
const pathnameChanged = previousPathnameRef.current !== pathname;
|
||||
previousPathnameRef.current = pathname;
|
||||
|
||||
if (currentRouteTarget) {
|
||||
if (!currentRouteSurfaceInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!focusedRouteTarget || pathnameChanged) {
|
||||
openThreadSurface(currentRouteSurfaceInput, "focus-or-replace");
|
||||
return;
|
||||
}
|
||||
|
||||
if (sameRouteTarget(currentRouteTarget, focusedRouteTarget)) {
|
||||
return;
|
||||
}
|
||||
|
||||
void navigateToRouteTarget(navigate, focusedRouteTarget);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!focusedRouteTarget) {
|
||||
return;
|
||||
}
|
||||
|
||||
void navigateToRouteTarget(navigate, focusedRouteTarget);
|
||||
}, [
|
||||
currentRouteSurfaceInput,
|
||||
currentRouteTarget,
|
||||
focusedRouteTarget,
|
||||
navigate,
|
||||
openThreadSurface,
|
||||
pathname,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function navigateToRouteTarget(
|
||||
navigate: ReturnType<typeof useNavigate>,
|
||||
target: NonNullable<ReturnType<typeof resolveThreadRouteTarget>>,
|
||||
) {
|
||||
if (target.kind === "server") {
|
||||
return navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: {
|
||||
environmentId: target.threadRef.environmentId,
|
||||
threadId: target.threadRef.threadId,
|
||||
},
|
||||
replace: true,
|
||||
search: {},
|
||||
});
|
||||
}
|
||||
|
||||
return navigate({
|
||||
to: "/draft/$draftId",
|
||||
params: {
|
||||
draftId: target.draftId,
|
||||
},
|
||||
replace: true,
|
||||
search: {},
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1881,13 +1881,18 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
[draftId]: nextDraftThread,
|
||||
};
|
||||
let nextDraftsByThreadKey = state.draftsByThreadKey;
|
||||
const previousDraftThread =
|
||||
previousThreadKeyForLogicalProject === undefined
|
||||
? undefined
|
||||
: nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];
|
||||
if (
|
||||
previousThreadKeyForLogicalProject &&
|
||||
previousThreadKeyForLogicalProject !== draftId &&
|
||||
!isComposerThreadKeyInUse(
|
||||
nextLogicalProjectDraftThreadKeyByLogicalProjectKey,
|
||||
previousThreadKeyForLogicalProject,
|
||||
)
|
||||
) &&
|
||||
!isDraftThreadPromoting(previousDraftThread)
|
||||
) {
|
||||
delete nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];
|
||||
if (state.draftsByThreadKey[previousThreadKeyForLogicalProject] !== undefined) {
|
||||
@@ -2153,6 +2158,9 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
||||
if (existing.prompt === prompt) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...existing,
|
||||
prompt,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createContext, useContext, type MutableRefObject } from "react";
|
||||
import type { ChatComposerHandle } from "./components/chat/ChatComposer";
|
||||
|
||||
export type ComposerHandleRef = MutableRefObject<ChatComposerHandle | null>;
|
||||
|
||||
export const ComposerHandleContext = createContext<ComposerHandleRef | null>(null);
|
||||
|
||||
export function useComposerHandleContext(): ComposerHandleRef | null {
|
||||
return useContext(ComposerHandleContext);
|
||||
}
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user