Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9fa2b75dc | ||
|
|
885a825bdb | ||
|
|
0ea58f2dbf | ||
|
|
1f83f781d7 | ||
|
|
ad4eb99e22 | ||
|
|
4bf8d7b74c | ||
|
|
971df8206d | ||
|
|
eecc2bc28d |
No files matched your search
@@ -22,3 +22,4 @@ apps/web/src/components/__screenshots__
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
artifacts/
|
||||
@@ -47,16 +47,12 @@ We are not accepting contributions yet.
|
||||
|
||||
Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## Performance benchmarks
|
||||
|
||||
See [docs/perf-benchmarks.md](./docs/perf-benchmarks.md) for the local perf harness, seeded scenarios, artifact format, and the commands for automated and manual benchmark runs.
|
||||
|
||||
## 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 serves the requested readiness path", async () => {
|
||||
it("returns once the backend reports a successful session endpoint", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
@@ -20,11 +20,6 @@ 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 () => {
|
||||
@@ -85,30 +80,4 @@ 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,8 +4,6 @@ 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 = 30_000;
|
||||
@@ -59,8 +57,6 @@ 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 (;;) {
|
||||
@@ -78,11 +74,11 @@ export async function waitForHttpReady(
|
||||
signal?.addEventListener("abort", abortRequest, { once: true });
|
||||
|
||||
try {
|
||||
const response = await fetchImpl(new URL(readinessPath, baseUrl).toString(), {
|
||||
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
|
||||
redirect: "manual",
|
||||
signal: requestController.signal,
|
||||
});
|
||||
if (isReady(response)) {
|
||||
if (response.ok) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
+37
-158
@@ -54,13 +54,7 @@ import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness"
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import {
|
||||
resolveDesktopUpdateChannel,
|
||||
shouldAcceptDesktopUpdateForCurrentVersion,
|
||||
shouldAllowDesktopPrereleaseUpdates,
|
||||
} from "./updateChannel";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
@@ -121,6 +115,8 @@ const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
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;
|
||||
@@ -148,8 +144,6 @@ 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;
|
||||
@@ -368,17 +362,13 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(
|
||||
baseUrl: string,
|
||||
options?: Parameters<typeof waitForHttpReady>[1],
|
||||
): Promise<void> {
|
||||
async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
const controller = new AbortController();
|
||||
backendReadinessAbortController = controller;
|
||||
|
||||
try {
|
||||
await waitForHttpReady(baseUrl, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
@@ -393,88 +383,6 @@ 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,
|
||||
@@ -552,16 +460,14 @@ function initializePackagedLogging(): void {
|
||||
}
|
||||
|
||||
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
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);
|
||||
});
|
||||
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);
|
||||
};
|
||||
|
||||
attachStream(child.stdout);
|
||||
attachStream(child.stderr);
|
||||
child.stdout?.on("data", writeChunk);
|
||||
child.stderr?.on("data", writeChunk);
|
||||
}
|
||||
|
||||
initializePackagedLogging();
|
||||
@@ -1171,9 +1077,6 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
||||
}
|
||||
|
||||
function configureAutoUpdater(): void {
|
||||
const currentVersion = app.getVersion();
|
||||
const updateChannel = resolveDesktopUpdateChannel(currentVersion);
|
||||
const allowPrerelease = shouldAllowDesktopPrereleaseUpdates(currentVersion);
|
||||
const githubToken =
|
||||
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
|
||||
if (githubToken) {
|
||||
@@ -1211,14 +1114,12 @@ function configureAutoUpdater(): void {
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
autoUpdater.channel = updateChannel;
|
||||
autoUpdater.allowPrerelease = allowPrerelease;
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
|
||||
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
|
||||
autoUpdater.allowDowngrade = false;
|
||||
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
|
||||
let lastLoggedDownloadMilestone = -1;
|
||||
console.info(
|
||||
`[desktop-updater] Configured update channel=${updateChannel} currentVersion=${currentVersion} allowPrerelease=${allowPrerelease}.`,
|
||||
);
|
||||
|
||||
if (isArm64HostRunningIntelBuild(desktopRuntimeInfo)) {
|
||||
console.info(
|
||||
@@ -1230,15 +1131,6 @@ function configureAutoUpdater(): void {
|
||||
console.info("[desktop-updater] Looking for updates...");
|
||||
});
|
||||
autoUpdater.on("update-available", (info) => {
|
||||
if (!shouldAcceptDesktopUpdateForCurrentVersion(currentVersion, info.version)) {
|
||||
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
|
||||
lastLoggedDownloadMilestone = -1;
|
||||
console.info(
|
||||
`[desktop-updater] Ignoring update ${info.version} on channel=${resolveDesktopUpdateChannel(info.version)} while currentVersion=${currentVersion} is on channel=${updateChannel}.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateState(
|
||||
reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
updateState,
|
||||
@@ -1330,7 +1222,7 @@ function startBackend(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const captureBackendLogs = !isDevelopment;
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
@@ -1367,8 +1259,6 @@ function startBackend(): void {
|
||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
||||
return;
|
||||
}
|
||||
const listeningDetector = new ServerListeningDetector();
|
||||
backendListeningDetector = listeningDetector;
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
@@ -1387,10 +1277,6 @@ 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;
|
||||
@@ -1403,14 +1289,6 @@ 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;
|
||||
@@ -1422,13 +1300,10 @@ 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;
|
||||
@@ -1830,7 +1705,7 @@ function createWindow(): BrowserWindow {
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
show: isDevelopment,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
@@ -1904,23 +1779,20 @@ function createWindow(): BrowserWindow {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
|
||||
let initialRevealScheduled = false;
|
||||
const revealInitialWindow = () => {
|
||||
if (initialRevealScheduled) {
|
||||
return;
|
||||
}
|
||||
initialRevealScheduled = true;
|
||||
revealWindow(window);
|
||||
};
|
||||
|
||||
window.once("ready-to-show", revealInitialWindow);
|
||||
if (!isDevelopment) {
|
||||
window.once("ready-to-show", () => {
|
||||
revealWindow(window);
|
||||
});
|
||||
}
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
setImmediate(() => {
|
||||
revealWindow(window);
|
||||
});
|
||||
} else {
|
||||
void window.loadURL(backendHttpUrl);
|
||||
void window.loadURL(resolveDesktopWindowUrl());
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -1932,6 +1804,14 @@ 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()`.
|
||||
@@ -2005,7 +1885,10 @@ async function bootstrap(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureInitialBackendWindowOpen();
|
||||
await waitForBackendHttpReady(backendHttpUrl);
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
@@ -2039,11 +1922,7 @@ app
|
||||
revealWindow(existingWindow);
|
||||
return;
|
||||
}
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
return;
|
||||
}
|
||||
ensureInitialBackendWindowOpen();
|
||||
mainWindow = createWindow();
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
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,12 +6,11 @@ describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
HOMEBREW_PREFIX: "/opt/homebrew",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
@@ -19,18 +18,9 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
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(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/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", () => {
|
||||
@@ -87,67 +77,11 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
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,79 +1,36 @@
|
||||
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 {
|
||||
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 shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellEnvironment.PATH
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellEnvironment.PATH ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
]);
|
||||
|
||||
if (shellEnvironment.PATH) {
|
||||
env.PATH = shellEnvironment.PATH;
|
||||
}
|
||||
|
||||
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
||||
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
|
||||
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);
|
||||
} catch {
|
||||
// Keep inherited environment if shell lookup fails.
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveDesktopUpdateChannel,
|
||||
shouldAcceptDesktopUpdateForCurrentVersion,
|
||||
shouldAllowDesktopPrereleaseUpdates,
|
||||
} from "./updateChannel";
|
||||
|
||||
describe("updateChannel", () => {
|
||||
it("uses the stable latest channel for plain versions", () => {
|
||||
expect(resolveDesktopUpdateChannel("0.0.17")).toBe("latest");
|
||||
expect(shouldAllowDesktopPrereleaseUpdates("0.0.17")).toBe(false);
|
||||
});
|
||||
|
||||
it("derives the prerelease channel from the installed version", () => {
|
||||
expect(resolveDesktopUpdateChannel("0.0.18-nightly.20260415")).toBe("nightly");
|
||||
expect(shouldAllowDesktopPrereleaseUpdates("0.0.18-nightly.20260415")).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts updates that stay on the same prerelease track", () => {
|
||||
expect(
|
||||
shouldAcceptDesktopUpdateForCurrentVersion(
|
||||
"0.0.18-nightly.20260415",
|
||||
"0.0.18-nightly.20260416",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects stable releases while running a nightly build", () => {
|
||||
expect(shouldAcceptDesktopUpdateForCurrentVersion("0.0.18-nightly.20260415", "0.0.17")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects updates from a different prerelease track", () => {
|
||||
expect(
|
||||
shouldAcceptDesktopUpdateForCurrentVersion("0.0.18-nightly.20260415", "0.0.18-beta.1"),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
const VERSION_PRERELEASE_CHANNEL_PATTERN =
|
||||
/^\d+\.\d+\.\d+(?:-([0-9A-Za-z-]+)(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
|
||||
function resolvePrereleaseChannel(version: string): string | null {
|
||||
const normalizedVersion = version.trim();
|
||||
const match = VERSION_PRERELEASE_CHANNEL_PATTERN.exec(normalizedVersion);
|
||||
const channel = match?.[1]?.trim().toLowerCase();
|
||||
return channel && channel.length > 0 ? channel : null;
|
||||
}
|
||||
|
||||
export function resolveDesktopUpdateChannel(version: string): string {
|
||||
return resolvePrereleaseChannel(version) ?? "latest";
|
||||
}
|
||||
|
||||
export function shouldAllowDesktopPrereleaseUpdates(version: string): boolean {
|
||||
return resolvePrereleaseChannel(version) !== null;
|
||||
}
|
||||
|
||||
export function shouldAcceptDesktopUpdateForCurrentVersion(
|
||||
currentVersion: string,
|
||||
candidateVersion: string,
|
||||
): boolean {
|
||||
return (
|
||||
resolveDesktopUpdateChannel(currentVersion) === resolveDesktopUpdateChannel(candidateVersion)
|
||||
);
|
||||
}
|
||||
@@ -488,7 +488,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEvents);
|
||||
},
|
||||
};
|
||||
|
||||
const queueTurnResponse = (
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { PERF_CATALOG_IDS, getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { seedPerfState } from "./seedPerfState.ts";
|
||||
|
||||
describe("seedPerfState", () => {
|
||||
const runParentDirsToCleanup: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
runParentDirsToCleanup
|
||||
.splice(0)
|
||||
.map((runParentDir) => rm(runParentDir, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("seeds large thread fixtures through the real event store and projection pipeline", async () => {
|
||||
const seeded = await seedPerfState("large_threads");
|
||||
runParentDirsToCleanup.push(seeded.runParentDir);
|
||||
const scenario = getPerfSeedScenario("large_threads");
|
||||
|
||||
expect(seeded.snapshot.projects).toHaveLength(5);
|
||||
expect(seeded.snapshot.threads).toHaveLength(30);
|
||||
expect(seeded.baseDir).toBe(join(seeded.runParentDir, "base"));
|
||||
expect(new Set(seeded.snapshot.threads.map((thread) => thread.projectId)).size).toBe(5);
|
||||
|
||||
const heavyThread = seeded.snapshot.threads.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
const heavyThreadScenario = scenario.threads.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
expect(heavyThread?.messages).toHaveLength(2_000);
|
||||
expect(heavyThreadScenario?.turnCount ?? Number.POSITIVE_INFINITY).toBeLessThan(100);
|
||||
expect((heavyThread?.activities.length ?? 0) > 0).toBe(true);
|
||||
expect((heavyThread?.proposedPlans.length ?? 0) > 0).toBe(true);
|
||||
expect((heavyThread?.checkpoints.length ?? 0) >= 20).toBe(true);
|
||||
expect((heavyThread?.checkpoints[0]?.files.length ?? 0) >= 12).toBe(true);
|
||||
});
|
||||
|
||||
it("enables assistant streaming in the burst base seed for websocket perf runs", async () => {
|
||||
const seeded = await seedPerfState("burst_base");
|
||||
runParentDirsToCleanup.push(seeded.runParentDir);
|
||||
|
||||
const rawSettings = await readFile(join(seeded.baseDir, "userdata/settings.json"), "utf8");
|
||||
expect(JSON.parse(rawSettings)).toMatchObject({
|
||||
enableAssistantStreaming: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,589 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { cp, mkdir, mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime } from "effect";
|
||||
|
||||
import {
|
||||
buildPerfAssistantMessageCountPlan,
|
||||
getPerfSeedScenario,
|
||||
perfEventId,
|
||||
perfMessageIdForThread,
|
||||
perfTurnIdForThread,
|
||||
type PerfProjectScenario,
|
||||
type PerfSeedScenario,
|
||||
type PerfSeedScenarioId,
|
||||
type PerfSeedThreadScenario,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { ServerConfig } from "../../src/config.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationProjectionPipeline } from "../../src/orchestration/Services/ProjectionPipeline.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../../src/persistence/Layers/Sqlite.ts";
|
||||
import { OrchestrationEventStore } from "../../src/persistence/Services/OrchestrationEventStore.ts";
|
||||
import { ServerSettingsService, ServerSettingsLive } from "../../src/serverSettings.ts";
|
||||
|
||||
export interface PerfSeededState {
|
||||
readonly scenarioId: PerfSeedScenarioId;
|
||||
readonly runParentDir: string;
|
||||
readonly baseDir: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
}
|
||||
|
||||
const templateDirPromises = new Map<PerfSeedScenarioId, Promise<string>>();
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
async function initializeGitWorkspace(workspaceRoot: string): Promise<void> {
|
||||
await mkdir(workspaceRoot, { recursive: true });
|
||||
runGit(workspaceRoot, ["init", "--initial-branch=main"]);
|
||||
runGit(workspaceRoot, ["config", "user.email", "[email protected]"]);
|
||||
runGit(workspaceRoot, ["config", "user.name", "Perf Fixture"]);
|
||||
await writeFile(
|
||||
join(workspaceRoot, "README.md"),
|
||||
"# Performance Workspace\n\nSeeded fixture state for local perf regression tests.\n",
|
||||
"utf8",
|
||||
);
|
||||
runGit(workspaceRoot, ["add", "."]);
|
||||
runGit(workspaceRoot, ["commit", "-m", "Initial perf workspace"]);
|
||||
}
|
||||
|
||||
function plusMs(baseTimeMs: number, offsetMs: number): string {
|
||||
return new Date(baseTimeMs + offsetMs).toISOString();
|
||||
}
|
||||
|
||||
function makeCommandId(prefix: string, threadId: string, turnIndex: number): CommandId {
|
||||
return CommandId.makeUnsafe(`${prefix}:${threadId}:${turnIndex.toString().padStart(4, "0")}`);
|
||||
}
|
||||
|
||||
function buildProjectEvent(
|
||||
project: PerfProjectScenario,
|
||||
workspaceRoot: string,
|
||||
createdAt: string,
|
||||
): Omit<OrchestrationEvent, "sequence"> {
|
||||
return {
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe(`perf-project-created:${String(project.id)}`),
|
||||
aggregateKind: "project",
|
||||
aggregateId: project.id,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: project.defaultModelSelection,
|
||||
scripts: [],
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildThreadCreatedEvent(
|
||||
thread: PerfSeedThreadScenario,
|
||||
project: PerfProjectScenario,
|
||||
createdAt: string,
|
||||
): Omit<OrchestrationEvent, "sequence"> {
|
||||
return {
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe(`perf-thread-created:${String(thread.id)}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: project.defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildUserMessageText(thread: PerfSeedThreadScenario, turnIndex: number): string {
|
||||
const base = `${thread.title} request ${turnIndex}: review the current workspace state and explain the next change.`;
|
||||
if (turnIndex % 11 === 0) {
|
||||
return `${base}\n\nFocus on virtualization, batching, and cross-thread navigation latency.`;
|
||||
}
|
||||
if (turnIndex % 7 === 0) {
|
||||
return `${base}\n\nSummarize CPU-sensitive paths and any websocket burst handling concerns.`;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
function buildAssistantMessageText(
|
||||
thread: PerfSeedThreadScenario,
|
||||
turnIndex: number,
|
||||
assistantMessageIndex: number,
|
||||
assistantMessageCount: number,
|
||||
): string {
|
||||
const phaseLabel =
|
||||
assistantMessageIndex === 1
|
||||
? "Opening"
|
||||
: assistantMessageIndex === assistantMessageCount
|
||||
? "Settled"
|
||||
: assistantMessageIndex % 5 === 0
|
||||
? "Checkpoint"
|
||||
: "Loop";
|
||||
const focusTopics = [
|
||||
"checked the visible timeline window and sidebar ordering",
|
||||
"trimmed redundant projection work before the next render pass",
|
||||
"reviewed websocket fan-out and message grouping pressure",
|
||||
"verified checkpoint rows stay bounded while hidden threads move",
|
||||
"kept the active route stable while background threads kept streaming",
|
||||
];
|
||||
const topic = focusTopics[(turnIndex + assistantMessageIndex) % focusTopics.length]!;
|
||||
const threadBias =
|
||||
thread.category === "heavy"
|
||||
? "The thread is still dense enough to stress virtualization."
|
||||
: thread.category === "burst"
|
||||
? "This pass is still carrying live burst pressure."
|
||||
: "Background churn is staying active without stealing focus.";
|
||||
|
||||
return `${thread.title} ${phaseLabel.toLowerCase()} ${assistantMessageIndex}/${assistantMessageCount} for turn ${turnIndex}: ${topic}. ${threadBias}`;
|
||||
}
|
||||
|
||||
function buildProposedPlanMarkdown(thread: PerfSeedThreadScenario, turnIndex: number): string {
|
||||
return [
|
||||
`## ${thread.title} plan ${turnIndex}`,
|
||||
"",
|
||||
"1. Measure the current thread switch path against a stable local budget.",
|
||||
"2. Reduce avoidable render churn in the visible timeline window.",
|
||||
"3. Validate websocket burst handling with real runtime events before tightening thresholds.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function buildCheckpointFiles(
|
||||
thread: PerfSeedThreadScenario,
|
||||
threadOrdinal: number,
|
||||
turnIndex: number,
|
||||
): ReadonlyArray<{
|
||||
readonly path: string;
|
||||
readonly kind: string;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}> {
|
||||
const nestedPathTemplates = [
|
||||
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "TimelineVirtualizer.tsx"],
|
||||
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "ThreadSummaryPane.tsx"],
|
||||
["apps", "web", "src", "hooks", `thread-${threadOrdinal + 1}`, "useThreadViewport.ts"],
|
||||
["apps", "web", "src", "stores", `thread-${threadOrdinal + 1}`, "timelineStore.ts"],
|
||||
[
|
||||
"apps",
|
||||
"server",
|
||||
"src",
|
||||
"orchestration",
|
||||
`thread-${threadOrdinal + 1}`,
|
||||
"projectionPipeline.ts",
|
||||
],
|
||||
["apps", "server", "src", "provider", `thread-${threadOrdinal + 1}`, "runtimeBuffer.ts"],
|
||||
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "fixtureBuilders.ts"],
|
||||
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "scenarioCatalog.ts"],
|
||||
["packages", "contracts", "src", "orchestration", `thread-${threadOrdinal + 1}`, "schemas.ts"],
|
||||
["docs", "perf", `thread-${threadOrdinal + 1}`, "notes", "regression-findings.md"],
|
||||
["scripts", "perf", `thread-${threadOrdinal + 1}`, "capture-profile.ts"],
|
||||
["test", "perf", "fixtures", `thread-${threadOrdinal + 1}`, "workspace-state.json"],
|
||||
] as const;
|
||||
const fileCount = thread.category === "heavy" ? 12 + (turnIndex % 7) : 7 + (turnIndex % 4);
|
||||
|
||||
return Array.from({ length: fileCount }, (_, fileIndex) => {
|
||||
const template = nestedPathTemplates[fileIndex % nestedPathTemplates.length]!;
|
||||
const variant = Math.floor(fileIndex / nestedPathTemplates.length);
|
||||
const baseSegments = [...template];
|
||||
const fileName = baseSegments.pop()!;
|
||||
const variantFileName =
|
||||
variant === 0
|
||||
? fileName
|
||||
: fileName.replace(/(\.[^.]*)$/, `-${(variant + 1).toString().padStart(2, "0")}$1`);
|
||||
const path = [...baseSegments, variantFileName].join("/");
|
||||
const kind =
|
||||
fileIndex % 9 === 0
|
||||
? "deleted"
|
||||
: fileIndex % 5 === 0
|
||||
? "added"
|
||||
: fileIndex % 4 === 0
|
||||
? "renamed"
|
||||
: "modified";
|
||||
|
||||
return {
|
||||
path,
|
||||
kind,
|
||||
additions: kind === "deleted" ? 0 : 4 + ((turnIndex + fileIndex) % 11),
|
||||
deletions: kind === "added" ? 0 : 1 + ((threadOrdinal + fileIndex + turnIndex) % 6),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildThreadTurnEvents(
|
||||
thread: PerfSeedThreadScenario,
|
||||
threadOrdinal: number,
|
||||
projectStartMs: number,
|
||||
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
|
||||
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
const threadStartMs = projectStartMs + threadOrdinal * 60_000;
|
||||
const assistantMessageCountPlan = buildPerfAssistantMessageCountPlan(thread);
|
||||
|
||||
for (let turnIndex = 1; turnIndex <= thread.turnCount; turnIndex += 1) {
|
||||
const turnId = perfTurnIdForThread(thread, turnIndex);
|
||||
const userMessageId = perfMessageIdForThread(thread, "user", turnIndex, 1);
|
||||
const assistantMessageCount = assistantMessageCountPlan[turnIndex - 1] ?? 1;
|
||||
const turnBaseMs = threadStartMs + turnIndex * 1_000;
|
||||
const userOccurredAt = plusMs(turnBaseMs, 0);
|
||||
const activityAssistantIndex =
|
||||
thread.activityStride !== null && turnIndex % thread.activityStride === 0
|
||||
? Math.max(2, Math.floor(assistantMessageCount * 0.35))
|
||||
: null;
|
||||
const planAssistantIndex =
|
||||
thread.planStride !== null && turnIndex % thread.planStride === 0
|
||||
? Math.max(2, Math.floor(assistantMessageCount * 0.7))
|
||||
: null;
|
||||
let lastAssistantMessageId = perfMessageIdForThread(
|
||||
thread,
|
||||
"assistant",
|
||||
turnIndex,
|
||||
assistantMessageCount,
|
||||
);
|
||||
let turnEventOffset = 0;
|
||||
const nextEventId = (prefix: string) =>
|
||||
perfEventId(prefix, thread.id, turnIndex * 100 + turnEventOffset++);
|
||||
|
||||
events.push({
|
||||
type: "thread.message-sent",
|
||||
eventId: nextEventId("perf-user-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: userOccurredAt,
|
||||
commandId: makeCommandId("perf-user-message", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: userMessageId,
|
||||
role: "user",
|
||||
text: buildUserMessageText(thread, turnIndex),
|
||||
attachments: [],
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: userOccurredAt,
|
||||
updatedAt: userOccurredAt,
|
||||
},
|
||||
});
|
||||
|
||||
for (
|
||||
let assistantMessageIndex = 1;
|
||||
assistantMessageIndex <= assistantMessageCount;
|
||||
assistantMessageIndex += 1
|
||||
) {
|
||||
const assistantOccurredAt = plusMs(turnBaseMs, 120 + assistantMessageIndex * 40);
|
||||
const assistantMessageId = perfMessageIdForThread(
|
||||
thread,
|
||||
"assistant",
|
||||
turnIndex,
|
||||
assistantMessageIndex,
|
||||
);
|
||||
lastAssistantMessageId = assistantMessageId;
|
||||
|
||||
events.push({
|
||||
type: "thread.message-sent",
|
||||
eventId: nextEventId("perf-assistant-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: assistantOccurredAt,
|
||||
commandId: makeCommandId("perf-assistant-message", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: buildAssistantMessageText(
|
||||
thread,
|
||||
turnIndex,
|
||||
assistantMessageIndex,
|
||||
assistantMessageCount,
|
||||
),
|
||||
attachments: [],
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: assistantOccurredAt,
|
||||
updatedAt: assistantOccurredAt,
|
||||
},
|
||||
});
|
||||
|
||||
if (activityAssistantIndex === assistantMessageIndex) {
|
||||
const activityOccurredAt = plusMs(turnBaseMs, 132 + assistantMessageIndex * 40);
|
||||
events.push({
|
||||
type: "thread.activity-appended",
|
||||
eventId: nextEventId("perf-activity"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: activityOccurredAt,
|
||||
commandId: makeCommandId("perf-activity", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
activity: {
|
||||
id: perfEventId("perf-activity-row", thread.id, turnIndex),
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: `Synthetic command batch ${turnIndex}.${assistantMessageIndex}`,
|
||||
payload: {
|
||||
command: "perf-simulated",
|
||||
batch: turnIndex,
|
||||
loop: assistantMessageIndex,
|
||||
threadCategory: thread.category,
|
||||
},
|
||||
turnId,
|
||||
createdAt: activityOccurredAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (planAssistantIndex === assistantMessageIndex) {
|
||||
const planOccurredAt = plusMs(turnBaseMs, 140 + assistantMessageIndex * 40);
|
||||
events.push({
|
||||
type: "thread.proposed-plan-upserted",
|
||||
eventId: nextEventId("perf-plan"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: planOccurredAt,
|
||||
commandId: makeCommandId("perf-plan", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
proposedPlan: {
|
||||
id: `perf-plan:${String(thread.id)}:${turnIndex.toString().padStart(4, "0")}`,
|
||||
turnId,
|
||||
planMarkdown: buildProposedPlanMarkdown(thread, turnIndex),
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: planOccurredAt,
|
||||
updatedAt: planOccurredAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (thread.diffStride !== null && turnIndex % thread.diffStride === 0) {
|
||||
const diffOccurredAt = plusMs(turnBaseMs, 180 + assistantMessageCount * 40);
|
||||
events.push({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: nextEventId("perf-diff"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: diffOccurredAt,
|
||||
commandId: makeCommandId("perf-diff", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
checkpointTurnCount: turnIndex,
|
||||
checkpointRef: CheckpointRef.makeUnsafe(
|
||||
`refs/perf/${String(thread.id)}/${turnIndex.toString().padStart(4, "0")}`,
|
||||
),
|
||||
status: "ready",
|
||||
files: buildCheckpointFiles(thread, threadOrdinal, turnIndex),
|
||||
assistantMessageId: lastAssistantMessageId,
|
||||
completedAt: diffOccurredAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
function buildScenarioEvents(
|
||||
scenario: PerfSeedScenario,
|
||||
workspaceRootsByProjectId: ReadonlyMap<ProjectId, string>,
|
||||
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
|
||||
const projectStartMs = Date.parse("2026-03-01T12:00:00.000Z");
|
||||
const threadsByProjectId = new Map<ProjectId, PerfSeedThreadScenario[]>();
|
||||
for (const thread of scenario.threads) {
|
||||
const existing = threadsByProjectId.get(thread.projectId) ?? [];
|
||||
existing.push(thread);
|
||||
threadsByProjectId.set(thread.projectId, existing);
|
||||
}
|
||||
|
||||
let globalThreadOrdinal = 0;
|
||||
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
|
||||
for (const [projectOrdinal, project] of scenario.projects.entries()) {
|
||||
const projectWorkspaceRoot = workspaceRootsByProjectId.get(project.id);
|
||||
if (!projectWorkspaceRoot) {
|
||||
throw new Error(`Missing workspace root for perf project '${String(project.id)}'.`);
|
||||
}
|
||||
const projectBaseMs = projectStartMs + projectOrdinal * 6 * 60_000;
|
||||
const projectCreatedAt = plusMs(projectBaseMs, 0);
|
||||
const projectThreads = threadsByProjectId.get(project.id) ?? [];
|
||||
events.push(buildProjectEvent(project, projectWorkspaceRoot, projectCreatedAt));
|
||||
|
||||
for (const [threadOrdinalWithinProject, thread] of projectThreads.entries()) {
|
||||
const threadCreatedAt = plusMs(projectBaseMs, threadOrdinalWithinProject * 45_000 + 50);
|
||||
const threadEvents = buildThreadTurnEvents(thread, globalThreadOrdinal, projectBaseMs);
|
||||
globalThreadOrdinal += 1;
|
||||
events.push(buildThreadCreatedEvent(thread, project, threadCreatedAt), ...threadEvents);
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
async function createTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const baseDir = await mkdtemp(join(tmpdir(), `t3-perf-template-${scenarioId}-`));
|
||||
const primaryProject = scenario.projects[0];
|
||||
if (!primaryProject) {
|
||||
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
|
||||
}
|
||||
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
|
||||
const workspaceRootsByProjectId = new Map<ProjectId, string>(
|
||||
scenario.projects.map((project) => [project.id, join(baseDir, project.workspaceDirectoryName)]),
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
scenario.projects.map((project) =>
|
||||
initializeGitWorkspace(join(baseDir, project.workspaceDirectoryName)),
|
||||
),
|
||||
);
|
||||
|
||||
const seedLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(OrchestrationProjectionPipelineLive),
|
||||
Layer.provideMerge(OrchestrationEventStoreLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(seedLayer);
|
||||
|
||||
const snapshot = await runtime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
enableAssistantStreaming: scenario.id === "burst_base",
|
||||
});
|
||||
|
||||
for (const event of buildScenarioEvents(scenario, workspaceRootsByProjectId)) {
|
||||
const storedEvent = yield* eventStore.append(event);
|
||||
yield* projectionPipeline.projectEvent(storedEvent);
|
||||
}
|
||||
|
||||
return yield* snapshotQuery.getSnapshot();
|
||||
}),
|
||||
);
|
||||
|
||||
const manifestPath = join(baseDir, "perf-seed-manifest.json");
|
||||
await writeFile(
|
||||
manifestPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
scenarioId,
|
||||
workspaceRoot,
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
projectCount: snapshot.projects.length,
|
||||
threadCount: snapshot.threads.length,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
await runtime.dispose();
|
||||
return baseDir;
|
||||
}
|
||||
|
||||
async function getTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
|
||||
const existing = templateDirPromises.get(scenarioId);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const created = createTemplateDir(scenarioId);
|
||||
templateDirPromises.set(scenarioId, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
export async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise<PerfSeededState> {
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const templateDir = await getTemplateDir(scenarioId);
|
||||
const runParentDir = await mkdtemp(join(tmpdir(), `t3-perf-run-${scenarioId}-`));
|
||||
const baseDir = join(runParentDir, "base");
|
||||
await cp(templateDir, baseDir, { recursive: true, force: true });
|
||||
const primaryProject = scenario.projects[0];
|
||||
if (!primaryProject) {
|
||||
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
|
||||
}
|
||||
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
|
||||
|
||||
const snapshotLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(snapshotLayer);
|
||||
const snapshot = await runtime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
return yield* snapshotQuery.getSnapshot();
|
||||
}),
|
||||
);
|
||||
await runtime.dispose();
|
||||
|
||||
return {
|
||||
scenarioId,
|
||||
runParentDir,
|
||||
baseDir,
|
||||
workspaceRoot,
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,920 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
CommandId,
|
||||
MessageId,
|
||||
type ModelSelection,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type OrchestrationEvent,
|
||||
type ProjectId,
|
||||
type TerminalEvent,
|
||||
ThreadId,
|
||||
type ThreadId as ThreadIdType,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
type ServerCommandLatencyMeasurement,
|
||||
startServerPerfHarness,
|
||||
summarizeCommandLatencyMeasurements,
|
||||
summarizeRpcLatencySeries,
|
||||
type ServerPerfHarness,
|
||||
type ServerRpcLatencySeries,
|
||||
} from "./serverPerfHarness.ts";
|
||||
import type { PerfLatencySample } from "@t3tools/shared/perf/artifact";
|
||||
|
||||
const CONTROL_PLANE_SAMPLE_COUNT = 4;
|
||||
const GIT_RPC_SAMPLE_COUNT = 6;
|
||||
const STREAM_THREAD_COUNT = 5;
|
||||
const SPAM_THREAD_COUNT = 8;
|
||||
const TERMINAL_SESSION_COUNT = 3;
|
||||
const TERMINAL_OUTPUT_LINE_COUNT = 260;
|
||||
const TERMINAL_OUTPUT_SLEEP_SECONDS = 0.04;
|
||||
const GIT_BRANCH_COUNT = 240;
|
||||
const GIT_UNTRACKED_FILE_COUNT = 160;
|
||||
const DEFAULT_WAIT_TIMEOUT_MS = 45_000;
|
||||
|
||||
interface SubscriptionCleanup {
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
interface EventWaiter<TValue, TResult> {
|
||||
readonly description: string;
|
||||
readonly select: (values: ReadonlyArray<TValue>) => TResult | null;
|
||||
readonly resolve: (value: TResult) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
readonly timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
class BufferedEventFeed<TValue> implements SubscriptionCleanup {
|
||||
private readonly values: TValue[] = [];
|
||||
private readonly waiters = new Set<EventWaiter<TValue, unknown>>();
|
||||
|
||||
push(value: TValue) {
|
||||
this.values.push(value);
|
||||
for (const waiter of this.waiters) {
|
||||
const match = waiter.select(this.values);
|
||||
if (match === null) {
|
||||
continue;
|
||||
}
|
||||
clearTimeout(waiter.timer);
|
||||
this.waiters.delete(waiter);
|
||||
waiter.resolve(match);
|
||||
}
|
||||
}
|
||||
|
||||
waitFor<TResult>(
|
||||
description: string,
|
||||
select: (values: ReadonlyArray<TValue>) => TResult | null,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<TResult> {
|
||||
const immediateMatch = select(this.values);
|
||||
if (immediateMatch !== null) {
|
||||
return Promise.resolve(immediateMatch);
|
||||
}
|
||||
|
||||
return new Promise<TResult>((resolve, reject) => {
|
||||
const waiter: EventWaiter<TValue, TResult> = {
|
||||
description,
|
||||
select,
|
||||
resolve,
|
||||
reject,
|
||||
timer: setTimeout(() => {
|
||||
this.waiters.delete(waiter as EventWaiter<TValue, unknown>);
|
||||
reject(new Error(`Timed out waiting for ${description} after ${timeoutMs}ms.`));
|
||||
}, timeoutMs),
|
||||
};
|
||||
this.waiters.add(waiter as EventWaiter<TValue, unknown>);
|
||||
});
|
||||
}
|
||||
|
||||
waitForEvent(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<TValue> {
|
||||
return this.waitFor(description, (values) => values.find(predicate) ?? null, timeoutMs);
|
||||
}
|
||||
|
||||
waitForCount(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
count: number,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<ReadonlyArray<TValue>> {
|
||||
return this.waitFor(
|
||||
description,
|
||||
(values) => {
|
||||
const matches = values.filter(predicate);
|
||||
return matches.length >= count ? matches.slice(0, count) : null;
|
||||
},
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
waitForDistinct<TKey extends string | number>(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
selectKey: (value: TValue) => TKey,
|
||||
count: number,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<ReadonlyArray<TValue>> {
|
||||
return this.waitFor(
|
||||
description,
|
||||
(values) => {
|
||||
const distinctMatches = new Map<TKey, TValue>();
|
||||
for (const value of values) {
|
||||
if (!predicate(value)) {
|
||||
continue;
|
||||
}
|
||||
const key = selectKey(value);
|
||||
if (!distinctMatches.has(key)) {
|
||||
distinctMatches.set(key, value);
|
||||
}
|
||||
}
|
||||
const matches = [...distinctMatches.values()];
|
||||
return matches.length >= count ? matches : null;
|
||||
},
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
for (const waiter of this.waiters) {
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.reject(new Error(`Buffered feed disposed while waiting for ${waiter.description}.`));
|
||||
}
|
||||
this.waiters.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(delayMs: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
function makeControlThreadId(label: string): ThreadIdType {
|
||||
return ThreadId.makeUnsafe(`perf-control-${label}-${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
function makeCommandId(label: string) {
|
||||
return CommandId.makeUnsafe(`perf-command:${label}:${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
function makeMessageId(label: string) {
|
||||
return MessageId.makeUnsafe(`perf-message:${label}:${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
async function dispatchCommand(harness: ServerPerfHarness, command: ClientOrchestrationCommand) {
|
||||
return await harness.rpc.request((client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand](command),
|
||||
);
|
||||
}
|
||||
|
||||
async function measureCommandLatency(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
readonly expectedEventType: OrchestrationEvent["type"];
|
||||
readonly loadProfile: string;
|
||||
readonly timeoutMs?: number;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}): Promise<ServerCommandLatencyMeasurement> {
|
||||
const startedAt = nowIso();
|
||||
const startedAtMs = performance.now();
|
||||
const result = await dispatchCommand(input.harness, input.command);
|
||||
const ackAtMs = performance.now();
|
||||
const event = await input.orchestrationEvents.waitForEvent(
|
||||
`${input.expectedEventType} for ${input.command.type}`,
|
||||
(candidate) =>
|
||||
candidate.type === input.expectedEventType &&
|
||||
String(candidate.commandId) === String(input.command.commandId),
|
||||
input.timeoutMs,
|
||||
);
|
||||
const eventAtMs = performance.now();
|
||||
|
||||
return {
|
||||
commandType: input.command.type,
|
||||
loadProfile: input.loadProfile,
|
||||
startedAt,
|
||||
dispatchToAckMs: ackAtMs - startedAtMs,
|
||||
dispatchToEventMs: eventAtMs - startedAtMs,
|
||||
ackToEventMs: eventAtMs - ackAtMs,
|
||||
resultSequence: result.sequence,
|
||||
eventSequence: event.sequence,
|
||||
...(input.metadata ? { metadata: input.metadata } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function createSupportThread(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly label: string;
|
||||
}): Promise<ThreadIdType> {
|
||||
const threadId = makeControlThreadId(`load-${input.label}`);
|
||||
const command = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`load-thread-create-${input.label}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf Load ${input.label}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
await dispatchCommand(input.harness, command);
|
||||
await input.orchestrationEvents.waitForEvent(
|
||||
`thread.created for load support thread ${input.label}`,
|
||||
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
|
||||
);
|
||||
return threadId;
|
||||
}
|
||||
|
||||
async function captureCreateArchiveSamples(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly loadProfile: string;
|
||||
readonly sampleCount: number;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
}): Promise<ReadonlyArray<ServerCommandLatencyMeasurement>> {
|
||||
const samples: ServerCommandLatencyMeasurement[] = [];
|
||||
|
||||
for (let sampleIndex = 0; sampleIndex < input.sampleCount; sampleIndex += 1) {
|
||||
const threadId = makeControlThreadId(`${input.loadProfile}-${sampleIndex + 1}`);
|
||||
const createCommand = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`thread-create-${input.loadProfile}-${sampleIndex + 1}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf ${input.loadProfile} ${sampleIndex + 1}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
samples.push(
|
||||
await measureCommandLatency({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
command: createCommand,
|
||||
expectedEventType: "thread.created",
|
||||
loadProfile: input.loadProfile,
|
||||
metadata: {
|
||||
sampleIndex: sampleIndex + 1,
|
||||
threadId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const archiveCommand = {
|
||||
type: "thread.archive",
|
||||
commandId: makeCommandId(`thread-archive-${input.loadProfile}-${sampleIndex + 1}`),
|
||||
threadId,
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
samples.push(
|
||||
await measureCommandLatency({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
command: archiveCommand,
|
||||
expectedEventType: "thread.archived",
|
||||
loadProfile: input.loadProfile,
|
||||
metadata: {
|
||||
sampleIndex: sampleIndex + 1,
|
||||
threadId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return samples;
|
||||
}
|
||||
|
||||
async function ensureStreamingThreads(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly count: number;
|
||||
}): Promise<ReadonlyArray<ThreadIdType>> {
|
||||
const threadIds: ThreadIdType[] = [
|
||||
PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
PERF_CATALOG_IDS.burstBase.fillerThreadId,
|
||||
];
|
||||
|
||||
while (threadIds.length < input.count) {
|
||||
threadIds.push(
|
||||
await createSupportThread({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
projectId: input.projectId,
|
||||
modelSelection: input.modelSelection,
|
||||
label: `stream-${threadIds.length + 1}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return threadIds;
|
||||
}
|
||||
|
||||
async function startAssistantStreamingLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
readonly label: string;
|
||||
}): Promise<void> {
|
||||
await Promise.all(
|
||||
input.threadIds.map((threadId, index) =>
|
||||
dispatchCommand(input.harness, {
|
||||
type: "thread.turn.start",
|
||||
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
|
||||
role: "user",
|
||||
text: `Perf load ${input.label} ${index + 1}`,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand),
|
||||
),
|
||||
);
|
||||
|
||||
const threadIds = new Set(input.threadIds.map(String));
|
||||
await input.orchestrationEvents.waitForDistinct(
|
||||
`assistant streaming output for ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.streaming &&
|
||||
threadIds.has(String(event.payload.threadId)),
|
||||
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
|
||||
input.threadIds.length,
|
||||
);
|
||||
}
|
||||
|
||||
async function startCreateTurnSpamLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly count: number;
|
||||
readonly label: string;
|
||||
}): Promise<{
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
readonly done: Promise<ReadonlyArray<ThreadIdType>>;
|
||||
}> {
|
||||
const threadIds = Array.from({ length: input.count }, (_, index) =>
|
||||
makeControlThreadId(`${input.label}-${index + 1}`),
|
||||
);
|
||||
const threadIdStrings = new Set(threadIds.map(String));
|
||||
|
||||
const done = Promise.all(
|
||||
threadIds.map(async (threadId, index) => {
|
||||
const createCommand = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`${input.label}-create-${index + 1}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf Spam ${index + 1}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
await dispatchCommand(input.harness, createCommand);
|
||||
await input.orchestrationEvents.waitForEvent(
|
||||
`thread.created for ${input.label}-${index + 1}`,
|
||||
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
|
||||
);
|
||||
await dispatchCommand(input.harness, {
|
||||
type: "thread.turn.start",
|
||||
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
|
||||
role: "user",
|
||||
text: `Perf spam ${input.label} ${index + 1}`,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand);
|
||||
return threadId;
|
||||
}),
|
||||
);
|
||||
|
||||
await input.orchestrationEvents.waitForCount(
|
||||
`thread.create spam ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.created" && threadIdStrings.has(String(event.payload.threadId)),
|
||||
Math.min(4, input.count),
|
||||
);
|
||||
await input.orchestrationEvents.waitForDistinct(
|
||||
`assistant spam output ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.streaming &&
|
||||
threadIdStrings.has(String(event.payload.threadId)),
|
||||
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
|
||||
Math.min(4, input.count),
|
||||
);
|
||||
|
||||
return {
|
||||
threadIds,
|
||||
done,
|
||||
};
|
||||
}
|
||||
|
||||
async function startTerminalLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly terminalEvents: BufferedEventFeed<TerminalEvent>;
|
||||
readonly workspaceRoot: string;
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
}): Promise<ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>> {
|
||||
const sessions = await Promise.all(
|
||||
input.threadIds.slice(0, TERMINAL_SESSION_COUNT).map(async (threadId, index) => {
|
||||
const terminalId = `perf-${index + 1}`;
|
||||
await input.harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalOpen]({
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd: input.workspaceRoot,
|
||||
cols: 120,
|
||||
rows: 32,
|
||||
}),
|
||||
);
|
||||
|
||||
const command = [
|
||||
"i=1",
|
||||
`while [ $i -le ${TERMINAL_OUTPUT_LINE_COUNT} ]`,
|
||||
"do",
|
||||
` printf 'perf-terminal-${index + 1}-%03d\\n' "$i"`,
|
||||
" i=$((i + 1))",
|
||||
` sleep ${TERMINAL_OUTPUT_SLEEP_SECONDS.toFixed(2)}`,
|
||||
"done",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
await input.harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalWrite]({
|
||||
threadId,
|
||||
terminalId,
|
||||
data: command,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
threadId,
|
||||
terminalId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const terminalIds = new Set(sessions.map((session) => session.terminalId));
|
||||
await input.terminalEvents.waitForDistinct(
|
||||
"terminal output load",
|
||||
(event) => event.type === "output" && terminalIds.has(event.terminalId),
|
||||
(event) => event.terminalId,
|
||||
sessions.length,
|
||||
30_000,
|
||||
);
|
||||
|
||||
return sessions;
|
||||
}
|
||||
|
||||
async function closeTerminalLoad(
|
||||
harness: ServerPerfHarness,
|
||||
sessions: ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>,
|
||||
): Promise<void> {
|
||||
await Promise.all(
|
||||
sessions.map((session) =>
|
||||
harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalClose]({
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
deleteHistory: true,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function seedGitPressure(workspaceRoot: string): Promise<void> {
|
||||
const untrackedDir = join(workspaceRoot, "perf-git-pressure");
|
||||
await mkdir(untrackedDir, { recursive: true });
|
||||
await Promise.all(
|
||||
Array.from({ length: GIT_UNTRACKED_FILE_COUNT }, (_, index) =>
|
||||
writeFile(
|
||||
join(untrackedDir, `untracked-${(index + 1).toString().padStart(3, "0")}.ts`),
|
||||
`export const perfFile${index + 1} = ${index + 1};\n`,
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (let index = 0; index < GIT_BRANCH_COUNT; index += 1) {
|
||||
runGit(workspaceRoot, ["branch", `perf/latency-${(index + 1).toString().padStart(4, "0")}`]);
|
||||
}
|
||||
}
|
||||
|
||||
async function measureRpcLatencySeries<TResult>(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly iterations: number;
|
||||
readonly execute: () => Promise<TResult>;
|
||||
}): Promise<ServerRpcLatencySeries> {
|
||||
const samples: PerfLatencySample[] = [];
|
||||
|
||||
for (let iteration = 0; iteration < input.iterations; iteration += 1) {
|
||||
const startedAt = nowIso();
|
||||
const startedAtMs = performance.now();
|
||||
await input.execute();
|
||||
const endedAtMs = performance.now();
|
||||
samples.push({
|
||||
name: `${input.name}-${iteration + 1}`,
|
||||
durationMs: endedAtMs - startedAtMs,
|
||||
startedAt,
|
||||
endedAt: nowIso(),
|
||||
metadata: {
|
||||
iteration: iteration + 1,
|
||||
loadProfile: input.loadProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
name: input.name,
|
||||
loadProfile: input.loadProfile,
|
||||
summary: summarizeRpcLatencySeries(samples),
|
||||
samples,
|
||||
};
|
||||
}
|
||||
|
||||
function groupCommandSeries(
|
||||
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
|
||||
loadProfile: string,
|
||||
) {
|
||||
const createSamples = samples.filter((sample) => sample.commandType === "thread.create");
|
||||
const archiveSamples = samples.filter((sample) => sample.commandType === "thread.archive");
|
||||
|
||||
return [
|
||||
{
|
||||
name: "thread.create",
|
||||
loadProfile,
|
||||
summary: summarizeCommandLatencyMeasurements(createSamples),
|
||||
samples: createSamples,
|
||||
},
|
||||
{
|
||||
name: "thread.archive",
|
||||
loadProfile,
|
||||
summary: summarizeCommandLatencyMeasurements(archiveSamples),
|
||||
samples: archiveSamples,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
|
||||
describe("server perf latency", () => {
|
||||
const disposables: Array<SubscriptionCleanup> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const disposable of disposables.splice(0)) {
|
||||
disposable.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("records idle and assistant-stream command latency at the websocket boundary", async () => {
|
||||
let harness: ServerPerfHarness | null = null;
|
||||
|
||||
try {
|
||||
harness = await startServerPerfHarness({
|
||||
suite: "server-latency-critical-commands",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "parallel_assistant_stream",
|
||||
});
|
||||
const runStartedAt = nowIso();
|
||||
|
||||
const burstProject = harness.seededState.snapshot.projects.find(
|
||||
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
|
||||
);
|
||||
expect(burstProject).toBeTruthy();
|
||||
const modelSelection = burstProject!.defaultModelSelection;
|
||||
expect(modelSelection).toBeTruthy();
|
||||
|
||||
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
|
||||
disposables.push(orchestrationEvents);
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
(event) => orchestrationEvents.push(event),
|
||||
),
|
||||
});
|
||||
|
||||
await sleep(250);
|
||||
|
||||
const idleSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "idle",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
const streamingThreadIds = await ensureStreamingThreads({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: STREAM_THREAD_COUNT,
|
||||
});
|
||||
await startAssistantStreamingLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
threadIds: streamingThreadIds,
|
||||
label: "stream-control-plane",
|
||||
});
|
||||
|
||||
const streamingSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "assistant-stream-5x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
const spamLoad = await startCreateTurnSpamLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: SPAM_THREAD_COUNT,
|
||||
label: "create-turn-spam-8x",
|
||||
});
|
||||
const spamSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "create-turn-spam-8x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
await spamLoad.done;
|
||||
|
||||
const commandLatency = [
|
||||
...groupCommandSeries(idleSamples, "idle"),
|
||||
...groupCommandSeries(streamingSamples, "assistant-stream-5x"),
|
||||
...groupCommandSeries(spamSamples, "create-turn-spam-8x"),
|
||||
];
|
||||
const result = await harness.finishRun({
|
||||
artifactBasename: "control-plane-stream-baseline",
|
||||
artifact: {
|
||||
suite: "server-latency-critical-commands",
|
||||
scenarioId: "burst_base_control_plane_stream_baseline",
|
||||
startedAt: runStartedAt,
|
||||
completedAt: nowIso(),
|
||||
commandLatency,
|
||||
rpcLatency: [],
|
||||
metadata: {
|
||||
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
streamingThreadCount: STREAM_THREAD_COUNT,
|
||||
spamThreadCount: SPAM_THREAD_COUNT,
|
||||
},
|
||||
},
|
||||
});
|
||||
harness = null;
|
||||
|
||||
expect(result.artifact.commandLatency).toHaveLength(6);
|
||||
for (const series of result.artifact.commandLatency) {
|
||||
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
|
||||
expect(series.summary.dispatchToEventMs.p50Ms).not.toBeNull();
|
||||
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
} finally {
|
||||
await harness?.dispose();
|
||||
}
|
||||
}, 180_000);
|
||||
|
||||
it("records command and git rpc latency under terminal and mixed server load", async () => {
|
||||
let harness: ServerPerfHarness | null = null;
|
||||
let terminalSessions: ReadonlyArray<{
|
||||
readonly threadId: ThreadIdType;
|
||||
readonly terminalId: string;
|
||||
}> = [];
|
||||
|
||||
try {
|
||||
harness = await startServerPerfHarness({
|
||||
suite: "server-latency-critical-commands",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "parallel_assistant_stream",
|
||||
});
|
||||
const runStartedAt = nowIso();
|
||||
|
||||
const burstProject = harness.seededState.snapshot.projects.find(
|
||||
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
|
||||
);
|
||||
expect(burstProject).toBeTruthy();
|
||||
const modelSelection = burstProject!.defaultModelSelection;
|
||||
expect(modelSelection).toBeTruthy();
|
||||
|
||||
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
|
||||
const terminalEvents = new BufferedEventFeed<TerminalEvent>();
|
||||
disposables.push(orchestrationEvents, terminalEvents);
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
(event) => orchestrationEvents.push(event),
|
||||
),
|
||||
});
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeTerminalEvents]({}),
|
||||
(event) => terminalEvents.push(event),
|
||||
),
|
||||
});
|
||||
|
||||
await sleep(250);
|
||||
await seedGitPressure(harness.seededState.workspaceRoot);
|
||||
|
||||
const gitLatencyIdle = await Promise.all([
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.status",
|
||||
loadProfile: "idle-repo-pressure",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitStatus]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.listBranches",
|
||||
loadProfile: "idle-repo-pressure",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitListBranches]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
const streamingThreadIds = await ensureStreamingThreads({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: STREAM_THREAD_COUNT,
|
||||
});
|
||||
|
||||
terminalSessions = await startTerminalLoad({
|
||||
harness,
|
||||
terminalEvents,
|
||||
workspaceRoot: harness.seededState.workspaceRoot,
|
||||
threadIds: streamingThreadIds,
|
||||
});
|
||||
|
||||
const terminalSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "terminal-output-3x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
await sleep(6_500);
|
||||
await startAssistantStreamingLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
threadIds: streamingThreadIds,
|
||||
label: "mixed-load",
|
||||
});
|
||||
await terminalEvents.waitForCount(
|
||||
"continued terminal output during mixed load",
|
||||
(event) =>
|
||||
event.type === "output" &&
|
||||
terminalSessions.some((session) => session.terminalId === event.terminalId),
|
||||
TERMINAL_SESSION_COUNT,
|
||||
30_000,
|
||||
);
|
||||
|
||||
const mixedSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
const gitLatencyMixed = await Promise.all([
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.status",
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitStatus]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.listBranches",
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitListBranches]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
await closeTerminalLoad(harness, terminalSessions);
|
||||
terminalSessions = [];
|
||||
|
||||
const result = await harness.finishRun({
|
||||
artifactBasename: "terminal-mixed-git-baseline",
|
||||
artifact: {
|
||||
suite: "server-latency-critical-commands",
|
||||
scenarioId: "burst_base_terminal_mixed_git_baseline",
|
||||
startedAt: runStartedAt,
|
||||
completedAt: nowIso(),
|
||||
commandLatency: [
|
||||
...groupCommandSeries(terminalSamples, "terminal-output-3x"),
|
||||
...groupCommandSeries(mixedSamples, "mixed-stream-terminal-git"),
|
||||
],
|
||||
rpcLatency: [...gitLatencyIdle, ...gitLatencyMixed],
|
||||
metadata: {
|
||||
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
gitRpcSampleCount: GIT_RPC_SAMPLE_COUNT,
|
||||
branchCount: GIT_BRANCH_COUNT,
|
||||
untrackedFileCount: GIT_UNTRACKED_FILE_COUNT,
|
||||
terminalSessionCount: TERMINAL_SESSION_COUNT,
|
||||
},
|
||||
},
|
||||
});
|
||||
harness = null;
|
||||
|
||||
expect(result.artifact.commandLatency).toHaveLength(4);
|
||||
expect(result.artifact.rpcLatency).toHaveLength(4);
|
||||
for (const series of result.artifact.commandLatency) {
|
||||
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
|
||||
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
for (const series of result.artifact.rpcLatency) {
|
||||
expect(series.samples).toHaveLength(GIT_RPC_SAMPLE_COUNT);
|
||||
expect(series.summary.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
} finally {
|
||||
if (harness && terminalSessions.length > 0) {
|
||||
await closeTerminalLoad(harness, terminalSessions).catch(() => undefined);
|
||||
}
|
||||
await harness?.dispose();
|
||||
}
|
||||
}, 180_000);
|
||||
});
|
||||
@@ -0,0 +1,393 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { join, resolve } from "node:path";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import * as NodeSocket from "@effect/platform-node/NodeSocket";
|
||||
import {
|
||||
type OrchestrationEvent,
|
||||
type TerminalEvent,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Scope,
|
||||
Stream,
|
||||
type Scope as ScopeService,
|
||||
} from "effect";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import {
|
||||
summarizeLatencySamples,
|
||||
summarizeLatencyValues,
|
||||
type PerfLatencySample,
|
||||
type PerfLatencySummary,
|
||||
writeJsonArtifact,
|
||||
} from "@t3tools/shared/perf/artifact";
|
||||
import type {
|
||||
PerfProviderScenarioId,
|
||||
PerfSeedScenarioId,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { seedPerfState, type PerfSeededState } from "./seedPerfState.ts";
|
||||
|
||||
const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
|
||||
const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const AUTO_BOOTSTRAP_PROJECT_ENV = "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD";
|
||||
|
||||
const makeWsRpcClient = RpcClient.make(WsRpcGroup);
|
||||
type WsRpcClient =
|
||||
typeof makeWsRpcClient extends Effect.Effect<infer Client, any, any> ? Client : never;
|
||||
|
||||
export interface ServerCommandLatencyMeasurement {
|
||||
readonly commandType: string;
|
||||
readonly loadProfile: string;
|
||||
readonly startedAt: string;
|
||||
readonly dispatchToAckMs: number;
|
||||
readonly dispatchToEventMs: number;
|
||||
readonly ackToEventMs: number;
|
||||
readonly resultSequence: number;
|
||||
readonly eventSequence: number;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ServerCommandLatencySummary {
|
||||
readonly count: number;
|
||||
readonly dispatchToAckMs: PerfLatencySummary;
|
||||
readonly dispatchToEventMs: PerfLatencySummary;
|
||||
readonly ackToEventMs: PerfLatencySummary;
|
||||
}
|
||||
|
||||
export interface ServerCommandLatencySeries {
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly summary: ServerCommandLatencySummary;
|
||||
readonly samples: ReadonlyArray<ServerCommandLatencyMeasurement>;
|
||||
}
|
||||
|
||||
export interface ServerRpcLatencySeries {
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly summary: PerfLatencySummary;
|
||||
readonly samples: ReadonlyArray<PerfLatencySample>;
|
||||
}
|
||||
|
||||
export interface ServerPerfRunArtifact {
|
||||
readonly suite: string;
|
||||
readonly scenarioId: string;
|
||||
readonly startedAt: string;
|
||||
readonly completedAt: string;
|
||||
readonly commandLatency: ReadonlyArray<ServerCommandLatencySeries>;
|
||||
readonly rpcLatency: ReadonlyArray<ServerRpcLatencySeries>;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface StartServerPerfHarnessOptions {
|
||||
readonly suite: string;
|
||||
readonly seedScenarioId: PerfSeedScenarioId;
|
||||
readonly providerScenarioId?: PerfProviderScenarioId;
|
||||
}
|
||||
|
||||
interface FinishServerPerfRunOptions {
|
||||
readonly artifactBasename?: string;
|
||||
readonly artifact: ServerPerfRunArtifact;
|
||||
}
|
||||
|
||||
export interface ServerPerfHarness {
|
||||
readonly seededState: PerfSeededState;
|
||||
readonly wsUrl: string;
|
||||
readonly artifactDir: string;
|
||||
readonly rpc: PerfWsRpcClient;
|
||||
readonly finishRun: (options: FinishServerPerfRunOptions) => Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: ServerPerfRunArtifact;
|
||||
}>;
|
||||
readonly dispose: () => Promise<void>;
|
||||
}
|
||||
|
||||
const wsRpcProtocolLayer = (wsUrl: string) =>
|
||||
RpcClient.layerProtocolSocket().pipe(
|
||||
Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
|
||||
Layer.provide(RpcSerialization.layerJson),
|
||||
);
|
||||
|
||||
async function pickFreePort(): Promise<number> {
|
||||
return await new Promise<number>((resolvePort, reject) => {
|
||||
const server = createServer();
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Unable to resolve a free localhost port."));
|
||||
return;
|
||||
}
|
||||
const { port } = address;
|
||||
server.close((closeError) => {
|
||||
if (closeError) {
|
||||
reject(closeError);
|
||||
return;
|
||||
}
|
||||
resolvePort(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function stopChildProcess(process: ChildProcess): Promise<void> {
|
||||
if (process.exitCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.kill("SIGTERM");
|
||||
const exited = await new Promise<boolean>((resolveExited) => {
|
||||
const timer = setTimeout(() => resolveExited(false), 5_000);
|
||||
process.once("exit", () => {
|
||||
clearTimeout(timer);
|
||||
resolveExited(true);
|
||||
});
|
||||
});
|
||||
|
||||
if (!exited && process.exitCode === null) {
|
||||
process.kill("SIGKILL");
|
||||
await new Promise<void>((resolveExited) => {
|
||||
process.once("exit", () => resolveExited());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureArtifactDir(suite: string, scenarioId: string): Promise<string> {
|
||||
const baseArtifactDir = resolve(
|
||||
process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf/server"),
|
||||
);
|
||||
const runId = `${suite}-${scenarioId}-${Date.now().toString()}`;
|
||||
const artifactDir = join(baseArtifactDir, runId);
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
async function writeServerLogs(
|
||||
artifactDir: string,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
basename: string,
|
||||
): Promise<void> {
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"),
|
||||
writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"),
|
||||
]);
|
||||
}
|
||||
|
||||
function buildPerfServerEnv(
|
||||
baseEnv: NodeJS.ProcessEnv,
|
||||
providerScenarioId?: PerfProviderScenarioId,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
[AUTO_BOOTSTRAP_PROJECT_ENV]: "false",
|
||||
};
|
||||
|
||||
if (!providerScenarioId) {
|
||||
delete env[PERF_PROVIDER_ENV];
|
||||
delete env[PERF_SCENARIO_ENV];
|
||||
return env;
|
||||
}
|
||||
|
||||
return {
|
||||
...env,
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
[PERF_SCENARIO_ENV]: providerScenarioId,
|
||||
};
|
||||
}
|
||||
|
||||
export class PerfWsRpcClient {
|
||||
private readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
|
||||
private readonly clientScope: Scope.Closeable;
|
||||
private readonly clientPromise: Promise<WsRpcClient>;
|
||||
private disposed = false;
|
||||
|
||||
constructor(private readonly wsUrl: string) {
|
||||
this.runtime = ManagedRuntime.make(wsRpcProtocolLayer(wsUrl));
|
||||
this.clientScope = this.runtime.runSync(Scope.make());
|
||||
this.clientPromise = this.runtime.runPromise(Scope.provide(this.clientScope)(makeWsRpcClient));
|
||||
}
|
||||
|
||||
async request<TSuccess, TError>(
|
||||
execute: (client: WsRpcClient) => Effect.Effect<TSuccess, TError, never>,
|
||||
): Promise<TSuccess> {
|
||||
if (this.disposed) {
|
||||
throw new Error(`WebSocket RPC client disposed for ${this.wsUrl}`);
|
||||
}
|
||||
|
||||
const client = await this.clientPromise;
|
||||
return await this.runtime.runPromise(Effect.suspend(() => execute(client)));
|
||||
}
|
||||
|
||||
subscribe<TValue>(
|
||||
connect: (client: WsRpcClient) => Stream.Stream<TValue, Error, never>,
|
||||
listener: (value: TValue) => void,
|
||||
): () => void {
|
||||
if (this.disposed) {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
const cancel = this.runtime.runCallback(
|
||||
Effect.promise(() => this.clientPromise).pipe(
|
||||
Effect.flatMap((client) =>
|
||||
Stream.runForEach(connect(client), (value) =>
|
||||
Effect.sync(() => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
listener(value);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
cancel();
|
||||
};
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
this.disposed = true;
|
||||
await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void));
|
||||
await this.runtime.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForRpcReady(wsUrl: string, process: ChildProcess): Promise<void> {
|
||||
const startedAtMs = performance.now();
|
||||
const timeoutMs = 45_000;
|
||||
|
||||
while (performance.now() - startedAtMs < timeoutMs) {
|
||||
if (process.exitCode !== null) {
|
||||
throw new Error(`Perf server exited early with code ${process.exitCode}.`);
|
||||
}
|
||||
|
||||
const client = new PerfWsRpcClient(wsUrl);
|
||||
try {
|
||||
await client.request((rpcClient) => rpcClient[WS_METHODS.serverGetSettings]({}));
|
||||
await client.dispose();
|
||||
return;
|
||||
} catch {
|
||||
await client.dispose().catch(() => undefined);
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for websocket readiness at ${wsUrl}.`);
|
||||
}
|
||||
|
||||
export function summarizeCommandLatencyMeasurements(
|
||||
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
|
||||
): ServerCommandLatencySummary {
|
||||
return {
|
||||
count: samples.length,
|
||||
dispatchToAckMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToAckMs)),
|
||||
dispatchToEventMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToEventMs)),
|
||||
ackToEventMs: summarizeLatencyValues(samples.map((sample) => sample.ackToEventMs)),
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeRpcLatencySeries(
|
||||
samples: ReadonlyArray<PerfLatencySample>,
|
||||
): PerfLatencySummary {
|
||||
return summarizeLatencySamples(samples);
|
||||
}
|
||||
|
||||
export async function startServerPerfHarness(
|
||||
options: StartServerPerfHarnessOptions,
|
||||
): Promise<ServerPerfHarness> {
|
||||
const seededState = await seedPerfState(options.seedScenarioId);
|
||||
const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId);
|
||||
const port = await pickFreePort();
|
||||
const wsUrl = `ws://127.0.0.1:${port}/ws`;
|
||||
const env = buildPerfServerEnv(process.env, options.providerScenarioId);
|
||||
|
||||
let stdoutBuffer = "";
|
||||
let stderrBuffer = "";
|
||||
let finished = false;
|
||||
const serverProcess = spawn(
|
||||
"bun",
|
||||
[
|
||||
"run",
|
||||
"apps/server/src/bin.ts",
|
||||
"--mode",
|
||||
"web",
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
`${port}`,
|
||||
"--base-dir",
|
||||
seededState.baseDir,
|
||||
"--no-browser",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
serverProcess.stdout?.on("data", (chunk) => {
|
||||
stdoutBuffer += chunk.toString();
|
||||
});
|
||||
serverProcess.stderr?.on("data", (chunk) => {
|
||||
stderrBuffer += chunk.toString();
|
||||
});
|
||||
|
||||
const cleanup = async () => {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
await stopChildProcess(serverProcess);
|
||||
await rm(seededState.runParentDir, { recursive: true, force: true });
|
||||
};
|
||||
|
||||
try {
|
||||
await waitForRpcReady(wsUrl, serverProcess);
|
||||
const rpc = new PerfWsRpcClient(wsUrl);
|
||||
|
||||
return {
|
||||
seededState,
|
||||
wsUrl,
|
||||
artifactDir,
|
||||
rpc,
|
||||
finishRun: async ({ artifactBasename, artifact }) => {
|
||||
const basename = artifactBasename ?? `${artifact.suite}-${artifact.scenarioId}`;
|
||||
await rpc.dispose();
|
||||
await cleanup();
|
||||
await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename);
|
||||
const artifactPath = join(artifactDir, `${basename}.json`);
|
||||
await writeJsonArtifact(artifactPath, artifact);
|
||||
return {
|
||||
artifactPath,
|
||||
artifact,
|
||||
};
|
||||
},
|
||||
dispose: async () => {
|
||||
await rpc.dispose().catch(() => undefined);
|
||||
await cleanup();
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export type { OrchestrationEvent, ScopeService, TerminalEvent, WsRpcClient };
|
||||
@@ -20,7 +20,8 @@
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"test:perf": "vitest run integration/perf"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { join } from "node:path";
|
||||
|
||||
import { seedPerfState } from "../integration/perf/seedPerfState.ts";
|
||||
import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
|
||||
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
|
||||
const scenarioId = process.argv[2];
|
||||
|
||||
if (scenarioId !== "large_threads" && scenarioId !== "burst_base") {
|
||||
console.error(`Expected a perf seed scenario id, received '${scenarioId ?? "<missing>"}'.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const seeded = await seedPerfState(scenarioId);
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const scenarioProjectById = new Map(scenario.projects.map((project) => [project.id, project]));
|
||||
const scenarioThreadById = new Map(scenario.threads.map((thread) => [thread.id, thread]));
|
||||
const projectById = new Map(seeded.snapshot.projects.map((project) => [project.id, project]));
|
||||
const payload = JSON.stringify(
|
||||
{
|
||||
scenarioId: seeded.scenarioId,
|
||||
runParentDir: seeded.runParentDir,
|
||||
baseDir: seeded.baseDir,
|
||||
workspaceRoot: seeded.workspaceRoot,
|
||||
projectTitle: seeded.snapshot.projects[0]?.title ?? null,
|
||||
projectSummaries: seeded.snapshot.projects.map((project) => ({
|
||||
id: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot:
|
||||
scenarioProjectById.get(project.id)?.workspaceDirectoryName !== undefined
|
||||
? join(seeded.baseDir, scenarioProjectById.get(project.id)?.workspaceDirectoryName ?? "")
|
||||
: project.workspaceRoot,
|
||||
threadCount: seeded.snapshot.threads.filter((thread) => thread.projectId === project.id)
|
||||
.length,
|
||||
})),
|
||||
threadSummaries: seeded.snapshot.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
projectTitle: projectById.get(thread.projectId)?.title ?? null,
|
||||
title: thread.title,
|
||||
turnCount: scenarioThreadById.get(thread.id)?.turnCount ?? null,
|
||||
messageCount: thread.messages.length,
|
||||
activityCount: thread.activities.length,
|
||||
proposedPlanCount: thread.proposedPlans.length,
|
||||
checkpointCount: thread.checkpoints.length,
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
process.stdout.write(`${PERF_SEED_JSON_START}\n${payload}\n${PERF_SEED_JSON_END}\n`);
|
||||
@@ -24,7 +24,6 @@ export interface ServerDerivedPaths {
|
||||
readonly dbPath: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly settingsPath: string;
|
||||
readonly providerStatusCacheDir: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly logsDir: string;
|
||||
@@ -77,13 +76,11 @@ 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,
|
||||
@@ -113,7 +110,6 @@ 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 }),
|
||||
],
|
||||
|
||||
@@ -226,7 +226,6 @@ 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 });
|
||||
}
|
||||
|
||||
@@ -42,16 +42,6 @@ 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",
|
||||
@@ -132,16 +122,6 @@ 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",
|
||||
@@ -374,7 +354,6 @@ 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");
|
||||
@@ -382,7 +361,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["trae", "kiro", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -75,14 +75,6 @@ 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 = {},
|
||||
@@ -281,7 +273,7 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
|
||||
return {
|
||||
command,
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
args: resolveCommandEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1505,329 +1505,6 @@ 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;
|
||||
|
||||
@@ -90,17 +90,6 @@ 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 {
|
||||
@@ -1256,34 +1245,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -27,10 +27,6 @@ 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";
|
||||
@@ -181,24 +177,6 @@ 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({
|
||||
@@ -247,15 +225,6 @@ 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,
|
||||
@@ -310,7 +279,6 @@ describe("ProviderCommandReactor", () => {
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
renameBranch,
|
||||
refreshStatus,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
stateDir,
|
||||
@@ -545,11 +513,9 @@ 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 () => {
|
||||
@@ -1275,61 +1241,6 @@ 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,13 +11,11 @@ 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";
|
||||
@@ -74,6 +72,8 @@ 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,6 +119,10 @@ 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()
|
||||
@@ -146,7 +150,6 @@ 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>({
|
||||
@@ -287,14 +290,14 @@ const make = Effect.gen(function* () {
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const activeSession = yield* resolveActiveSession(threadId);
|
||||
const existingSessionThreadId =
|
||||
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
||||
thread.session && thread.session.status !== "stopped" ? 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"
|
||||
@@ -449,7 +452,6 @@ 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", {
|
||||
|
||||
@@ -6,7 +6,7 @@ describe("fixPath", () => {
|
||||
it("hydrates PATH on linux using the resolved login shell", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
|
||||
@@ -17,39 +17,6 @@ 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,57 +1,28 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
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 ?? ""));
|
||||
}
|
||||
import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
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 {
|
||||
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;
|
||||
}
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
const result = (options.readPath ?? readPathFromLoginShell)(shell);
|
||||
if (result) {
|
||||
env.PATH = result;
|
||||
}
|
||||
|
||||
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);
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { Effect, Stream } from "effect";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts";
|
||||
|
||||
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const STREAM_SAMPLE_EVENT_COUNT = 96;
|
||||
|
||||
describe("PerfProviderAdapter", () => {
|
||||
const previousScenarioEnv = process.env[PERF_SCENARIO_ENV];
|
||||
|
||||
afterEach(() => {
|
||||
if (previousScenarioEnv === undefined) {
|
||||
delete process.env[PERF_SCENARIO_ENV];
|
||||
return;
|
||||
}
|
||||
process.env[PERF_SCENARIO_ENV] = previousScenarioEnv;
|
||||
});
|
||||
|
||||
it("emits canonical runtime events for the dense assistant stream scenario", async () => {
|
||||
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
|
||||
const adapter = await Effect.runPromise(makePerfProviderAdapter);
|
||||
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
|
||||
|
||||
await Effect.runPromise(
|
||||
adapter.startSession({
|
||||
threadId,
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEventsPromise = Effect.runPromise(
|
||||
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "exercise the dense perf scenario",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEvents = Array.from(await firstEventsPromise);
|
||||
expect(firstEvents.filter((event) => event.type === "turn.started")).toHaveLength(3);
|
||||
expect(new Set(firstEvents.slice(0, 18).map((event) => String(event.threadId)))).toEqual(
|
||||
new Set([
|
||||
String(threadId),
|
||||
String(PERF_CATALOG_IDS.burstBase.navigationThreadId),
|
||||
String(PERF_CATALOG_IDS.burstBase.fillerThreadId),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
firstEvents.some(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
|
||||
event.type === "content.delta" &&
|
||||
event.payload.delta.includes("Navigation lane"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
firstEvents.some(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
firstEvents.some(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.fillerThreadId &&
|
||||
event.type === "item.updated" &&
|
||||
event.payload.itemType === "command_execution",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const firstBurstFollowupCompletionIndex = firstEvents.findIndex(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message" &&
|
||||
String(event.itemId ?? "").includes("followup"),
|
||||
);
|
||||
const burstWorklogIdsBeforeFollowup = new Set(
|
||||
firstEvents
|
||||
.slice(0, firstBurstFollowupCompletionIndex)
|
||||
.filter(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.started" &&
|
||||
event.payload.itemType === "command_execution",
|
||||
)
|
||||
.map((event) => String(event.itemId)),
|
||||
);
|
||||
const burstAssistantMessageLengths = firstEvents
|
||||
.flatMap((event) => {
|
||||
if (
|
||||
event.threadId !== threadId ||
|
||||
event.type !== "item.completed" ||
|
||||
event.payload.itemType !== "assistant_message" ||
|
||||
event.payload.detail === undefined
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
return [event.payload.detail.length];
|
||||
})
|
||||
.slice(0, 4);
|
||||
|
||||
expect(firstBurstFollowupCompletionIndex).toBeGreaterThan(0);
|
||||
expect(burstWorklogIdsBeforeFollowup.size).toBeGreaterThanOrEqual(3);
|
||||
expect(new Set(burstAssistantMessageLengths).size).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("assigns fresh runtime ids when the same burst thread is sent twice", async () => {
|
||||
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
|
||||
const adapter = await Effect.runPromise(makePerfProviderAdapter);
|
||||
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
|
||||
|
||||
await Effect.runPromise(
|
||||
adapter.startSession({
|
||||
threadId,
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEventsPromise = Effect.runPromise(
|
||||
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "first dense perf pass",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEvents = Array.from(await firstEventsPromise);
|
||||
|
||||
const secondEventsPromise = Effect.runPromise(
|
||||
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "second dense perf pass",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const secondEvents = Array.from(await secondEventsPromise);
|
||||
|
||||
const firstNavigationTurnStarted = firstEvents.find(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
|
||||
event.type === "turn.started",
|
||||
);
|
||||
const secondNavigationTurnStarted = secondEvents.find(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
|
||||
event.type === "turn.started",
|
||||
);
|
||||
const firstBurstAssistantCompletion = firstEvents.find(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message",
|
||||
);
|
||||
const secondBurstAssistantCompletion = secondEvents.find(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message",
|
||||
);
|
||||
const secondRunNamespaceSuffix = `--perf-run-${String(threadId)}-0002`;
|
||||
|
||||
expect(firstNavigationTurnStarted?.turnId).toBe(PERF_CATALOG_IDS.provider.navigationLiveTurnId);
|
||||
expect(firstBurstAssistantCompletion?.itemId).toBeDefined();
|
||||
expect(secondNavigationTurnStarted?.turnId).toBeDefined();
|
||||
expect(secondBurstAssistantCompletion?.itemId).toBeDefined();
|
||||
expect(secondNavigationTurnStarted?.turnId).not.toBe(firstNavigationTurnStarted?.turnId);
|
||||
expect(secondBurstAssistantCompletion?.itemId).not.toBe(firstBurstAssistantCompletion?.itemId);
|
||||
expect(String(secondNavigationTurnStarted?.turnId)).toContain(secondRunNamespaceSuffix);
|
||||
expect(String(secondBurstAssistantCompletion?.itemId)).toContain(secondRunNamespaceSuffix);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,456 @@
|
||||
import {
|
||||
EventId,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
RuntimeSessionId,
|
||||
TurnId,
|
||||
type ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
type ProviderUserInputAnswers,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
import {
|
||||
getPerfProviderScenario,
|
||||
type PerfProviderScenario,
|
||||
type TimedFixtureProviderRuntimeEvent,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import {
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
type ProviderAdapterError,
|
||||
} from "../provider/Errors.ts";
|
||||
import type {
|
||||
ProviderAdapterShape,
|
||||
ProviderThreadSnapshot,
|
||||
ProviderThreadTurnSnapshot,
|
||||
} from "../provider/Services/ProviderAdapter.ts";
|
||||
import { getPerfProviderScenarioId } from "./config.ts";
|
||||
|
||||
interface PerfSessionState {
|
||||
session: ProviderSession;
|
||||
snapshot: ProviderThreadSnapshot;
|
||||
turnCount: number;
|
||||
pendingTimers: Set<ReturnType<typeof setTimeout>>;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function sessionNotFound(threadId: ThreadId): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider: "codex",
|
||||
threadId: String(threadId),
|
||||
});
|
||||
}
|
||||
|
||||
function resolvePerfScenario(inputText: string | undefined): PerfProviderScenario {
|
||||
const scenarioId = getPerfProviderScenarioId();
|
||||
if (scenarioId) {
|
||||
return getPerfProviderScenario(scenarioId);
|
||||
}
|
||||
|
||||
const trimmedInput = inputText?.trim() || "perf request";
|
||||
return {
|
||||
id: "dense_assistant_stream",
|
||||
provider: "codex",
|
||||
sentinelText: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`,
|
||||
totalDurationMs: 48,
|
||||
events: [
|
||||
{
|
||||
delayMs: 0,
|
||||
type: "turn.started",
|
||||
payload: {
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
},
|
||||
{
|
||||
delayMs: 16,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: `Perf fallback response for: ${trimmedInput}. `,
|
||||
},
|
||||
},
|
||||
{
|
||||
delayMs: 32,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
delayMs: 48,
|
||||
type: "turn.completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function toIdleSession(session: ProviderSession, updatedAt: string): ProviderSession {
|
||||
const { activeTurnId: _activeTurnId, ...rest } = session;
|
||||
return {
|
||||
...rest,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function namespacePerfFixtureId(
|
||||
baseId: string,
|
||||
sourceThreadId: ThreadId,
|
||||
runIndex: number,
|
||||
): string {
|
||||
return `${baseId}--perf-run-${String(sourceThreadId)}-${runIndex.toString().padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
function buildRuntimeEvent(input: {
|
||||
readonly template: TimedFixtureProviderRuntimeEvent;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId;
|
||||
readonly startedAtMs: number;
|
||||
readonly index: number;
|
||||
readonly runIndex: number;
|
||||
}): ProviderRuntimeEvent {
|
||||
const eventThreadId = input.template.threadId ?? input.threadId;
|
||||
const eventTurnId =
|
||||
input.template.turnId === undefined
|
||||
? input.turnId
|
||||
: input.runIndex === 1
|
||||
? input.template.turnId
|
||||
: TurnId.makeUnsafe(
|
||||
namespacePerfFixtureId(String(input.template.turnId), input.threadId, input.runIndex),
|
||||
);
|
||||
const createdAt = new Date(input.startedAtMs + (input.template.delayMs ?? 0)).toISOString();
|
||||
return {
|
||||
type: input.template.type,
|
||||
eventId: EventId.makeUnsafe(
|
||||
`perf-runtime:${String(eventThreadId)}:${String(eventTurnId)}:${input.index.toString().padStart(4, "0")}`,
|
||||
),
|
||||
provider: "codex",
|
||||
threadId: eventThreadId,
|
||||
turnId: eventTurnId,
|
||||
createdAt,
|
||||
...(input.template.itemId
|
||||
? {
|
||||
itemId: RuntimeItemId.makeUnsafe(
|
||||
input.runIndex === 1
|
||||
? input.template.itemId
|
||||
: namespacePerfFixtureId(input.template.itemId, input.threadId, input.runIndex),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(input.template.requestId
|
||||
? {
|
||||
requestId: RuntimeRequestId.makeUnsafe(
|
||||
input.runIndex === 1
|
||||
? input.template.requestId
|
||||
: namespacePerfFixtureId(input.template.requestId, input.threadId, input.runIndex),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
payload: input.template.payload,
|
||||
} as ProviderRuntimeEvent;
|
||||
}
|
||||
|
||||
export const makePerfProviderAdapter = Effect.gen(function* () {
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const sessions = new Map<ThreadId, PerfSessionState>();
|
||||
|
||||
const clearPendingTimers = (threadId: ThreadId) =>
|
||||
Effect.sync(() => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
for (const timer of state.pendingTimers) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
state.pendingTimers.clear();
|
||||
});
|
||||
|
||||
const scheduleRuntimeEvent = (input: {
|
||||
readonly state: PerfSessionState;
|
||||
readonly event: ProviderRuntimeEvent;
|
||||
readonly delayMs: number;
|
||||
readonly onAfterEmit?: () => void;
|
||||
}) =>
|
||||
Effect.sync(() => {
|
||||
const timer = setTimeout(() => {
|
||||
input.state.pendingTimers.delete(timer);
|
||||
Effect.runFork(
|
||||
Queue.offer(runtimeEvents, input.event).pipe(
|
||||
Effect.tap(() => Effect.sync(() => input.onAfterEmit?.())),
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
}, input.delayMs);
|
||||
input.state.pendingTimers.add(timer);
|
||||
});
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (
|
||||
input: ProviderSessionStartInput,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== "codex") {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "startSession",
|
||||
issue: `Perf provider only supports codex sessions, received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const createdAt = nowIso();
|
||||
const session: ProviderSession = {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId: input.threadId,
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(input.modelSelection?.model ? { model: input.modelSelection.model } : {}),
|
||||
resumeCursor:
|
||||
input.resumeCursor ??
|
||||
RuntimeSessionId.makeUnsafe(`perf-resume:${String(input.threadId)}:${Date.now()}`),
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(input.threadId, {
|
||||
session,
|
||||
snapshot: {
|
||||
threadId: input.threadId,
|
||||
turns: [],
|
||||
},
|
||||
turnCount: 0,
|
||||
pendingTimers: new Set(),
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (
|
||||
input: ProviderSendTurnInput,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(input.threadId);
|
||||
if (!state) {
|
||||
return yield* Effect.fail(sessionNotFound(input.threadId));
|
||||
}
|
||||
|
||||
yield* clearPendingTimers(input.threadId);
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnId = TurnId.makeUnsafe(
|
||||
`perf-turn:${String(input.threadId)}:${state.turnCount.toString().padStart(4, "0")}`,
|
||||
);
|
||||
const scenario = resolvePerfScenario(input.input);
|
||||
const startedAtMs = Date.now();
|
||||
const sentAt = new Date(startedAtMs).toISOString();
|
||||
|
||||
state.session = {
|
||||
...state.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: sentAt,
|
||||
};
|
||||
|
||||
const userTurnItem = {
|
||||
type: "userMessage",
|
||||
content: [{ type: "text", text: input.input ?? "" }],
|
||||
} as const;
|
||||
const nextTurn: ProviderThreadTurnSnapshot = {
|
||||
id: turnId,
|
||||
items: [userTurnItem],
|
||||
};
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: [...state.snapshot.turns, nextTurn],
|
||||
};
|
||||
|
||||
let assistantText = "";
|
||||
const updateAssistantSnapshot = (completedAt: string) => {
|
||||
state.session = toIdleSession(state.session, completedAt);
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.map((turn) =>
|
||||
turn.id === turnId
|
||||
? {
|
||||
...turn,
|
||||
items:
|
||||
assistantText.length > 0
|
||||
? [...turn.items, { type: "agentMessage", text: assistantText }]
|
||||
: turn.items,
|
||||
}
|
||||
: turn,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
yield* Effect.forEach(
|
||||
scenario.events,
|
||||
(template, index) => {
|
||||
const event = buildRuntimeEvent({
|
||||
template,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
startedAtMs,
|
||||
index,
|
||||
runIndex: state.turnCount,
|
||||
});
|
||||
const delayMs = template.delayMs ?? 0;
|
||||
return scheduleRuntimeEvent({
|
||||
state,
|
||||
event,
|
||||
delayMs,
|
||||
onAfterEmit: () => {
|
||||
if (
|
||||
event.threadId === input.threadId &&
|
||||
event.type === "content.delta" &&
|
||||
event.payload.streamKind === "assistant_text"
|
||||
) {
|
||||
assistantText += event.payload.delta;
|
||||
}
|
||||
if (event.threadId === input.threadId && event.type === "turn.completed") {
|
||||
updateAssistantSnapshot(event.createdAt);
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
} satisfies ProviderTurnStartResult;
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
threadId,
|
||||
turnId,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return yield* Effect.fail(sessionNotFound(threadId));
|
||||
}
|
||||
yield* clearPendingTimers(threadId);
|
||||
const interruptedTurnId = turnId ?? state.session.activeTurnId;
|
||||
state.session = toIdleSession(state.session, nowIso());
|
||||
if (interruptedTurnId) {
|
||||
yield* Queue.offer(runtimeEvents, {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(
|
||||
`perf-runtime:${String(threadId)}:${String(interruptedTurnId)}:interrupted`,
|
||||
),
|
||||
provider: "codex",
|
||||
threadId,
|
||||
turnId: interruptedTurnId,
|
||||
createdAt: nowIso(),
|
||||
payload: {
|
||||
state: "interrupted",
|
||||
},
|
||||
} satisfies ProviderRuntimeEvent);
|
||||
}
|
||||
});
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
threadId,
|
||||
_requestId: ApprovalRequestId,
|
||||
_decision: ProviderApprovalDecision,
|
||||
) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId)));
|
||||
|
||||
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
|
||||
threadId,
|
||||
_requestId,
|
||||
_answers: ProviderUserInputAnswers,
|
||||
) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId)));
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
if (!sessions.has(threadId)) {
|
||||
return yield* Effect.fail(sessionNotFound(threadId));
|
||||
}
|
||||
yield* clearPendingTimers(threadId);
|
||||
sessions.delete(threadId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
|
||||
Effect.succeed(sessions.has(threadId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.succeed(sessions.get(threadId)!.snapshot)
|
||||
: Effect.fail(sessionNotFound(threadId));
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
threadId,
|
||||
numTurns,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return yield* Effect.fail(sessionNotFound(threadId));
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer between 0 and the current turn count.",
|
||||
});
|
||||
}
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
|
||||
};
|
||||
state.turnCount = state.snapshot.turns.length;
|
||||
return state.snapshot;
|
||||
});
|
||||
|
||||
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
Array.from(sessions.keys()),
|
||||
(threadId) => clearPendingTimers(threadId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
sessions.clear();
|
||||
});
|
||||
|
||||
return {
|
||||
provider: "codex",
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEvents);
|
||||
},
|
||||
} satisfies ProviderAdapterShape<ProviderAdapterError>;
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderUnsupportedError } from "../provider/Errors.ts";
|
||||
import { makeProviderServiceLive } from "../provider/Layers/ProviderService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ProviderAdapterRegistry } from "../provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts";
|
||||
|
||||
export const PerfProviderLayerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const adapter = yield* makePerfProviderAdapter;
|
||||
const adapterRegistryLayer = Layer.succeed(ProviderAdapterRegistry, {
|
||||
getByProvider: (provider) =>
|
||||
provider === adapter.provider
|
||||
? Effect.succeed(adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed([adapter.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service);
|
||||
|
||||
return makeProviderServiceLive().pipe(
|
||||
Layer.provide(adapterRegistryLayer),
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,160 @@
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { getClaudeModelCapabilities } from "../provider/Layers/ClaudeProvider.ts";
|
||||
import { getCodexModelCapabilities } from "../provider/Layers/CodexProvider.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import {
|
||||
ProviderRegistry,
|
||||
type ProviderRegistryShape,
|
||||
} from "../provider/Services/ProviderRegistry.ts";
|
||||
|
||||
const makeProviderModel = (input: {
|
||||
readonly slug: string;
|
||||
readonly name: string;
|
||||
readonly capabilities: ServerProviderModel["capabilities"];
|
||||
}): ServerProviderModel => ({
|
||||
slug: input.slug,
|
||||
name: input.name,
|
||||
isCustom: false,
|
||||
capabilities: input.capabilities,
|
||||
});
|
||||
|
||||
const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
makeProviderModel({
|
||||
slug: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
name: "GPT-5.4",
|
||||
capabilities: getCodexModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.codex),
|
||||
}),
|
||||
];
|
||||
|
||||
const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
makeProviderModel({
|
||||
slug: DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
|
||||
name: "Claude Sonnet 4.6",
|
||||
capabilities: getClaudeModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.claudeAgent),
|
||||
}),
|
||||
];
|
||||
|
||||
const makeProviderSnapshot = (input: {
|
||||
readonly provider: ServerProvider["provider"];
|
||||
readonly enabled: boolean;
|
||||
readonly checkedAt: string;
|
||||
}): ServerProvider => {
|
||||
if (input.provider === "codex") {
|
||||
return {
|
||||
provider: "codex",
|
||||
enabled: input.enabled,
|
||||
installed: true,
|
||||
version: "perf-fixture",
|
||||
status: input.enabled ? "ready" : "disabled",
|
||||
auth: input.enabled
|
||||
? {
|
||||
status: "authenticated",
|
||||
type: "perf",
|
||||
label: "Local perf harness",
|
||||
}
|
||||
: {
|
||||
status: "unknown",
|
||||
},
|
||||
checkedAt: input.checkedAt,
|
||||
message: input.enabled ? "Perf fixture provider active." : "Disabled in T3 Code settings.",
|
||||
models: CODEX_MODELS,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
provider: "claudeAgent",
|
||||
enabled: input.enabled,
|
||||
installed: false,
|
||||
version: null,
|
||||
status: input.enabled ? "warning" : "disabled",
|
||||
auth: {
|
||||
status: "unknown",
|
||||
},
|
||||
checkedAt: input.checkedAt,
|
||||
message: input.enabled
|
||||
? "Perf harness only stubs Codex runtime sessions."
|
||||
: "Disabled in T3 Code settings.",
|
||||
models: CLAUDE_MODELS,
|
||||
};
|
||||
};
|
||||
|
||||
const loadPerfProviderSnapshots = Effect.fn("loadPerfProviderSnapshots")(function* (input: {
|
||||
readonly serverSettings: ServerSettingsService["Service"];
|
||||
}) {
|
||||
const settings = yield* input.serverSettings.getSettings;
|
||||
const checkedAt = new Date().toISOString();
|
||||
return [
|
||||
makeProviderSnapshot({
|
||||
provider: "codex",
|
||||
enabled: settings.providers.codex.enabled,
|
||||
checkedAt,
|
||||
}),
|
||||
makeProviderSnapshot({
|
||||
provider: "claudeAgent",
|
||||
enabled: settings.providers.claudeAgent.enabled,
|
||||
checkedAt,
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
|
||||
const loadPerfProviderSnapshotsSafely = (
|
||||
serverSettings: ServerSettingsService["Service"],
|
||||
fallback: ReadonlyArray<ServerProvider>,
|
||||
) =>
|
||||
loadPerfProviderSnapshots({ serverSettings }).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => fallback),
|
||||
);
|
||||
|
||||
export const PerfProviderRegistryLive = Layer.effect(
|
||||
ProviderRegistry,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
yield* loadPerfProviderSnapshotsSafely(serverSettings, [
|
||||
makeProviderSnapshot({
|
||||
provider: "codex",
|
||||
enabled: true,
|
||||
checkedAt: new Date().toISOString(),
|
||||
}),
|
||||
makeProviderSnapshot({
|
||||
provider: "claudeAgent",
|
||||
enabled: false,
|
||||
checkedAt: new Date().toISOString(),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const refreshProviders = Effect.fn("refreshPerfProviders")(function* () {
|
||||
const previous = yield* Ref.get(providersRef);
|
||||
const next = yield* loadPerfProviderSnapshotsSafely(serverSettings, previous);
|
||||
yield* Ref.set(providersRef, next);
|
||||
if (!Equal.equals(previous, next)) {
|
||||
yield* PubSub.publish(changesPubSub, next);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(serverSettings.streamChanges, () => refreshProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return {
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (_provider) => refreshProviders(),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
} satisfies ProviderRegistryShape;
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { PerfProviderScenarioId } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
export const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
export const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
export const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
export const PERF_HEADFUL_ENV = "T3CODE_PERF_HEADFUL";
|
||||
|
||||
export function isPerfProviderEnabled(): boolean {
|
||||
return process.env[PERF_PROVIDER_ENV] === "1";
|
||||
}
|
||||
|
||||
export function getPerfProviderScenarioId(): PerfProviderScenarioId | null {
|
||||
const rawScenarioId = process.env[PERF_SCENARIO_ENV]?.trim();
|
||||
if (rawScenarioId === "dense_assistant_stream" || rawScenarioId === "parallel_assistant_stream") {
|
||||
return rawScenarioId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -36,7 +36,6 @@ 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.
|
||||
@@ -72,7 +71,6 @@ export const migrationEntries = [
|
||||
[21, "AuthSessionClientMetadata", Migration0021],
|
||||
[22, "AuthSessionLastConnectedAt", Migration0022],
|
||||
[23, "ProjectionThreadShellSummary", Migration0023],
|
||||
[24, "BackfillProjectionThreadShellSummary", Migration0024],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
-218
@@ -1,218 +0,0 @@
|
||||
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",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,277 +0,0 @@
|
||||
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)
|
||||
`;
|
||||
});
|
||||
@@ -663,46 +663,6 @@ 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* () {
|
||||
@@ -738,7 +698,6 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
Stream.map((settings) => settings.providers.claudeAgent),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingClaudeProvider,
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -552,46 +552,6 @@ 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* () {
|
||||
@@ -642,7 +602,6 @@ export const CodexProviderLive = Layer.effect(
|
||||
Stream.map((settings) => settings.providers.codex),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingCodexProvider,
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -31,7 +31,6 @@ 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";
|
||||
|
||||
@@ -563,61 +562,6 @@ 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();
|
||||
@@ -625,11 +569,6 @@ 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(" ");
|
||||
@@ -657,11 +596,8 @@ 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(
|
||||
refreshed.find((status) => status.provider === "codex")?.status,
|
||||
initial.find((status) => status.provider === "codex")?.status,
|
||||
"ready",
|
||||
);
|
||||
|
||||
|
||||
@@ -4,9 +4,8 @@
|
||||
* @module ProviderRegistryLive
|
||||
*/
|
||||
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
|
||||
import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
|
||||
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config";
|
||||
import { ClaudeProviderLive } from "./ClaudeProvider";
|
||||
import { CodexProviderLive } from "./CodexProvider";
|
||||
import type { ClaudeProviderShape } from "../Services/ClaudeProvider";
|
||||
@@ -14,14 +13,6 @@ 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,
|
||||
@@ -41,152 +32,61 @@ 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 fallbackProviders = yield* loadProviders(codexProvider, claudeProvider);
|
||||
const cachePathByProvider = new Map(
|
||||
PROVIDER_CACHE_IDS.map(
|
||||
(provider) =>
|
||||
[
|
||||
provider,
|
||||
resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
provider,
|
||||
}),
|
||||
] as const,
|
||||
),
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
yield* loadProviders(codexProvider, claudeProvider),
|
||||
);
|
||||
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 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,
|
||||
);
|
||||
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 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);
|
||||
}
|
||||
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
const syncProvider = Effect.fn("syncProvider")(function* (
|
||||
provider: ServerProvider,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
|
||||
switch (provider) {
|
||||
case "codex":
|
||||
return yield* codexProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
yield* codexProvider.refresh;
|
||||
break;
|
||||
case "claudeAgent":
|
||||
return yield* claudeProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
yield* claudeProvider.refresh;
|
||||
break;
|
||||
default:
|
||||
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)));
|
||||
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
break;
|
||||
}
|
||||
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: Ref.get(providersRef),
|
||||
getProviders: syncProviders({ publish: false }).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
refresh: (provider?: ProviderKind) =>
|
||||
refresh(provider).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => [] as ReadonlyArray<ServerProvider>),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
|
||||
@@ -11,7 +11,6 @@ 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> {
|
||||
@@ -21,7 +20,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const initialSettings = yield* input.getSettings;
|
||||
const initialSnapshot = input.initialSnapshot(initialSettings);
|
||||
const initialSnapshot = yield* input.checkProvider;
|
||||
const snapshotRef = yield* Ref.make(initialSnapshot);
|
||||
const settingsRef = yield* Ref.make(initialSettings);
|
||||
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
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,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,105 +0,0 @@
|
||||
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 }));
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -58,10 +58,6 @@ 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 {
|
||||
@@ -297,7 +293,6 @@ const buildAppUnderTest = (options?: {
|
||||
open?: Partial<OpenShape>;
|
||||
gitCore?: Partial<GitCoreShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
gitStatusBroadcaster?: Partial<GitStatusBroadcasterShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
orchestrationEngine?: Partial<OrchestrationEngineShape>;
|
||||
@@ -346,11 +341,7 @@ const buildAppUnderTest = (options?: {
|
||||
const gitManagerLayer = Layer.mock(GitManager)({
|
||||
...options?.layers?.gitManager,
|
||||
});
|
||||
const gitStatusBroadcasterLayer = options?.layers?.gitStatusBroadcaster
|
||||
? Layer.mock(GitStatusBroadcaster)({
|
||||
...options.layers.gitStatusBroadcaster,
|
||||
})
|
||||
: GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
|
||||
const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
|
||||
|
||||
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
|
||||
disableListenLog: true,
|
||||
@@ -1790,20 +1781,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () =>
|
||||
Effect.gen(function* () {
|
||||
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 providers = [] as const;
|
||||
const changeEvent = {
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
@@ -1860,20 +1838,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () =>
|
||||
Effect.gen(function* () {
|
||||
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;
|
||||
const providers = [] as const;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
@@ -1886,7 +1851,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
},
|
||||
providerRegistry: {
|
||||
getProviders: Effect.succeed([]),
|
||||
streamChanges: Stream.succeed(nextProviders),
|
||||
streamChanges: Stream.succeed(providers),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1900,13 +1865,10 @@ 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: nextProviders },
|
||||
payload: { providers },
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
@@ -2951,24 +2913,6 @@ 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: {
|
||||
@@ -2993,9 +2937,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
gitStatusBroadcaster: {
|
||||
refreshStatus,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
@@ -3073,7 +3014,6 @@ 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" }> =>
|
||||
|
||||
@@ -72,6 +72,9 @@ import {
|
||||
orchestrationDispatchRouteLayer,
|
||||
orchestrationSnapshotRouteLayer,
|
||||
} from "./orchestration/http";
|
||||
import { isPerfProviderEnabled } from "./perf/config";
|
||||
import { PerfProviderRegistryLive } from "./perf/PerfProviderRegistry";
|
||||
import { PerfProviderLayerLive } from "./perf/PerfProviderLayers";
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -134,7 +137,7 @@ const CheckpointingLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
);
|
||||
|
||||
const ProviderLayerLive = Layer.unwrap(
|
||||
const DefaultProviderLayerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
@@ -163,6 +166,14 @@ const ProviderLayerLive = Layer.unwrap(
|
||||
}),
|
||||
);
|
||||
|
||||
const SelectedProviderLayerLive = isPerfProviderEnabled()
|
||||
? PerfProviderLayerLive
|
||||
: DefaultProviderLayerLive;
|
||||
|
||||
const SelectedProviderRegistryLayerLive = isPerfProviderEnabled()
|
||||
? PerfProviderRegistryLive
|
||||
: ProviderRegistryLive;
|
||||
|
||||
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
|
||||
|
||||
const GitManagerLayerLive = GitManagerLive.pipe(
|
||||
@@ -199,11 +210,11 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe(
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
Layer.provideMerge(ProviderLayerLive),
|
||||
Layer.provideMerge(SelectedProviderLayerLive),
|
||||
Layer.provideMerge(TerminalLayerLive),
|
||||
Layer.provideMerge(PersistenceLayerLive),
|
||||
Layer.provideMerge(KeybindingsLive),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SelectedProviderRegistryLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(WorkspaceLayerLive),
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { DEFAULT_MODEL_BY_PROVIDER, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { DEFAULT_MODEL_BY_PROVIDER } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Deferred, Effect, Fiber, Option, Ref, Stream } from "effect";
|
||||
import { Deferred, Effect, Fiber, Option, Ref } from "effect";
|
||||
|
||||
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 { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
getAutoBootstrapDefaultModelSelection,
|
||||
launchStartupHeartbeat,
|
||||
makeCommandGate,
|
||||
resolveAutoBootstrapWelcomeTargets,
|
||||
resolveWelcomeBase,
|
||||
ServerRuntimeStartupError,
|
||||
} from "./serverRuntimeStartup.ts";
|
||||
|
||||
@@ -101,109 +93,3 @@ 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,18 +157,7 @@ export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
});
|
||||
|
||||
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 autoBootstrapWelcome = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
@@ -232,7 +221,12 @@ export const resolveAutoBootstrapWelcomeTargets = 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;
|
||||
@@ -277,7 +271,7 @@ const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>)
|
||||
Effect.withSpan(`server.startup.${phase}`),
|
||||
);
|
||||
|
||||
export const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const keybindings = yield* Keybindings;
|
||||
const orchestrationReactor = yield* OrchestrationReactor;
|
||||
@@ -328,13 +322,15 @@ export const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
|
||||
);
|
||||
|
||||
const welcomeBase = yield* resolveWelcomeBase;
|
||||
const environment = yield* serverEnvironment.getDescriptor;
|
||||
yield* Effect.logDebug("startup phase: preparing welcome payload");
|
||||
const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome);
|
||||
const environment = yield* serverEnvironment.getDescriptor;
|
||||
yield* Effect.logDebug("startup phase: publishing welcome event", {
|
||||
environmentId: environment.environmentId,
|
||||
cwd: welcomeBase.cwd,
|
||||
projectName: welcomeBase.projectName,
|
||||
cwd: welcome.cwd,
|
||||
projectName: welcome.projectName,
|
||||
bootstrapProjectId: welcome.bootstrapProjectId,
|
||||
bootstrapThreadId: welcome.bootstrapThreadId,
|
||||
});
|
||||
yield* runStartupPhase(
|
||||
"welcome.publish",
|
||||
@@ -343,47 +339,10 @@ export const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
type: "welcome",
|
||||
payload: {
|
||||
environment,
|
||||
...welcomeBase,
|
||||
...welcome,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
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,
|
||||
|
||||
+2
-19
@@ -1,4 +1,4 @@
|
||||
import { Cause, Duration, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import {
|
||||
type AuthAccessStreamEvent,
|
||||
AuthSessionId,
|
||||
@@ -85,8 +85,6 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
);
|
||||
}
|
||||
|
||||
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
|
||||
|
||||
function toAuthAccessStreamEvent(
|
||||
change: BootstrapCredentialChange | SessionCredentialChange,
|
||||
revision: number,
|
||||
@@ -466,7 +464,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
branch: worktree.worktree.branch,
|
||||
worktreePath: targetWorktreePath,
|
||||
});
|
||||
yield* refreshGitStatus(targetWorktreePath);
|
||||
}
|
||||
|
||||
yield* runSetupProgram();
|
||||
@@ -921,7 +918,6 @@ 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) => ({
|
||||
@@ -931,26 +927,13 @@ 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,
|
||||
}),
|
||||
liveUpdates,
|
||||
Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
"test:browser:install": "playwright install --with-deps chromium",
|
||||
"test:perf": "vitest run --config vitest.perf.config.ts",
|
||||
"test:perf:install": "playwright install --with-deps chromium"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
resolveEffectiveEnvMode,
|
||||
resolveEnvModeLabel,
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
@@ -158,16 +157,6 @@ 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,10 +50,6 @@ 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,9 +20,6 @@ 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;
|
||||
@@ -35,9 +32,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
threadId,
|
||||
draftId,
|
||||
onEnvModeChange,
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
envLocked,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
@@ -65,13 +59,11 @@ 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 =
|
||||
effectiveEnvModeOverride ??
|
||||
resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: serverThread !== undefined,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: serverThread !== undefined,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const envModeLocked = envLocked || (serverThread !== undefined && activeWorktreePath !== null);
|
||||
|
||||
const showEnvironmentPicker =
|
||||
@@ -106,9 +98,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
threadId={threadId}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
envLocked={envLocked}
|
||||
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
|
||||
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
|
||||
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
|
||||
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
|
||||
@@ -49,9 +49,6 @@ 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;
|
||||
}
|
||||
@@ -80,9 +77,6 @@ export function BranchToolbarBranchSelector({
|
||||
threadId,
|
||||
draftId,
|
||||
envLocked,
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
@@ -114,21 +108,16 @@ export function BranchToolbarBranchSelector({
|
||||
const activeProject = useStore(activeProjectSelector);
|
||||
|
||||
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
|
||||
const activeThreadBranch =
|
||||
activeThreadBranchOverride !== undefined
|
||||
? activeThreadBranchOverride
|
||||
: (serverThread?.branch ?? draftThread?.branch ?? null);
|
||||
const activeThreadBranch = 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 =
|
||||
effectiveEnvModeOverride ??
|
||||
resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread branch mutation (colocated — only this component calls it)
|
||||
@@ -157,7 +146,6 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
onActiveThreadBranchOverrideChange?.(branch);
|
||||
setThreadBranchAction(threadRef, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
@@ -179,7 +167,6 @@ export function BranchToolbarBranchSelector({
|
||||
serverSession,
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
setThreadBranchAction,
|
||||
setDraftThreadContext,
|
||||
draftId,
|
||||
|
||||
@@ -4,7 +4,6 @@ import { memo, useMemo } from "react";
|
||||
import {
|
||||
resolveCurrentWorkspaceLabel,
|
||||
resolveEnvModeLabel,
|
||||
resolveLockedWorkspaceLabel,
|
||||
type EnvMode,
|
||||
} from "./BranchToolbar.logic";
|
||||
import {
|
||||
@@ -44,12 +43,12 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
{activeWorktreePath ? (
|
||||
<>
|
||||
<FolderGitIcon className="size-3" />
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FolderIcon className="size-3" />
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -57,7 +57,6 @@ vi.mock("../lib/gitStatusState", () => ({
|
||||
}));
|
||||
|
||||
const THREAD_ID = "thread-browser-test" as ThreadId;
|
||||
const THREAD_TITLE = "Browser test thread";
|
||||
const ARCHIVED_SECONDARY_THREAD_ID = "thread-secondary-project-archived" as ThreadId;
|
||||
const PROJECT_ID = "project-1" as ProjectId;
|
||||
const SECOND_PROJECT_ID = "project-2" as ProjectId;
|
||||
@@ -289,7 +288,7 @@ function createSnapshotForTargetUser(options: {
|
||||
{
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: THREAD_TITLE,
|
||||
title: "Browser test thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
@@ -1804,55 +1803,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("shows Kiro in the open picker menu and opens the project cwd with it", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["kiro"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const menuButton = await waitForElement(
|
||||
() => document.querySelector('button[aria-label="Copy options"]'),
|
||||
"Unable to find Open picker button.",
|
||||
);
|
||||
(menuButton as HTMLButtonElement).click();
|
||||
|
||||
const kiroItem = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) =>
|
||||
item.textContent?.includes("Kiro"),
|
||||
) ?? null,
|
||||
"Unable to find Kiro menu item.",
|
||||
);
|
||||
(kiroItem as HTMLElement).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "kiro",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("filters the open picker menu and opens VSCodium from the menu", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
@@ -2336,287 +2286,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps new-worktree mode on empty server threads and bootstraps the first send", async () => {
|
||||
const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: {
|
||||
...snapshot,
|
||||
threads: snapshot.threads.map((thread) =>
|
||||
thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread,
|
||||
),
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 1,
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
|
||||
return {
|
||||
sequence: fixture.snapshot.snapshotSequence + 1,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(findButtonByText("New worktree")).toBeTruthy();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");
|
||||
await waitForLayout();
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(false);
|
||||
sendButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const turnStartRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
|
||||
request.type === "thread.turn.start",
|
||||
) as
|
||||
| {
|
||||
_tag: string;
|
||||
type?: string;
|
||||
bootstrap?: {
|
||||
createThread?: { projectId?: string };
|
||||
prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string };
|
||||
runSetupScript?: boolean;
|
||||
};
|
||||
}
|
||||
| undefined;
|
||||
|
||||
expect(turnStartRequest).toMatchObject({
|
||||
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
|
||||
type: "thread.turn.start",
|
||||
bootstrap: {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/repo/project",
|
||||
baseBranch: "main",
|
||||
branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/),
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
});
|
||||
expect(turnStartRequest?.bootstrap?.createThread).toBeUndefined();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("updates the selected worktree base branch on empty server threads", async () => {
|
||||
const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: {
|
||||
...snapshot,
|
||||
threads: snapshot.threads.map((thread) =>
|
||||
thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread,
|
||||
),
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 2,
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "release/next",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
|
||||
return {
|
||||
sequence: fixture.snapshot.snapshotSequence + 1,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
await page.getByText("From main", { exact: true }).click();
|
||||
await page.getByText("release/next", { exact: true }).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(findButtonByText("From release/next")).toBeTruthy();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");
|
||||
await waitForLayout();
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(false);
|
||||
sendButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const turnStartRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
|
||||
request.type === "thread.turn.start",
|
||||
) as
|
||||
| {
|
||||
_tag: string;
|
||||
type?: string;
|
||||
bootstrap?: {
|
||||
prepareWorktree?: { baseBranch?: string };
|
||||
};
|
||||
}
|
||||
| undefined;
|
||||
|
||||
expect(turnStartRequest?.bootstrap?.prepareWorktree?.baseBranch).toBe("release/next");
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("clears pending worktree overrides when switching empty server threads", async () => {
|
||||
const secondThreadId = "thread-browser-test-second" as ThreadId;
|
||||
const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);
|
||||
const snapshotWithSecondThread = addThreadToSnapshot(snapshot, secondThreadId);
|
||||
const snapshotWithTwoThreads = {
|
||||
...snapshotWithSecondThread,
|
||||
threads: snapshotWithSecondThread.threads.map((thread) => {
|
||||
if (thread.id === THREAD_ID) {
|
||||
return Object.assign({}, thread, { session: null, title: "Thread alpha" });
|
||||
}
|
||||
if (thread.id === secondThreadId) {
|
||||
return Object.assign({}, thread, { session: null, title: "Thread beta" });
|
||||
}
|
||||
return thread;
|
||||
}),
|
||||
};
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: snapshotWithTwoThreads,
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 2,
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "release/next",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
|
||||
return {
|
||||
sequence: fixture.snapshot.snapshotSequence + 1,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
await page.getByText("From main", { exact: true }).click();
|
||||
await page.getByText("release/next", { exact: true }).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(findButtonByText("From release/next")).toBeTruthy();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await mounted.router.navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: {
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
threadId: secondThreadId,
|
||||
},
|
||||
});
|
||||
|
||||
await waitForURL(
|
||||
mounted.router,
|
||||
(path) => path === serverThreadPath(secondThreadId),
|
||||
"Route should switch to the second empty server thread.",
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(findButtonByText("Current checkout")).toBeTruthy();
|
||||
expect(findButtonByText("From release/next")).toBeNull();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(findButtonByText("From main")).toBeTruthy();
|
||||
expect(findButtonByText("From release/next")).toBeNull();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows the send state once bootstrap dispatch is in flight", async () => {
|
||||
useTerminalStateStore.setState({
|
||||
terminalStateByThreadKey: {},
|
||||
@@ -3414,34 +3083,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("exposes the full thread title on the sidebar row tooltip", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-thread-tooltip-target" as MessageId,
|
||||
targetText: "thread tooltip target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const threadTitle = page.getByTestId(`thread-title-${THREAD_ID}`);
|
||||
|
||||
await expect.element(threadTitle).toBeInTheDocument();
|
||||
await threadTitle.hover();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip).not.toBeNull();
|
||||
expect(tooltip?.textContent).toContain(THREAD_TITLE);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows the confirm archive action after clicking the archive button", async () => {
|
||||
localStorage.setItem(
|
||||
"t3code:client-settings:v1",
|
||||
@@ -3581,98 +3222,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("creates a fresh worktree draft from an existing worktree thread when the default mode is worktree", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: {
|
||||
...createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-new-thread-worktree-default-test" as MessageId,
|
||||
targetText: "new thread worktree default test",
|
||||
}),
|
||||
threads: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-new-thread-worktree-default-test" as MessageId,
|
||||
targetText: "new thread worktree default test",
|
||||
}).threads.map((thread) =>
|
||||
thread.id === THREAD_ID
|
||||
? Object.assign({}, thread, {
|
||||
branch: "feature/existing",
|
||||
worktreePath: "/repo/.t3/worktrees/existing",
|
||||
})
|
||||
: thread,
|
||||
),
|
||||
},
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
settings: {
|
||||
...nextFixture.serverConfig.settings,
|
||||
defaultThreadEnvMode: "worktree",
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
const newThreadPath = await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should change to a new draft thread.",
|
||||
);
|
||||
const newDraftId = draftIdFromPath(newThreadPath);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftSession(newDraftId)).toMatchObject({
|
||||
envMode: "worktree",
|
||||
worktreePath: null,
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("creates a new draft instead of reusing a promoting draft thread", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-promoting-draft-new-thread-test" as MessageId,
|
||||
targetText: "promoting draft new thread test",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
const firstDraftPath = await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should change to the first draft thread.",
|
||||
);
|
||||
const firstDraftId = draftIdFromPath(firstDraftPath);
|
||||
const firstThreadId = draftThreadIdFor(firstDraftId);
|
||||
|
||||
await materializePromotedDraftThreadViaDomainEvent(firstThreadId);
|
||||
expect(mounted.router.state.location.pathname).toBe(firstDraftPath);
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
const secondDraftPath = await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path) && path !== firstDraftPath,
|
||||
"Route should change to a second draft thread instead of reusing the promoting draft.",
|
||||
);
|
||||
expect(draftIdFromPath(secondDraftPath)).not.toBe(firstDraftId);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("snapshots sticky codex settings into a new draft thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelectionByProvider: {
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
deriveComposerSendState,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
resolveSendEnvMode,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
waitForStartedServerThread,
|
||||
} from "./ChatView.logic";
|
||||
@@ -83,17 +82,6 @@ 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(
|
||||
|
||||
@@ -8,6 +8,7 @@ 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";
|
||||
@@ -16,10 +17,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);
|
||||
|
||||
@@ -156,11 +157,10 @@ export function readFileAsDataUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveSendEnvMode(input: {
|
||||
requestedEnvMode: DraftThreadEnvMode;
|
||||
isGitRepo: boolean;
|
||||
}): DraftThreadEnvMode {
|
||||
return input.isGitRepo ? input.requestedEnvMode : "local";
|
||||
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 cloneComposerImageForRetry(
|
||||
|
||||
@@ -91,7 +91,6 @@ import {
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
@@ -144,6 +143,7 @@ import {
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildLocalDraftThread,
|
||||
buildTemporaryWorktreeBranchName,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
@@ -156,7 +156,6 @@ import {
|
||||
deriveLockedProvider,
|
||||
readFileAsDataUrl,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
resolveSendEnvMode,
|
||||
revokeBlobPreviewUrl,
|
||||
revokeUserMessagePreviewUrls,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
@@ -689,9 +688,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
|
||||
Record<string, string[]>
|
||||
>({});
|
||||
const [pendingServerThreadEnvMode, setPendingServerThreadEnvMode] =
|
||||
useState<DraftThreadEnvMode | null>(null);
|
||||
const [pendingServerThreadBranch, setPendingServerThreadBranch] = useState<string | null>();
|
||||
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
{},
|
||||
@@ -2047,42 +2043,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}, []);
|
||||
|
||||
const activeWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const derivedEnvMode: DraftThreadEnvMode = resolveEffectiveEnvMode({
|
||||
const envMode: DraftThreadEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: isServerThread,
|
||||
draftThreadEnvMode: isLocalDraftThread ? draftThread?.envMode : undefined,
|
||||
});
|
||||
const canOverrideServerThreadEnvMode = Boolean(
|
||||
isServerThread &&
|
||||
activeThread &&
|
||||
activeThread.messages.length === 0 &&
|
||||
activeThread.worktreePath === null &&
|
||||
!envLocked,
|
||||
);
|
||||
const envMode: DraftThreadEnvMode = canOverrideServerThreadEnvMode
|
||||
? (pendingServerThreadEnvMode ?? draftThread?.envMode ?? derivedEnvMode)
|
||||
: derivedEnvMode;
|
||||
const activeThreadBranch =
|
||||
canOverrideServerThreadEnvMode && pendingServerThreadBranch !== undefined
|
||||
? pendingServerThreadBranch
|
||||
: (activeThread?.branch ?? null);
|
||||
const sendEnvMode = resolveSendEnvMode({
|
||||
requestedEnvMode: envMode,
|
||||
isGitRepo,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setPendingServerThreadEnvMode(null);
|
||||
setPendingServerThreadBranch(undefined);
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (canOverrideServerThreadEnvMode) {
|
||||
return;
|
||||
}
|
||||
setPendingServerThreadEnvMode(null);
|
||||
setPendingServerThreadBranch(undefined);
|
||||
}, [canOverrideServerThreadEnvMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) {
|
||||
@@ -2395,15 +2360,15 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const threadIdForSend = activeThread.id;
|
||||
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
|
||||
const baseBranchForWorktree =
|
||||
isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath
|
||||
? activeThreadBranch
|
||||
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
|
||||
? activeThread.branch
|
||||
: null;
|
||||
|
||||
// In worktree mode, require an explicit base branch so we don't silently
|
||||
// fall back to local execution when branch selection is missing.
|
||||
const shouldCreateWorktree =
|
||||
isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath;
|
||||
if (shouldCreateWorktree && !activeThreadBranch) {
|
||||
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
|
||||
if (shouldCreateWorktree && !activeThread.branch) {
|
||||
setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
|
||||
return;
|
||||
}
|
||||
@@ -2542,7 +2507,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
modelSelection: threadCreateModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
branch: activeThreadBranch,
|
||||
branch: activeThread.branch,
|
||||
worktreePath: activeThread.worktreePath,
|
||||
createdAt: activeThread.createdAt,
|
||||
},
|
||||
@@ -2994,7 +2959,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
modelSelection: nextThreadModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
branch: activeThreadBranch,
|
||||
branch: activeThread.branch,
|
||||
worktreePath: activeThread.worktreePath,
|
||||
createdAt,
|
||||
})
|
||||
@@ -3053,7 +3018,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}, [
|
||||
activeProject,
|
||||
activeProposedPlan,
|
||||
activeThreadBranch,
|
||||
activeThread,
|
||||
beginLocalDispatch,
|
||||
isConnecting,
|
||||
@@ -3102,11 +3066,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
);
|
||||
const onEnvModeChange = useCallback(
|
||||
(mode: DraftThreadEnvMode) => {
|
||||
if (canOverrideServerThreadEnvMode) {
|
||||
setPendingServerThreadEnvMode(mode);
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
if (isLocalDraftThread) {
|
||||
setDraftThreadContext(composerDraftTarget, {
|
||||
envMode: mode,
|
||||
@@ -3116,11 +3075,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[
|
||||
canOverrideServerThreadEnvMode,
|
||||
composerDraftTarget,
|
||||
draftThread?.worktreePath,
|
||||
isLocalDraftThread,
|
||||
setPendingServerThreadEnvMode,
|
||||
scheduleComposerFocus,
|
||||
setDraftThreadContext,
|
||||
],
|
||||
@@ -3171,7 +3128,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
|
||||
<div
|
||||
className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background"
|
||||
data-testid={`chat-thread-${activeThread.id}`}
|
||||
>
|
||||
{/* Top bar */}
|
||||
<header
|
||||
className={cn(
|
||||
@@ -3229,6 +3189,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
{/* Messages — LegendList handles virtualization and scrolling internally */}
|
||||
<MessagesTimeline
|
||||
key={activeThread.id}
|
||||
hasMessages={timelineEntries.length > 0}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnId={activeLatestTurn?.turnId ?? null}
|
||||
@@ -3342,13 +3303,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
{...(canOverrideServerThreadEnvMode ? { effectiveEnvModeOverride: envMode } : {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
|
||||
@@ -114,9 +114,7 @@ export function buildThreadActionItems(input: {
|
||||
searchTerms: [thread.title, projectTitle ?? "", thread.branch ?? ""],
|
||||
title: thread.title,
|
||||
description: descriptionParts.join(" · "),
|
||||
timestamp: formatRelativeTimeLabel(
|
||||
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
|
||||
),
|
||||
timestamp: formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt),
|
||||
icon: input.icon,
|
||||
run: async () => {
|
||||
await input.runThread(thread);
|
||||
|
||||
@@ -1020,15 +1020,6 @@ 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,7 +3,6 @@ import type {
|
||||
GitStackedAction,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
|
||||
export type GitActionIconName = "commit" | "push" | "pr";
|
||||
|
||||
@@ -355,15 +354,6 @@ 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,24 +34,6 @@ 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`;
|
||||
|
||||
@@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createThreadJumpHintVisibilityController,
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
getVisibleSidebarThreadIds,
|
||||
resolveAdjacentThreadId,
|
||||
getFallbackThreadIdAfterDelete,
|
||||
@@ -122,20 +121,6 @@ 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 = {
|
||||
@@ -184,28 +169,6 @@ 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({
|
||||
|
||||
@@ -12,9 +12,6 @@ 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;
|
||||
@@ -186,12 +183,6 @@ 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,
|
||||
@@ -252,13 +243,6 @@ 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;
|
||||
|
||||
@@ -43,7 +43,6 @@ import {
|
||||
type GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedProjectKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
@@ -82,7 +81,6 @@ 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 {
|
||||
@@ -124,7 +122,6 @@ import {
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
import {
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
resolveAdjacentThreadId,
|
||||
isContextMenuPointerDown,
|
||||
resolveProjectStatusIndicator,
|
||||
@@ -650,21 +647,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
onClick={handleRenameInputClick}
|
||||
/>
|
||||
) : (
|
||||
<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>
|
||||
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
@@ -762,9 +745,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
: "text-muted-foreground/40"
|
||||
}`}
|
||||
>
|
||||
{formatRelativeTimeLabel(
|
||||
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
|
||||
)}
|
||||
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
@@ -1120,11 +1101,6 @@ 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;
|
||||
@@ -1468,7 +1444,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey);
|
||||
const thread = sidebarThreadByKey.get(threadKey);
|
||||
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
|
||||
}
|
||||
clearSelection();
|
||||
@@ -1489,7 +1465,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
const deletedThreadKeys = new Set(threadKeys);
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey);
|
||||
const thread = sidebarThreadByKey.get(threadKey);
|
||||
if (!thread) continue;
|
||||
await deleteThread(scopeThreadRef(thread.environmentId, thread.id), {
|
||||
deletedThreadKeys,
|
||||
@@ -1503,6 +1479,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
deleteThread,
|
||||
markThreadUnread,
|
||||
removeFromSelection,
|
||||
sidebarThreadByKey,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1631,7 +1608,12 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const api = readLocalApi();
|
||||
if (!api) return;
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null;
|
||||
const thread =
|
||||
projectThreads.find(
|
||||
(projectThread) =>
|
||||
projectThread.environmentId === threadRef.environmentId &&
|
||||
projectThread.id === threadRef.threadId,
|
||||
) ?? null;
|
||||
if (!thread) return;
|
||||
const threadWorkspacePath = thread.worktreePath ?? project.cwd ?? null;
|
||||
const clicked = await api.contextMenu.show(
|
||||
@@ -1693,6 +1675,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
deleteThread,
|
||||
markThreadUnread,
|
||||
project.cwd,
|
||||
projectThreads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2881,30 +2864,6 @@ 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 = () => {
|
||||
|
||||
@@ -1902,7 +1902,7 @@ export const ChatComposer = memo(
|
||||
isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0",
|
||||
)}
|
||||
>
|
||||
<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">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<ProviderModelPicker
|
||||
compact={isComposerFooterCompact}
|
||||
provider={selectedProvider}
|
||||
|
||||
@@ -1,160 +0,0 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -92,6 +92,7 @@ const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface MessagesTimelineProps {
|
||||
hasMessages: boolean;
|
||||
isWorking: boolean;
|
||||
activeTurnInProgress: boolean;
|
||||
activeTurnId?: TurnId | null;
|
||||
@@ -120,6 +121,7 @@ interface MessagesTimelineProps {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
hasMessages,
|
||||
isWorking,
|
||||
activeTurnInProgress,
|
||||
activeTurnId,
|
||||
@@ -170,24 +172,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}
|
||||
}, [listRef, onIsAtEndChange]);
|
||||
|
||||
const previousRowCountRef = useRef(rows.length);
|
||||
useEffect(() => {
|
||||
const previousRowCount = previousRowCountRef.current;
|
||||
previousRowCountRef.current = rows.length;
|
||||
|
||||
if (previousRowCount > 0 || rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
onIsAtEndChange(true);
|
||||
const frameId = window.requestAnimationFrame(() => {
|
||||
void listRef.current?.scrollToEnd?.({ animated: false });
|
||||
});
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
};
|
||||
}, [listRef, onIsAtEndChange, rows.length]);
|
||||
|
||||
// Memoised context value — only changes on state transitions, NOT on
|
||||
// every streaming chunk. Callbacks from ChatView are useCallback-stable.
|
||||
const sharedState = useMemo<TimelineRowSharedState>(
|
||||
@@ -236,7 +220,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
[],
|
||||
);
|
||||
|
||||
if (rows.length === 0 && !isWorking) {
|
||||
if (!hasMessages && !isWorking) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground/30">
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
AntigravityIcon,
|
||||
CursorIcon,
|
||||
Icon,
|
||||
KiroIcon,
|
||||
TraeIcon,
|
||||
IntelliJIdeaIcon,
|
||||
VisualStudioCode,
|
||||
@@ -33,11 +32,6 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
Icon: TraeIcon,
|
||||
value: "trae",
|
||||
},
|
||||
{
|
||||
label: "Kiro",
|
||||
Icon: KiroIcon,
|
||||
value: "kiro",
|
||||
},
|
||||
{
|
||||
label: "VS Code",
|
||||
Icon: VisualStudioCode,
|
||||
|
||||
@@ -12,7 +12,7 @@ import { cn } from "~/lib/utils";
|
||||
const Select = SelectPrimitive.Root;
|
||||
|
||||
const selectTriggerVariants = cva(
|
||||
"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",
|
||||
"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",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
|
||||
@@ -1881,18 +1881,13 @@ 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) {
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationShellSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mockSubscribeThread = vi.fn();
|
||||
@@ -71,74 +65,6 @@ vi.mock("../../rpc/wsTransport", () => ({
|
||||
WsTransport: MockWsTransport,
|
||||
}));
|
||||
|
||||
function makeThreadShellSnapshot(params: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly sessionStatus?:
|
||||
| "idle"
|
||||
| "starting"
|
||||
| "running"
|
||||
| "ready"
|
||||
| "interrupted"
|
||||
| "stopped"
|
||||
| "error";
|
||||
readonly hasPendingApprovals?: boolean;
|
||||
readonly hasPendingUserInput?: boolean;
|
||||
readonly hasActionableProposedPlan?: boolean;
|
||||
}): OrchestrationShellSnapshot {
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const turnId = TurnId.make("turn-1");
|
||||
|
||||
return {
|
||||
snapshotSequence: 1,
|
||||
projects: [],
|
||||
updatedAt: "2026-04-13T00:00:00.000Z",
|
||||
threads: [
|
||||
{
|
||||
id: params.threadId,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn:
|
||||
params.sessionStatus === "running"
|
||||
? {
|
||||
turnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-13T00:00:00.000Z",
|
||||
startedAt: "2026-04-13T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
}
|
||||
: null,
|
||||
createdAt: "2026-04-13T00:00:00.000Z",
|
||||
updatedAt: "2026-04-13T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: params.sessionStatus
|
||||
? {
|
||||
threadId: params.threadId,
|
||||
status: params.sessionStatus,
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: params.sessionStatus === "running" ? turnId : null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-04-13T00:00:00.000Z",
|
||||
}
|
||||
: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: params.hasPendingApprovals ?? false,
|
||||
hasPendingUserInput: params.hasPendingUserInput ?? false,
|
||||
hasActionableProposedPlan: params.hasActionableProposedPlan ?? false,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("retainThreadDetailSubscription", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
@@ -193,89 +119,16 @@ describe("retainThreadDetailSubscription", () => {
|
||||
expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
|
||||
|
||||
releaseSecond();
|
||||
await vi.advanceTimersByTimeAsync(2 * 60 * 1000);
|
||||
await vi.advanceTimersByTimeAsync(2 * 60 * 1000 - 1);
|
||||
expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(28 * 60 * 1000);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
|
||||
|
||||
stop();
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("keeps non-idle thread detail subscriptions attached until the thread becomes idle", async () => {
|
||||
const {
|
||||
retainThreadDetailSubscription,
|
||||
startEnvironmentConnectionService,
|
||||
resetEnvironmentServiceForTests,
|
||||
} = await import("./service");
|
||||
|
||||
const stop = startEnvironmentConnectionService(new QueryClient());
|
||||
const environmentId = EnvironmentId.make("env-1");
|
||||
const threadId = ThreadId.make("thread-active");
|
||||
|
||||
const connectionInput = mockCreateEnvironmentConnection.mock.calls[0]?.[0];
|
||||
expect(connectionInput).toBeDefined();
|
||||
|
||||
connectionInput.syncShellSnapshot(
|
||||
makeThreadShellSnapshot({
|
||||
threadId,
|
||||
sessionStatus: "ready",
|
||||
hasPendingApprovals: true,
|
||||
}),
|
||||
environmentId,
|
||||
);
|
||||
|
||||
const release = retainThreadDetailSubscription(environmentId, threadId);
|
||||
expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
|
||||
|
||||
release();
|
||||
await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
|
||||
expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
|
||||
|
||||
connectionInput.applyShellEvent(
|
||||
{
|
||||
kind: "thread-upserted",
|
||||
sequence: 2,
|
||||
thread: makeThreadShellSnapshot({
|
||||
threadId,
|
||||
sessionStatus: "idle",
|
||||
}).threads[0]!,
|
||||
},
|
||||
environmentId,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
|
||||
expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
|
||||
|
||||
stop();
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("allows a larger idle cache before capacity eviction starts", async () => {
|
||||
const {
|
||||
retainThreadDetailSubscription,
|
||||
startEnvironmentConnectionService,
|
||||
resetEnvironmentServiceForTests,
|
||||
} = await import("./service");
|
||||
|
||||
const stop = startEnvironmentConnectionService(new QueryClient());
|
||||
const environmentId = EnvironmentId.make("env-1");
|
||||
|
||||
for (let index = 0; index < 12; index += 1) {
|
||||
const release = retainThreadDetailSubscription(
|
||||
environmentId,
|
||||
ThreadId.make(`thread-${index + 1}`),
|
||||
);
|
||||
release();
|
||||
}
|
||||
|
||||
expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
|
||||
|
||||
stop();
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("disposes cached thread detail subscriptions when the environment service resets", async () => {
|
||||
const {
|
||||
retainThreadDetailSubscription,
|
||||
|
||||
@@ -54,7 +54,6 @@ import { createEnvironmentConnection, type EnvironmentConnection } from "./conne
|
||||
import {
|
||||
useStore,
|
||||
selectProjectsAcrossEnvironments,
|
||||
selectSidebarThreadSummaryByRef,
|
||||
selectThreadByRef,
|
||||
selectThreadsAcrossEnvironments,
|
||||
} from "~/store";
|
||||
@@ -87,15 +86,8 @@ const threadDetailSubscriptions = new Map<string, ThreadDetailSubscriptionEntry>
|
||||
let activeService: EnvironmentServiceState | null = null;
|
||||
let needsProviderInvalidation = false;
|
||||
|
||||
// Thread detail subscription cache policy:
|
||||
// - Active consumers keep a subscription retained via refCount.
|
||||
// - Released subscriptions stay warm for a longer idle TTL to avoid churn
|
||||
// while moving around the UI.
|
||||
// - Threads with active work or pending user action are sticky and are never
|
||||
// evicted while they remain non-idle.
|
||||
// - Capacity eviction only targets idle cached subscriptions.
|
||||
const THREAD_DETAIL_SUBSCRIPTION_IDLE_EVICTION_MS = 15 * 60 * 1000;
|
||||
const MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS = 32;
|
||||
const THREAD_DETAIL_SUBSCRIPTION_IDLE_EVICTION_MS = 2 * 60 * 1000;
|
||||
const MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS = 8;
|
||||
const NOOP = () => undefined;
|
||||
|
||||
function getThreadDetailSubscriptionKey(environmentId: EnvironmentId, threadId: ThreadId): string {
|
||||
@@ -112,55 +104,6 @@ function clearThreadDetailSubscriptionEviction(
|
||||
return entry;
|
||||
}
|
||||
|
||||
function isNonIdleThreadDetailSubscription(entry: ThreadDetailSubscriptionEntry): boolean {
|
||||
const threadRef = scopeThreadRef(entry.environmentId, entry.threadId);
|
||||
const state = useStore.getState();
|
||||
const sidebarThread = selectSidebarThreadSummaryByRef(state, threadRef);
|
||||
|
||||
// Prefer shell/sidebar state first because it carries the coarse thread
|
||||
// readiness flags used throughout the UI (pending approvals/input/plan).
|
||||
if (sidebarThread) {
|
||||
if (
|
||||
sidebarThread.hasPendingApprovals ||
|
||||
sidebarThread.hasPendingUserInput ||
|
||||
sidebarThread.hasActionableProposedPlan
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const orchestrationStatus = sidebarThread.session?.orchestrationStatus;
|
||||
if (
|
||||
orchestrationStatus &&
|
||||
orchestrationStatus !== "idle" &&
|
||||
orchestrationStatus !== "stopped"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sidebarThread.latestTurn?.state === "running") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const thread = selectThreadByRef(state, threadRef);
|
||||
if (!thread) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const orchestrationStatus = thread.session?.orchestrationStatus;
|
||||
return (
|
||||
Boolean(
|
||||
orchestrationStatus && orchestrationStatus !== "idle" && orchestrationStatus !== "stopped",
|
||||
) ||
|
||||
thread.latestTurn?.state === "running" ||
|
||||
thread.pendingSourceProposedPlan !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
function shouldEvictThreadDetailSubscription(entry: ThreadDetailSubscriptionEntry): boolean {
|
||||
return entry.refCount === 0 && !isNonIdleThreadDetailSubscription(entry);
|
||||
}
|
||||
|
||||
function attachThreadDetailSubscription(entry: ThreadDetailSubscriptionEntry): boolean {
|
||||
if (entry.unsubscribeConnectionListener !== null) {
|
||||
entry.unsubscribeConnectionListener();
|
||||
@@ -238,20 +181,11 @@ function reconcileThreadDetailSubscriptionsForEnvironment(
|
||||
|
||||
function scheduleThreadDetailSubscriptionEviction(entry: ThreadDetailSubscriptionEntry): void {
|
||||
clearThreadDetailSubscriptionEviction(entry);
|
||||
if (!shouldEvictThreadDetailSubscription(entry)) {
|
||||
return;
|
||||
}
|
||||
|
||||
entry.evictionTimeoutId = setTimeout(() => {
|
||||
const currentEntry = threadDetailSubscriptions.get(
|
||||
getThreadDetailSubscriptionKey(entry.environmentId, entry.threadId),
|
||||
);
|
||||
if (!currentEntry) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentEntry.evictionTimeoutId = null;
|
||||
if (!shouldEvictThreadDetailSubscription(currentEntry)) {
|
||||
if (!currentEntry || currentEntry.refCount > 0) {
|
||||
return;
|
||||
}
|
||||
disposeThreadDetailSubscriptionByKey(
|
||||
@@ -266,7 +200,7 @@ function evictIdleThreadDetailSubscriptionsToCapacity(): void {
|
||||
}
|
||||
|
||||
const idleEntries = [...threadDetailSubscriptions.entries()]
|
||||
.filter(([, entry]) => shouldEvictThreadDetailSubscription(entry))
|
||||
.filter(([, entry]) => entry.refCount === 0)
|
||||
.toSorted(([, left], [, right]) => left.lastAccessedAt - right.lastAccessedAt);
|
||||
|
||||
for (const [key] of idleEntries) {
|
||||
@@ -277,42 +211,6 @@ function evictIdleThreadDetailSubscriptionsToCapacity(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function reconcileThreadDetailSubscriptionEvictionState(
|
||||
entry: ThreadDetailSubscriptionEntry,
|
||||
): void {
|
||||
clearThreadDetailSubscriptionEviction(entry);
|
||||
if (!shouldEvictThreadDetailSubscription(entry)) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleThreadDetailSubscriptionEviction(entry);
|
||||
}
|
||||
|
||||
function reconcileThreadDetailSubscriptionEvictionForThread(
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
): void {
|
||||
const entry = threadDetailSubscriptions.get(
|
||||
getThreadDetailSubscriptionKey(environmentId, threadId),
|
||||
);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
reconcileThreadDetailSubscriptionEvictionState(entry);
|
||||
}
|
||||
|
||||
function reconcileThreadDetailSubscriptionEvictionForEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
): void {
|
||||
for (const entry of threadDetailSubscriptions.values()) {
|
||||
if (entry.environmentId === environmentId) {
|
||||
reconcileThreadDetailSubscriptionEvictionState(entry);
|
||||
}
|
||||
}
|
||||
evictIdleThreadDetailSubscriptionsToCapacity();
|
||||
}
|
||||
|
||||
export function retainThreadDetailSubscription(
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
@@ -335,7 +233,7 @@ export function retainThreadDetailSubscription(
|
||||
existing.refCount = Math.max(0, existing.refCount - 1);
|
||||
existing.lastAccessedAt = Date.now();
|
||||
if (existing.refCount === 0) {
|
||||
reconcileThreadDetailSubscriptionEvictionState(existing);
|
||||
scheduleThreadDetailSubscriptionEviction(existing);
|
||||
evictIdleThreadDetailSubscriptionsToCapacity();
|
||||
}
|
||||
};
|
||||
@@ -365,7 +263,7 @@ export function retainThreadDetailSubscription(
|
||||
entry.refCount = Math.max(0, entry.refCount - 1);
|
||||
entry.lastAccessedAt = Date.now();
|
||||
if (entry.refCount === 0) {
|
||||
reconcileThreadDetailSubscriptionEvictionState(entry);
|
||||
scheduleThreadDetailSubscriptionEviction(entry);
|
||||
evictIdleThreadDetailSubscriptionsToCapacity();
|
||||
}
|
||||
};
|
||||
@@ -575,8 +473,6 @@ function applyRecoveredEventBatch(
|
||||
for (const threadId of batchEffects.removeTerminalStateThreadIds) {
|
||||
useTerminalStateStore.getState().removeTerminalState(scopeThreadRef(environmentId, threadId));
|
||||
}
|
||||
|
||||
reconcileThreadDetailSubscriptionEvictionForEnvironment(environmentId);
|
||||
}
|
||||
|
||||
export function applyEnvironmentThreadDetailEvent(
|
||||
@@ -611,8 +507,6 @@ function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: En
|
||||
if (previousThread?.archivedAt === null && event.thread.archivedAt !== null && threadRef) {
|
||||
useTerminalStateStore.getState().removeTerminalState(threadRef);
|
||||
}
|
||||
reconcileThreadDetailSubscriptionEvictionForThread(environmentId, event.thread.id);
|
||||
evictIdleThreadDetailSubscriptionsToCapacity();
|
||||
return;
|
||||
case "thread-removed":
|
||||
if (threadRef) {
|
||||
@@ -635,7 +529,6 @@ function createEnvironmentConnectionHandlers() {
|
||||
environmentId,
|
||||
snapshot.threads.map((thread) => thread.id),
|
||||
);
|
||||
reconcileThreadDetailSubscriptionEvictionForEnvironment(environmentId);
|
||||
reconcileSnapshotDerivedState();
|
||||
},
|
||||
applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => {
|
||||
|
||||
@@ -87,8 +87,7 @@ function useNewThreadState() {
|
||||
if (
|
||||
latestActiveDraftThread &&
|
||||
currentRouteTarget?.kind === "draft" &&
|
||||
latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
|
||||
latestActiveDraftThread.promotedTo == null
|
||||
latestActiveDraftThread.logicalProjectKey === logicalProjectKey
|
||||
) {
|
||||
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
|
||||
setDraftThreadContext(currentRouteTarget.draftId, {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { parseScopedThreadKey, scopeProjectRef, scopeThreadRef } from "@t3tools/
|
||||
import { type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useRouter } from "@tanstack/react-router";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
@@ -33,12 +33,6 @@ export function useThreadActions() {
|
||||
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
|
||||
const router = useRouter();
|
||||
const { handleNewThread } = useNewThreadHandler();
|
||||
// Keep a ref so archiveThread can call handleNewThread without appearing in
|
||||
// its dependency array — handleNewThread is inherently unstable (depends on
|
||||
// the projects list) and would otherwise cascade new references into every
|
||||
// sidebar row via archiveThread → attemptArchiveThread.
|
||||
const handleNewThreadRef = useRef(handleNewThread);
|
||||
handleNewThreadRef.current = handleNewThread;
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
|
||||
@@ -79,10 +73,10 @@ export function useThreadActions() {
|
||||
currentRouteThreadRef?.threadId === threadRef.threadId &&
|
||||
currentRouteThreadRef.environmentId === threadRef.environmentId
|
||||
) {
|
||||
await handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId));
|
||||
await handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId));
|
||||
}
|
||||
},
|
||||
[getCurrentRouteThreadRef, resolveThreadTarget],
|
||||
[getCurrentRouteThreadRef, handleNewThread, resolveThreadTarget],
|
||||
);
|
||||
|
||||
const unarchiveThread = useCallback(async (target: ScopedThreadRef) => {
|
||||
|
||||
@@ -417,56 +417,6 @@ describe("WsTransport", () => {
|
||||
await transport.dispose();
|
||||
}, 5_000);
|
||||
|
||||
it("clears slow unary request tracking when the transport reconnects", async () => {
|
||||
const slowAckThresholdMs = 25;
|
||||
setSlowRpcAckThresholdMsForTests(slowAckThresholdMs);
|
||||
const transport = createTransport("ws://localhost:3020");
|
||||
|
||||
const requestPromise = transport.request((client) =>
|
||||
client[WS_METHODS.serverUpsertKeybinding]({
|
||||
command: "terminal.toggle",
|
||||
key: "ctrl+k",
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const firstSocket = getSocket();
|
||||
firstSocket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(firstSocket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const firstRequest = JSON.parse(firstSocket.sent[0] ?? "{}") as { id: string };
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getSlowRpcAckRequests()).toMatchObject([
|
||||
{
|
||||
requestId: firstRequest.id,
|
||||
tag: WS_METHODS.serverUpsertKeybinding,
|
||||
},
|
||||
]);
|
||||
}, 1_000);
|
||||
|
||||
void requestPromise.catch(() => undefined);
|
||||
|
||||
await transport.reconnect();
|
||||
|
||||
expect(getSlowRpcAckRequests()).toEqual([]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(2);
|
||||
});
|
||||
|
||||
const secondSocket = getSocket();
|
||||
secondSocket.open();
|
||||
|
||||
await transport.dispose();
|
||||
}, 5_000);
|
||||
|
||||
it("sends unary RPC requests and resolves successful exits", async () => {
|
||||
const transport = createTransport("ws://localhost:3020");
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
import { RpcClient } from "effect/unstable/rpc";
|
||||
|
||||
import { ClientTracingLive } from "../observability/clientTracing";
|
||||
import { clearAllTrackedRpcRequests } from "./requestLatencyState";
|
||||
import {
|
||||
createWsRpcProtocolLayer,
|
||||
makeWsRpcProtocolClient,
|
||||
@@ -190,7 +189,6 @@ export class WsTransport {
|
||||
throw new Error("Transport disposed");
|
||||
}
|
||||
|
||||
clearAllTrackedRpcRequests();
|
||||
const previousSession = this.session;
|
||||
this.session = this.createSession();
|
||||
await this.closeSession(previousSession);
|
||||
|
||||
@@ -5,10 +5,12 @@ import {
|
||||
EnvironmentId,
|
||||
EventId,
|
||||
MessageId,
|
||||
type OrchestrationShellSnapshot,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
@@ -21,6 +23,8 @@ import {
|
||||
selectThreadExistsByRef,
|
||||
setThreadBranch,
|
||||
selectThreadsAcrossEnvironments,
|
||||
syncServerReadModel,
|
||||
syncServerShellSnapshot,
|
||||
type AppState,
|
||||
type EnvironmentState,
|
||||
} from "./store";
|
||||
@@ -367,6 +371,75 @@ describe("thread selection memoization", () => {
|
||||
});
|
||||
});
|
||||
|
||||
function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"][number]>) {
|
||||
return {
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...overrides,
|
||||
} satisfies OrchestrationReadModel["threads"][number];
|
||||
}
|
||||
|
||||
function makeReadModel(thread: OrchestrationReadModel["threads"][number]): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 1,
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
projects: [
|
||||
{
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
};
|
||||
}
|
||||
|
||||
function makeReadModelProject(
|
||||
overrides: Partial<OrchestrationReadModel["projects"][number]>,
|
||||
): OrchestrationReadModel["projects"][number] {
|
||||
return {
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
scripts: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("setThreadBranch", () => {
|
||||
it("updates only the scoped thread environment", () => {
|
||||
const sharedThreadId = ThreadId.make("thread-shared");
|
||||
@@ -407,6 +480,236 @@ describe("setThreadBranch", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("store read model sync", () => {
|
||||
it("marks bootstrap complete after snapshot sync", () => {
|
||||
const initialState = withActiveEnvironmentState(
|
||||
localEnvironmentStateOf(makeState(makeThread())),
|
||||
{
|
||||
bootstrapComplete: false,
|
||||
},
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(
|
||||
initialState,
|
||||
makeReadModel(makeReadModelThread({})),
|
||||
localEnvironmentId,
|
||||
);
|
||||
|
||||
expect(localEnvironmentStateOf(next).bootstrapComplete).toBe(true);
|
||||
});
|
||||
|
||||
it("updates shell state without discarding hydrated thread detail", () => {
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
title: "Initial thread",
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("message-1"),
|
||||
role: "assistant",
|
||||
text: "hydrated body",
|
||||
createdAt: "2026-02-13T00:00:01.000Z",
|
||||
completedAt: "2026-02-13T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const shellSnapshot: OrchestrationShellSnapshot = {
|
||||
snapshotSequence: 2,
|
||||
projects: [
|
||||
{
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-02-13T00:00:00.000Z",
|
||||
updatedAt: "2026-02-13T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Renamed thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature/renamed",
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-02-13T00:00:00.000Z",
|
||||
updatedAt: "2026-02-13T00:00:02.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
},
|
||||
],
|
||||
updatedAt: "2026-02-13T00:00:02.000Z",
|
||||
};
|
||||
|
||||
const next = syncServerShellSnapshot(initialState, shellSnapshot, localEnvironmentId);
|
||||
const thread = selectThreadByRef(
|
||||
next,
|
||||
scopeThreadRef(localEnvironmentId, ThreadId.make("thread-1")),
|
||||
);
|
||||
|
||||
expect(thread?.title).toBe("Renamed thread");
|
||||
expect(thread?.branch).toBe("feature/renamed");
|
||||
expect(thread?.messages).toEqual([
|
||||
expect.objectContaining({
|
||||
id: MessageId.make("message-1"),
|
||||
text: "hydrated body",
|
||||
}),
|
||||
]);
|
||||
expect(localEnvironmentStateOf(next).bootstrapComplete).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves claude model slugs without an active session", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel, localEnvironmentId);
|
||||
|
||||
expect(threadsOf(next)[0]?.modelSelection.model).toBe("claude-opus-4-6");
|
||||
});
|
||||
|
||||
it("resolves claude aliases when session provider is claudeAgent", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "sonnet",
|
||||
},
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel, localEnvironmentId);
|
||||
|
||||
expect(threadsOf(next)[0]?.modelSelection.model).toBe("claude-sonnet-4-6");
|
||||
});
|
||||
|
||||
it("preserves project and thread updatedAt timestamps from the read model", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
updatedAt: "2026-02-27T00:05:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel, localEnvironmentId);
|
||||
|
||||
expect(projectsOf(next)[0]?.updatedAt).toBe("2026-02-27T00:00:00.000Z");
|
||||
expect(threadsOf(next)[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z");
|
||||
});
|
||||
|
||||
it("maps archivedAt from the read model", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const archivedAt = "2026-02-28T00:00:00.000Z";
|
||||
const next = syncServerReadModel(
|
||||
initialState,
|
||||
makeReadModel(
|
||||
makeReadModelThread({
|
||||
archivedAt,
|
||||
}),
|
||||
),
|
||||
localEnvironmentId,
|
||||
);
|
||||
|
||||
expect(threadsOf(next)[0]?.archivedAt).toBe(archivedAt);
|
||||
});
|
||||
|
||||
it("replaces projects using snapshot order during recovery", () => {
|
||||
const project1 = ProjectId.make("project-1");
|
||||
const project2 = ProjectId.make("project-2");
|
||||
const project3 = ProjectId.make("project-3");
|
||||
const initialState: AppState = makeEmptyState({
|
||||
projectIds: [project2, project1],
|
||||
projectById: {
|
||||
[project2]: {
|
||||
id: project2,
|
||||
environmentId: localEnvironmentId,
|
||||
name: "Project 2",
|
||||
cwd: "/tmp/project-2",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
scripts: [],
|
||||
},
|
||||
[project1]: {
|
||||
id: project1,
|
||||
environmentId: localEnvironmentId,
|
||||
name: "Project 1",
|
||||
cwd: "/tmp/project-1",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
scripts: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
const readModel: OrchestrationReadModel = {
|
||||
snapshotSequence: 2,
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
projects: [
|
||||
makeReadModelProject({
|
||||
id: project1,
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
}),
|
||||
makeReadModelProject({
|
||||
id: project2,
|
||||
title: "Project 2",
|
||||
workspaceRoot: "/tmp/project-2",
|
||||
}),
|
||||
makeReadModelProject({
|
||||
id: project3,
|
||||
title: "Project 3",
|
||||
workspaceRoot: "/tmp/project-3",
|
||||
}),
|
||||
],
|
||||
threads: [],
|
||||
};
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel, localEnvironmentId);
|
||||
|
||||
expect(projectsOf(next).map((project) => project.id)).toEqual([project1, project2, project3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("incremental orchestration updates", () => {
|
||||
it("does not mark bootstrap complete for incremental events", () => {
|
||||
const state = withActiveEnvironmentState(localEnvironmentStateOf(makeState(makeThread())), {
|
||||
|
||||
+225
-140
@@ -3,7 +3,6 @@ import type {
|
||||
MessageId,
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationEvent,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationMessage,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationReadModel,
|
||||
@@ -23,6 +22,12 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveModelSlugForProvider } from "@t3tools/shared/model";
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
findLatestProposedPlan,
|
||||
hasActionableProposedPlan,
|
||||
} from "./session-logic";
|
||||
import {
|
||||
type ChatMessage,
|
||||
type Project,
|
||||
@@ -41,33 +46,11 @@ import { getThreadFromEnvironmentState } from "./threadDerivation";
|
||||
export interface EnvironmentState {
|
||||
projectIds: ProjectId[];
|
||||
projectById: Record<ProjectId, Project>;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread bookkeeping — written by BOTH shell stream and detail stream.
|
||||
// Both streams ensure the thread is registered here; the bookkeeping is
|
||||
// additive (append-only IDs) so concurrent writes are safe.
|
||||
// ---------------------------------------------------------------------------
|
||||
threadIds: ThreadId[];
|
||||
threadIdsByProjectId: Record<ProjectId, ThreadId[]>;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread shell / session / turn — written by BOTH shell stream and detail
|
||||
// stream. The shell stream is the *authoritative* source (server pre-
|
||||
// computes these from the projection pipeline), but the detail stream also
|
||||
// writes them so the active thread has up-to-date state even if the shell
|
||||
// event hasn't arrived yet. Structural equality checks in both write
|
||||
// functions prevent unnecessary React re-renders when both streams deliver
|
||||
// equivalent data.
|
||||
// ---------------------------------------------------------------------------
|
||||
threadShellById: Record<ThreadId, ThreadShell>;
|
||||
threadSessionById: Record<ThreadId, ThreadSession | null>;
|
||||
threadTurnStateById: Record<ThreadId, ThreadTurnState>;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread detail content — written ONLY by the detail stream
|
||||
// (writeThreadState / syncServerThreadDetail). The shell stream never
|
||||
// touches these.
|
||||
// ---------------------------------------------------------------------------
|
||||
messageIdsByThreadId: Record<ThreadId, MessageId[]>;
|
||||
messageByThreadId: Record<ThreadId, Record<MessageId, ChatMessage>>;
|
||||
activityIdsByThreadId: Record<ThreadId, string[]>;
|
||||
@@ -76,16 +59,7 @@ export interface EnvironmentState {
|
||||
proposedPlanByThreadId: Record<ThreadId, Record<string, ProposedPlan>>;
|
||||
turnDiffIdsByThreadId: Record<ThreadId, TurnId[]>;
|
||||
turnDiffSummaryByThreadId: Record<ThreadId, Record<TurnId, TurnDiffSummary>>;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sidebar summary — written ONLY by the shell stream
|
||||
// (writeThreadShellState / mapThreadShell). Pre-computed server-side with
|
||||
// fields like latestUserMessageAt, hasPendingApprovals, etc. The detail
|
||||
// stream must NOT write here; the shell stream is the single source of
|
||||
// truth for sidebar data.
|
||||
// ---------------------------------------------------------------------------
|
||||
sidebarThreadSummaryById: Record<ThreadId, SidebarThreadSummary>;
|
||||
|
||||
bootstrapComplete: boolean;
|
||||
}
|
||||
|
||||
@@ -334,47 +308,40 @@ function toThreadTurnState(thread: Thread): ThreadTurnState {
|
||||
};
|
||||
}
|
||||
|
||||
function sourceProposedPlansEqual(
|
||||
left: OrchestrationLatestTurn["sourceProposedPlan"] | undefined,
|
||||
right: OrchestrationLatestTurn["sourceProposedPlan"] | undefined,
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (left === undefined || right === undefined) return false;
|
||||
return left.threadId === right.threadId && left.planId === right.planId;
|
||||
function getLatestUserMessageAt(messages: ReadonlyArray<ChatMessage>): string | null {
|
||||
let latestUserMessageAt: string | null = null;
|
||||
for (const message of messages) {
|
||||
if (message.role !== "user") {
|
||||
continue;
|
||||
}
|
||||
if (latestUserMessageAt === null || message.createdAt > latestUserMessageAt) {
|
||||
latestUserMessageAt = message.createdAt;
|
||||
}
|
||||
}
|
||||
return latestUserMessageAt;
|
||||
}
|
||||
|
||||
function latestTurnsEqual(
|
||||
left: OrchestrationLatestTurn | null | undefined,
|
||||
right: OrchestrationLatestTurn | null | undefined,
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (left == null || right == null) return false;
|
||||
return (
|
||||
left.turnId === right.turnId &&
|
||||
left.state === right.state &&
|
||||
left.requestedAt === right.requestedAt &&
|
||||
left.startedAt === right.startedAt &&
|
||||
left.completedAt === right.completedAt &&
|
||||
left.assistantMessageId === right.assistantMessageId &&
|
||||
sourceProposedPlansEqual(left.sourceProposedPlan, right.sourceProposedPlan)
|
||||
);
|
||||
}
|
||||
|
||||
function threadSessionsEqual(
|
||||
left: ThreadSession | null | undefined,
|
||||
right: ThreadSession | null | undefined,
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (left == null || right == null) return false;
|
||||
return (
|
||||
left.provider === right.provider &&
|
||||
left.status === right.status &&
|
||||
left.orchestrationStatus === right.orchestrationStatus &&
|
||||
left.activeTurnId === right.activeTurnId &&
|
||||
left.createdAt === right.createdAt &&
|
||||
left.updatedAt === right.updatedAt &&
|
||||
left.lastError === right.lastError
|
||||
);
|
||||
function buildSidebarThreadSummary(thread: Thread): SidebarThreadSummary {
|
||||
return {
|
||||
id: thread.id,
|
||||
environmentId: thread.environmentId,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
interactionMode: thread.interactionMode,
|
||||
session: thread.session,
|
||||
createdAt: thread.createdAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
latestTurn: thread.latestTurn,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
latestUserMessageAt: getLatestUserMessageAt(thread.messages),
|
||||
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
|
||||
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
|
||||
hasActionableProposedPlan: hasActionableProposedPlan(
|
||||
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function sidebarThreadSummariesEqual(
|
||||
@@ -387,11 +354,11 @@ function sidebarThreadSummariesEqual(
|
||||
left.projectId === right.projectId &&
|
||||
left.title === right.title &&
|
||||
left.interactionMode === right.interactionMode &&
|
||||
threadSessionsEqual(left.session, right.session) &&
|
||||
left.session === right.session &&
|
||||
left.createdAt === right.createdAt &&
|
||||
left.archivedAt === right.archivedAt &&
|
||||
left.updatedAt === right.updatedAt &&
|
||||
latestTurnsEqual(left.latestTurn, right.latestTurn) &&
|
||||
left.latestTurn === right.latestTurn &&
|
||||
left.branch === right.branch &&
|
||||
left.worktreePath === right.worktreePath &&
|
||||
left.latestUserMessageAt === right.latestUserMessageAt &&
|
||||
@@ -424,8 +391,8 @@ function threadShellsEqual(left: ThreadShell | undefined, right: ThreadShell): b
|
||||
function threadTurnStatesEqual(left: ThreadTurnState | undefined, right: ThreadTurnState): boolean {
|
||||
return (
|
||||
left !== undefined &&
|
||||
latestTurnsEqual(left.latestTurn, right.latestTurn) &&
|
||||
sourceProposedPlansEqual(left.pendingSourceProposedPlan, right.pendingSourceProposedPlan)
|
||||
left.latestTurn === right.latestTurn &&
|
||||
left.pendingSourceProposedPlan === right.pendingSourceProposedPlan
|
||||
);
|
||||
}
|
||||
|
||||
@@ -499,32 +466,34 @@ function getThreads(state: EnvironmentState): Thread[] {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a thread is registered in the bookkeeping indices (threadIds,
|
||||
* threadIdsByProjectId). Shared by both the shell stream and detail stream
|
||||
* write paths — the bookkeeping is additive (append-only IDs) so concurrent
|
||||
* writes from both streams are safe.
|
||||
*/
|
||||
function ensureThreadRegistered(
|
||||
function writeThreadState(
|
||||
state: EnvironmentState,
|
||||
threadId: ThreadId,
|
||||
nextProjectId: ProjectId,
|
||||
previousProjectId: ProjectId | undefined,
|
||||
nextThread: Thread,
|
||||
previousThread?: Thread,
|
||||
): EnvironmentState {
|
||||
const nextShell = toThreadShell(nextThread);
|
||||
const nextTurnState = toThreadTurnState(nextThread);
|
||||
const previousShell = state.threadShellById[nextThread.id];
|
||||
const previousTurnState = state.threadTurnStateById[nextThread.id];
|
||||
const previousSummary = state.sidebarThreadSummaryById[nextThread.id];
|
||||
const nextSummary = buildSidebarThreadSummary(nextThread);
|
||||
|
||||
let nextState = state;
|
||||
|
||||
if (!state.threadIds.includes(threadId)) {
|
||||
if (!state.threadIds.includes(nextThread.id)) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
threadIds: [...nextState.threadIds, threadId],
|
||||
threadIds: [...nextState.threadIds, nextThread.id],
|
||||
};
|
||||
}
|
||||
|
||||
const previousProjectId = previousThread?.projectId;
|
||||
const nextProjectId = nextThread.projectId;
|
||||
if (previousProjectId !== nextProjectId) {
|
||||
let threadIdsByProjectId = nextState.threadIdsByProjectId;
|
||||
if (previousProjectId) {
|
||||
const previousIds = threadIdsByProjectId[previousProjectId] ?? EMPTY_THREAD_IDS;
|
||||
const nextIds = removeId(previousIds, threadId);
|
||||
const nextIds = removeId(previousIds, nextThread.id);
|
||||
if (nextIds.length === 0) {
|
||||
const { [previousProjectId]: _removed, ...rest } = threadIdsByProjectId;
|
||||
threadIdsByProjectId = rest as Record<ProjectId, ThreadId[]>;
|
||||
@@ -536,7 +505,7 @@ function ensureThreadRegistered(
|
||||
}
|
||||
}
|
||||
const projectThreadIds = threadIdsByProjectId[nextProjectId] ?? EMPTY_THREAD_IDS;
|
||||
const nextProjectThreadIds = appendId(projectThreadIds, threadId);
|
||||
const nextProjectThreadIds = appendId(projectThreadIds, nextThread.id);
|
||||
if (!arraysEqual(projectThreadIds, nextProjectThreadIds)) {
|
||||
threadIdsByProjectId = {
|
||||
...threadIdsByProjectId,
|
||||
@@ -551,36 +520,6 @@ function ensureThreadRegistered(
|
||||
}
|
||||
}
|
||||
|
||||
return nextState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write thread state from the **detail stream** (per-thread subscription).
|
||||
*
|
||||
* Owns: messages, activities, proposed plans, turn diff summaries.
|
||||
* Also writes threadShellById / threadSessionById / threadTurnStateById so
|
||||
* the active thread has up-to-date state even if the shell stream event
|
||||
* hasn't arrived yet (both streams use structural equality checks to avoid
|
||||
* unnecessary re-renders when delivering equivalent data).
|
||||
* Does NOT write sidebarThreadSummaryById — that is shell-stream-only.
|
||||
*/
|
||||
function writeThreadState(
|
||||
state: EnvironmentState,
|
||||
nextThread: Thread,
|
||||
previousThread?: Thread,
|
||||
): EnvironmentState {
|
||||
const nextShell = toThreadShell(nextThread);
|
||||
const nextTurnState = toThreadTurnState(nextThread);
|
||||
const previousShell = state.threadShellById[nextThread.id];
|
||||
const previousTurnState = state.threadTurnStateById[nextThread.id];
|
||||
|
||||
let nextState = ensureThreadRegistered(
|
||||
state,
|
||||
nextThread.id,
|
||||
nextThread.projectId,
|
||||
previousThread?.projectId,
|
||||
);
|
||||
|
||||
if (!threadShellsEqual(previousShell, nextShell)) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
@@ -591,7 +530,7 @@ function writeThreadState(
|
||||
};
|
||||
}
|
||||
|
||||
if (!threadSessionsEqual(previousThread?.session ?? null, nextThread.session)) {
|
||||
if ((previousThread?.session ?? null) !== nextThread.session) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
threadSessionById: {
|
||||
@@ -671,20 +610,19 @@ function writeThreadState(
|
||||
};
|
||||
}
|
||||
|
||||
if (!sidebarThreadSummariesEqual(previousSummary, nextSummary)) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
sidebarThreadSummaryById: {
|
||||
...nextState.sidebarThreadSummaryById,
|
||||
[nextThread.id]: nextSummary,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return nextState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write thread state from the **shell stream** (all-threads subscription).
|
||||
*
|
||||
* Owns: sidebarThreadSummaryById (pre-computed server-side sidebar data).
|
||||
* Also writes threadShellById / threadSessionById / threadTurnStateById as
|
||||
* the authoritative source for these fields. The detail stream may also
|
||||
* write them for the focused thread (see writeThreadState); structural
|
||||
* equality checks prevent unnecessary re-renders.
|
||||
* Does NOT write message/activity/proposedPlan/turnDiff content — that is
|
||||
* detail-stream-only.
|
||||
*/
|
||||
function writeThreadShellState(
|
||||
state: EnvironmentState,
|
||||
nextThread: {
|
||||
@@ -694,14 +632,49 @@ function writeThreadShellState(
|
||||
summary: SidebarThreadSummary;
|
||||
},
|
||||
): EnvironmentState {
|
||||
let nextState = state;
|
||||
const previousShell = state.threadShellById[nextThread.shell.id];
|
||||
const previousProjectId = previousShell?.projectId;
|
||||
const nextProjectId = nextThread.shell.projectId;
|
||||
|
||||
let nextState = ensureThreadRegistered(
|
||||
state,
|
||||
nextThread.shell.id,
|
||||
nextThread.shell.projectId,
|
||||
previousShell?.projectId,
|
||||
);
|
||||
if (!state.threadIds.includes(nextThread.shell.id)) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
threadIds: [...nextState.threadIds, nextThread.shell.id],
|
||||
};
|
||||
}
|
||||
|
||||
if (previousProjectId !== nextProjectId) {
|
||||
let threadIdsByProjectId = nextState.threadIdsByProjectId;
|
||||
if (previousProjectId) {
|
||||
const previousIds = threadIdsByProjectId[previousProjectId] ?? EMPTY_THREAD_IDS;
|
||||
const nextIds = removeId(previousIds, nextThread.shell.id);
|
||||
if (nextIds.length === 0) {
|
||||
const { [previousProjectId]: _removed, ...rest } = threadIdsByProjectId;
|
||||
threadIdsByProjectId = rest as Record<ProjectId, ThreadId[]>;
|
||||
} else if (!arraysEqual(previousIds, nextIds)) {
|
||||
threadIdsByProjectId = {
|
||||
...threadIdsByProjectId,
|
||||
[previousProjectId]: nextIds,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const projectThreadIds = threadIdsByProjectId[nextProjectId] ?? EMPTY_THREAD_IDS;
|
||||
const nextProjectThreadIds = appendId(projectThreadIds, nextThread.shell.id);
|
||||
if (!arraysEqual(projectThreadIds, nextProjectThreadIds)) {
|
||||
threadIdsByProjectId = {
|
||||
...threadIdsByProjectId,
|
||||
[nextProjectId]: nextProjectThreadIds,
|
||||
};
|
||||
}
|
||||
if (threadIdsByProjectId !== nextState.threadIdsByProjectId) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
threadIdsByProjectId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!threadShellsEqual(previousShell, nextThread.shell)) {
|
||||
nextState = {
|
||||
@@ -713,9 +686,7 @@ function writeThreadShellState(
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
!threadSessionsEqual(state.threadSessionById[nextThread.shell.id] ?? null, nextThread.session)
|
||||
) {
|
||||
if ((state.threadSessionById[nextThread.shell.id] ?? null) !== nextThread.session) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
threadSessionById: {
|
||||
@@ -1038,6 +1009,82 @@ function buildProjectState(
|
||||
};
|
||||
}
|
||||
|
||||
function buildThreadState(
|
||||
threads: ReadonlyArray<Thread>,
|
||||
): Pick<
|
||||
EnvironmentState,
|
||||
| "threadIds"
|
||||
| "threadIdsByProjectId"
|
||||
| "threadShellById"
|
||||
| "threadSessionById"
|
||||
| "threadTurnStateById"
|
||||
| "messageIdsByThreadId"
|
||||
| "messageByThreadId"
|
||||
| "activityIdsByThreadId"
|
||||
| "activityByThreadId"
|
||||
| "proposedPlanIdsByThreadId"
|
||||
| "proposedPlanByThreadId"
|
||||
| "turnDiffIdsByThreadId"
|
||||
| "turnDiffSummaryByThreadId"
|
||||
| "sidebarThreadSummaryById"
|
||||
> {
|
||||
const threadIds: ThreadId[] = [];
|
||||
const threadIdsByProjectId: Record<ProjectId, ThreadId[]> = {};
|
||||
const threadShellById: Record<ThreadId, ThreadShell> = {};
|
||||
const threadSessionById: Record<ThreadId, ThreadSession | null> = {};
|
||||
const threadTurnStateById: Record<ThreadId, ThreadTurnState> = {};
|
||||
const messageIdsByThreadId: Record<ThreadId, MessageId[]> = {};
|
||||
const messageByThreadId: Record<ThreadId, Record<MessageId, ChatMessage>> = {};
|
||||
const activityIdsByThreadId: Record<ThreadId, string[]> = {};
|
||||
const activityByThreadId: Record<ThreadId, Record<string, OrchestrationThreadActivity>> = {};
|
||||
const proposedPlanIdsByThreadId: Record<ThreadId, string[]> = {};
|
||||
const proposedPlanByThreadId: Record<ThreadId, Record<string, ProposedPlan>> = {};
|
||||
const turnDiffIdsByThreadId: Record<ThreadId, TurnId[]> = {};
|
||||
const turnDiffSummaryByThreadId: Record<ThreadId, Record<TurnId, TurnDiffSummary>> = {};
|
||||
const sidebarThreadSummaryById: Record<ThreadId, SidebarThreadSummary> = {};
|
||||
|
||||
for (const thread of threads) {
|
||||
threadIds.push(thread.id);
|
||||
threadIdsByProjectId[thread.projectId] = [
|
||||
...(threadIdsByProjectId[thread.projectId] ?? EMPTY_THREAD_IDS),
|
||||
thread.id,
|
||||
];
|
||||
threadShellById[thread.id] = toThreadShell(thread);
|
||||
threadSessionById[thread.id] = thread.session;
|
||||
threadTurnStateById[thread.id] = toThreadTurnState(thread);
|
||||
const messageSlice = buildMessageSlice(thread);
|
||||
messageIdsByThreadId[thread.id] = messageSlice.ids;
|
||||
messageByThreadId[thread.id] = messageSlice.byId;
|
||||
const activitySlice = buildActivitySlice(thread);
|
||||
activityIdsByThreadId[thread.id] = activitySlice.ids;
|
||||
activityByThreadId[thread.id] = activitySlice.byId;
|
||||
const proposedPlanSlice = buildProposedPlanSlice(thread);
|
||||
proposedPlanIdsByThreadId[thread.id] = proposedPlanSlice.ids;
|
||||
proposedPlanByThreadId[thread.id] = proposedPlanSlice.byId;
|
||||
const turnDiffSlice = buildTurnDiffSlice(thread);
|
||||
turnDiffIdsByThreadId[thread.id] = turnDiffSlice.ids;
|
||||
turnDiffSummaryByThreadId[thread.id] = turnDiffSlice.byId;
|
||||
sidebarThreadSummaryById[thread.id] = buildSidebarThreadSummary(thread);
|
||||
}
|
||||
|
||||
return {
|
||||
threadIds,
|
||||
threadIdsByProjectId,
|
||||
threadShellById,
|
||||
threadSessionById,
|
||||
threadTurnStateById,
|
||||
messageIdsByThreadId,
|
||||
messageByThreadId,
|
||||
activityIdsByThreadId,
|
||||
activityByThreadId,
|
||||
proposedPlanIdsByThreadId,
|
||||
proposedPlanByThreadId,
|
||||
turnDiffIdsByThreadId,
|
||||
turnDiffSummaryByThreadId,
|
||||
sidebarThreadSummaryById,
|
||||
};
|
||||
}
|
||||
|
||||
function getStoredEnvironmentState(
|
||||
state: AppState,
|
||||
environmentId: EnvironmentId,
|
||||
@@ -1069,6 +1116,25 @@ function commitEnvironmentState(
|
||||
};
|
||||
}
|
||||
|
||||
function syncEnvironmentReadModel(
|
||||
state: EnvironmentState,
|
||||
readModel: OrchestrationReadModel,
|
||||
environmentId: EnvironmentId,
|
||||
): EnvironmentState {
|
||||
const projects = readModel.projects
|
||||
.filter((project) => project.deletedAt === null)
|
||||
.map((project) => mapProject(project, environmentId));
|
||||
const threads = readModel.threads
|
||||
.filter((thread) => thread.deletedAt === null)
|
||||
.map((thread) => mapThread(thread, environmentId));
|
||||
return {
|
||||
...state,
|
||||
...buildProjectState(projects),
|
||||
...buildThreadState(threads),
|
||||
bootstrapComplete: true,
|
||||
};
|
||||
}
|
||||
|
||||
function syncEnvironmentShellSnapshot(
|
||||
state: EnvironmentState,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
@@ -1109,6 +1175,22 @@ function syncEnvironmentShellSnapshot(
|
||||
return nextState;
|
||||
}
|
||||
|
||||
export function syncServerReadModel(
|
||||
state: AppState,
|
||||
readModel: OrchestrationReadModel,
|
||||
environmentId: EnvironmentId,
|
||||
): AppState {
|
||||
return commitEnvironmentState(
|
||||
state,
|
||||
environmentId,
|
||||
syncEnvironmentReadModel(
|
||||
getStoredEnvironmentState(state, environmentId),
|
||||
readModel,
|
||||
environmentId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function syncServerShellSnapshot(
|
||||
state: AppState,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
@@ -1925,6 +2007,7 @@ export function setThreadBranch(
|
||||
|
||||
interface AppStore extends AppState {
|
||||
setActiveEnvironmentId: (environmentId: EnvironmentId) => void;
|
||||
syncServerReadModel: (readModel: OrchestrationReadModel, environmentId: EnvironmentId) => void;
|
||||
syncServerShellSnapshot: (
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
environmentId: EnvironmentId,
|
||||
@@ -1948,6 +2031,8 @@ export const useStore = create<AppStore>((set) => ({
|
||||
...initialState,
|
||||
setActiveEnvironmentId: (environmentId) =>
|
||||
set((state) => setActiveEnvironmentId(state, environmentId)),
|
||||
syncServerReadModel: (readModel, environmentId) =>
|
||||
set((state) => syncServerReadModel(state, readModel, environmentId)),
|
||||
syncServerShellSnapshot: (snapshot, environmentId) =>
|
||||
set((state) => syncServerShellSnapshot(state, snapshot, environmentId)),
|
||||
syncServerThreadDetail: (thread, environmentId) =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type ScopedProjectRef, type ScopedThreadRef, type ThreadId } from "@t3tools/contracts";
|
||||
import { selectEnvironmentState, type AppState, type EnvironmentState } from "./store";
|
||||
import { type Project, type Thread } from "./types";
|
||||
import { type Project, type SidebarThreadSummary, type Thread } from "./types";
|
||||
import { getThreadFromEnvironmentState } from "./threadDerivation";
|
||||
|
||||
export function createProjectSelectorByRef(
|
||||
@@ -10,6 +10,15 @@ export function createProjectSelectorByRef(
|
||||
ref ? selectEnvironmentState(state, ref.environmentId).projectById[ref.projectId] : undefined;
|
||||
}
|
||||
|
||||
export function createSidebarThreadSummarySelectorByRef(
|
||||
ref: ScopedThreadRef | null | undefined,
|
||||
): (state: AppState) => SidebarThreadSummary | undefined {
|
||||
return (state) =>
|
||||
ref
|
||||
? selectEnvironmentState(state, ref.environmentId).sidebarThreadSummaryById[ref.threadId]
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function createScopedThreadSelector(
|
||||
resolveRef: (state: AppState) => ScopedThreadRef | null | undefined,
|
||||
): (state: AppState) => Thread | undefined {
|
||||
|
||||
@@ -57,7 +57,8 @@ export function formatRelativeTime(isoDate: string): { value: string; suffix: st
|
||||
const diffMs = Date.now() - new Date(isoDate).getTime();
|
||||
if (diffMs < 0) return { value: "just now", suffix: null };
|
||||
const seconds = Math.floor(diffMs / 1000);
|
||||
if (seconds < 60) return { value: "just now", suffix: null };
|
||||
if (seconds < 5) return { value: "just now", suffix: null };
|
||||
if (seconds < 60) return { value: `${seconds}s`, suffix: "ago" };
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
|
||||
const hours = Math.floor(minutes / 60);
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { access, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { once } from "node:events";
|
||||
|
||||
import { chromium, type Browser, type BrowserContext, type Page } from "playwright";
|
||||
|
||||
import {
|
||||
type BrowserPerfMetrics,
|
||||
summarizeBrowserPerfMetrics,
|
||||
type PerfRunArtifact,
|
||||
type PerfServerMetricSample,
|
||||
writePerfArtifact,
|
||||
} from "../../../../test/perf/support/artifact";
|
||||
import {
|
||||
installBrowserPerfCollector,
|
||||
PERF_BROWSER_GLOBAL,
|
||||
} from "../../../../test/perf/support/browserMetrics";
|
||||
import type { PerfThresholdProfile } from "../../../../test/perf/support/thresholds";
|
||||
import type {
|
||||
PerfProviderScenarioId,
|
||||
PerfSeedScenarioId,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import {
|
||||
NoopServerSampler,
|
||||
type PerfServerSampler,
|
||||
} from "../../../../test/perf/support/serverSampler";
|
||||
import { buildPerfServerEnv } from "./serverEnv";
|
||||
|
||||
const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
|
||||
const serverBinPath = resolve(repoRoot, "apps/server/dist/bin.mjs");
|
||||
const serverClientIndexPath = resolve(repoRoot, "apps/server/dist/client/index.html");
|
||||
const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
const PERF_HEADFUL_ENV = "T3CODE_PERF_HEADFUL";
|
||||
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
|
||||
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
|
||||
|
||||
interface PerfSeedThreadSummary {
|
||||
readonly id: string;
|
||||
readonly projectId: string;
|
||||
readonly projectTitle: string | null;
|
||||
readonly title: string;
|
||||
readonly turnCount: number | null;
|
||||
readonly messageCount: number;
|
||||
readonly activityCount: number;
|
||||
readonly proposedPlanCount: number;
|
||||
readonly checkpointCount: number;
|
||||
}
|
||||
|
||||
interface PerfSeedProjectSummary {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly threadCount: number;
|
||||
}
|
||||
|
||||
export interface PerfSeededState {
|
||||
readonly scenarioId: PerfSeedScenarioId;
|
||||
readonly runParentDir: string;
|
||||
readonly baseDir: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly projectTitle: string | null;
|
||||
readonly projectSummaries: ReadonlyArray<PerfSeedProjectSummary>;
|
||||
readonly threadSummaries: ReadonlyArray<PerfSeedThreadSummary>;
|
||||
}
|
||||
|
||||
interface StartPerfAppHarnessOptions {
|
||||
readonly suite: string;
|
||||
readonly seedScenarioId: PerfSeedScenarioId;
|
||||
readonly providerScenarioId?: PerfProviderScenarioId;
|
||||
readonly serverSampler?: PerfServerSampler;
|
||||
}
|
||||
|
||||
interface FinishPerfRunOptions {
|
||||
readonly suite: string;
|
||||
readonly scenarioId: string;
|
||||
readonly thresholds: PerfThresholdProfile;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
readonly actionSummary?: {
|
||||
readonly threadSwitchActionPrefix?: string;
|
||||
readonly burstActionName?: string;
|
||||
};
|
||||
readonly artifactBasename?: string;
|
||||
}
|
||||
|
||||
export interface PerfAppHarness {
|
||||
readonly seededState: PerfSeededState;
|
||||
readonly page: Page;
|
||||
readonly url: string;
|
||||
readonly artifactDir: string;
|
||||
readonly startAction: (name: string) => Promise<void>;
|
||||
readonly endAction: (name: string) => Promise<number | null>;
|
||||
readonly resetBrowserMetrics: () => Promise<void>;
|
||||
readonly sampleMountedRows: (label: string) => Promise<number>;
|
||||
readonly snapshotBrowserMetrics: () => Promise<BrowserPerfMetrics>;
|
||||
readonly finishRun: (options: FinishPerfRunOptions) => Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: PerfRunArtifact;
|
||||
readonly browserMetrics: BrowserPerfMetrics;
|
||||
readonly serverMetrics: ReadonlyArray<PerfServerMetricSample> | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
async function pickFreePort(): Promise<number> {
|
||||
return await new Promise<number>((resolvePort, reject) => {
|
||||
const server = createServer();
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Unable to resolve a free localhost port."));
|
||||
return;
|
||||
}
|
||||
const { port } = address;
|
||||
server.close((closeError) => {
|
||||
if (closeError) {
|
||||
reject(closeError);
|
||||
return;
|
||||
}
|
||||
resolvePort(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForServerReady(url: string, process: ChildProcess): Promise<void> {
|
||||
const startedAt = Date.now();
|
||||
const timeoutMs = 45_000;
|
||||
const requestTimeoutMs = 1_000;
|
||||
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
if (process.exitCode !== null) {
|
||||
throw new Error(`Perf server exited early with code ${process.exitCode}.`);
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
redirect: "manual",
|
||||
signal: AbortSignal.timeout(requestTimeoutMs),
|
||||
});
|
||||
if (response.ok) {
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Ignore connection races while the server is still starting.
|
||||
}
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for perf server readiness at ${url}.`);
|
||||
}
|
||||
|
||||
async function verifyBuiltArtifacts(): Promise<void> {
|
||||
await Promise.all([access(serverBinPath), access(serverClientIndexPath)]).catch(() => {
|
||||
throw new Error(
|
||||
`Built perf artifacts are missing. Expected ${serverBinPath} and ${serverClientIndexPath}. Run bun run test:perf:web or build the app first.`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function stopChildProcess(process: ChildProcess): Promise<void> {
|
||||
if (process.exitCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.kill("SIGTERM");
|
||||
const exited = await new Promise<boolean>((resolveExited) => {
|
||||
const timer = setTimeout(() => resolveExited(false), 5_000);
|
||||
process.once("exit", () => {
|
||||
clearTimeout(timer);
|
||||
resolveExited(true);
|
||||
});
|
||||
});
|
||||
|
||||
if (!exited && process.exitCode === null) {
|
||||
process.kill("SIGKILL");
|
||||
await new Promise<void>((resolveExited) => {
|
||||
process.once("exit", () => resolveExited());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureArtifactDir(suite: string, scenarioId: string): Promise<string> {
|
||||
const baseArtifactDir = resolve(
|
||||
process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf"),
|
||||
);
|
||||
const runId = `${suite}-${scenarioId}-${Date.now().toString()}`;
|
||||
const artifactDir = join(baseArtifactDir, runId);
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
async function cleanupPerfRunDir(runParentDir: string): Promise<void> {
|
||||
await rm(runParentDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
async function writeServerLogs(
|
||||
artifactDir: string,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
basename: string,
|
||||
): Promise<void> {
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"),
|
||||
writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"),
|
||||
]);
|
||||
}
|
||||
|
||||
async function invokeBrowserCollector<T>(
|
||||
page: Page,
|
||||
fn: (collectorName: string, ...args: ReadonlyArray<unknown>) => T,
|
||||
...args: ReadonlyArray<unknown>
|
||||
): Promise<T> {
|
||||
return await page.evaluate(
|
||||
({ collectorName, args: serializedArgs, fnSource }) => {
|
||||
const runtimeFn = new Function(
|
||||
"collectorName",
|
||||
"args",
|
||||
`return (${fnSource})(collectorName, ...args);`,
|
||||
) as (collectorName: string, args: ReadonlyArray<unknown>) => T;
|
||||
return runtimeFn(collectorName, serializedArgs);
|
||||
},
|
||||
{
|
||||
collectorName: PERF_BROWSER_GLOBAL,
|
||||
args,
|
||||
fnSource: fn.toString(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function parsePerfSeededState(stdout: string): PerfSeededState {
|
||||
const startIndex = stdout.lastIndexOf(PERF_SEED_JSON_START);
|
||||
const endIndex = stdout.lastIndexOf(PERF_SEED_JSON_END);
|
||||
|
||||
if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {
|
||||
const payload = stdout.slice(startIndex + PERF_SEED_JSON_START.length, endIndex).trim();
|
||||
return JSON.parse(payload) as PerfSeededState;
|
||||
}
|
||||
|
||||
return JSON.parse(stdout) as PerfSeededState;
|
||||
}
|
||||
|
||||
export async function startPerfAppHarness(
|
||||
options: StartPerfAppHarnessOptions,
|
||||
): Promise<PerfAppHarness> {
|
||||
await verifyBuiltArtifacts();
|
||||
|
||||
const seededState = await (async () => {
|
||||
const seedProcess = spawn(
|
||||
"bun",
|
||||
["run", "apps/server/scripts/seedPerfState.ts", options.seedScenarioId],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env: process.env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
seedProcess.stdout?.on("data", (chunk) => {
|
||||
stdout += chunk.toString();
|
||||
});
|
||||
seedProcess.stderr?.on("data", (chunk) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
const [exitCode] = (await once(seedProcess, "exit")) as [number | null];
|
||||
if (exitCode !== 0) {
|
||||
throw new Error(`Perf seed command failed with code ${exitCode ?? "unknown"}.\n${stderr}`);
|
||||
}
|
||||
return parsePerfSeededState(stdout);
|
||||
})();
|
||||
const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId);
|
||||
const port = await pickFreePort();
|
||||
const url = `http://127.0.0.1:${port}/`;
|
||||
const env = buildPerfServerEnv(process.env, options.providerScenarioId);
|
||||
|
||||
let stdoutBuffer = "";
|
||||
let stderrBuffer = "";
|
||||
const serverProcess = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
serverBinPath,
|
||||
"--mode",
|
||||
"web",
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
`${port}`,
|
||||
"--base-dir",
|
||||
seededState.baseDir,
|
||||
"--no-browser",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
serverProcess.stdout?.on("data", (chunk) => {
|
||||
stdoutBuffer += chunk.toString();
|
||||
});
|
||||
serverProcess.stderr?.on("data", (chunk) => {
|
||||
stderrBuffer += chunk.toString();
|
||||
});
|
||||
let browser: Browser | null = null;
|
||||
let context: BrowserContext | null = null;
|
||||
let page: Page | null = null;
|
||||
|
||||
try {
|
||||
await waitForServerReady(url, serverProcess);
|
||||
|
||||
browser = await chromium.launch({
|
||||
headless: process.env[PERF_HEADFUL_ENV] !== "1",
|
||||
});
|
||||
context = await browser.newContext({
|
||||
viewport: { width: 1440, height: 960 },
|
||||
});
|
||||
await context.addInitScript(installBrowserPerfCollector, "[data-timeline-row-kind]");
|
||||
page = await context.newPage();
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
|
||||
const firstProjectTitle =
|
||||
seededState.projectSummaries[0]?.title ??
|
||||
seededState.projectTitle ??
|
||||
getPerfSeedScenario(options.seedScenarioId).projects[0]?.title;
|
||||
if (!firstProjectTitle) {
|
||||
throw new Error(`Seed scenario '${options.seedScenarioId}' produced no projects.`);
|
||||
}
|
||||
await page.getByText(firstProjectTitle, { exact: true }).first().waitFor({ timeout: 45_000 });
|
||||
|
||||
const sampler = options.serverSampler ?? new NoopServerSampler();
|
||||
if (serverProcess.pid) {
|
||||
await sampler.start({ pid: serverProcess.pid });
|
||||
}
|
||||
const runStartedAt = new Date().toISOString();
|
||||
const readyPage = page;
|
||||
if (!readyPage) {
|
||||
throw new Error("Perf app harness did not initialize a browser page.");
|
||||
}
|
||||
|
||||
let finishPromise:
|
||||
| Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: PerfRunArtifact;
|
||||
readonly browserMetrics: BrowserPerfMetrics;
|
||||
readonly serverMetrics: ReadonlyArray<PerfServerMetricSample> | null;
|
||||
}>
|
||||
| undefined;
|
||||
|
||||
const teardown = async () => {
|
||||
await Promise.allSettled([
|
||||
context ? context.close() : Promise.resolve(),
|
||||
browser ? browser.close() : Promise.resolve(),
|
||||
]);
|
||||
await stopChildProcess(serverProcess);
|
||||
await cleanupPerfRunDir(seededState.runParentDir);
|
||||
};
|
||||
|
||||
return {
|
||||
seededState,
|
||||
page: readyPage,
|
||||
url,
|
||||
artifactDir,
|
||||
startAction: (name) =>
|
||||
invokeBrowserCollector(
|
||||
readyPage,
|
||||
(collectorName, actionName) => {
|
||||
(window as Window & Record<string, any>)[collectorName]?.startAction(
|
||||
actionName as string,
|
||||
);
|
||||
},
|
||||
name,
|
||||
),
|
||||
endAction: (name) =>
|
||||
invokeBrowserCollector(
|
||||
readyPage,
|
||||
(collectorName, actionName) => {
|
||||
return (
|
||||
(window as Window & Record<string, any>)[collectorName]?.endAction(
|
||||
actionName as string,
|
||||
) ?? null
|
||||
);
|
||||
},
|
||||
name,
|
||||
),
|
||||
resetBrowserMetrics: () =>
|
||||
invokeBrowserCollector(readyPage, (collectorName) => {
|
||||
(window as Window & Record<string, any>)[collectorName]?.reset();
|
||||
}),
|
||||
sampleMountedRows: (label) =>
|
||||
invokeBrowserCollector(
|
||||
readyPage,
|
||||
(collectorName, sampleLabel) => {
|
||||
return (
|
||||
(window as Window & Record<string, any>)[collectorName]?.sampleMountedRows(
|
||||
sampleLabel as string,
|
||||
) ?? 0
|
||||
);
|
||||
},
|
||||
label,
|
||||
),
|
||||
snapshotBrowserMetrics: () =>
|
||||
invokeBrowserCollector(readyPage, (collectorName) => {
|
||||
return ((window as Window & Record<string, any>)[collectorName]?.snapshot() ?? {
|
||||
actions: [],
|
||||
longTasks: [],
|
||||
rafGapsMs: [],
|
||||
mountedRowSamples: [],
|
||||
}) as BrowserPerfMetrics;
|
||||
}),
|
||||
finishRun: async (finishOptions) => {
|
||||
if (finishPromise) {
|
||||
return await finishPromise;
|
||||
}
|
||||
|
||||
finishPromise = (async () => {
|
||||
const completedAt = new Date().toISOString();
|
||||
const browserMetrics: BrowserPerfMetrics = await (async () => {
|
||||
try {
|
||||
return await invokeBrowserCollector(readyPage, (collectorName) => {
|
||||
return ((window as Window & Record<string, any>)[collectorName]?.snapshot() ?? {
|
||||
actions: [],
|
||||
longTasks: [],
|
||||
rafGapsMs: [],
|
||||
mountedRowSamples: [],
|
||||
}) as BrowserPerfMetrics;
|
||||
});
|
||||
} catch {
|
||||
return {
|
||||
actions: [],
|
||||
longTasks: [],
|
||||
rafGapsMs: [],
|
||||
mountedRowSamples: [],
|
||||
} satisfies BrowserPerfMetrics;
|
||||
}
|
||||
})();
|
||||
const serverMetrics = await sampler.stop();
|
||||
await teardown();
|
||||
|
||||
const basename =
|
||||
finishOptions.artifactBasename ?? `${finishOptions.suite}-${finishOptions.scenarioId}`;
|
||||
await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename);
|
||||
const artifact: PerfRunArtifact = {
|
||||
suite: finishOptions.suite,
|
||||
scenarioId: finishOptions.scenarioId,
|
||||
startedAt: runStartedAt,
|
||||
completedAt,
|
||||
thresholds: finishOptions.thresholds,
|
||||
summary: summarizeBrowserPerfMetrics(browserMetrics, finishOptions.actionSummary),
|
||||
browserMetrics,
|
||||
serverMetrics,
|
||||
...(finishOptions.metadata ? { metadata: finishOptions.metadata } : {}),
|
||||
};
|
||||
const artifactPath = join(artifactDir, `${basename}.json`);
|
||||
await writePerfArtifact(artifactPath, artifact);
|
||||
|
||||
return {
|
||||
artifactPath,
|
||||
artifact,
|
||||
browserMetrics,
|
||||
serverMetrics,
|
||||
};
|
||||
})();
|
||||
|
||||
return await finishPromise;
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await Promise.allSettled([
|
||||
context ? context.close() : Promise.resolve(),
|
||||
browser ? browser.close() : Promise.resolve(),
|
||||
]);
|
||||
await stopChildProcess(serverProcess);
|
||||
await cleanupPerfRunDir(seededState.runParentDir);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { Page } from "playwright";
|
||||
|
||||
import type { PerfAppHarness } from "./appHarness";
|
||||
|
||||
export async function ensureThreadRowVisible(
|
||||
page: Page,
|
||||
projectTitle: string,
|
||||
threadId: string,
|
||||
): Promise<void> {
|
||||
const threadRow = page.getByTestId(`thread-row-${threadId}`);
|
||||
if (await threadRow.isVisible().catch(() => false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projectToggle = page.getByText(projectTitle, { exact: true }).first();
|
||||
await projectToggle.click();
|
||||
await threadRow.waitFor({ state: "visible", timeout: 20_000 });
|
||||
}
|
||||
|
||||
export async function waitForThreadRoute(
|
||||
page: Page,
|
||||
input: {
|
||||
readonly threadId: string;
|
||||
readonly messageId?: string;
|
||||
readonly extraSelector?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
const path = `/${encodeURIComponent(input.threadId)}`;
|
||||
const threadSelector = `[data-testid="chat-thread-${input.threadId}"]`;
|
||||
await page.waitForFunction(
|
||||
({ expectedPath, threadSelector, messageSelector, extraSelector }) => {
|
||||
const pathMatches = window.location.pathname === expectedPath;
|
||||
if (!pathMatches) {
|
||||
return false;
|
||||
}
|
||||
if (!document.querySelector(threadSelector)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (messageSelector && !document.querySelector(messageSelector)) {
|
||||
return false;
|
||||
}
|
||||
if (extraSelector && !document.querySelector(extraSelector)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
expectedPath: path,
|
||||
threadSelector,
|
||||
messageSelector: input.messageId ? `[data-message-id="${input.messageId}"]` : null,
|
||||
extraSelector: input.extraSelector ?? null,
|
||||
},
|
||||
{ timeout: 45_000 },
|
||||
);
|
||||
}
|
||||
|
||||
export async function measureThreadSwitch(
|
||||
harness: PerfAppHarness,
|
||||
input: {
|
||||
readonly actionName: string;
|
||||
readonly projectTitle: string;
|
||||
readonly threadId: string;
|
||||
readonly messageId?: string;
|
||||
readonly extraSelector?: string;
|
||||
},
|
||||
): Promise<number | null> {
|
||||
await ensureThreadRowVisible(harness.page, input.projectTitle, input.threadId);
|
||||
await harness.startAction(input.actionName);
|
||||
await harness.page.getByTestId(`thread-row-${input.threadId}`).click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: input.threadId,
|
||||
...(input.messageId ? { messageId: input.messageId } : {}),
|
||||
...(input.extraSelector ? { extraSelector: input.extraSelector } : {}),
|
||||
});
|
||||
return await harness.endAction(input.actionName);
|
||||
}
|
||||
|
||||
export async function scrollTimelineTo(page: Page, position: "top" | "bottom"): Promise<void> {
|
||||
await page.evaluate(async (targetPosition) => {
|
||||
const timelineRoot = document.querySelector<HTMLElement>('[data-timeline-root="true"]');
|
||||
const scrollContainer = timelineRoot?.parentElement;
|
||||
if (!scrollContainer) {
|
||||
throw new Error("Messages scroll container not found.");
|
||||
}
|
||||
|
||||
scrollContainer.scrollTo({
|
||||
top: targetPosition === "bottom" ? scrollContainer.scrollHeight : 0,
|
||||
behavior: "auto",
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
||||
});
|
||||
}, position);
|
||||
}
|
||||
|
||||
export async function typeIntoComposerAndSend(page: Page, message: string): Promise<void> {
|
||||
const editor = page.getByTestId("composer-editor");
|
||||
await editor.click();
|
||||
await page.keyboard.type(message);
|
||||
await page.getByRole("button", { name: "Send message" }).click();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { PerfProviderScenarioId } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
export const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
export const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const AUTO_BOOTSTRAP_PROJECT_ENV = "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD";
|
||||
|
||||
export function buildPerfServerEnv(
|
||||
baseEnv: NodeJS.ProcessEnv,
|
||||
providerScenarioId?: PerfProviderScenarioId,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
[AUTO_BOOTSTRAP_PROJECT_ENV]: "false",
|
||||
};
|
||||
|
||||
if (!providerScenarioId) {
|
||||
delete env[PERF_PROVIDER_ENV];
|
||||
delete env[PERF_SCENARIO_ENV];
|
||||
return env;
|
||||
}
|
||||
|
||||
return {
|
||||
...env,
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
[PERF_SCENARIO_ENV]: providerScenarioId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { percentile } from "../../../../test/perf/support/artifact";
|
||||
import { installBrowserPerfCollector } from "../../../../test/perf/support/browserMetrics";
|
||||
import { buildPerfServerEnv, PERF_PROVIDER_ENV, PERF_SCENARIO_ENV } from "./serverEnv";
|
||||
|
||||
describe("percentile", () => {
|
||||
it("returns the minimum value for the zero percentile", () => {
|
||||
expect(percentile([9, 3, 6], 0)).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("installBrowserPerfCollector", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("cancels the previous animation frame loop before reset starts a new one", () => {
|
||||
let nextHandle = 1;
|
||||
const callbacks = new Map<number, FrameRequestCallback>();
|
||||
const requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {
|
||||
const handle = nextHandle++;
|
||||
callbacks.set(handle, callback);
|
||||
return handle;
|
||||
});
|
||||
const cancelAnimationFrame = vi.fn((handle: number) => {
|
||||
callbacks.delete(handle);
|
||||
});
|
||||
|
||||
vi.stubGlobal("window", {
|
||||
requestAnimationFrame,
|
||||
cancelAnimationFrame,
|
||||
} as unknown as Window & typeof globalThis);
|
||||
vi.stubGlobal("document", {
|
||||
querySelectorAll: vi.fn(() => []),
|
||||
} as unknown as Document);
|
||||
vi.stubGlobal("PerformanceObserver", undefined);
|
||||
|
||||
installBrowserPerfCollector();
|
||||
|
||||
const collector = window.__t3PerfCollector;
|
||||
expect(collector).toBeDefined();
|
||||
expect(requestAnimationFrame).toHaveBeenCalledTimes(1);
|
||||
|
||||
collector?.reset();
|
||||
expect(cancelAnimationFrame).toHaveBeenCalledWith(1);
|
||||
expect(requestAnimationFrame).toHaveBeenCalledTimes(2);
|
||||
|
||||
collector?.reset();
|
||||
expect(cancelAnimationFrame).toHaveBeenLastCalledWith(2);
|
||||
expect(requestAnimationFrame).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPerfServerEnv", () => {
|
||||
it("does not enable the perf provider when no live provider scenario is requested", () => {
|
||||
const env = buildPerfServerEnv({
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
[PERF_SCENARIO_ENV]: "dense_assistant_stream",
|
||||
KEEP_ME: "yes",
|
||||
});
|
||||
|
||||
expect(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).toBe("false");
|
||||
expect(env[PERF_PROVIDER_ENV]).toBeUndefined();
|
||||
expect(env[PERF_SCENARIO_ENV]).toBeUndefined();
|
||||
expect(env.KEEP_ME).toBe("yes");
|
||||
});
|
||||
|
||||
it("enables the perf provider only when a live provider scenario is requested", () => {
|
||||
const env = buildPerfServerEnv({}, "dense_assistant_stream");
|
||||
|
||||
expect(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).toBe("false");
|
||||
expect(env[PERF_PROVIDER_ENV]).toBe("1");
|
||||
expect(env[PERF_SCENARIO_ENV]).toBe("dense_assistant_stream");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { summarizeBrowserPerfMetrics } from "../../../../test/perf/support/artifact";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { PERF_THRESHOLDS } from "../../../../test/perf/support/thresholds";
|
||||
import { startPerfAppHarness, type PerfAppHarness } from "./appHarness";
|
||||
import {
|
||||
ensureThreadRowVisible,
|
||||
measureThreadSwitch,
|
||||
scrollTimelineTo,
|
||||
waitForThreadRoute,
|
||||
} from "./pagePerfHelpers";
|
||||
|
||||
test("virtualization stays bounded and heavy thread switches remain snappy", async () => {
|
||||
const thresholds = PERF_THRESHOLDS.local;
|
||||
let harness: PerfAppHarness | null = null;
|
||||
let finished = false;
|
||||
|
||||
try {
|
||||
harness = await startPerfAppHarness({
|
||||
suite: "virtualization",
|
||||
seedScenarioId: "large_threads",
|
||||
});
|
||||
|
||||
const heavyAThreadSummary = harness.seededState.threadSummaries.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
const heavyBThreadSummary = harness.seededState.threadSummaries.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
);
|
||||
const heavyAProjectTitle =
|
||||
heavyAThreadSummary?.projectTitle ?? PERF_CATALOG_IDS.largeThreads.heavyAProjectTitle;
|
||||
const heavyBProjectTitle =
|
||||
heavyBThreadSummary?.projectTitle ?? PERF_CATALOG_IDS.largeThreads.heavyBProjectTitle;
|
||||
const heavyThreadMessageCount = heavyAThreadSummary?.messageCount ?? 0;
|
||||
expect(heavyAThreadSummary).toBeDefined();
|
||||
expect(heavyBThreadSummary).toBeDefined();
|
||||
expect(heavyThreadMessageCount).toBeGreaterThanOrEqual(2_000);
|
||||
expect(heavyAThreadSummary?.turnCount ?? 0).toBeLessThan(100);
|
||||
expect(heavyBThreadSummary?.turnCount ?? 0).toBeLessThan(100);
|
||||
|
||||
await ensureThreadRowVisible(
|
||||
harness.page,
|
||||
heavyAProjectTitle,
|
||||
PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
await harness.page
|
||||
.getByTestId(`thread-row-${PERF_CATALOG_IDS.largeThreads.heavyAThreadId}`)
|
||||
.click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
});
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
|
||||
await ensureThreadRowVisible(
|
||||
harness.page,
|
||||
heavyBProjectTitle,
|
||||
PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
);
|
||||
await harness.page
|
||||
.getByTestId(`thread-row-${PERF_CATALOG_IDS.largeThreads.heavyBThreadId}`)
|
||||
.click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
});
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
|
||||
await harness.resetBrowserMetrics();
|
||||
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: "thread-switch-warmup-a",
|
||||
projectTitle: heavyAProjectTitle,
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
});
|
||||
|
||||
const mountedRows = await harness.sampleMountedRows("heavy-a-open");
|
||||
expect(mountedRows).toBeLessThanOrEqual(thresholds.maxMountedTimelineRows);
|
||||
|
||||
const measuredTargets = [
|
||||
{
|
||||
actionName: "thread-switch-1",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-2",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-3",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-4",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-5",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-6",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
},
|
||||
] as const;
|
||||
|
||||
for (const target of measuredTargets) {
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: target.actionName,
|
||||
projectTitle:
|
||||
target.threadId === PERF_CATALOG_IDS.largeThreads.heavyAThreadId
|
||||
? heavyAProjectTitle
|
||||
: heavyBProjectTitle,
|
||||
threadId: target.threadId,
|
||||
messageId: target.messageId,
|
||||
});
|
||||
await harness.sampleMountedRows(`${target.actionName}-rows`);
|
||||
}
|
||||
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
await harness.sampleMountedRows("scroll-start");
|
||||
await scrollTimelineTo(harness.page, "top");
|
||||
await harness.sampleMountedRows("scroll-top");
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
await harness.sampleMountedRows("scroll-bottom");
|
||||
|
||||
const browserMetrics = await harness.snapshotBrowserMetrics();
|
||||
const summary = summarizeBrowserPerfMetrics(browserMetrics, {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
});
|
||||
|
||||
expect(summary.threadSwitchP50Ms).not.toBeNull();
|
||||
expect(summary.threadSwitchP95Ms).not.toBeNull();
|
||||
expect(summary.threadSwitchP50Ms ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
|
||||
thresholds.threadSwitchP50Ms,
|
||||
);
|
||||
expect(summary.threadSwitchP95Ms ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
|
||||
thresholds.threadSwitchP95Ms,
|
||||
);
|
||||
expect(summary.maxMountedTimelineRows).toBeLessThanOrEqual(thresholds.maxMountedTimelineRows);
|
||||
expect(summary.maxLongTaskMs).toBeLessThanOrEqual(thresholds.maxLongTaskMs);
|
||||
expect(summary.maxRafGapMs).toBeLessThanOrEqual(thresholds.maxRafGapMs);
|
||||
|
||||
await harness.finishRun({
|
||||
suite: "virtualization",
|
||||
scenarioId: "large_threads",
|
||||
thresholds,
|
||||
metadata: {
|
||||
heavyThreadMessageCount,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
},
|
||||
});
|
||||
finished = true;
|
||||
} finally {
|
||||
if (harness && !finished) {
|
||||
await harness.finishRun({
|
||||
suite: "virtualization",
|
||||
scenarioId: "large_threads",
|
||||
thresholds,
|
||||
metadata: {
|
||||
heavyThreadMessageCount: harness.seededState.threadSummaries.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
)?.messageCount,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { summarizeBrowserPerfMetrics } from "../../../../test/perf/support/artifact";
|
||||
import { PERF_CATALOG_IDS, PERF_PROVIDER_SCENARIOS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { PERF_THRESHOLDS } from "../../../../test/perf/support/thresholds";
|
||||
import { startPerfAppHarness, type PerfAppHarness } from "./appHarness";
|
||||
import {
|
||||
ensureThreadRowVisible,
|
||||
measureThreadSwitch,
|
||||
typeIntoComposerAndSend,
|
||||
waitForThreadRoute,
|
||||
} from "./pagePerfHelpers";
|
||||
|
||||
test("high-frequency websocket events stay responsive under real built-app flow", async () => {
|
||||
const thresholds = PERF_THRESHOLDS.local;
|
||||
let harness: PerfAppHarness | null = null;
|
||||
let finished = false;
|
||||
|
||||
try {
|
||||
harness = await startPerfAppHarness({
|
||||
suite: "websocket-application",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "dense_assistant_stream",
|
||||
});
|
||||
|
||||
const projectTitle = harness.seededState.projectTitle ?? "Performance Workspace";
|
||||
const streamScenario = PERF_PROVIDER_SCENARIOS.dense_assistant_stream;
|
||||
expect(streamScenario.totalDurationMs).toBeGreaterThanOrEqual(10_000);
|
||||
|
||||
await ensureThreadRowVisible(
|
||||
harness.page,
|
||||
projectTitle,
|
||||
PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
);
|
||||
await harness.page
|
||||
.getByTestId(`thread-row-${PERF_CATALOG_IDS.burstBase.burstThreadId}`)
|
||||
.click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
messageId: PERF_CATALOG_IDS.burstBase.burstTerminalMessageId,
|
||||
});
|
||||
|
||||
await harness.resetBrowserMetrics();
|
||||
await harness.startAction("burst-completion");
|
||||
await typeIntoComposerAndSend(harness.page, "Run the dense websocket perf burst.");
|
||||
|
||||
await harness.page.waitForTimeout(900);
|
||||
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: "thread-switch-burst-nav",
|
||||
projectTitle,
|
||||
threadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
});
|
||||
await harness.page.waitForFunction(
|
||||
(messageNeedle) => document.body.textContent?.includes(messageNeedle as string) ?? false,
|
||||
"Navigation lane",
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
const navigationTimelineText = await harness.page
|
||||
.locator('[data-timeline-root="true"]')
|
||||
.textContent();
|
||||
expect(navigationTimelineText ?? "").toContain("Navigation lane");
|
||||
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: "thread-switch-burst-return",
|
||||
projectTitle,
|
||||
threadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
});
|
||||
|
||||
await harness.page.waitForFunction(
|
||||
(sentinelText) => document.body.textContent?.includes(sentinelText as string) ?? false,
|
||||
streamScenario.sentinelText,
|
||||
{ timeout: streamScenario.totalDurationMs + 15_000 },
|
||||
);
|
||||
await harness.endAction("burst-completion");
|
||||
|
||||
const browserMetrics = await harness.snapshotBrowserMetrics();
|
||||
const summary = summarizeBrowserPerfMetrics(browserMetrics, {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
burstActionName: "burst-completion",
|
||||
});
|
||||
|
||||
expect(summary.burstCompletionMs).not.toBeNull();
|
||||
expect(summary.burstCompletionMs ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
|
||||
thresholds.burstCompletionMs,
|
||||
);
|
||||
expect(summary.maxLongTaskMs).toBeLessThanOrEqual(thresholds.maxLongTaskMs);
|
||||
expect(summary.longTasksOver50Ms).toBeLessThanOrEqual(thresholds.longTasksOver50MsMax);
|
||||
expect(summary.maxRafGapMs).toBeLessThanOrEqual(thresholds.maxRafGapMs);
|
||||
|
||||
const burstNavActions = browserMetrics.actions.filter((action) =>
|
||||
action.name.startsWith("thread-switch-burst"),
|
||||
);
|
||||
expect(burstNavActions).toHaveLength(2);
|
||||
for (const action of burstNavActions) {
|
||||
expect(action.durationMs).toBeLessThanOrEqual(thresholds.threadSwitchP95Ms);
|
||||
}
|
||||
|
||||
await harness.finishRun({
|
||||
suite: "websocket-application",
|
||||
scenarioId: "dense_assistant_stream",
|
||||
thresholds,
|
||||
metadata: {
|
||||
burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
fillerThreadId: PERF_CATALOG_IDS.burstBase.fillerThreadId,
|
||||
navigationLiveAssistantMessageId:
|
||||
PERF_CATALOG_IDS.provider.navigationLiveAssistantMessageId,
|
||||
burstLiveAssistantMessageId: PERF_CATALOG_IDS.provider.burstLiveAssistantMessageId,
|
||||
sentinelText: streamScenario.sentinelText,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
burstActionName: "burst-completion",
|
||||
},
|
||||
});
|
||||
finished = true;
|
||||
} finally {
|
||||
if (harness && !finished) {
|
||||
await harness.finishRun({
|
||||
suite: "websocket-application",
|
||||
scenarioId: "dense_assistant_stream",
|
||||
thresholds,
|
||||
metadata: {
|
||||
burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
fillerThreadId: PERF_CATALOG_IDS.burstBase.fillerThreadId,
|
||||
navigationLiveAssistantMessageId:
|
||||
PERF_CATALOG_IDS.provider.navigationLiveAssistantMessageId,
|
||||
burstLiveAssistantMessageId: PERF_CATALOG_IDS.provider.burstLiveAssistantMessageId,
|
||||
sentinelText: PERF_PROVIDER_SCENARIOS.dense_assistant_stream.sentinelText,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
burstActionName: "burst-completion",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
+10
-1
@@ -21,5 +21,14 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src", "vite.config.ts", "test"]
|
||||
"include": [
|
||||
"src",
|
||||
"vite.config.ts",
|
||||
"test",
|
||||
"../../packages/shared/src/perf/artifact.ts",
|
||||
"../../test/perf/support/artifact.ts",
|
||||
"../../test/perf/support/browserMetrics.ts",
|
||||
"../../test/perf/support/serverSampler.ts",
|
||||
"../../test/perf/support/thresholds.ts"
|
||||
]
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import tailwindcss from "@tailwindcss/vite";
|
||||
import react, { reactCompilerPreset } from "@vitejs/plugin-react";
|
||||
import babel from "@rolldown/plugin-babel";
|
||||
import { tanstackRouter } from "@tanstack/router-plugin/vite";
|
||||
import { configDefaults } from "vitest/config";
|
||||
import { defineConfig } from "vite";
|
||||
import pkg from "./package.json" with { type: "json" };
|
||||
|
||||
@@ -102,4 +103,7 @@ export default defineConfig({
|
||||
emptyOutDir: true,
|
||||
sourcemap: buildSourcemap,
|
||||
},
|
||||
test: {
|
||||
exclude: [...configDefaults.exclude, "test/perf/**/*.perf.test.ts"],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["test/perf/**/*.perf.test.ts"],
|
||||
environment: "node",
|
||||
fileParallelism: false,
|
||||
maxConcurrency: 1,
|
||||
testTimeout: 180_000,
|
||||
hookTimeout: 180_000,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
# Performance Benchmarks
|
||||
|
||||
This repository has a local performance regression harness for the built web app and built server. It is intentionally separate from the normal unit and browser test suites.
|
||||
|
||||
The benchmark is meant to answer two questions:
|
||||
|
||||
- Does large-thread rendering and thread-to-thread navigation stay snappy?
|
||||
- Does high-frequency websocket event application stay responsive under a realistic built-app flow?
|
||||
|
||||
## What it runs
|
||||
|
||||
The perf suite does not use Vite dev mode. Each run does this:
|
||||
|
||||
1. Seeds a real server base dir with deterministic fixture data using the normal event store and projection pipeline.
|
||||
2. Starts the built `t3` server from `apps/server/dist/bin.mjs`.
|
||||
3. Serves the built web bundle from `apps/server/dist/client`.
|
||||
4. Launches Chromium with Playwright.
|
||||
5. Installs an in-page collector for action timings, long tasks, `requestAnimationFrame` gaps, and mounted timeline row counts.
|
||||
6. Writes a JSON artifact plus server stdout and stderr logs under `artifacts/perf/`.
|
||||
|
||||
The current implementation is browser-focused, but the harness already reserves a server sampling hook so later server-only CPU and memory benchmarks can share the same scenarios and artifact format.
|
||||
|
||||
## Main pieces
|
||||
|
||||
- `packages/shared/src/perf/scenarioCatalog.ts`
|
||||
- Shared scenario catalog for both seeded state and live provider traffic.
|
||||
- `apps/server/integration/perf/seedPerfState.ts`
|
||||
- Creates the temporary sqlite-backed base dir using real orchestration events and projections.
|
||||
- `apps/server/src/perf/PerfProviderAdapter.ts`
|
||||
- Perf-only mock provider that emits paced runtime events over the normal provider -> websocket -> client path.
|
||||
- `apps/web/test/perf/appHarness.ts`
|
||||
- Starts the built app, launches Chromium, installs the browser collector, and writes artifacts.
|
||||
- `test/perf/support/browserMetrics.ts`
|
||||
- Collects action durations, long tasks, `requestAnimationFrame` gaps, and mounted row samples inside the page.
|
||||
- `test/perf/support/artifact.ts`
|
||||
- Defines the JSON artifact format and summary math.
|
||||
- `test/perf/support/thresholds.ts`
|
||||
- Local budgets that currently gate the suite.
|
||||
- `test/perf/support/serverSampler.ts`
|
||||
- Extension point for future CPU and memory sampling. The current implementation is `NoopServerSampler`, so `serverMetrics` is `null` today.
|
||||
|
||||
## Scenarios
|
||||
|
||||
### `large_threads`
|
||||
|
||||
Seeded app state used by the virtualization benchmark.
|
||||
|
||||
- 5 projects
|
||||
- 30 threads total
|
||||
- 2 heavy threads
|
||||
- 1 burst thread
|
||||
- 27 light filler threads spread across all projects
|
||||
|
||||
The two heavy threads currently seed:
|
||||
|
||||
- `84` and `96` turns
|
||||
- `2,000` messages
|
||||
- periodic worklog/activity rows
|
||||
- periodic proposed-plan rows
|
||||
- frequent checkpoint rows with larger changed-file trees
|
||||
|
||||
This keeps the thread count and project list closer to a real workspace mix: many projects, many sidebar rows, and heavy conversations that stay under `100` turns while still retaining thousands of messages because each turn fans out into multiple assistant messages. The heavy timelines also include the non-message rows that tend to stress grouping, virtualization, and diff-tree rendering.
|
||||
|
||||
### `burst_base`
|
||||
|
||||
Seeded app state used by the websocket benchmark.
|
||||
|
||||
- 1 burst target thread
|
||||
- 1 navigation thread
|
||||
- 1 filler thread
|
||||
|
||||
This smaller seed keeps the focus on live websocket application while still covering cross-thread background activity.
|
||||
|
||||
### `dense_assistant_stream`
|
||||
|
||||
Live provider scenario used by the websocket benchmark.
|
||||
|
||||
- runs for about `10` seconds
|
||||
- spans `24` cycles
|
||||
- updates `3` lanes at once: `burst`, `navigation`, and `filler`
|
||||
- interleaves assistant messages with multiple worklog/tool lifecycles
|
||||
|
||||
Each cycle emits, per lane:
|
||||
|
||||
1. an assistant intro message
|
||||
2. three worklog/tool command lifecycles with file payloads
|
||||
3. an assistant followup message
|
||||
|
||||
The message fragments vary in length on purpose so the live stream does not render as uniformly sized chunks.
|
||||
|
||||
## What each benchmark asserts
|
||||
|
||||
### Virtualization benchmark
|
||||
|
||||
File: `apps/web/test/perf/virtualization.perf.test.ts`
|
||||
|
||||
This benchmark:
|
||||
|
||||
- opens the large-thread seed on the built app
|
||||
- navigates between the two heavy threads through the real sidebar
|
||||
- measures a warmup switch and then six measured thread switches
|
||||
- samples mounted timeline row counts
|
||||
- scrolls bottom -> top -> bottom to catch jank
|
||||
|
||||
It currently fails if the local budgets in `test/perf/support/thresholds.ts` are exceeded:
|
||||
|
||||
- max mounted timeline rows: `140`
|
||||
- thread switch p50: `250ms`
|
||||
- thread switch p95: `500ms`
|
||||
- max long task: `120ms`
|
||||
- max `requestAnimationFrame` gap: `120ms`
|
||||
|
||||
### Websocket benchmark
|
||||
|
||||
File: `apps/web/test/perf/websocket-application.perf.test.ts`
|
||||
|
||||
This benchmark:
|
||||
|
||||
- starts the built app with the perf provider enabled
|
||||
- opens the burst thread
|
||||
- sends one real composer message
|
||||
- lets the mock provider emit the live multi-thread websocket burst
|
||||
- switches to another thread during the burst and back again
|
||||
- waits for the sentinel text that marks the end of the scenario
|
||||
|
||||
It currently fails if these budgets are exceeded:
|
||||
|
||||
- burst completion: `14,000ms`
|
||||
- max long task: `120ms`
|
||||
- long tasks over `50ms`: `2`
|
||||
- max `requestAnimationFrame` gap: `120ms`
|
||||
- burst-time thread switches: `500ms` max each
|
||||
|
||||
## Commands
|
||||
|
||||
### One-time browser setup
|
||||
|
||||
Install Chromium for the perf suite:
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
bun run test:perf:install
|
||||
```
|
||||
|
||||
### Run the full automated benchmark suite
|
||||
|
||||
From the repo root:
|
||||
|
||||
```bash
|
||||
bun run test:perf:web
|
||||
```
|
||||
|
||||
That command builds `@t3tools/web`, builds `t3`, and then runs the dedicated perf Vitest config.
|
||||
|
||||
### Re-run the perf suite without rebuilding
|
||||
|
||||
If the built artifacts already exist and you have not changed the built app since the last build:
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
bun run test:perf
|
||||
```
|
||||
|
||||
### Watch the automated run in a live browser
|
||||
|
||||
```bash
|
||||
T3CODE_PERF_HEADFUL=1 bun run test:perf:web
|
||||
```
|
||||
|
||||
If you already have fresh build artifacts:
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
T3CODE_PERF_HEADFUL=1 bun run test:perf
|
||||
```
|
||||
|
||||
### Open the seeded app manually for exploration
|
||||
|
||||
Large-thread virtualization state:
|
||||
|
||||
```bash
|
||||
bun run perf:open:build -- --scenario large_threads --open
|
||||
```
|
||||
|
||||
Websocket burst state:
|
||||
|
||||
```bash
|
||||
bun run perf:open:build -- --scenario burst_base --provider dense_assistant_stream --open
|
||||
```
|
||||
|
||||
If the app is already built, use the faster commands:
|
||||
|
||||
```bash
|
||||
bun run perf:open -- --scenario large_threads --open
|
||||
bun run perf:open -- --scenario burst_base --provider dense_assistant_stream --open
|
||||
```
|
||||
|
||||
For the websocket scenario, open the burst thread and send one message to start the live stream.
|
||||
|
||||
### Inspect the seeded topology directly
|
||||
|
||||
The seed script prints the generated project and thread summaries as JSON:
|
||||
|
||||
```bash
|
||||
bun run apps/server/scripts/seedPerfState.ts large_threads
|
||||
bun run apps/server/scripts/seedPerfState.ts burst_base
|
||||
```
|
||||
|
||||
## Artifacts
|
||||
|
||||
By default each run writes to:
|
||||
|
||||
```text
|
||||
artifacts/perf/<suite>-<scenario>-<timestamp>/
|
||||
```
|
||||
|
||||
Each run currently includes:
|
||||
|
||||
- `<suite>-<scenario>.json`
|
||||
- `<suite>-<scenario>.server.stdout.log`
|
||||
- `<suite>-<scenario>.server.stderr.log`
|
||||
|
||||
The JSON artifact contains:
|
||||
|
||||
- run metadata
|
||||
- threshold profile
|
||||
- summary metrics
|
||||
- raw browser metrics
|
||||
- `serverMetrics`, reserved for later server sampling
|
||||
|
||||
Current summary fields:
|
||||
|
||||
- `maxMountedTimelineRows`
|
||||
- `threadSwitchP50Ms`
|
||||
- `threadSwitchP95Ms`
|
||||
- `maxLongTaskMs`
|
||||
- `longTasksOver50Ms`
|
||||
- `maxRafGapMs`
|
||||
- `burstCompletionMs`
|
||||
|
||||
To change the artifact output directory for one run:
|
||||
|
||||
```bash
|
||||
T3CODE_PERF_ARTIFACT_DIR=/tmp/t3-perf bun run test:perf:web
|
||||
```
|
||||
|
||||
## Internal env vars
|
||||
|
||||
These are the perf-specific env vars in the current harness:
|
||||
|
||||
- `T3CODE_PERF_HEADFUL=1`
|
||||
- Launch Chromium headed instead of headless.
|
||||
- `T3CODE_PERF_ARTIFACT_DIR=/path/to/output`
|
||||
- Override the artifact directory.
|
||||
- `T3CODE_PERF_PROVIDER=1`
|
||||
- Enables the perf provider path on the server.
|
||||
- `T3CODE_PERF_SCENARIO=dense_assistant_stream`
|
||||
- Selects the live perf provider scenario.
|
||||
|
||||
In normal usage, the automated harness and `perf:open` script set the provider env vars for you.
|
||||
|
||||
## Notes and limitations
|
||||
|
||||
- This is a local benchmark suite. It is not wired into CI yet.
|
||||
- The normal `apps/web` test suite excludes `test/perf/**/*.perf.test.ts`. Perf tests only run through `apps/web/vitest.perf.config.ts`.
|
||||
- The budgets are intentionally conservative first-pass tripwires, not tuned production SLOs.
|
||||
- The current harness measures browser responsiveness only. Server sampling is an explicit extension point, not implemented metrics yet.
|
||||
@@ -25,9 +25,6 @@ This document covers how to run desktop releases from one tag, first without sig
|
||||
- Background checks run on startup delay + interval.
|
||||
- No automatic download or install.
|
||||
- The desktop UI shows a rocket update button when an update is available; click once to download, click again after download to restart/install.
|
||||
- Update channel selection:
|
||||
- Stable builds (`X.Y.Z`) only accept stable updates.
|
||||
- Prerelease builds (for example `X.Y.Z-nightly.N`) stay on that prerelease track and ignore stable or differently-tagged prerelease releases.
|
||||
- Provider: GitHub Releases (`provider: github`) configured at build time.
|
||||
- Repository slug source:
|
||||
- `T3CODE_DESKTOP_UPDATE_REPOSITORY` (format `owner/repo`), if set.
|
||||
|
||||
@@ -40,6 +40,10 @@
|
||||
"typecheck": "turbo run typecheck",
|
||||
"lint": "oxlint --report-unused-disable-directives",
|
||||
"test": "turbo run test",
|
||||
"test:perf:server": "cd apps/server && bun run test:perf",
|
||||
"test:perf:web": "turbo run build --filter=@t3tools/web && turbo run build --filter=t3 && cd apps/web && bun run test:perf",
|
||||
"perf:open": "node scripts/open-perf-app.ts",
|
||||
"perf:open:build": "turbo run build --filter=@t3tools/web && turbo run build --filter=t3 && node scripts/open-perf-app.ts",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"fmt:check": "oxfmt --check",
|
||||
|
||||
@@ -8,14 +8,12 @@ type EditorDefinition = {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly commands: readonly [string, ...string[]] | null;
|
||||
readonly baseArgs?: readonly string[];
|
||||
readonly launchStyle: EditorLaunchStyle;
|
||||
};
|
||||
|
||||
export const EDITORS = [
|
||||
{ id: "cursor", label: "Cursor", commands: ["cursor"], launchStyle: "goto" },
|
||||
{ id: "trae", label: "Trae", commands: ["trae"], launchStyle: "goto" },
|
||||
{ id: "kiro", label: "Kiro", commands: ["kiro"], baseArgs: ["ide"], launchStyle: "goto" },
|
||||
{ id: "vscode", label: "VS Code", commands: ["code"], launchStyle: "goto" },
|
||||
{
|
||||
id: "vscode-insiders",
|
||||
|
||||
@@ -59,6 +59,14 @@
|
||||
"./qrCode": {
|
||||
"types": "./src/qrCode.ts",
|
||||
"import": "./src/qrCode.ts"
|
||||
},
|
||||
"./perf/scenarioCatalog": {
|
||||
"types": "./src/perf/scenarioCatalog.ts",
|
||||
"import": "./src/perf/scenarioCatalog.ts"
|
||||
},
|
||||
"./perf/artifact": {
|
||||
"types": "./src/perf/artifact.ts",
|
||||
"import": "./src/perf/artifact.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -3,11 +3,8 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
applyGitStatusStreamEvent,
|
||||
buildTemporaryWorktreeBranchName,
|
||||
isTemporaryWorktreeBranch,
|
||||
normalizeGitRemoteUrl,
|
||||
parseGitHubRepositoryNameWithOwnerFromRemoteUrl,
|
||||
WORKTREE_BRANCH_PREFIX,
|
||||
} from "./git";
|
||||
|
||||
describe("normalizeGitRemoteUrl", () => {
|
||||
@@ -53,24 +50,6 @@ describe("parseGitHubRepositoryNameWithOwnerFromRemoteUrl", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTemporaryWorktreeBranch", () => {
|
||||
it("matches the generated temporary worktree branch format", () => {
|
||||
expect(isTemporaryWorktreeBranch(buildTemporaryWorktreeBranchName())).toBe(true);
|
||||
});
|
||||
|
||||
it("matches generated temporary worktree branches", () => {
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef`)).toBe(true);
|
||||
expect(isTemporaryWorktreeBranch(` ${WORKTREE_BRANCH_PREFIX}/deadbeef `)).toBe(true);
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/DEADBEEF`)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects non-temporary branch names", () => {
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/feature/demo`)).toBe(false);
|
||||
expect(isTemporaryWorktreeBranch("main")).toBe(false);
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef-extra`)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyGitStatusStreamEvent", () => {
|
||||
it("treats a remote-only update as a repository when local state is missing", () => {
|
||||
const remote: GitStatusRemoteResult = {
|
||||
|
||||
@@ -6,11 +6,6 @@ import type {
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Random from "effect/Random";
|
||||
|
||||
export const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
|
||||
/**
|
||||
* Sanitize an arbitrary string into a valid, lowercase git branch fragment.
|
||||
@@ -85,15 +80,6 @@ export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
|
||||
return branchName.slice(firstSeparatorIndex + 1);
|
||||
}
|
||||
|
||||
export function buildTemporaryWorktreeBranchName(): string {
|
||||
const token = Effect.runSync(Random.nextUUIDv4).replace(/-/g, "").slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
|
||||
export function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a git remote URL into a stable comparison key.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
|
||||
export interface PerfLatencySample {
|
||||
readonly name: string;
|
||||
readonly durationMs: number;
|
||||
readonly startedAt: string;
|
||||
readonly endedAt: string;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface PerfLatencySummary {
|
||||
readonly count: number;
|
||||
readonly minMs: number | null;
|
||||
readonly avgMs: number | null;
|
||||
readonly p50Ms: number | null;
|
||||
readonly p95Ms: number | null;
|
||||
readonly maxMs: number | null;
|
||||
}
|
||||
|
||||
export function percentile(values: ReadonlyArray<number>, target: number): number | null {
|
||||
if (values.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const sorted = values.toSorted((left, right) => left - right);
|
||||
const clampedTarget = Math.min(Math.max(target, 0), 1);
|
||||
const index = Math.min(
|
||||
sorted.length - 1,
|
||||
Math.max(0, Math.ceil(sorted.length * clampedTarget) - 1),
|
||||
);
|
||||
return sorted[index] ?? null;
|
||||
}
|
||||
|
||||
export function summarizeLatencyValues(values: ReadonlyArray<number>): PerfLatencySummary {
|
||||
if (values.length === 0) {
|
||||
return {
|
||||
count: 0,
|
||||
minMs: null,
|
||||
avgMs: null,
|
||||
p50Ms: null,
|
||||
p95Ms: null,
|
||||
maxMs: null,
|
||||
};
|
||||
}
|
||||
|
||||
const minMs = values.reduce((currentMin, value) => Math.min(currentMin, value), values[0]!);
|
||||
const maxMs = values.reduce((currentMax, value) => Math.max(currentMax, value), values[0]!);
|
||||
const avgMs = values.reduce((sum, value) => sum + value, 0) / values.length;
|
||||
|
||||
return {
|
||||
count: values.length,
|
||||
minMs,
|
||||
avgMs,
|
||||
p50Ms: percentile(values, 0.5),
|
||||
p95Ms: percentile(values, 0.95),
|
||||
maxMs,
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeLatencySamples(
|
||||
samples: ReadonlyArray<PerfLatencySample>,
|
||||
): PerfLatencySummary {
|
||||
return summarizeLatencyValues(samples.map((sample) => sample.durationMs));
|
||||
}
|
||||
|
||||
export async function writeJsonArtifact<TArtifact extends object>(
|
||||
outputPath: string,
|
||||
artifact: TArtifact,
|
||||
): Promise<void> {
|
||||
const resolvedOutputPath = resolve(outputPath);
|
||||
await mkdir(dirname(resolvedOutputPath), { recursive: true });
|
||||
await writeFile(`${resolvedOutputPath}`, `${JSON.stringify(artifact, null, 2)}\n`, "utf8");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,10 +2,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
extractPathFromShellOutput,
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readEnvironmentFromLoginShell,
|
||||
readPathFromLaunchctl,
|
||||
readPathFromLoginShell,
|
||||
} from "./shell";
|
||||
|
||||
@@ -63,38 +60,6 @@ describe("readPathFromLoginShell", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("readPathFromLaunchctl", () => {
|
||||
it("returns a trimmed PATH value from launchctl", () => {
|
||||
const execFile = vi.fn<
|
||||
(
|
||||
file: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: { encoding: "utf8"; timeout: number },
|
||||
) => string
|
||||
>(() => " /opt/homebrew/bin:/usr/bin \n");
|
||||
|
||||
expect(readPathFromLaunchctl(execFile)).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(execFile).toHaveBeenCalledWith("/bin/launchctl", ["getenv", "PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 2000,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns undefined when launchctl is unavailable", () => {
|
||||
const execFile = vi.fn<
|
||||
(
|
||||
file: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: { encoding: "utf8"; timeout: number },
|
||||
) => string
|
||||
>(() => {
|
||||
throw new Error("spawn /bin/launchctl ENOENT");
|
||||
});
|
||||
|
||||
expect(readPathFromLaunchctl(execFile)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("readEnvironmentFromLoginShell", () => {
|
||||
it("extracts multiple environment variables from a login shell command", () => {
|
||||
const execFile = vi.fn<
|
||||
@@ -161,30 +126,3 @@ describe("readEnvironmentFromLoginShell", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("listLoginShellCandidates", () => {
|
||||
it("returns env shell, user shell, then the platform fallback without duplicates", () => {
|
||||
expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
|
||||
"/opt/homebrew/bin/nu",
|
||||
"/bin/zsh",
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to the platform default when no shells are available", () => {
|
||||
expect(listLoginShellCandidates("linux", undefined, "")).toEqual(["/bin/bash"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergePathEntries", () => {
|
||||
it("prefers login-shell PATH entries and keeps inherited extras", () => {
|
||||
expect(
|
||||
mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
|
||||
).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
});
|
||||
|
||||
it("uses the platform-specific delimiter", () => {
|
||||
expect(mergePathEntries("C:\\Tools;C:\\Windows", "C:\\Windows;C:\\Git", "win32")).toBe(
|
||||
"C:\\Tools;C:\\Windows;C:\\Git",
|
||||
);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user