Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc4ee0b932 | ||
|
|
d3d096c6f7 | ||
|
|
c9b07d665d | ||
|
|
2e42f3fdf6 | ||
|
|
008ac5c3e5 | ||
|
|
9dcea68bce | ||
|
|
5f7ec73a22 | ||
|
|
569fea87a9 | ||
|
|
33dadb5aec | ||
|
|
d18e43b674 | ||
|
|
6f699346e4 | ||
|
|
f5ecca4480 | ||
|
|
cadd708646 | ||
|
|
5f7becf386 | ||
|
|
9b29be916b | ||
|
|
047a0a697c | ||
|
|
77fcad3586 | ||
|
|
801b83e937 | ||
|
|
f2205bdc42 | ||
|
|
1bf048eb8b | ||
|
|
f7fa62aaf9 | ||
|
|
57d7746a5d | ||
|
|
850c912556 | ||
|
|
dff8784aef | ||
|
|
96c9306dbd | ||
|
|
94d13a2b75 | ||
|
|
7a008461fc | ||
|
|
f59ee36bf1 | ||
|
|
2fce84a1d4 | ||
|
|
f9019cd63f | ||
|
|
f9372a4c3d | ||
|
|
934037cb66 | ||
|
|
5467d11980 | ||
|
|
1f4a3f65bf | ||
|
|
26cc1fffb3 | ||
|
|
97880e8870 | ||
|
|
b80e8476b8 | ||
|
|
e0e01b4a54 | ||
|
|
58e5f714b0 | ||
|
|
4ae9de311b | ||
|
|
5fa09fa2d9 | ||
|
|
12c3af7821 | ||
|
|
e2316814da | ||
|
|
678f827f0b |
No files matched your search
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
@@ -50,6 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `commandPalette.toggle`: open or close the global command palette
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
|
||||
@@ -49,6 +49,14 @@ Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Before local development, prepare the environment and install dependencies:
|
||||
|
||||
```bash
|
||||
# Optional: only needed if you use mise for dev tool management.
|
||||
mise install
|
||||
bun install .
|
||||
```
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -36,6 +36,57 @@ describe("resolveDesktopBackendPort", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number, host: string) => {
|
||||
if (port === 3773 && host === "127.0.0.1") return true;
|
||||
if (port === 3773 && host === "0.0.0.0") return false;
|
||||
return port === 3774;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0"],
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3774);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3774, "0.0.0.0"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("checks overlapping hosts sequentially to avoid self-interference", async () => {
|
||||
let inFlightCount = 0;
|
||||
const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
|
||||
inFlightCount += 1;
|
||||
const overlapped = inFlightCount > 1;
|
||||
await Promise.resolve();
|
||||
inFlightCount -= 1;
|
||||
return !overlapped;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0", "::"],
|
||||
startPort: 3773,
|
||||
maxPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3773, "::"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when the scan range is exhausted", async () => {
|
||||
const canListenOnHost = vi.fn(async () => false);
|
||||
|
||||
@@ -46,7 +97,9 @@ describe("resolveDesktopBackendPort", () => {
|
||||
maxPort: 65535,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
|
||||
).rejects.toThrow(
|
||||
"No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
|
||||
);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[65534, "127.0.0.1"],
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface ResolveDesktopBackendPortOptions {
|
||||
readonly host: string;
|
||||
readonly startPort?: number;
|
||||
readonly maxPort?: number;
|
||||
readonly requiredHosts?: ReadonlyArray<string>;
|
||||
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
@@ -21,10 +22,37 @@ const defaultCanListenOnHost = async (port: number, host: string): Promise<boole
|
||||
const isValidPort = (port: number): boolean =>
|
||||
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
|
||||
|
||||
const normalizeHosts = (
|
||||
host: string,
|
||||
requiredHosts: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> =>
|
||||
Array.from(
|
||||
new Set(
|
||||
[host, ...requiredHosts]
|
||||
.map((candidate) => candidate.trim())
|
||||
.filter((candidate) => candidate.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
async function canListenOnAllHosts(
|
||||
port: number,
|
||||
hosts: ReadonlyArray<string>,
|
||||
canListenOnHost: (port: number, host: string) => Promise<boolean>,
|
||||
): Promise<boolean> {
|
||||
for (const candidateHost of hosts) {
|
||||
if (!(await canListenOnHost(port, candidateHost))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function resolveDesktopBackendPort({
|
||||
host,
|
||||
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
maxPort = MAX_TCP_PORT,
|
||||
requiredHosts = [],
|
||||
canListenOnHost = defaultCanListenOnHost,
|
||||
}: ResolveDesktopBackendPortOptions): Promise<number> {
|
||||
if (!isValidPort(startPort)) {
|
||||
@@ -39,15 +67,17 @@ export async function resolveDesktopBackendPort({
|
||||
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
|
||||
}
|
||||
|
||||
const hostsToCheck = normalizeHosts(host, requiredHosts);
|
||||
|
||||
// Keep desktop startup predictable across app restarts by probing upward from
|
||||
// the same preferred port instead of picking a fresh ephemeral port.
|
||||
for (let port = startPort; port <= maxPort; port += 1) {
|
||||
if (await canListenOnHost(port, host)) {
|
||||
if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
|
||||
`No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
} from "./backendReadiness";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend reports a successful session endpoint", async () => {
|
||||
it("returns once the backend serves the requested readiness path", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
@@ -20,6 +20,11 @@ describe("waitForHttpReady", () => {
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("retries after a readiness request stalls past the per-request timeout", async () => {
|
||||
@@ -80,4 +85,30 @@ describe("waitForHttpReady", () => {
|
||||
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
|
||||
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
|
||||
});
|
||||
|
||||
it("supports custom readiness predicates", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
path: "/api/healthz",
|
||||
isReady: (response) => response.status === 204,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,11 @@ export interface WaitForHttpReadyOptions {
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly fetchImpl?: typeof fetch;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly path?: string;
|
||||
readonly isReady?: (response: Response) => boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_INTERVAL_MS = 100;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
|
||||
|
||||
@@ -57,6 +59,8 @@ export async function waitForHttpReady(
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
|
||||
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
const readinessPath = options?.path ?? "/";
|
||||
const isReady = options?.isReady ?? ((response: Response) => response.ok);
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
for (;;) {
|
||||
@@ -74,11 +78,11 @@ export async function waitForHttpReady(
|
||||
signal?.addEventListener("abort", abortRequest, { once: true });
|
||||
|
||||
try {
|
||||
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
|
||||
const response = await fetchImpl(new URL(readinessPath, baseUrl).toString(), {
|
||||
redirect: "manual",
|
||||
signal: requestController.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
if (isReady(response)) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
+198
-35
@@ -7,6 +7,7 @@ import * as Path from "node:path";
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
type BrowserWindowConstructorOptions,
|
||||
clipboard,
|
||||
dialog,
|
||||
ipcMain,
|
||||
@@ -54,6 +55,7 @@ import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
@@ -100,7 +102,7 @@ const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
||||
@@ -117,6 +119,16 @@ 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;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
BrowserWindowConstructorOptions,
|
||||
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
|
||||
>;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
type LinuxDesktopNamedApp = Electron.App & {
|
||||
@@ -133,6 +145,8 @@ let backendWsUrl = "";
|
||||
let backendEndpointUrl: string | null = null;
|
||||
let backendAdvertisedHost: string | null = null;
|
||||
let backendReadinessAbortController: AbortController | null = null;
|
||||
let backendInitialWindowOpenInFlight: Promise<void> | null = null;
|
||||
let backendListeningDetector: ServerListeningDetector | null = null;
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
@@ -351,13 +365,17 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
|
||||
async function waitForBackendHttpReady(
|
||||
baseUrl: string,
|
||||
options?: Parameters<typeof waitForHttpReady>[1],
|
||||
): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
const controller = new AbortController();
|
||||
backendReadinessAbortController = controller;
|
||||
|
||||
try {
|
||||
await waitForHttpReady(baseUrl, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
@@ -372,6 +390,88 @@ function cancelBackendReadinessWait(): void {
|
||||
backendReadinessAbortController = null;
|
||||
}
|
||||
|
||||
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
const listeningPromise = backendListeningDetector?.promise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
cancelBackendReadinessWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function ensureInitialBackendWindowOpen(): void {
|
||||
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0] ?? null;
|
||||
if (isDevelopment || existingWindow !== null || backendInitialWindowOpenInFlight !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextOpen = waitForBackendWindowReady(backendHttpUrl)
|
||||
.then((source) => {
|
||||
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
|
||||
if (mainWindow ?? BrowserWindow.getAllWindows()[0]) {
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
|
||||
);
|
||||
console.warn("[desktop] backend readiness check timed out during packaged bootstrap", error);
|
||||
})
|
||||
.finally(() => {
|
||||
if (backendInitialWindowOpenInFlight === nextOpen) {
|
||||
backendInitialWindowOpenInFlight = null;
|
||||
}
|
||||
});
|
||||
|
||||
backendInitialWindowOpenInFlight = nextOpen;
|
||||
}
|
||||
|
||||
function writeDesktopStreamChunk(
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: unknown,
|
||||
@@ -449,14 +549,16 @@ function initializePackagedLogging(): void {
|
||||
}
|
||||
|
||||
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
if (!app.isPackaged || backendLogSink === null) return;
|
||||
const writeChunk = (chunk: unknown): void => {
|
||||
if (!backendLogSink) return;
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink.write(buffer);
|
||||
const attachStream = (stream: NodeJS.ReadableStream | null | undefined): void => {
|
||||
stream?.on("data", (chunk: unknown) => {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink?.write(buffer);
|
||||
backendListeningDetector?.push(buffer);
|
||||
});
|
||||
};
|
||||
child.stdout?.on("data", writeChunk);
|
||||
child.stderr?.on("data", writeChunk);
|
||||
|
||||
attachStream(child.stdout);
|
||||
attachStream(child.stderr);
|
||||
}
|
||||
|
||||
initializePackagedLogging();
|
||||
@@ -1211,7 +1313,7 @@ function startBackend(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const captureBackendLogs = !isDevelopment;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
@@ -1248,6 +1350,8 @@ function startBackend(): void {
|
||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
||||
return;
|
||||
}
|
||||
const listeningDetector = new ServerListeningDetector();
|
||||
backendListeningDetector = listeningDetector;
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
@@ -1266,6 +1370,10 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(error);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1278,6 +1386,14 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(
|
||||
new Error(
|
||||
`backend exited before logging readiness (code=${code ?? "null"} signal=${signal ?? "null"})`,
|
||||
),
|
||||
);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1289,10 +1405,13 @@ function startBackend(): void {
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
});
|
||||
|
||||
ensureInitialBackendWindowOpen();
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
cancelBackendReadinessWait();
|
||||
backendListeningDetector = null;
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1648,19 +1767,58 @@ function getInitialWindowBackgroundColor(): string {
|
||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
titleBarStyle: "hidden",
|
||||
titleBarOverlay: {
|
||||
color: TITLEBAR_COLOR,
|
||||
height: TITLEBAR_HEIGHT,
|
||||
symbolColor: nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function syncWindowAppearance(window: BrowserWindow): void {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor());
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions();
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
}
|
||||
|
||||
function syncAllWindowAppearance(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
syncWindowAppearance(window);
|
||||
}
|
||||
}
|
||||
|
||||
nativeTheme.on("updated", syncAllWindowAppearance);
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: isDevelopment,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
...getWindowTitleBarOptions(),
|
||||
webPreferences: {
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
@@ -1695,6 +1853,14 @@ function createWindow(): BrowserWindow {
|
||||
);
|
||||
}
|
||||
|
||||
if (params.mediaType === "image") {
|
||||
menuTemplate.push({
|
||||
label: "Copy Image",
|
||||
click: () => window.webContents.copyImageAt(params.x, params.y),
|
||||
});
|
||||
menuTemplate.push({ type: "separator" });
|
||||
}
|
||||
|
||||
menuTemplate.push(
|
||||
{ role: "cut", enabled: params.editFlags.canCut },
|
||||
{ role: "copy", enabled: params.editFlags.canCopy },
|
||||
@@ -1721,20 +1887,23 @@ function createWindow(): BrowserWindow {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
if (!isDevelopment) {
|
||||
window.once("ready-to-show", () => {
|
||||
revealWindow(window);
|
||||
});
|
||||
}
|
||||
|
||||
let initialRevealScheduled = false;
|
||||
const revealInitialWindow = () => {
|
||||
if (initialRevealScheduled) {
|
||||
return;
|
||||
}
|
||||
initialRevealScheduled = true;
|
||||
revealWindow(window);
|
||||
};
|
||||
|
||||
window.once("ready-to-show", revealInitialWindow);
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
setImmediate(() => {
|
||||
revealWindow(window);
|
||||
});
|
||||
} else {
|
||||
void window.loadURL(resolveDesktopWindowUrl());
|
||||
void window.loadURL(backendHttpUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -1746,14 +1915,6 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
function resolveDesktopWindowUrl(): string {
|
||||
if (backendHttpUrl) {
|
||||
return backendHttpUrl;
|
||||
}
|
||||
|
||||
return `${DESKTOP_SCHEME}://app`;
|
||||
}
|
||||
|
||||
// Override Electron's userData path before the `ready` event so that
|
||||
// Chromium session data uses a filesystem-friendly directory name.
|
||||
// Must be called synchronously at the top level — before `app.whenReady()`.
|
||||
@@ -1773,6 +1934,7 @@ async function bootstrap(): Promise<void> {
|
||||
(await resolveDesktopBackendPort({
|
||||
host: DESKTOP_LOOPBACK_HOST,
|
||||
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS,
|
||||
}));
|
||||
writeDesktopLogHeader(
|
||||
configuredBackendPort === undefined
|
||||
@@ -1826,10 +1988,7 @@ async function bootstrap(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
await waitForBackendHttpReady(backendHttpUrl);
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
ensureInitialBackendWindowOpen();
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
@@ -1863,7 +2022,11 @@ app
|
||||
revealWindow(existingWindow);
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
return;
|
||||
}
|
||||
ensureInitialBackendWindowOpen();
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
|
||||
describe("ServerListeningDetector", () => {
|
||||
it("resolves when the server logs the listening line", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listening on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves when the listening line arrives across multiple chunks", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listen");
|
||||
detector.push("ing on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects when the server exits before logging readiness", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
const error = new Error("server exited");
|
||||
|
||||
detector.fail(error);
|
||||
|
||||
await expect(detector.promise).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
const LISTENING_LOG_FRAGMENT = "Listening on http://";
|
||||
const MAX_BUFFER_CHARS = 8_192;
|
||||
|
||||
export class ServerListeningDetector {
|
||||
private buffer = "";
|
||||
private settled = false;
|
||||
private readonly resolvePromise: () => void;
|
||||
private readonly rejectPromise: (error: unknown) => void;
|
||||
readonly promise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
let resolvePromise: (() => void) | null = null;
|
||||
let rejectPromise: ((error: unknown) => void) | null = null;
|
||||
|
||||
this.promise = new Promise<void>((resolve, reject) => {
|
||||
resolvePromise = resolve;
|
||||
rejectPromise = reject;
|
||||
});
|
||||
|
||||
this.resolvePromise = () => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
resolvePromise?.();
|
||||
};
|
||||
this.rejectPromise = (error) => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
rejectPromise?.(error);
|
||||
};
|
||||
}
|
||||
|
||||
push(chunk: unknown): void {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
|
||||
this.buffer = `${this.buffer}${text.replace(/\r/g, "")}`;
|
||||
if (this.buffer.includes(LISTENING_LOG_FRAGMENT)) {
|
||||
this.resolvePromise();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.buffer.length > MAX_BUFFER_CHARS) {
|
||||
this.buffer = this.buffer.slice(-MAX_BUFFER_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
fail(error: unknown): void {
|
||||
this.rejectPromise(error);
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,12 @@ describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
HOMEBREW_PREFIX: "/opt/homebrew",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
@@ -18,9 +19,18 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
expect(env.HOMEBREW_PREFIX).toBe("/opt/homebrew");
|
||||
});
|
||||
|
||||
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
||||
@@ -77,11 +87,67 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing does not return one", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => ({}));
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "darwin",
|
||||
readEnvironment,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(2, "/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read login shell environment from /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
|
||||
@@ -1,36 +1,79 @@
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const;
|
||||
|
||||
function logShellEnvironmentWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[desktop] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
options: {
|
||||
platform?: NodeJS.Platform;
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
|
||||
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
|
||||
const shellEnvironment: Partial<Record<string, string>> = {};
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
|
||||
if (shellEnvironment.PATH) {
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read login shell environment from ${shell}.`, error);
|
||||
}
|
||||
}
|
||||
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
]);
|
||||
|
||||
if (shellEnvironment.PATH) {
|
||||
env.PATH = shellEnvironment.PATH;
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellEnvironment.PATH
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellEnvironment.PATH ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
|
||||
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
||||
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
} catch {
|
||||
// Keep inherited environment if shell lookup fails.
|
||||
|
||||
for (const name of [
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const) {
|
||||
if (!env[name] && shellEnvironment[name]) {
|
||||
env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to synchronize the desktop shell environment.", error);
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,10 @@ import {
|
||||
AuthError,
|
||||
type ServerAuthShape,
|
||||
} from "../Services/ServerAuth.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
|
||||
|
||||
type BootstrapExchangeResult = {
|
||||
@@ -65,6 +68,13 @@ export const makeServerAuth = Effect.gen(function* () {
|
||||
|
||||
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause: SessionCredentialError) =>
|
||||
Effect.logWarning("Rejected authenticated session credential.").pipe(
|
||||
Effect.annotateLogs({
|
||||
reason: cause.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
|
||||
@@ -33,10 +33,12 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -66,6 +68,7 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("loopback-browser");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
|
||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
||||
import { resolveSessionCookieName } from "../utils.ts";
|
||||
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
|
||||
|
||||
export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
@@ -30,7 +30,10 @@ export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
policy,
|
||||
bootstrapMethods,
|
||||
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
|
||||
sessionCookieName: SESSION_COOKIE_NAME,
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -2,10 +2,10 @@ import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "
|
||||
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
|
||||
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
|
||||
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
resolveSessionCookieName,
|
||||
signPayload,
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../utils.ts";
|
||||
@@ -81,11 +82,16 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
|
||||
}
|
||||
|
||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
});
|
||||
|
||||
const toSessionCredentialError = (message: string) => (cause: unknown) =>
|
||||
new SessionCredentialError({
|
||||
@@ -472,7 +478,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
cookieName: SESSION_COOKIE_NAME,
|
||||
cookieName,
|
||||
issue,
|
||||
verify,
|
||||
issueWebSocketToken,
|
||||
|
||||
@@ -2,7 +2,18 @@ import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
export const SESSION_COOKIE_NAME = "t3_session";
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
|
||||
|
||||
@@ -82,10 +82,15 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -136,10 +141,15 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -24,6 +24,7 @@ export interface ServerDerivedPaths {
|
||||
readonly dbPath: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly settingsPath: string;
|
||||
readonly providerStatusCacheDir: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly logsDir: string;
|
||||
@@ -76,11 +77,13 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
const providerLogsDir = join(logsDir, "provider");
|
||||
const providerStatusCacheDir = join(baseDir, "caches");
|
||||
return {
|
||||
stateDir,
|
||||
dbPath,
|
||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||
settingsPath: join(stateDir, "settings.json"),
|
||||
providerStatusCacheDir,
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
@@ -110,6 +113,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
|
||||
],
|
||||
|
||||
@@ -40,6 +40,24 @@ function writeTextFile(
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectory(
|
||||
dirPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
|
||||
/** Run a raw git command for test setup (not under test). */
|
||||
function git(
|
||||
cwd: string,
|
||||
@@ -299,6 +317,21 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns isRepo: false for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
|
||||
const result = yield* (yield* GitCore).listBranches({ cwd: deletedDir });
|
||||
|
||||
expect(result.isRepo).toBe(false);
|
||||
expect(result.hasOriginRemote).toBe(false);
|
||||
expect(result.branches).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the current branch with current: true", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -793,7 +826,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
|
||||
it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
@@ -812,7 +845,9 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
@@ -823,10 +858,22 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
expect(input.cwd).toBe("/repo");
|
||||
expect(input.args).toEqual([
|
||||
"--git-dir",
|
||||
"/repo/.git",
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
]);
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
@@ -853,70 +900,80 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
it.effect(
|
||||
"briefly backs off failed upstream refreshes across sibling worktrees on one remote",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "origin/feature/pr-123\n"
|
||||
: "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when branch does not exist", () =>
|
||||
@@ -1014,7 +1071,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
remoteName,
|
||||
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
@@ -1626,6 +1682,37 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a non-repo status for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
const core = yield* GitCore;
|
||||
|
||||
const status = yield* core.statusDetails(deletedDir);
|
||||
const localStatus = yield* core.statusDetailsLocal(deletedDir);
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
expect(localStatus).toEqual(status);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
type ExecuteGitProgress,
|
||||
type GitCommitOptions,
|
||||
type GitCoreShape,
|
||||
type GitStatusDetails,
|
||||
type ExecuteGitInput,
|
||||
type ExecuteGitResult,
|
||||
} from "../Services/GitCore.ts";
|
||||
@@ -59,17 +60,27 @@ const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
|
||||
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
|
||||
const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitStatusDetails>({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
remainder: string;
|
||||
};
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
class StatusRemoteRefreshCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
upstreamRef: string;
|
||||
remoteName: string;
|
||||
upstreamBranch: string;
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
@@ -359,6 +370,16 @@ function quoteGitCommand(args: ReadonlyArray<string>): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function isMissingGitCwdError(error: GitCommandError): boolean {
|
||||
const normalized = `${error.detail}\n${error.message}`.toLowerCase();
|
||||
return (
|
||||
normalized.includes("no such file or directory") ||
|
||||
normalized.includes("notfound: filesystem.access") ||
|
||||
normalized.includes("enoent") ||
|
||||
normalized.includes("not a directory")
|
||||
);
|
||||
}
|
||||
|
||||
function toGitCommandError(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
detail: string,
|
||||
@@ -896,17 +917,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
);
|
||||
});
|
||||
|
||||
const fetchUpstreamRefForStatus = (
|
||||
const fetchRemoteForStatus = (
|
||||
gitCommonDir: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
remoteName: string,
|
||||
): Effect.Effect<void, GitCommandError> => {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
const fetchCwd =
|
||||
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
|
||||
return executeGit(
|
||||
"GitCore.fetchUpstreamRefForStatus",
|
||||
"GitCore.fetchRemoteForStatus",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
@@ -922,18 +942,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
|
||||
});
|
||||
|
||||
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
|
||||
cacheKey: StatusUpstreamRefreshCacheKey,
|
||||
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
|
||||
cacheKey: StatusRemoteRefreshCacheKey,
|
||||
) {
|
||||
yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
|
||||
upstreamRef: cacheKey.upstreamRef,
|
||||
remoteName: cacheKey.remoteName,
|
||||
upstreamBranch: cacheKey.upstreamBranch,
|
||||
});
|
||||
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
|
||||
return true as const;
|
||||
});
|
||||
|
||||
const statusUpstreamRefreshCache = yield* Cache.makeWith(refreshStatusUpstreamCacheEntry, {
|
||||
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
|
||||
timeToLive: (exit) =>
|
||||
@@ -949,12 +965,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
if (!upstream) return;
|
||||
const gitCommonDir = yield* resolveGitCommonDir(cwd);
|
||||
yield* Cache.get(
|
||||
statusUpstreamRefreshCache,
|
||||
new StatusUpstreamRefreshCacheKey({
|
||||
statusRemoteRefreshCache,
|
||||
new StatusRemoteRefreshCacheKey({
|
||||
gitCommonDir,
|
||||
upstreamRef: upstream.upstreamRef,
|
||||
remoteName: upstream.remoteName,
|
||||
upstreamBranch: upstream.upstreamBranch,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1190,7 +1204,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
|
||||
|
||||
if (statusResult === null) {
|
||||
return NON_REPOSITORY_STATUS_DETAILS;
|
||||
}
|
||||
|
||||
if (statusResult.code !== 0) {
|
||||
const stderr = statusResult.stderr.trim();
|
||||
@@ -1322,7 +1340,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
);
|
||||
|
||||
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
return yield* readStatusDetailsLocal(cwd);
|
||||
});
|
||||
|
||||
@@ -1719,6 +1740,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () =>
|
||||
Effect.succeed({
|
||||
code: 128,
|
||||
stdout: "",
|
||||
stderr: "fatal: not a git repository",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (localBranchResult.code !== 0) {
|
||||
|
||||
@@ -76,6 +76,105 @@ layer("GitHubCliLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("trims pull request fields decoded from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: " Add PR thread creation \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/pr-threads\t",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: " octocat/codething-mvp ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " octocat ",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
number: 42,
|
||||
title: "Add PR thread creation",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-threads",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing pr lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 43,
|
||||
title: " Valid PR ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: " feature/pr-list ",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 43,
|
||||
title: "Valid PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/43",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-list",
|
||||
state: "open",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Effect, Layer, Schema, SchemaIssue } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { GitHubCliError } from "@t3tools/contracts";
|
||||
@@ -7,8 +7,12 @@ import {
|
||||
GitHubCli,
|
||||
type GitHubRepositoryCloneUrls,
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
} from "../Services/GitHubCli.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
@@ -63,76 +67,12 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const mergedAt = input.mergedAt;
|
||||
const state = input.state;
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
return "merged";
|
||||
}
|
||||
if (state === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
const RawGitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
function normalizePullRequestSummary(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
|
||||
): GitHubPullRequestSummary {
|
||||
const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
|
||||
const headRepositoryOwnerLogin =
|
||||
raw.headRepositoryOwner?.login ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizePullRequestState(raw),
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
|
||||
): GitHubRepositoryCloneUrls {
|
||||
@@ -194,14 +134,24 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: decodeGitHubJson(
|
||||
raw,
|
||||
Schema.Array(RawGitHubPullRequestSchema),
|
||||
"listOpenPullRequests",
|
||||
"GitHub CLI returned invalid PR list JSON.",
|
||||
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
|
||||
),
|
||||
getPullRequest: (input) =>
|
||||
execute({
|
||||
@@ -216,14 +166,24 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitHubJson(
|
||||
raw,
|
||||
RawGitHubPullRequestSchema,
|
||||
"getPullRequest",
|
||||
"GitHub CLI returned invalid pull request JSON.",
|
||||
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "getPullRequest",
|
||||
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizePullRequestSummary),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
execute({
|
||||
|
||||
@@ -186,6 +186,24 @@ function makeTempDir(
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectory(
|
||||
dirPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
|
||||
function runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
@@ -694,6 +712,144 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status trims PR metadata returned by gh before publishing it", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-trimmed-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-trimmed-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 14,
|
||||
title: " Existing PR title \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/14 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/status-trimmed-pr\t",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 14,
|
||||
title: "Existing PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-trimmed-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-valid-pr-entry"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-valid-pr-entry"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 15,
|
||||
title: " Valid PR title ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/15 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/status-valid-pr-entry\t",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 15,
|
||||
title: "Valid PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-valid-pr-entry",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status preserves lowercase merged and closed PR states from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-lowercase-state"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-lowercase-state"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 16,
|
||||
title: "Closed PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/16",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-lowercase-state",
|
||||
state: "closed",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
updatedAt: "2026-01-02T00:00:00.000Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns an explicit non-repo result for non-git directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
|
||||
@@ -720,6 +876,35 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns an explicit non-repo result for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-");
|
||||
const cwd = path.join(rootDir, "deleted-repo");
|
||||
yield* makeDirectory(cwd);
|
||||
yield* removePath(cwd);
|
||||
const { manager } = yield* makeManager();
|
||||
|
||||
const status = yield* manager.status({ cwd });
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status briefly caches repeated lookups for the same cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -1,7 +1,18 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import { Cache, Duration, Effect, Exit, FileSystem, Layer, Option, Path, Ref } from "effect";
|
||||
import {
|
||||
Cache,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
Ref,
|
||||
Result,
|
||||
} from "effect";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitActionProgressPhase,
|
||||
@@ -34,6 +45,10 @@ import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScr
|
||||
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import {
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
@@ -240,85 +255,6 @@ function matchesBranchHeadContext(
|
||||
return true;
|
||||
}
|
||||
|
||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: PullRequestInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
const state = record.state;
|
||||
const mergedAt = record.mergedAt;
|
||||
const updatedAt = record.updatedAt;
|
||||
const isCrossRepository = record.isCrossRepository;
|
||||
const headRepositoryRecord =
|
||||
typeof record.headRepository === "object" && record.headRepository !== null
|
||||
? (record.headRepository as Record<string, unknown>)
|
||||
: null;
|
||||
const headRepositoryOwnerRecord =
|
||||
typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null
|
||||
? (record.headRepositoryOwner as Record<string, unknown>)
|
||||
: null;
|
||||
const headRepositoryNameWithOwner =
|
||||
typeof record.headRepositoryNameWithOwner === "string"
|
||||
? record.headRepositoryNameWithOwner
|
||||
: typeof headRepositoryRecord?.nameWithOwner === "string"
|
||||
? headRepositoryRecord.nameWithOwner
|
||||
: null;
|
||||
const headRepositoryOwnerLogin =
|
||||
typeof record.headRepositoryOwnerLogin === "string"
|
||||
? record.headRepositoryOwnerLogin
|
||||
: typeof headRepositoryOwnerRecord?.login === "string"
|
||||
? headRepositoryOwnerRecord.login
|
||||
: null;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalizedState: "open" | "closed" | "merged";
|
||||
if (
|
||||
(typeof mergedAt === "string" && mergedAt.trim().length > 0) ||
|
||||
state === "MERGED" ||
|
||||
state === "merged"
|
||||
) {
|
||||
normalizedState = "merged";
|
||||
} else if (state === "OPEN" || state === "open" || state === undefined || state === null) {
|
||||
normalizedState = "open";
|
||||
} else if (state === "CLOSED" || state === "closed") {
|
||||
normalizedState = "closed";
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
state: normalizedState,
|
||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
|
||||
return {
|
||||
number: summary.number,
|
||||
@@ -947,13 +883,23 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
continue;
|
||||
}
|
||||
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||
});
|
||||
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
gitManagerError(
|
||||
"findLatestPr",
|
||||
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
decoded.failure,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for (const pr of parsePullRequestList(parsedJson)) {
|
||||
return Effect.succeed(decoded.success);
|
||||
}),
|
||||
);
|
||||
|
||||
for (const pr of pullRequests) {
|
||||
if (!matchesBranchHeadContext(pr, headContext)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { Cause, Exit, Result, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export interface NormalizedGitHubPullRequestRecord {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: string | null;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
const GitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
function trimOptionalString(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim() ?? "";
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const normalizedState = input.state?.trim().toUpperCase();
|
||||
if (
|
||||
(typeof input.mergedAt === "string" && input.mergedAt.trim().length > 0) ||
|
||||
normalizedState === "MERGED"
|
||||
) {
|
||||
return "merged";
|
||||
}
|
||||
if (normalizedState === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestRecord(
|
||||
raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
|
||||
): NormalizedGitHubPullRequestRecord {
|
||||
const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
|
||||
const headRepositoryOwnerLogin =
|
||||
trimOptionalString(raw.headRepositoryOwner?.login) ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizeGitHubPullRequestState(raw),
|
||||
updatedAt:
|
||||
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
|
||||
const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
|
||||
const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
|
||||
|
||||
export const formatGitHubJsonDecodeError = formatSchemaError;
|
||||
|
||||
export function decodeGitHubPullRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<
|
||||
ReadonlyArray<NormalizedGitHubPullRequestRecord>,
|
||||
Cause.Cause<Schema.SchemaError>
|
||||
> {
|
||||
const result = decodeGitHubPullRequestList(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
const pullRequests: NormalizedGitHubPullRequestRecord[] = [];
|
||||
for (const entry of result.success) {
|
||||
const decodedEntry = decodeGitHubPullRequestEntry(entry);
|
||||
if (Exit.isFailure(decodedEntry)) {
|
||||
continue;
|
||||
}
|
||||
pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value));
|
||||
}
|
||||
return Result.succeed(pullRequests);
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
|
||||
export function decodeGitHubPullRequestJson(
|
||||
raw: string,
|
||||
): Result.Result<NormalizedGitHubPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
|
||||
const result = decodeGitHubPullRequest(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
return Result.succeed(normalizeGitHubPullRequestRecord(result.success));
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
@@ -226,6 +226,7 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
|
||||
@@ -42,6 +42,16 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const kiroLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLaunch, {
|
||||
command: "kiro",
|
||||
args: ["ide", "/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -122,6 +132,16 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const kiroLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLineAndColumn, {
|
||||
command: "kiro",
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -354,6 +374,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "kiro.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
@@ -361,7 +382,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, ["trae", "kiro", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
+19
-6
@@ -75,6 +75,14 @@ function resolveCommandEditorArgs(
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
@@ -273,7 +281,7 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
|
||||
return {
|
||||
command,
|
||||
args: resolveCommandEditorArgs(editorDef, input.cwd),
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -293,11 +301,16 @@ export const launchDetached = (launch: EditorLaunch) =>
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const isWin32 = process.platform === "win32";
|
||||
child = spawn(
|
||||
launch.command,
|
||||
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
|
||||
{
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: isWin32,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
|
||||
@@ -144,10 +144,20 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.succeed(projectionSnapshot),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: projectionSnapshot.snapshotSequence,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: projectionSnapshot.updatedAt,
|
||||
}),
|
||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
|
||||
@@ -1505,6 +1505,329 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears stale pending approvals from projected shell summaries", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-stale-approval-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:00.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-stale-approval"),
|
||||
title: "Project Stale Approval",
|
||||
workspaceRoot: "/tmp/project-stale-approval",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:30:00.000Z",
|
||||
updatedAt: "2026-02-26T12:30:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-stale-approval-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:01.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-approval"),
|
||||
projectId: ProjectId.make("project-stale-approval"),
|
||||
title: "Thread Stale Approval",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:30:01.000Z",
|
||||
updatedAt: "2026-02-26T12:30:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-approval-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:02.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-approval-requested"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: {
|
||||
requestId: "approval-request-stale-1",
|
||||
requestKind: "command",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:30:02.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-approval-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:03.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-approval-failed"),
|
||||
tone: "error",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
payload: {
|
||||
requestId: "approval-request-stale-1",
|
||||
detail: "Unknown pending permission request: approval-request-stale-1",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:30:03.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly requestId: string;
|
||||
readonly status: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
request_id AS "requestId",
|
||||
status,
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id = 'approval-request-stale-1'
|
||||
`;
|
||||
assert.deepEqual(approvalRows, [
|
||||
{
|
||||
requestId: "approval-request-stale-1",
|
||||
status: "resolved",
|
||||
resolvedAt: "2026-02-26T12:30:03.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly pendingApprovalCount: number;
|
||||
}>`
|
||||
SELECT pending_approval_count AS "pendingApprovalCount"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-stale-approval'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [{ pendingApprovalCount: 0 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores non-stale provider approval response failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-nonstale-approval-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:00.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-nonstale-approval"),
|
||||
title: "Project Non-Stale Approval",
|
||||
workspaceRoot: "/tmp/project-nonstale-approval",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:45:00.000Z",
|
||||
updatedAt: "2026-02-26T12:45:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-nonstale-approval-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:01.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
projectId: ProjectId.make("project-nonstale-approval"),
|
||||
title: "Thread Non-Stale Approval",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:45:01.000Z",
|
||||
updatedAt: "2026-02-26T12:45:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-nonstale-approval-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:02.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-nonstale-approval-requested"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: {
|
||||
requestId: "approval-request-nonstale-existing",
|
||||
requestKind: "command",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:45:02.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-nonstale-approval-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:03.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-nonstale-approval-failed-existing"),
|
||||
tone: "error",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
payload: {
|
||||
requestId: "approval-request-nonstale-existing",
|
||||
detail: "Provider timed out while responding to approval request",
|
||||
},
|
||||
turnId: TurnId.make("turn-nonstale-failure"),
|
||||
createdAt: "2026-02-26T12:45:03.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-nonstale-approval-5"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:04.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-5"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-5"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-nonstale-approval-failed-missing"),
|
||||
tone: "error",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
payload: {
|
||||
requestId: "approval-request-nonstale-missing",
|
||||
detail: "Provider timed out while responding to approval request",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:45:04.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly requestId: string;
|
||||
readonly status: string;
|
||||
readonly turnId: string | null;
|
||||
readonly createdAt: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
request_id AS "requestId",
|
||||
status,
|
||||
turn_id AS "turnId",
|
||||
created_at AS "createdAt",
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id IN (
|
||||
'approval-request-nonstale-existing',
|
||||
'approval-request-nonstale-missing'
|
||||
)
|
||||
ORDER BY request_id
|
||||
`;
|
||||
assert.deepEqual(approvalRows, [
|
||||
{
|
||||
requestId: "approval-request-nonstale-existing",
|
||||
status: "pending",
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:45:02.000Z",
|
||||
resolvedAt: null,
|
||||
},
|
||||
]);
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly pendingApprovalCount: number;
|
||||
}>`
|
||||
SELECT pending_approval_count AS "pendingApprovalCount"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-nonstale-approval'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [{ pendingApprovalCount: 1 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not fallback-retain messages whose turnId is removed by revert", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -89,6 +90,88 @@ function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||
return typeof requestId === "string" ? ApprovalRequestId.make(requestId) : null;
|
||||
}
|
||||
|
||||
function isStalePendingApprovalFailureDetail(detail: string | null): boolean {
|
||||
if (detail === null) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
detail.includes("stale pending approval request") ||
|
||||
detail.includes("unknown pending approval request") ||
|
||||
detail.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
|
||||
function derivePendingUserInputCountFromActivities(
|
||||
activities: ReadonlyArray<ProjectionThreadActivity>,
|
||||
): number {
|
||||
const openRequestIds = new Set<string>();
|
||||
const ordered = [...activities].toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.activityId.localeCompare(right.activityId),
|
||||
);
|
||||
|
||||
for (const activity of ordered) {
|
||||
const requestId = extractActivityRequestId(activity.payload);
|
||||
if (requestId === null) {
|
||||
continue;
|
||||
}
|
||||
const payload =
|
||||
typeof activity.payload === "object" && activity.payload !== null
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
|
||||
if (activity.kind === "user-input.requested") {
|
||||
openRequestIds.add(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (activity.kind === "user-input.resolved") {
|
||||
openRequestIds.delete(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
activity.kind === "provider.user-input.respond.failed" &&
|
||||
detail !== null &&
|
||||
(detail.includes("stale pending user-input request") ||
|
||||
detail.includes("unknown pending user-input request"))
|
||||
) {
|
||||
openRequestIds.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
return openRequestIds.size;
|
||||
}
|
||||
|
||||
function deriveHasActionableProposedPlan(input: {
|
||||
readonly latestTurnId: string | null;
|
||||
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
|
||||
}): boolean {
|
||||
const sorted = [...input.proposedPlans].toSorted(
|
||||
(left, right) =>
|
||||
left.updatedAt.localeCompare(right.updatedAt) || left.planId.localeCompare(right.planId),
|
||||
);
|
||||
|
||||
let latestForTurn: ProjectionThreadProposedPlan | null = null;
|
||||
if (input.latestTurnId !== null) {
|
||||
for (let index = sorted.length - 1; index >= 0; index -= 1) {
|
||||
const plan = sorted[index];
|
||||
if (plan?.turnId === input.latestTurnId) {
|
||||
latestForTurn = plan;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (latestForTurn !== null) {
|
||||
return latestForTurn.implementedAt === null;
|
||||
}
|
||||
|
||||
const latestPlan = sorted.at(-1) ?? null;
|
||||
return latestPlan !== null && latestPlan.implementedAt === null;
|
||||
}
|
||||
|
||||
function retainProjectionMessagesAfterRevert(
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
turns: ReadonlyArray<ProjectionTurn>,
|
||||
@@ -432,6 +515,48 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const refreshThreadShellSummary = Effect.fn("refreshThreadShellSummary")(function* (
|
||||
threadId: ThreadId,
|
||||
) {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [messages, proposedPlans, activities, pendingApprovals] = yield* Effect.all([
|
||||
projectionThreadMessageRepository.listByThreadId({ threadId }),
|
||||
projectionThreadProposedPlanRepository.listByThreadId({ threadId }),
|
||||
projectionThreadActivityRepository.listByThreadId({ threadId }),
|
||||
projectionPendingApprovalRepository.listByThreadId({ threadId }),
|
||||
]);
|
||||
|
||||
const latestUserMessageAt =
|
||||
messages
|
||||
.filter((message) => message.role === "user")
|
||||
.map((message) => message.createdAt)
|
||||
.toSorted()
|
||||
.at(-1) ?? null;
|
||||
|
||||
const pendingApprovalCount = pendingApprovals.filter(
|
||||
(approval) => approval.status === "pending",
|
||||
).length;
|
||||
const pendingUserInputCount = derivePendingUserInputCountFromActivities(activities);
|
||||
const hasActionableProposedPlan = deriveHasActionableProposedPlan({
|
||||
latestTurnId: existingRow.value.latestTurnId,
|
||||
proposedPlans,
|
||||
});
|
||||
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestUserMessageAt,
|
||||
pendingApprovalCount,
|
||||
pendingUserInputCount,
|
||||
hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0,
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadsProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
@@ -450,6 +575,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
return;
|
||||
@@ -554,7 +683,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.activity-appended": {
|
||||
case "thread.activity-appended":
|
||||
case "thread.approval-response-requested":
|
||||
case "thread.user-input-response-requested": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
@@ -565,6 +696,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
...existingRow.value,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -580,6 +712,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.session.activeTurnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -595,6 +728,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.turnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -610,6 +744,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: null,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1121,6 +1256,34 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.payload.activity.kind === "provider.approval.respond.failed") {
|
||||
const payload =
|
||||
typeof event.payload.activity.payload === "object" &&
|
||||
event.payload.activity.payload !== null
|
||||
? (event.payload.activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail =
|
||||
typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
if (isStalePendingApprovalFailureDetail(detail)) {
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
if (existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
yield* projectionPendingApprovalRepository.upsert({
|
||||
requestId,
|
||||
threadId: existingRow.value.threadId,
|
||||
turnId: existingRow.value.turnId,
|
||||
status: "resolved",
|
||||
decision: null,
|
||||
createdAt: existingRow.value.createdAt,
|
||||
resolvedAt: event.payload.activity.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -62,9 +62,15 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
@@ -74,9 +80,15 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:04.000Z',
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
'2026-02-24T00:00:02.000Z',
|
||||
'2026-02-24T00:00:03.000Z',
|
||||
NULL
|
||||
@@ -341,6 +353,81 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.equal(shellSnapshot.snapshotSequence, 5);
|
||||
assert.deepEqual(shellSnapshot.projects, [
|
||||
{
|
||||
id: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
name: "Build",
|
||||
command: "bun run build",
|
||||
icon: "build",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
updatedAt: "2026-02-24T00:00:01.000Z",
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(shellSnapshot.threads, [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
turnId: asTurnId("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-24T00:00:08.000Z",
|
||||
startedAt: "2026-02-24T00:00:08.000Z",
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
assistantMessageId: asMessageId("message-1"),
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
planId: "plan-1",
|
||||
},
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||
},
|
||||
latestUserMessageAt: "2026-02-24T00:00:04.000Z",
|
||||
hasPendingApprovals: true,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -629,4 +716,309 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps thread detail activity ordering consistent with shell snapshot ordering", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_thread_activities`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-01T00:00:00.000Z',
|
||||
'2026-04-01T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-01T00:00:02.000Z',
|
||||
'2026-04-01T00:00:03.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'activity-unsequenced',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'unsequenced first',
|
||||
'{"source":"unsequenced"}',
|
||||
NULL,
|
||||
'2026-04-01T00:00:06.000Z'
|
||||
),
|
||||
(
|
||||
'activity-sequence-2',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'sequence two',
|
||||
'{"source":"sequence-2"}',
|
||||
2,
|
||||
'2026-04-01T00:00:04.000Z'
|
||||
),
|
||||
(
|
||||
'activity-sequence-1',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'sequence one',
|
||||
'{"source":"sequence-1"}',
|
||||
1,
|
||||
'2026-04-01T00:00:05.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
const snapshot = yield* snapshotQuery.getSnapshot();
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.deepEqual(threadDetail.value.activities, snapshot.threads[0]?.activities ?? []);
|
||||
}
|
||||
|
||||
assert.deepEqual(snapshot.threads[0]?.activities ?? [], [
|
||||
{
|
||||
id: asEventId("activity-unsequenced"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "unsequenced first",
|
||||
payload: { source: "unsequenced" },
|
||||
turnId: null,
|
||||
createdAt: "2026-04-01T00:00:06.000Z",
|
||||
},
|
||||
{
|
||||
id: asEventId("activity-sequence-1"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "sequence one",
|
||||
payload: { source: "sequence-1" },
|
||||
turnId: null,
|
||||
sequence: 1,
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
},
|
||||
{
|
||||
id: asEventId("activity-sequence-2"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "sequence two",
|
||||
payload: { source: "sequence-2" },
|
||||
turnId: null,
|
||||
sequence: 2,
|
||||
createdAt: "2026-04-01T00:00:04.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses projection_threads.latest_turn_id for targeted thread latest turn queries", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-02T00:00:00.000Z',
|
||||
'2026-04-02T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-running',
|
||||
'2026-04-02T00:00:04.000Z',
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-02T00:00:02.000Z',
|
||||
'2026-04-02T00:00:03.000Z',
|
||||
NULL,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_turns (
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
started_at,
|
||||
completed_at,
|
||||
checkpoint_turn_count,
|
||||
checkpoint_ref,
|
||||
checkpoint_status,
|
||||
checkpoint_files_json
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'thread-1',
|
||||
'turn-completed',
|
||||
'message-user-1',
|
||||
NULL,
|
||||
NULL,
|
||||
'message-assistant-1',
|
||||
'completed',
|
||||
'2026-04-02T00:00:05.000Z',
|
||||
'2026-04-02T00:00:06.000Z',
|
||||
'2026-04-02T00:00:20.000Z',
|
||||
5,
|
||||
'checkpoint-5',
|
||||
'ready',
|
||||
'[]'
|
||||
),
|
||||
(
|
||||
'thread-1',
|
||||
'turn-running',
|
||||
'message-user-2',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'running',
|
||||
'2026-04-02T00:00:30.000Z',
|
||||
'2026-04-02T00:00:30.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
)
|
||||
`;
|
||||
|
||||
const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadShell._tag, "Some");
|
||||
if (threadShell._tag === "Some") {
|
||||
assert.equal(threadShell.value.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(threadShell.value.latestTurn?.state, "running");
|
||||
assert.equal(threadShell.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z");
|
||||
}
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.equal(threadDetail.value.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(threadDetail.value.latestTurn?.state, "running");
|
||||
assert.equal(threadDetail.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -6,16 +6,19 @@ import {
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
ProjectScript,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type OrchestrationThreadShell,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -48,6 +51,8 @@ import {
|
||||
} from "../Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const decodeShellSnapshot = Schema.decodeUnknownEffect(OrchestrationShellSnapshot);
|
||||
const decodeThread = Schema.decodeUnknownEffect(OrchestrationThread);
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
@@ -155,6 +160,64 @@ function computeSnapshotSequence(
|
||||
return Number.isFinite(minSequence) ? minSequence : 0;
|
||||
}
|
||||
|
||||
function mapLatestTurn(
|
||||
row: Schema.Schema.Type<typeof ProjectionLatestTurnDbRowSchema>,
|
||||
): OrchestrationLatestTurn {
|
||||
return {
|
||||
turnId: row.turnId,
|
||||
state:
|
||||
row.state === "error"
|
||||
? "error"
|
||||
: row.state === "interrupted"
|
||||
? "interrupted"
|
||||
: row.state === "completed"
|
||||
? "completed"
|
||||
: "running",
|
||||
requestedAt: row.requestedAt,
|
||||
startedAt: row.startedAt,
|
||||
completedAt: row.completedAt,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
|
||||
? {
|
||||
sourceProposedPlan: {
|
||||
threadId: row.sourceProposedPlanThreadId,
|
||||
planId: row.sourceProposedPlanId,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function mapSessionRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadSessionDbRowSchema>,
|
||||
): OrchestrationSession {
|
||||
return {
|
||||
threadId: row.threadId,
|
||||
status: row.status,
|
||||
providerName: row.providerName,
|
||||
runtimeMode: row.runtimeMode,
|
||||
activeTurnId: row.activeTurnId,
|
||||
lastError: row.lastError,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function mapProjectShellRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>,
|
||||
repositoryIdentity: OrchestrationProject["repositoryIdentity"],
|
||||
): OrchestrationProjectShell {
|
||||
return {
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
repositoryIdentity,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -204,6 +267,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
ORDER BY created_at ASC, thread_id ASC
|
||||
@@ -381,6 +448,27 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getActiveProjectRowById = SqlSchema.findOneOption({
|
||||
Request: ProjectIdLookupInput,
|
||||
Result: ProjectionProjectLookupRowSchema,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_projects
|
||||
WHERE project_id = ${projectId}
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({
|
||||
Request: ProjectIdLookupInput,
|
||||
Result: ProjectionThreadIdLookupRowSchema,
|
||||
@@ -415,6 +503,146 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getActiveThreadRowById = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadMessageRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadMessageDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
role,
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
is_streaming AS "isStreaming",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_messages
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, message_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadProposedPlanRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadProposedPlanDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
plan_id AS "planId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
implemented_at AS "implementedAt",
|
||||
implementation_thread_id AS "implementationThreadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, plan_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const getThreadSessionRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadSessionDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
status,
|
||||
provider_name AS "providerName",
|
||||
runtime_mode AS "runtimeMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_sessions
|
||||
WHERE thread_id = ${threadId}
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const getLatestTurnRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionLatestTurnDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
turns.thread_id AS "threadId",
|
||||
turns.turn_id AS "turnId",
|
||||
turns.state,
|
||||
turns.requested_at AS "requestedAt",
|
||||
turns.started_at AS "startedAt",
|
||||
turns.completed_at AS "completedAt",
|
||||
turns.assistant_message_id AS "assistantMessageId",
|
||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_threads threads
|
||||
JOIN projection_turns turns
|
||||
ON turns.thread_id = threads.thread_id
|
||||
AND turns.turn_id = threads.latest_turn_id
|
||||
WHERE threads.thread_id = ${threadId}
|
||||
AND threads.deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listCheckpointRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionCheckpointDbRowSchema,
|
||||
@@ -724,6 +952,145 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
Effect.all([
|
||||
listProjectRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjects:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjects:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
|
||||
Effect.gen(function* () {
|
||||
let updatedAt: string | null = null;
|
||||
for (const row of projectRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of threadRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of sessionRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of latestTurnRows) {
|
||||
updatedAt = maxIso(updatedAt, row.requestedAt);
|
||||
if (row.startedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.startedAt);
|
||||
}
|
||||
if (row.completedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
}
|
||||
}
|
||||
for (const row of stateRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
|
||||
const repositoryIdentities = new Map(
|
||||
yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(row.workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
);
|
||||
const latestTurnByThread = new Map(
|
||||
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
|
||||
);
|
||||
const sessionByThread = new Map(
|
||||
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
|
||||
);
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects: projectRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map((row) =>
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
),
|
||||
threads: threadRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map(
|
||||
(row): OrchestrationThreadShell => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: row.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
|
||||
}),
|
||||
),
|
||||
updatedAt: updatedAt ?? new Date(0).toISOString(),
|
||||
};
|
||||
|
||||
return yield* decodeShellSnapshot(snapshot).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot",
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
Effect.mapError((error) => {
|
||||
if (isPersistenceError(error)) {
|
||||
return error;
|
||||
}
|
||||
return toPersistenceSqlError("ProjectionSnapshotQuery.getShellSnapshot:query")(error);
|
||||
}),
|
||||
);
|
||||
|
||||
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
|
||||
readProjectionCounts(undefined).pipe(
|
||||
Effect.mapError(
|
||||
@@ -770,6 +1137,27 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const getProjectShellById: ProjectionSnapshotQueryShape["getProjectShellById"] = (projectId) =>
|
||||
getActiveProjectRowById({ projectId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getProjectShellById:query",
|
||||
"ProjectionSnapshotQuery.getProjectShellById:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((option) =>
|
||||
Option.isNone(option)
|
||||
? Effect.succeed(Option.none<OrchestrationProjectShell>())
|
||||
: repositoryIdentityResolver
|
||||
.resolve(option.value.workspaceRoot)
|
||||
.pipe(
|
||||
Effect.map((repositoryIdentity) =>
|
||||
Option.some(mapProjectShellRow(option.value, repositoryIdentity)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] =
|
||||
(projectId) =>
|
||||
getFirstActiveThreadIdByProject({ projectId }).pipe(
|
||||
@@ -826,12 +1214,217 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThreadShell>();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
|
||||
} satisfies OrchestrationThreadShell);
|
||||
});
|
||||
|
||||
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [
|
||||
threadRow,
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
checkpointRows,
|
||||
latestTurnRow,
|
||||
sessionRow,
|
||||
] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getThread:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadMessageRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadProposedPlanRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPlans:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPlans:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadActivityRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listCheckpointRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThread>();
|
||||
}
|
||||
|
||||
const thread = {
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
id: row.messageId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
turnId: row.turnId,
|
||||
streaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
if (row.attachments !== null) {
|
||||
return Object.assign(message, { attachments: row.attachments });
|
||||
}
|
||||
return message;
|
||||
}),
|
||||
proposedPlans: proposedPlanRows.map((row) => ({
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
implementedAt: row.implementedAt,
|
||||
implementationThreadId: row.implementationThreadId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
})),
|
||||
activities: activityRows.map((row) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
if (row.sequence !== null) {
|
||||
return Object.assign(activity, { sequence: row.sequence });
|
||||
}
|
||||
return activity;
|
||||
}),
|
||||
checkpoints: checkpointRows.map((row) => ({
|
||||
turnId: row.turnId,
|
||||
checkpointTurnCount: row.checkpointTurnCount,
|
||||
checkpointRef: row.checkpointRef,
|
||||
status: row.status,
|
||||
files: row.files,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
completedAt: row.completedAt,
|
||||
})),
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
};
|
||||
|
||||
return Option.some(
|
||||
yield* decodeThread(thread).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("ProjectionSnapshotQuery.getThreadDetailById:decodeThread"),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
getSnapshot,
|
||||
getShellSnapshot,
|
||||
getCounts,
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
getProjectShellById,
|
||||
getFirstActiveThreadIdByProjectId,
|
||||
getThreadCheckpointContext,
|
||||
getThreadShellById,
|
||||
getThreadDetailById,
|
||||
} satisfies ProjectionSnapshotQueryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -27,6 +27,10 @@ import {
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
@@ -177,6 +181,24 @@ describe("ProviderCommandReactor", () => {
|
||||
: "renamed-branch",
|
||||
}),
|
||||
);
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "renamed-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
);
|
||||
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>((_) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
@@ -225,6 +247,15 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(GitStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||
refreshStatus,
|
||||
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
|
||||
} satisfies GitStatusBroadcasterShape),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(TextGeneration, {
|
||||
generateBranchName,
|
||||
@@ -279,6 +310,7 @@ describe("ProviderCommandReactor", () => {
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
renameBranch,
|
||||
refreshStatus,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
stateDir,
|
||||
@@ -513,9 +545,11 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await waitFor(() => harness.refreshStatus.mock.calls.length === 1);
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({
|
||||
message: "Add a safer reconnect backoff.",
|
||||
});
|
||||
expect(harness.refreshStatus.mock.calls[0]?.[0]).toBe("/tmp/provider-project-worktree");
|
||||
});
|
||||
|
||||
it("forwards codex model options through session start and turn send", async () => {
|
||||
@@ -1241,6 +1275,61 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("starts a fresh session when only projected session state exists", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-stale"),
|
||||
role: "user",
|
||||
text: "resume codex",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
});
|
||||
|
||||
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -11,11 +11,13 @@ import {
|
||||
type RuntimeMode,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";
|
||||
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
||||
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||
@@ -72,8 +74,6 @@ const serverCommandId = (tag: string): CommandId =>
|
||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
const DEFAULT_THREAD_TITLE = "New thread";
|
||||
|
||||
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
|
||||
@@ -119,10 +119,6 @@ function stalePendingRequestDetail(
|
||||
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
|
||||
}
|
||||
|
||||
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
}
|
||||
|
||||
function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
@@ -150,6 +146,7 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const git = yield* GitCore;
|
||||
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||
@@ -290,14 +287,14 @@ const make = Effect.gen(function* () {
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const activeSession = yield* resolveActiveSession(threadId);
|
||||
const existingSessionThreadId =
|
||||
thread.session && thread.session.status !== "stopped" ? thread.id : null;
|
||||
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
@@ -452,6 +449,7 @@ const make = Effect.gen(function* () {
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||
|
||||
@@ -9,7 +9,11 @@
|
||||
import type {
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationProject,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadShell,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -44,6 +48,17 @@ export interface ProjectionSnapshotQueryShape {
|
||||
*/
|
||||
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read the latest orchestration shell snapshot.
|
||||
*
|
||||
* Returns only projects and thread shell summaries so clients can bootstrap
|
||||
* lightweight navigation state without hydrating every thread body.
|
||||
*/
|
||||
readonly getShellSnapshot: () => Effect.Effect<
|
||||
OrchestrationShellSnapshot,
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read aggregate projection counts without hydrating the full read model.
|
||||
*/
|
||||
@@ -56,6 +71,13 @@ export interface ProjectionSnapshotQueryShape {
|
||||
workspaceRoot: string,
|
||||
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active project shell row by id.
|
||||
*/
|
||||
readonly getProjectShellById: (
|
||||
projectId: ProjectId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read the earliest active thread for a project.
|
||||
*/
|
||||
@@ -69,6 +91,20 @@ export interface ProjectionSnapshotQueryShape {
|
||||
readonly getThreadCheckpointContext: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread shell row by id.
|
||||
*/
|
||||
readonly getThreadShellById: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThreadShell>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread detail snapshot by id.
|
||||
*/
|
||||
readonly getThreadDetailById: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,7 @@ describe("fixPath", () => {
|
||||
it("hydrates PATH on linux using the resolved login shell", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
};
|
||||
const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
|
||||
@@ -17,6 +17,39 @@ describe("fixPath", () => {
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenCalledWith("/bin/zsh");
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing fails", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readPath = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => undefined);
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
fixPath({
|
||||
env,
|
||||
platform: "darwin",
|
||||
readPath,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu");
|
||||
expect(readPath).toHaveBeenNthCalledWith(2, "/bin/zsh");
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read PATH from login shell /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,28 +1,57 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell";
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readPathFromLoginShell,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
function logPathHydrationWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[server] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function fixPath(
|
||||
options: {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
platform?: NodeJS.Platform;
|
||||
readPath?: typeof readPathFromLoginShell;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const env = options.env ?? process.env;
|
||||
const logWarning = options.logWarning ?? logPathHydrationWarning;
|
||||
const readPath = options.readPath ?? readPathFromLoginShell;
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
const result = (options.readPath ?? readPathFromLoginShell)(shell);
|
||||
if (result) {
|
||||
env.PATH = result;
|
||||
let shellPath: string | undefined;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
shellPath = readPath(shell);
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read PATH from login shell ${shell}.`, error);
|
||||
}
|
||||
|
||||
if (shellPath) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellPath
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to hydrate PATH from the user environment.", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,6 +88,10 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
@@ -55,6 +59,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
${row.hasActionableProposedPlan},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
@@ -70,6 +78,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
archived_at = excluded.archived_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
has_actionable_proposed_plan = excluded.has_actionable_proposed_plan,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
});
|
||||
@@ -92,6 +104,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
@@ -116,6 +132,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE project_id = ${projectId}
|
||||
|
||||
@@ -35,6 +35,8 @@ import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
|
||||
import Migration0020 from "./Migrations/020_AuthAccessManagement.ts";
|
||||
import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts";
|
||||
import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
|
||||
import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
|
||||
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -69,6 +71,8 @@ export const migrationEntries = [
|
||||
[20, "AuthAccessManagement", Migration0020],
|
||||
[21, "AuthSessionClientMetadata", Migration0021],
|
||||
[22, "AuthSessionLastConnectedAt", Migration0022],
|
||||
[23, "ProjectionThreadShellSummary", Migration0023],
|
||||
[24, "BackfillProjectionThreadShellSummary", Migration0024],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN latest_user_message_at TEXT
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN pending_approval_count INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN pending_user_input_count INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN has_actionable_proposed_plan INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
});
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("024_BackfillProjectionThreadShellSummary", (it) => {
|
||||
it.effect("backfills thread shell summary fields and clears stale projected approvals", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 23 });
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'approval-required',
|
||||
'plan',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'message-user-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'user',
|
||||
'Need help',
|
||||
NULL,
|
||||
0,
|
||||
'2026-02-24T00:01:00.000Z',
|
||||
'2026-02-24T00:01:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'activity-approval-requested',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'approval',
|
||||
'approval.requested',
|
||||
'Command approval requested',
|
||||
'{"requestId":"approval-1","requestKind":"command"}',
|
||||
NULL,
|
||||
'2026-02-24T00:02:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-approval-stale',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'error',
|
||||
'provider.approval.respond.failed',
|
||||
'Provider approval response failed',
|
||||
'{"requestId":"approval-1","detail":"Unknown pending permission request: approval-1"}',
|
||||
NULL,
|
||||
'2026-02-24T00:03:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-user-input-requested',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'info',
|
||||
'user-input.requested',
|
||||
'User input requested',
|
||||
'{"requestId":"input-1","questions":[{"id":"area","header":"Area","question":"Which repo area should I inspect next?","options":[{"label":"Server","description":"Server orchestration."}]}]}',
|
||||
NULL,
|
||||
'2026-02-24T00:04:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_proposed_plans (
|
||||
plan_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
implemented_at,
|
||||
implementation_thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'plan-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'# Do the thing',
|
||||
NULL,
|
||||
NULL,
|
||||
'2026-02-24T00:05:00.000Z',
|
||||
'2026-02-24T00:05:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_pending_approvals (
|
||||
request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
status,
|
||||
decision,
|
||||
created_at,
|
||||
resolved_at
|
||||
)
|
||||
VALUES (
|
||||
'approval-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'pending',
|
||||
NULL,
|
||||
'2026-02-24T00:02:00.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 24 });
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly latestUserMessageAt: string | null;
|
||||
readonly pendingApprovalCount: number;
|
||||
readonly pendingUserInputCount: number;
|
||||
readonly hasActionableProposedPlan: number;
|
||||
}>`
|
||||
SELECT
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-1'
|
||||
`;
|
||||
assert.deepStrictEqual(threadRows, [
|
||||
{
|
||||
latestUserMessageAt: "2026-02-24T00:01:00.000Z",
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 1,
|
||||
hasActionableProposedPlan: 1,
|
||||
},
|
||||
]);
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly status: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
status,
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id = 'approval-1'
|
||||
`;
|
||||
assert.deepStrictEqual(approvalRows, [
|
||||
{
|
||||
status: "resolved",
|
||||
resolvedAt: "2026-02-24T00:03:00.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
INSERT OR IGNORE INTO projection_pending_approvals (
|
||||
request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
status,
|
||||
decision,
|
||||
created_at,
|
||||
resolved_at
|
||||
)
|
||||
SELECT
|
||||
requested.request_id,
|
||||
requested.thread_id,
|
||||
requested.turn_id,
|
||||
'pending',
|
||||
NULL,
|
||||
requested.created_at,
|
||||
NULL
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
created_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at ASC, activity_id ASC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'approval.requested'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS requested
|
||||
WHERE requested.row_number = 1
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_resolutions AS (
|
||||
SELECT
|
||||
resolved.request_id,
|
||||
resolved.resolved_at,
|
||||
resolved.decision
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
created_at AS resolved_at,
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.decision') IN (
|
||||
'accept',
|
||||
'acceptForSession',
|
||||
'decline',
|
||||
'cancel'
|
||||
)
|
||||
THEN json_extract(payload_json, '$.decision')
|
||||
ELSE NULL
|
||||
END AS decision,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at DESC, activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'approval.resolved'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS resolved
|
||||
WHERE resolved.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = (
|
||||
SELECT latest_resolutions.decision
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
),
|
||||
resolved_at = (
|
||||
SELECT latest_resolutions.resolved_at
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_response_events AS (
|
||||
SELECT
|
||||
response.request_id,
|
||||
response.resolved_at,
|
||||
response.decision
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
occurred_at AS resolved_at,
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.decision') IN (
|
||||
'accept',
|
||||
'acceptForSession',
|
||||
'decline',
|
||||
'cancel'
|
||||
)
|
||||
THEN json_extract(payload_json, '$.decision')
|
||||
ELSE NULL
|
||||
END AS decision,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY occurred_at DESC, sequence DESC
|
||||
) AS row_number
|
||||
FROM orchestration_events
|
||||
WHERE event_type = 'thread.approval-response-requested'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS response
|
||||
WHERE response.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = (
|
||||
SELECT latest_response_events.decision
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
),
|
||||
resolved_at = (
|
||||
SELECT latest_response_events.resolved_at
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_stale_failures AS (
|
||||
SELECT
|
||||
failure.request_id,
|
||||
failure.resolved_at
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
created_at AS resolved_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at DESC, activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'provider.approval.respond.failed'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
AND (
|
||||
lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%stale pending approval request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending approval request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending permission request%'
|
||||
)
|
||||
) AS failure
|
||||
WHERE failure.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = NULL,
|
||||
resolved_at = (
|
||||
SELECT latest_stale_failures.resolved_at
|
||||
FROM latest_stale_failures
|
||||
WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE status = 'pending'
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_stale_failures
|
||||
WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET
|
||||
latest_user_message_at = (
|
||||
SELECT MAX(message.created_at)
|
||||
FROM projection_thread_messages AS message
|
||||
WHERE message.thread_id = projection_threads.thread_id
|
||||
AND message.role = 'user'
|
||||
),
|
||||
pending_approval_count = COALESCE((
|
||||
SELECT COUNT(*)
|
||||
FROM projection_pending_approvals
|
||||
WHERE projection_pending_approvals.thread_id = projection_threads.thread_id
|
||||
AND projection_pending_approvals.status = 'pending'
|
||||
), 0),
|
||||
pending_user_input_count = COALESCE((
|
||||
WITH latest_user_input_states AS (
|
||||
SELECT
|
||||
latest.request_id,
|
||||
latest.kind,
|
||||
latest.detail
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(activity.payload_json, '$.requestId') AS request_id,
|
||||
activity.kind,
|
||||
lower(COALESCE(json_extract(activity.payload_json, '$.detail'), '')) AS detail,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(activity.payload_json, '$.requestId')
|
||||
ORDER BY activity.created_at DESC, activity.activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities AS activity
|
||||
WHERE activity.thread_id = projection_threads.thread_id
|
||||
AND json_extract(activity.payload_json, '$.requestId') IS NOT NULL
|
||||
AND activity.kind IN (
|
||||
'user-input.requested',
|
||||
'user-input.resolved',
|
||||
'provider.user-input.respond.failed'
|
||||
)
|
||||
) AS latest
|
||||
WHERE latest.row_number = 1
|
||||
)
|
||||
SELECT COUNT(*)
|
||||
FROM latest_user_input_states
|
||||
WHERE latest_user_input_states.kind = 'user-input.requested'
|
||||
OR (
|
||||
latest_user_input_states.kind = 'provider.user-input.respond.failed'
|
||||
AND latest_user_input_states.detail NOT LIKE '%stale pending user-input request%'
|
||||
AND latest_user_input_states.detail NOT LIKE '%unknown pending user-input request%'
|
||||
)
|
||||
), 0),
|
||||
has_actionable_proposed_plan = COALESCE((
|
||||
SELECT CASE
|
||||
WHEN projection_threads.latest_turn_id IS NOT NULL
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_proposed_plans AS latest_turn_plan_exists
|
||||
WHERE latest_turn_plan_exists.thread_id = projection_threads.thread_id
|
||||
AND latest_turn_plan_exists.turn_id = projection_threads.latest_turn_id
|
||||
)
|
||||
THEN CASE
|
||||
WHEN (
|
||||
SELECT latest_turn_plan.implemented_at
|
||||
FROM projection_thread_proposed_plans AS latest_turn_plan
|
||||
WHERE latest_turn_plan.thread_id = projection_threads.thread_id
|
||||
AND latest_turn_plan.turn_id = projection_threads.latest_turn_id
|
||||
ORDER BY latest_turn_plan.updated_at DESC, latest_turn_plan.plan_id DESC
|
||||
LIMIT 1
|
||||
) IS NULL
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END
|
||||
WHEN EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_proposed_plans AS any_plan
|
||||
WHERE any_plan.thread_id = projection_threads.thread_id
|
||||
)
|
||||
THEN CASE
|
||||
WHEN (
|
||||
SELECT latest_plan.implemented_at
|
||||
FROM projection_thread_proposed_plans AS latest_plan
|
||||
WHERE latest_plan.thread_id = projection_threads.thread_id
|
||||
ORDER BY latest_plan.updated_at DESC, latest_plan.plan_id DESC
|
||||
LIMIT 1
|
||||
) IS NULL
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END
|
||||
ELSE 0
|
||||
END
|
||||
), 0)
|
||||
`;
|
||||
});
|
||||
@@ -9,6 +9,7 @@
|
||||
import {
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
NonNegativeInt,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
@@ -33,6 +34,10 @@ export const ProjectionThread = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
hasActionableProposedPlan: NonNegativeInt,
|
||||
deletedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type ProjectionThread = typeof ProjectionThread.Type;
|
||||
|
||||
@@ -1408,6 +1408,150 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("clamps oversized Claude usage to the reported context window", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 1234,
|
||||
duration_api_ms: 1200,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-result-usage-clamped",
|
||||
usage: {
|
||||
total_tokens: 535000,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.finish();
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
|
||||
assert.equal(usageEvent?.type, "thread.token-usage.updated");
|
||||
if (usageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(usageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 200000,
|
||||
lastUsedTokens: 200000,
|
||||
totalProcessedTokens: 535000,
|
||||
maxTokens: 200000,
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"preserves oversized Claude result totals after task progress snapshots are recorded",
|
||||
() => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_progress",
|
||||
task_id: "task-usage-clamped",
|
||||
description: "Thinking through the patch",
|
||||
usage: {
|
||||
total_tokens: 190000,
|
||||
},
|
||||
session_id: "sdk-session-task-usage-clamped",
|
||||
uuid: "task-usage-progress-clamped",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 1234,
|
||||
duration_api_ms: 1200,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-result-usage-clamped-after-progress",
|
||||
usage: {
|
||||
total_tokens: 535000,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.finish();
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvents = runtimeEvents.filter(
|
||||
(event) => event.type === "thread.token-usage.updated",
|
||||
);
|
||||
const finalUsageEvent = usageEvents.at(-1);
|
||||
assert.equal(finalUsageEvent?.type, "thread.token-usage.updated");
|
||||
if (finalUsageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(finalUsageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 190000,
|
||||
lastUsedTokens: 190000,
|
||||
totalProcessedTokens: 535000,
|
||||
maxTokens: 200000,
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"emits completion only after turn result when assistant frames arrive before deltas",
|
||||
() => {
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
type SDKResultMessage,
|
||||
type SettingSource,
|
||||
type SDKUserMessage,
|
||||
ModelUsage,
|
||||
NonNullableUsage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -272,24 +274,14 @@ function asRuntimeItemId(value: string): RuntimeItemId {
|
||||
return RuntimeItemId.make(value);
|
||||
}
|
||||
|
||||
function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined {
|
||||
if (!modelUsage || typeof modelUsage !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
function maxClaudeContextWindowFromModelUsage(
|
||||
modelUsage: Record<string, ModelUsage> | undefined,
|
||||
): number | undefined {
|
||||
if (!modelUsage) return undefined;
|
||||
|
||||
let maxContextWindow: number | undefined;
|
||||
for (const value of Object.values(modelUsage as Record<string, unknown>)) {
|
||||
if (!value || typeof value !== "object") {
|
||||
continue;
|
||||
}
|
||||
const contextWindow = (value as { contextWindow?: unknown }).contextWindow;
|
||||
if (
|
||||
typeof contextWindow !== "number" ||
|
||||
!Number.isFinite(contextWindow) ||
|
||||
contextWindow <= 0
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
for (const value of Object.values(modelUsage)) {
|
||||
const contextWindow = value.contextWindow;
|
||||
maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow);
|
||||
}
|
||||
|
||||
@@ -297,53 +289,58 @@ function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | und
|
||||
}
|
||||
|
||||
function normalizeClaudeTokenUsage(
|
||||
usage: unknown,
|
||||
value: NonNullableUsage | undefined,
|
||||
contextWindow?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
if (!usage || typeof usage !== "object") {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const record = usage as Record<string, unknown>;
|
||||
const directUsedTokens =
|
||||
typeof record.total_tokens === "number" && Number.isFinite(record.total_tokens)
|
||||
? record.total_tokens
|
||||
: undefined;
|
||||
const usage = value as Record<string, unknown>;
|
||||
const inputTokens =
|
||||
(typeof record.input_tokens === "number" && Number.isFinite(record.input_tokens)
|
||||
? record.input_tokens
|
||||
(typeof usage.input_tokens === "number" && Number.isFinite(usage.input_tokens)
|
||||
? usage.input_tokens
|
||||
: 0) +
|
||||
(typeof record.cache_creation_input_tokens === "number" &&
|
||||
Number.isFinite(record.cache_creation_input_tokens)
|
||||
? record.cache_creation_input_tokens
|
||||
(typeof usage.cache_creation_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_creation_input_tokens)
|
||||
? usage.cache_creation_input_tokens
|
||||
: 0) +
|
||||
(typeof record.cache_read_input_tokens === "number" &&
|
||||
Number.isFinite(record.cache_read_input_tokens)
|
||||
? record.cache_read_input_tokens
|
||||
(typeof usage.cache_read_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_read_input_tokens)
|
||||
? usage.cache_read_input_tokens
|
||||
: 0);
|
||||
const outputTokens =
|
||||
typeof record.output_tokens === "number" && Number.isFinite(record.output_tokens)
|
||||
? record.output_tokens
|
||||
typeof usage.output_tokens === "number" && Number.isFinite(usage.output_tokens)
|
||||
? usage.output_tokens
|
||||
: 0;
|
||||
const derivedUsedTokens = inputTokens + outputTokens;
|
||||
const usedTokens = directUsedTokens ?? (derivedUsedTokens > 0 ? derivedUsedTokens : undefined);
|
||||
if (usedTokens === undefined || usedTokens <= 0) {
|
||||
const derivedTotalProcessedTokens = inputTokens + outputTokens;
|
||||
const totalProcessedTokens =
|
||||
(typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens)
|
||||
? usage.total_tokens
|
||||
: undefined) ?? (derivedTotalProcessedTokens > 0 ? derivedTotalProcessedTokens : undefined);
|
||||
if (totalProcessedTokens === undefined || totalProcessedTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens =
|
||||
typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
|
||||
? contextWindow
|
||||
: undefined;
|
||||
const usedTokens =
|
||||
maxTokens !== undefined ? Math.min(totalProcessedTokens, maxTokens) : totalProcessedTokens;
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
lastUsedTokens: usedTokens,
|
||||
...(totalProcessedTokens > usedTokens ? { totalProcessedTokens } : {}),
|
||||
...(inputTokens > 0 ? { inputTokens } : {}),
|
||||
...(outputTokens > 0 ? { outputTokens } : {}),
|
||||
...(typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
|
||||
? { maxTokens: contextWindow }
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(typeof usage.tool_uses === "number" && Number.isFinite(usage.tool_uses)
|
||||
? { toolUses: usage.tool_uses }
|
||||
: {}),
|
||||
...(typeof record.tool_uses === "number" && Number.isFinite(record.tool_uses)
|
||||
? { toolUses: record.tool_uses }
|
||||
: {}),
|
||||
...(typeof record.duration_ms === "number" && Number.isFinite(record.duration_ms)
|
||||
? { durationMs: record.duration_ms }
|
||||
...(typeof usage.duration_ms === "number" && Number.isFinite(usage.duration_ms)
|
||||
? { durationMs: usage.duration_ms }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -1328,8 +1325,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
errorMessage?: string,
|
||||
result?: SDKResultMessage,
|
||||
) {
|
||||
const resultUsage =
|
||||
result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
|
||||
const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
|
||||
if (resultContextWindow !== undefined) {
|
||||
context.lastKnownContextWindow = resultContextWindow;
|
||||
@@ -1341,9 +1336,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
// Instead, use the last known context-window-accurate usage from task_progress
|
||||
// events and treat the accumulated total as totalProcessedTokens.
|
||||
const accumulatedSnapshot = normalizeClaudeTokenUsage(
|
||||
resultUsage,
|
||||
result?.usage,
|
||||
resultContextWindow ?? context.lastKnownContextWindow,
|
||||
);
|
||||
const accumulatedTotalProcessedTokens =
|
||||
accumulatedSnapshot?.totalProcessedTokens ?? accumulatedSnapshot?.usedTokens;
|
||||
const lastGoodUsage = context.lastKnownTokenUsage;
|
||||
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
|
||||
const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
|
||||
@@ -1352,8 +1349,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens
|
||||
? { totalProcessedTokens: accumulatedSnapshot.usedTokens }
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? { totalProcessedTokens: accumulatedTotalProcessedTokens }
|
||||
: {}),
|
||||
}
|
||||
: accumulatedSnapshot;
|
||||
|
||||
@@ -4,12 +4,16 @@ import type {
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuth,
|
||||
ServerProviderSlashCommand,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
query as claudeQuery,
|
||||
type SlashCommand as ClaudeSlashCommand,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
@@ -276,18 +280,6 @@ function extractClaudeAuthMethodFromOutput(result: CommandResult): string | unde
|
||||
return Option.getOrUndefined(findAuthMethod(parsed.success));
|
||||
}
|
||||
|
||||
// ── Dynamic model capability adjustment ─────────────────────────────
|
||||
|
||||
/** Subscription types where the 1M context window is included in the plan. */
|
||||
const PREMIUM_SUBSCRIPTION_TYPES = new Set([
|
||||
"max",
|
||||
"maxplan",
|
||||
"max5",
|
||||
"max20",
|
||||
"enterprise",
|
||||
"team",
|
||||
]);
|
||||
|
||||
function toTitleCaseWords(value: string): string {
|
||||
return value
|
||||
.split(/[\s_-]+/g)
|
||||
@@ -348,53 +340,78 @@ function claudeAuthMetadata(input: {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Models where 1M context is included in premium Claude Code subscriptions
|
||||
* without needing extra usage enabled.
|
||||
*/
|
||||
const MODELS_WITH_INCLUDED_1M_CONTEXT = new Set(["claude-opus-4-6"]);
|
||||
|
||||
/**
|
||||
* Adjust the built-in model list based on the user's detected subscription.
|
||||
*
|
||||
* - Premium tiers (Max, Enterprise, Team): 1M context becomes the default
|
||||
* for models that include it in the plan (currently only Opus).
|
||||
* - Other tiers (Pro, free, unknown): 200k context stays the default;
|
||||
* 1M remains available as a manual option so users can still enable it.
|
||||
*/
|
||||
export function adjustModelsForSubscription(
|
||||
baseModels: ReadonlyArray<ServerProviderModel>,
|
||||
subscriptionType: string | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
|
||||
if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
|
||||
return baseModels;
|
||||
}
|
||||
|
||||
// Flip 1M to be the default only for models that include it in the plan
|
||||
return baseModels.map((model) => {
|
||||
const caps = model.capabilities;
|
||||
if (!caps || caps.contextWindowOptions.length === 0) return model;
|
||||
if (!MODELS_WITH_INCLUDED_1M_CONTEXT.has(model.slug)) return model;
|
||||
|
||||
return {
|
||||
...model,
|
||||
capabilities: {
|
||||
...caps,
|
||||
contextWindowOptions: caps.contextWindowOptions.map((opt) =>
|
||||
opt.value === "1m"
|
||||
? { value: opt.value, label: opt.label, isDefault: true as const }
|
||||
: { value: opt.value, label: opt.label },
|
||||
),
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ── SDK capability probe ────────────────────────────────────────────
|
||||
|
||||
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
|
||||
|
||||
function nonEmptyProbeString(value: string): string | undefined {
|
||||
const candidate = value.trim();
|
||||
return candidate ? candidate : undefined;
|
||||
}
|
||||
|
||||
function parseClaudeInitializationCommands(
|
||||
commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
|
||||
): ReadonlyArray<ServerProviderSlashCommand> {
|
||||
return dedupeSlashCommands(
|
||||
(commands ?? []).flatMap((command) => {
|
||||
const name = nonEmptyProbeString(command.name);
|
||||
if (!name) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const description = nonEmptyProbeString(command.description);
|
||||
const argumentHint = nonEmptyProbeString(command.argumentHint);
|
||||
|
||||
return [
|
||||
{
|
||||
name,
|
||||
...(description ? { description } : {}),
|
||||
...(argumentHint ? { input: { hint: argumentHint } } : {}),
|
||||
} satisfies ServerProviderSlashCommand,
|
||||
];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function dedupeSlashCommands(
|
||||
commands: ReadonlyArray<ServerProviderSlashCommand>,
|
||||
): ReadonlyArray<ServerProviderSlashCommand> {
|
||||
const commandsByName = new Map<string, ServerProviderSlashCommand>();
|
||||
|
||||
for (const command of commands) {
|
||||
const name = nonEmptyProbeString(command.name);
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = name.toLowerCase();
|
||||
const existing = commandsByName.get(key);
|
||||
if (!existing) {
|
||||
commandsByName.set(key, {
|
||||
...command,
|
||||
name,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
commandsByName.set(key, {
|
||||
...existing,
|
||||
...(existing.description
|
||||
? {}
|
||||
: command.description
|
||||
? { description: command.description }
|
||||
: {}),
|
||||
...(existing.input?.hint
|
||||
? {}
|
||||
: command.input?.hint
|
||||
? { input: { hint: command.input.hint } }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
return [...commandsByName.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe account information by spawning a lightweight Claude Agent SDK
|
||||
* session and reading the initialization result.
|
||||
@@ -416,13 +433,16 @@ const probeClaudeCapabilities = (binaryPath: string) => {
|
||||
pathToClaudeCodeExecutable: binaryPath,
|
||||
abortController: abort,
|
||||
maxTurns: 0,
|
||||
settingSources: [],
|
||||
settingSources: ["user", "project", "local"],
|
||||
allowedTools: [],
|
||||
stderr: () => {},
|
||||
},
|
||||
});
|
||||
const init = await q.initializationResult();
|
||||
return { subscriptionType: init.account?.subscriptionType };
|
||||
return {
|
||||
subscriptionType: init.account?.subscriptionType,
|
||||
slashCommands: parseClaudeInitializationCommands(init.commands),
|
||||
};
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
@@ -451,6 +471,9 @@ const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: Readonly
|
||||
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
|
||||
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
|
||||
resolveSlashCommands?: (
|
||||
binaryPath: string,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProviderSlashCommand> | undefined>,
|
||||
): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
@@ -546,6 +569,14 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
});
|
||||
}
|
||||
|
||||
const slashCommands =
|
||||
(resolveSlashCommands
|
||||
? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
)
|
||||
: undefined) ?? [];
|
||||
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
|
||||
|
||||
// ── Auth check + subscription detection ────────────────────────────
|
||||
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
@@ -571,8 +602,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
|
||||
}
|
||||
|
||||
const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
|
||||
|
||||
// ── Handle auth results (same logic as before, adjusted models) ──
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
@@ -581,7 +610,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -600,7 +630,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -617,7 +648,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -631,6 +663,46 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
});
|
||||
});
|
||||
|
||||
const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvider => {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Claude provider status has not been checked in this session yet.",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const ClaudeProviderLive = Layer.effect(
|
||||
ClaudeProvider,
|
||||
Effect.gen(function* () {
|
||||
@@ -640,12 +712,18 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
const subscriptionProbeCache = yield* Cache.make({
|
||||
capacity: 1,
|
||||
timeToLive: Duration.minutes(5),
|
||||
lookup: (binaryPath: string) =>
|
||||
probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
|
||||
lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath),
|
||||
});
|
||||
|
||||
const checkProvider = checkClaudeProviderStatus((binaryPath) =>
|
||||
Cache.get(subscriptionProbeCache, binaryPath),
|
||||
const checkProvider = checkClaudeProviderStatus(
|
||||
(binaryPath) =>
|
||||
Cache.get(subscriptionProbeCache, binaryPath).pipe(
|
||||
Effect.map((probe) => probe?.subscriptionType),
|
||||
),
|
||||
(binaryPath) =>
|
||||
Cache.get(subscriptionProbeCache, binaryPath).pipe(
|
||||
Effect.map((probe) => probe?.slashCommands),
|
||||
),
|
||||
).pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
@@ -660,6 +738,7 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
Stream.map((settings) => settings.providers.claudeAgent),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingClaudeProvider,
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuth,
|
||||
ServerProviderSkill,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -44,7 +45,7 @@ import {
|
||||
codexAuthSubType,
|
||||
type CodexAccountSnapshot,
|
||||
} from "../codexAccount";
|
||||
import { probeCodexAccount } from "../codexAppServer";
|
||||
import { probeCodexDiscovery } from "../codexAppServer";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
@@ -304,8 +305,9 @@ const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
|
||||
const probeCodexCapabilities = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
}) =>
|
||||
Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
|
||||
Effect.tryPromise((signal) => probeCodexDiscovery({ ...input, signal })).pipe(
|
||||
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
Effect.map((result) => {
|
||||
@@ -334,6 +336,11 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
}) => Effect.Effect<CodexAccountSnapshot | undefined>,
|
||||
resolveSkills?: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProviderSkill> | undefined>,
|
||||
): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
@@ -449,12 +456,22 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
});
|
||||
}
|
||||
|
||||
const skills =
|
||||
(resolveSkills
|
||||
? yield* resolveSkills({
|
||||
binaryPath: codexSettings.binaryPath,
|
||||
homePath: codexSettings.homePath,
|
||||
cwd: process.cwd(),
|
||||
}).pipe(Effect.orElseSucceed(() => undefined))
|
||||
: undefined) ?? [];
|
||||
|
||||
if (yield* hasCustomModelProvider) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -484,6 +501,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -500,6 +518,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -518,6 +537,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -532,6 +552,46 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
});
|
||||
});
|
||||
|
||||
const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
codexSettings.customModels,
|
||||
DEFAULT_CODEX_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex provider status has not been checked in this session yet.",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const CodexProviderLive = Layer.effect(
|
||||
CodexProvider,
|
||||
Effect.gen(function* () {
|
||||
@@ -543,16 +603,29 @@ export const CodexProviderLive = Layer.effect(
|
||||
capacity: 4,
|
||||
timeToLive: Duration.minutes(5),
|
||||
lookup: (key: string) => {
|
||||
const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
|
||||
const [binaryPath, homePath, cwd] = JSON.parse(key) as [string, string | undefined, string];
|
||||
return probeCodexCapabilities({
|
||||
binaryPath,
|
||||
cwd,
|
||||
...(homePath ? { homePath } : {}),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const checkProvider = checkCodexProviderStatus((input) =>
|
||||
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
|
||||
const getDiscovery = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
}) =>
|
||||
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath, input.cwd]));
|
||||
|
||||
const checkProvider = checkCodexProviderStatus(
|
||||
(input) =>
|
||||
getDiscovery({
|
||||
...input,
|
||||
cwd: process.cwd(),
|
||||
}).pipe(Effect.map((discovery) => discovery?.account)),
|
||||
(input) => getDiscovery(input).pipe(Effect.map((discovery) => discovery?.skills)),
|
||||
).pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
@@ -569,6 +642,7 @@ export const CodexProviderLive = Layer.effect(
|
||||
Stream.map((settings) => settings.providers.codex),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingCodexProvider,
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from "./CodexProvider";
|
||||
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider";
|
||||
import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry";
|
||||
import { ServerConfig } from "../../config";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry";
|
||||
|
||||
@@ -221,6 +222,49 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes probed codex skills in the provider snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "pro" as const,
|
||||
sparkEnabled: true,
|
||||
}),
|
||||
() =>
|
||||
Effect.succeed([
|
||||
{
|
||||
name: "github:gh-fix-ci",
|
||||
path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
|
||||
enabled: true,
|
||||
displayName: "CI Debug",
|
||||
shortDescription: "Debug failing GitHub Actions checks",
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(status.skills, [
|
||||
{
|
||||
name: "github:gh-fix-ci",
|
||||
path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
|
||||
enabled: true,
|
||||
displayName: "CI Debug",
|
||||
shortDescription: "Debug failing GitHub Actions checks",
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
@@ -499,6 +543,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
@@ -509,12 +555,69 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
|
||||
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();
|
||||
@@ -522,6 +625,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
const joined = args.join(" ");
|
||||
@@ -549,8 +657,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
const registry = yield* ProviderRegistry;
|
||||
|
||||
const initial = yield* registry.getProviders;
|
||||
assert.deepStrictEqual(initial, []);
|
||||
|
||||
const refreshed = yield* registry.refresh("codex");
|
||||
assert.strictEqual(
|
||||
initial.find((status) => status.provider === "codex")?.status,
|
||||
refreshed.find((status) => status.provider === "codex")?.status,
|
||||
"ready",
|
||||
);
|
||||
|
||||
@@ -887,6 +998,85 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes probed claude slash commands in the provider snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
() => Effect.succeed("maxplan"),
|
||||
() =>
|
||||
Effect.succeed([
|
||||
{
|
||||
name: "review",
|
||||
description: "Review a pull request",
|
||||
input: { hint: "pr-or-branch" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(status.slashCommands, [
|
||||
{
|
||||
name: "review",
|
||||
description: "Review a pull request",
|
||||
input: { hint: "pr-or-branch" },
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("deduplicates probed claude slash commands by name", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
() => Effect.succeed("maxplan"),
|
||||
() =>
|
||||
Effect.succeed([
|
||||
{
|
||||
name: "ui",
|
||||
description: "Explore and refine UI",
|
||||
},
|
||||
{
|
||||
name: "ui",
|
||||
input: { hint: "component-or-screen" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(status.slashCommands, [
|
||||
{
|
||||
name: "ui",
|
||||
description: "Explore and refine UI",
|
||||
input: { hint: "component-or-screen" },
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns an api key label for claude api key auth", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
* @module ProviderRegistryLive
|
||||
*/
|
||||
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
|
||||
import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config";
|
||||
import { ClaudeProviderLive } from "./ClaudeProvider";
|
||||
import { CodexProviderLive } from "./CodexProvider";
|
||||
import type { ClaudeProviderShape } from "../Services/ClaudeProvider";
|
||||
@@ -13,6 +14,14 @@ import { ClaudeProvider } from "../Services/ClaudeProvider";
|
||||
import type { CodexProviderShape } from "../Services/CodexProvider";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry";
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
PROVIDER_CACHE_IDS,
|
||||
orderProviderSnapshots,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache";
|
||||
|
||||
const loadProviders = (
|
||||
codexProvider: CodexProviderShape,
|
||||
@@ -32,61 +41,152 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
Effect.gen(function* () {
|
||||
const codexProvider = yield* CodexProvider;
|
||||
const claudeProvider = yield* ClaudeProvider;
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
yield* loadProviders(codexProvider, claudeProvider),
|
||||
const fallbackProviders = yield* loadProviders(codexProvider, claudeProvider);
|
||||
const cachePathByProvider = new Map(
|
||||
PROVIDER_CACHE_IDS.map(
|
||||
(provider) =>
|
||||
[
|
||||
provider,
|
||||
resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
provider,
|
||||
}),
|
||||
] as const,
|
||||
),
|
||||
);
|
||||
const fallbackByProvider = new Map(
|
||||
fallbackProviders.map((provider) => [provider.provider, provider] as const),
|
||||
);
|
||||
const cachedProviders = yield* Effect.forEach(
|
||||
PROVIDER_CACHE_IDS,
|
||||
(provider) => {
|
||||
const filePath = cachePathByProvider.get(provider)!;
|
||||
const fallbackProvider = fallbackByProvider.get(provider)!;
|
||||
return readProviderStatusCache(filePath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.map((cachedProvider) =>
|
||||
cachedProvider === undefined
|
||||
? undefined
|
||||
: hydrateCachedProvider({
|
||||
cachedProvider,
|
||||
fallbackProvider,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.map((providers) =>
|
||||
orderProviderSnapshots(
|
||||
providers.filter((provider): provider is ServerProvider => provider !== undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
|
||||
const syncProviders = Effect.fn("syncProviders")(function* (options?: {
|
||||
readonly publish?: boolean;
|
||||
}) {
|
||||
const previousProviders = yield* Ref.get(providersRef);
|
||||
const providers = yield* loadProviders(codexProvider, claudeProvider);
|
||||
yield* Ref.set(providersRef, providers);
|
||||
const persistProvider = (provider: ServerProvider) =>
|
||||
writeProviderStatusCache({
|
||||
filePath: cachePathByProvider.get(provider.provider)!,
|
||||
provider,
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.ignore,
|
||||
);
|
||||
|
||||
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [provider.provider, provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(provider.provider, provider);
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* Effect.forEach(nextProviders, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
if (options?.publish !== false) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
const syncProvider = Effect.fn("syncProvider")(function* (
|
||||
provider: ServerProvider,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
|
||||
switch (provider) {
|
||||
case "codex":
|
||||
yield* codexProvider.refresh;
|
||||
break;
|
||||
return yield* codexProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
case "claudeAgent":
|
||||
yield* claudeProvider.refresh;
|
||||
break;
|
||||
return yield* claudeProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
default:
|
||||
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
break;
|
||||
return yield* Effect.all(
|
||||
[
|
||||
codexProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
),
|
||||
claudeProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
),
|
||||
],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.andThen(Ref.get(providersRef)));
|
||||
}
|
||||
return yield* syncProviders();
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, (provider) =>
|
||||
syncProvider(provider),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, (provider) =>
|
||||
syncProvider(provider),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return {
|
||||
getProviders: syncProviders({ publish: false }).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (provider?: ProviderKind) =>
|
||||
refresh(provider).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
Effect.orElseSucceed(() => [] as ReadonlyArray<ServerProvider>),
|
||||
),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import readline from "node:readline";
|
||||
import type { ServerProviderSkill } from "@t3tools/contracts";
|
||||
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
|
||||
|
||||
interface JsonRpcProbeResponse {
|
||||
@@ -10,10 +11,74 @@ interface JsonRpcProbeResponse {
|
||||
};
|
||||
}
|
||||
|
||||
export interface CodexDiscoverySnapshot {
|
||||
readonly account: CodexAccountSnapshot;
|
||||
readonly skills: ReadonlyArray<ServerProviderSkill>;
|
||||
}
|
||||
|
||||
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
|
||||
return typeof response.error?.message === "string" ? response.error.message : undefined;
|
||||
}
|
||||
|
||||
function readObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function readArray(value: unknown): ReadonlyArray<unknown> | undefined {
|
||||
return Array.isArray(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function readString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function nonEmptyTrimmed(value: unknown): string | undefined {
|
||||
const candidate = readString(value)?.trim();
|
||||
return candidate ? candidate : undefined;
|
||||
}
|
||||
|
||||
function parseCodexSkillsResult(result: unknown, cwd: string): ReadonlyArray<ServerProviderSkill> {
|
||||
const resultRecord = readObject(result);
|
||||
const dataBuckets = readArray(resultRecord?.data) ?? [];
|
||||
const matchingBucket = dataBuckets.find(
|
||||
(value) => nonEmptyTrimmed(readObject(value)?.cwd) === cwd,
|
||||
);
|
||||
const rawSkills =
|
||||
readArray(readObject(matchingBucket)?.skills) ?? readArray(resultRecord?.skills) ?? [];
|
||||
|
||||
return rawSkills.flatMap((value) => {
|
||||
const skill = readObject(value);
|
||||
const display = readObject(skill?.interface);
|
||||
const name = nonEmptyTrimmed(skill?.name);
|
||||
const path = nonEmptyTrimmed(skill?.path);
|
||||
if (!name || !path) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
name,
|
||||
path,
|
||||
enabled: skill?.enabled !== false,
|
||||
...(nonEmptyTrimmed(skill?.description)
|
||||
? { description: nonEmptyTrimmed(skill?.description) }
|
||||
: {}),
|
||||
...(nonEmptyTrimmed(skill?.scope) ? { scope: nonEmptyTrimmed(skill?.scope) } : {}),
|
||||
...(nonEmptyTrimmed(display?.displayName)
|
||||
? { displayName: nonEmptyTrimmed(display?.displayName) }
|
||||
: {}),
|
||||
...(nonEmptyTrimmed(skill?.shortDescription) || nonEmptyTrimmed(display?.shortDescription)
|
||||
? {
|
||||
shortDescription:
|
||||
nonEmptyTrimmed(skill?.shortDescription) ??
|
||||
nonEmptyTrimmed(display?.shortDescription),
|
||||
}
|
||||
: {}),
|
||||
} satisfies ServerProviderSkill,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCodexInitializeParams() {
|
||||
return {
|
||||
clientInfo: {
|
||||
@@ -40,11 +105,12 @@ export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): vo
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export async function probeCodexAccount(input: {
|
||||
export async function probeCodexDiscovery(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<CodexAccountSnapshot> {
|
||||
}): Promise<CodexDiscoverySnapshot> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(input.binaryPath, ["app-server"], {
|
||||
env: {
|
||||
@@ -57,6 +123,8 @@ export async function probeCodexAccount(input: {
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
let completed = false;
|
||||
let account: CodexAccountSnapshot | undefined;
|
||||
let skills: ReadonlyArray<ServerProviderSkill> | undefined;
|
||||
|
||||
const cleanup = () => {
|
||||
output.removeAllListeners();
|
||||
@@ -79,15 +147,25 @@ export async function probeCodexAccount(input: {
|
||||
reject(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(`Codex account probe failed: ${String(error)}.`),
|
||||
: new Error(`Codex discovery probe failed: ${String(error)}.`),
|
||||
),
|
||||
);
|
||||
|
||||
const maybeResolve = () => {
|
||||
if (account && skills !== undefined) {
|
||||
const resolvedAccount = account;
|
||||
const resolvedSkills = skills;
|
||||
finish(() => resolve({ account: resolvedAccount, skills: resolvedSkills }));
|
||||
}
|
||||
};
|
||||
|
||||
if (input.signal?.aborted) {
|
||||
fail(new Error("Codex account probe aborted."));
|
||||
fail(new Error("Codex discovery probe aborted."));
|
||||
return;
|
||||
}
|
||||
input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted.")));
|
||||
input.signal?.addEventListener("abort", () =>
|
||||
fail(new Error("Codex discovery probe aborted.")),
|
||||
);
|
||||
|
||||
const writeMessage = (message: unknown) => {
|
||||
if (!child.stdin.writable) {
|
||||
@@ -103,7 +181,7 @@ export async function probeCodexAccount(input: {
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
fail(new Error("Received invalid JSON from codex app-server during account probe."));
|
||||
fail(new Error("Received invalid JSON from codex app-server during discovery probe."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -120,18 +198,27 @@ export async function probeCodexAccount(input: {
|
||||
}
|
||||
|
||||
writeMessage({ method: "initialized" });
|
||||
writeMessage({ id: 2, method: "account/read", params: {} });
|
||||
writeMessage({ id: 2, method: "skills/list", params: { cwds: [input.cwd] } });
|
||||
writeMessage({ id: 3, method: "account/read", params: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.id === 2) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
skills = errorMessage ? [] : parseCodexSkillsResult(response.result, input.cwd);
|
||||
maybeResolve();
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.id === 3) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`account/read failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
finish(() => resolve(readCodexAccountSnapshot(response.result)));
|
||||
account = readCodexAccountSnapshot(response.result);
|
||||
maybeResolve();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
readonly initialSnapshot: (settings: Settings) => ServerProvider;
|
||||
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
@@ -20,7 +21,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const initialSettings = yield* input.getSettings;
|
||||
const initialSnapshot = yield* input.checkProvider;
|
||||
const initialSnapshot = input.initialSnapshot(initialSettings);
|
||||
const snapshotRef = yield* Ref.make(initialSnapshot);
|
||||
const settingsRef = yield* Ref.make(initialSettings);
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ import type {
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderAuth,
|
||||
ServerProviderSkill,
|
||||
ServerProviderSlashCommand,
|
||||
ServerProviderModel,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -130,6 +132,8 @@ export function buildServerProvider(input: {
|
||||
enabled: boolean;
|
||||
checkedAt: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
|
||||
skills?: ReadonlyArray<ServerProviderSkill>;
|
||||
probe: ProviderProbeResult;
|
||||
}): ServerProvider {
|
||||
return {
|
||||
@@ -142,6 +146,8 @@ export function buildServerProvider(input: {
|
||||
checkedAt: input.checkedAt,
|
||||
...(input.probe.message ? { message: input.probe.message } : {}),
|
||||
models: input.models,
|
||||
slashCommands: [...(input.slashCommands ?? [])],
|
||||
skills: [...(input.skills ?? [])],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem } from "effect";
|
||||
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "./providerStatusCache";
|
||||
|
||||
const makeProvider = (
|
||||
provider: ServerProvider["provider"],
|
||||
overrides?: Partial<ServerProvider>,
|
||||
): ServerProvider => ({
|
||||
provider,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-11T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
it.effect("writes and reads provider status snapshots", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-" });
|
||||
const codexProvider = makeProvider("codex");
|
||||
const claudeProvider = makeProvider("claudeAgent", {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
});
|
||||
const codexPath = resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
provider: "codex",
|
||||
});
|
||||
const claudePath = resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
yield* writeProviderStatusCache({
|
||||
filePath: codexPath,
|
||||
provider: codexProvider,
|
||||
});
|
||||
yield* writeProviderStatusCache({
|
||||
filePath: claudePath,
|
||||
provider: claudeProvider,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(codexPath), codexProvider);
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(claudePath), claudeProvider);
|
||||
}),
|
||||
);
|
||||
|
||||
it("hydrates cached provider status onto current settings-derived models", () => {
|
||||
const cachedCodex = makeProvider("codex", {
|
||||
checkedAt: "2026-04-10T12:00:00.000Z",
|
||||
models: [],
|
||||
message: "Cached message",
|
||||
skills: [
|
||||
{
|
||||
name: "github:gh-fix-ci",
|
||||
path: "/tmp/skills/gh-fix-ci/SKILL.md",
|
||||
enabled: true,
|
||||
displayName: "CI Debug",
|
||||
},
|
||||
],
|
||||
});
|
||||
const fallbackCodex = makeProvider("codex", {
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
message: "Pending refresh",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(
|
||||
hydrateCachedProvider({
|
||||
cachedProvider: cachedCodex,
|
||||
fallbackProvider: fallbackCodex,
|
||||
}),
|
||||
{
|
||||
...fallbackCodex,
|
||||
installed: cachedCodex.installed,
|
||||
version: cachedCodex.version,
|
||||
status: cachedCodex.status,
|
||||
auth: cachedCodex.auth,
|
||||
checkedAt: cachedCodex.checkedAt,
|
||||
slashCommands: cachedCodex.slashCommands,
|
||||
skills: cachedCodex.skills,
|
||||
message: cachedCodex.message,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores stale cached enabled state when the provider is now disabled", () => {
|
||||
const cachedCodex = makeProvider("codex", {
|
||||
checkedAt: "2026-04-10T12:00:00.000Z",
|
||||
message: "Cached ready status",
|
||||
});
|
||||
const disabledFallback = makeProvider("codex", {
|
||||
enabled: false,
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "disabled",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(
|
||||
hydrateCachedProvider({
|
||||
cachedProvider: cachedCodex,
|
||||
fallbackProvider: disabledFallback,
|
||||
}),
|
||||
disabledFallback,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import * as nodePath from "node:path";
|
||||
import { type ServerProvider, ServerProvider as ServerProviderSchema } from "@t3tools/contracts";
|
||||
import { Cause, Effect, FileSystem, Path, Schema } from "effect";
|
||||
|
||||
export const PROVIDER_CACHE_IDS = ["codex", "claudeAgent"] as const satisfies ReadonlyArray<
|
||||
ServerProvider["provider"]
|
||||
>;
|
||||
|
||||
const decodeProviderStatusCache = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(ServerProviderSchema),
|
||||
);
|
||||
|
||||
const providerOrderRank = (provider: ServerProvider["provider"]): number => {
|
||||
const rank = PROVIDER_CACHE_IDS.indexOf(provider);
|
||||
return rank === -1 ? Number.MAX_SAFE_INTEGER : rank;
|
||||
};
|
||||
|
||||
export const orderProviderSnapshots = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
[...providers].toSorted(
|
||||
(left, right) => providerOrderRank(left.provider) - providerOrderRank(right.provider),
|
||||
);
|
||||
|
||||
export const hydrateCachedProvider = (input: {
|
||||
readonly cachedProvider: ServerProvider;
|
||||
readonly fallbackProvider: ServerProvider;
|
||||
}): ServerProvider => {
|
||||
if (
|
||||
!input.fallbackProvider.enabled ||
|
||||
input.cachedProvider.enabled !== input.fallbackProvider.enabled
|
||||
) {
|
||||
return input.fallbackProvider;
|
||||
}
|
||||
|
||||
const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
|
||||
const hydratedProvider: ServerProvider = {
|
||||
...fallbackWithoutMessage,
|
||||
installed: input.cachedProvider.installed,
|
||||
version: input.cachedProvider.version,
|
||||
status: input.cachedProvider.status,
|
||||
auth: input.cachedProvider.auth,
|
||||
checkedAt: input.cachedProvider.checkedAt,
|
||||
slashCommands: input.cachedProvider.slashCommands,
|
||||
skills: input.cachedProvider.skills,
|
||||
};
|
||||
|
||||
return input.cachedProvider.message
|
||||
? { ...hydratedProvider, message: input.cachedProvider.message }
|
||||
: hydratedProvider;
|
||||
};
|
||||
|
||||
export const resolveProviderStatusCachePath = (input: {
|
||||
readonly cacheDir: string;
|
||||
readonly provider: ServerProvider["provider"];
|
||||
}) => nodePath.join(input.cacheDir, `${input.provider}.json`);
|
||||
|
||||
export const readProviderStatusCache = (filePath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return yield* decodeProviderStatusCache(trimmed).pipe(
|
||||
Effect.matchCauseEffect({
|
||||
onFailure: (cause) =>
|
||||
Effect.logWarning("failed to parse provider status cache, ignoring", {
|
||||
path: filePath,
|
||||
issues: Cause.pretty(cause),
|
||||
}).pipe(Effect.as(undefined)),
|
||||
onSuccess: Effect.succeed,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const writeProviderStatusCache = (input: {
|
||||
readonly filePath: string;
|
||||
readonly provider: ServerProvider;
|
||||
}) => {
|
||||
const tempPath = `${input.filePath}.${process.pid}.${Date.now()}.tmp`;
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const encoded = `${JSON.stringify(input.provider, null, 2)}\n`;
|
||||
|
||||
yield* fs.makeDirectory(path.dirname(input.filePath), { recursive: true });
|
||||
yield* fs.writeFileString(tempPath, encoded);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }));
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
+81
-240
@@ -31,6 +31,7 @@ import {
|
||||
FileSystem,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Option,
|
||||
Path,
|
||||
Stream,
|
||||
} from "effect";
|
||||
@@ -57,6 +58,10 @@ import {
|
||||
import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "./git/Services/GitStatusBroadcaster.ts";
|
||||
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
|
||||
import { Open, type OpenShape } from "./open.ts";
|
||||
import {
|
||||
@@ -68,7 +73,6 @@ import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionSnapshotQueryShape,
|
||||
} from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { PersistenceSqlError } from "./persistence/Errors.ts";
|
||||
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
ProviderRegistry,
|
||||
@@ -293,6 +297,7 @@ const buildAppUnderTest = (options?: {
|
||||
open?: Partial<OpenShape>;
|
||||
gitCore?: Partial<GitCoreShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
gitStatusBroadcaster?: Partial<GitStatusBroadcasterShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
orchestrationEngine?: Partial<OrchestrationEngineShape>;
|
||||
@@ -341,7 +346,11 @@ const buildAppUnderTest = (options?: {
|
||||
const gitManagerLayer = Layer.mock(GitManager)({
|
||||
...options?.layers?.gitManager,
|
||||
});
|
||||
const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
|
||||
const gitStatusBroadcasterLayer = options?.layers?.gitStatusBroadcaster
|
||||
? Layer.mock(GitStatusBroadcaster)({
|
||||
...options.layers.gitStatusBroadcaster,
|
||||
})
|
||||
: GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
|
||||
|
||||
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
|
||||
disableListenLog: true,
|
||||
@@ -410,6 +419,20 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery)({
|
||||
getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
}),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
...options?.layers?.projectionSnapshotQuery,
|
||||
}),
|
||||
),
|
||||
@@ -789,7 +812,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
"browser-session-cookie",
|
||||
"bearer-session-token",
|
||||
]);
|
||||
assert.equal(body.auth.sessionCookieName, "t3_session");
|
||||
assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -1767,7 +1790,20 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () =>
|
||||
Effect.gen(function* () {
|
||||
const providers = [] as const;
|
||||
const providers = [
|
||||
{
|
||||
provider: "codex" as const,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready" as const,
|
||||
auth: { status: "authenticated" as const },
|
||||
checkedAt: "2026-04-11T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const;
|
||||
const changeEvent = {
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
@@ -1824,7 +1860,20 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const providers = [] as const;
|
||||
const nextProviders = [
|
||||
{
|
||||
provider: "codex" as const,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready" as const,
|
||||
auth: { status: "authenticated" as const },
|
||||
checkedAt: "2026-04-11T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
@@ -1837,7 +1886,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
},
|
||||
providerRegistry: {
|
||||
getProviders: Effect.succeed([]),
|
||||
streamChanges: Stream.succeed(providers),
|
||||
streamChanges: Stream.succeed(nextProviders),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1851,10 +1900,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
const [first, second] = Array.from(events);
|
||||
assert.equal(first?.type, "snapshot");
|
||||
if (first?.type === "snapshot") {
|
||||
assert.deepEqual(first.config.providers, []);
|
||||
}
|
||||
assert.deepEqual(second, {
|
||||
version: 1,
|
||||
type: "providerStatuses",
|
||||
payload: { providers },
|
||||
payload: { providers: nextProviders },
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
@@ -2748,11 +2800,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const snapshotResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})),
|
||||
);
|
||||
assert.equal(snapshotResult.snapshotSequence, 1);
|
||||
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
@@ -2904,6 +2951,24 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "t3code/bootstrap-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
);
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
@@ -2928,6 +2993,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
gitStatusBroadcaster: {
|
||||
refreshStatus,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
@@ -3005,6 +3073,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
projectCwd: "/tmp/project",
|
||||
worktreePath: "/tmp/bootstrap-worktree",
|
||||
});
|
||||
assert.deepEqual(refreshStatus.mock.calls[0]?.[0], "/tmp/bootstrap-worktree");
|
||||
|
||||
const setupActivities = dispatchedCommands.filter(
|
||||
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
|
||||
@@ -3306,234 +3375,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const now = new Date().toISOString();
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
let replayCursor: number | null = null;
|
||||
const makeEvent = (sequence: number): OrchestrationEvent =>
|
||||
({
|
||||
sequence,
|
||||
eventId: `event-${sequence}`,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "thread.reverted",
|
||||
payload: {
|
||||
threadId,
|
||||
turnCount: sequence,
|
||||
},
|
||||
}) as OrchestrationEvent;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
getReadModel: () =>
|
||||
Effect.succeed({
|
||||
...makeDefaultOrchestrationReadModel(),
|
||||
snapshotSequence: 1,
|
||||
}),
|
||||
readEvents: (fromSequenceExclusive) => {
|
||||
replayCursor = fromSequenceExclusive;
|
||||
return Stream.make(makeEvent(2), makeEvent(3));
|
||||
},
|
||||
streamDomainEvents: Stream.make(makeEvent(3), makeEvent(4)),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
|
||||
Stream.take(3),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(replayCursor, 1);
|
||||
assert.deepEqual(
|
||||
Array.from(events).map((event) => event.sequence),
|
||||
[2, 3, 4],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("enriches replayed project events only once before streaming them to subscribers", () =>
|
||||
Effect.gen(function* () {
|
||||
let resolveCalls = 0;
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/t3tools/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:t3tools/t3code.git",
|
||||
},
|
||||
displayName: "t3tools/t3code",
|
||||
provider: "github" as const,
|
||||
owner: "t3tools",
|
||||
name: "t3code",
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
getReadModel: () =>
|
||||
Effect.succeed({
|
||||
...makeDefaultOrchestrationReadModel(),
|
||||
snapshotSequence: 0,
|
||||
}),
|
||||
readEvents: () =>
|
||||
Stream.make({
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: defaultProjectId,
|
||||
occurredAt: "2026-04-06T00:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "project.meta-updated",
|
||||
payload: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Replayed Project",
|
||||
updatedAt: "2026-04-06T00:00:00.000Z",
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "project.meta-updated" }>),
|
||||
streamDomainEvents: Stream.empty,
|
||||
},
|
||||
repositoryIdentityResolver: {
|
||||
resolve: () => {
|
||||
resolveCalls += 1;
|
||||
return Effect.succeed(repositoryIdentity);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
|
||||
Stream.take(1),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const event = Array.from(events)[0];
|
||||
assert.equal(resolveCalls, 1);
|
||||
assert.equal(event?.type, "project.meta-updated");
|
||||
assert.deepEqual(
|
||||
event && event.type === "project.meta-updated" ? event.payload.repositoryIdentity : null,
|
||||
repositoryIdentity,
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("enriches subscribed project meta updates with repository identity metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/t3tools/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "upstream",
|
||||
remoteUrl: "[email protected]:T3Tools/t3code.git",
|
||||
},
|
||||
displayName: "T3Tools/t3code",
|
||||
provider: "github",
|
||||
owner: "T3Tools",
|
||||
name: "t3code",
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
getReadModel: () =>
|
||||
Effect.succeed({
|
||||
...makeDefaultOrchestrationReadModel(),
|
||||
snapshotSequence: 0,
|
||||
}),
|
||||
streamDomainEvents: Stream.make({
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: defaultProjectId,
|
||||
occurredAt: "2026-04-05T00:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "project.meta-updated",
|
||||
payload: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Renamed Project",
|
||||
updatedAt: "2026-04-05T00:00:00.000Z",
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "project.meta-updated" }>),
|
||||
},
|
||||
repositoryIdentityResolver: {
|
||||
resolve: () => Effect.succeed(repositoryIdentity),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
|
||||
Stream.take(1),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const event = Array.from(events)[0];
|
||||
assert.equal(event?.type, "project.meta-updated");
|
||||
assert.deepEqual(
|
||||
event && event.type === "project.meta-updated" ? event.payload.repositoryIdentity : null,
|
||||
repositoryIdentity,
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc orchestration.getSnapshot errors", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
projectionSnapshotQuery: {
|
||||
getSnapshot: () =>
|
||||
Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
operation: "ProjectionSnapshotQuery.getSnapshot",
|
||||
detail: "projection unavailable",
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const result = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})).pipe(
|
||||
Effect.result,
|
||||
),
|
||||
);
|
||||
|
||||
assertTrue(result._tag === "Failure");
|
||||
assertTrue(result.failure._tag === "OrchestrationGetSnapshotError");
|
||||
assertInclude(result.failure.message, "Failed to load orchestration snapshot");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc terminal methods", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = {
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
import { DEFAULT_MODEL_BY_PROVIDER } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { DEFAULT_MODEL_BY_PROVIDER, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Deferred, Effect, Fiber, Option, Ref } from "effect";
|
||||
import { Deferred, Effect, Fiber, Option, Ref, Stream } from "effect";
|
||||
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import {
|
||||
getAutoBootstrapDefaultModelSelection,
|
||||
launchStartupHeartbeat,
|
||||
makeCommandGate,
|
||||
resolveAutoBootstrapWelcomeTargets,
|
||||
resolveWelcomeBase,
|
||||
ServerRuntimeStartupError,
|
||||
} from "./serverRuntimeStartup.ts";
|
||||
|
||||
@@ -70,6 +78,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
yield* launchStartupHeartbeat.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getCounts: () =>
|
||||
Deferred.await(releaseCounts).pipe(
|
||||
Effect.as({
|
||||
@@ -78,8 +87,11 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
}),
|
||||
),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
Effect.provideService(AnalyticsService, {
|
||||
record: () => Effect.void,
|
||||
@@ -89,3 +101,109 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolveWelcomeBase derives cwd and project name from server config", () =>
|
||||
Effect.gen(function* () {
|
||||
const welcome = yield* resolveWelcomeBase.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
} as never),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(welcome, {
|
||||
cwd: "/tmp/startup-project",
|
||||
projectName: "startup-project",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and thread ids", () => {
|
||||
const bootstrapProjectId = ProjectId.make("project-startup-bootstrap");
|
||||
const bootstrapThreadId = ThreadId.make("thread-startup-bootstrap");
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const targets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () =>
|
||||
Effect.succeed(
|
||||
Option.some({
|
||||
id: bootstrapProjectId,
|
||||
title: "Startup Project",
|
||||
workspaceRoot: "/tmp/startup-project",
|
||||
defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
}),
|
||||
),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(targets, {
|
||||
bootstrapProjectId,
|
||||
bootstrapThreadId,
|
||||
});
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const targets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
assert.equal(typeof targets.bootstrapProjectId, "string");
|
||||
assert.equal(typeof targets.bootstrapThreadId, "string");
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), ["project.create", "thread.create"]);
|
||||
}),
|
||||
);
|
||||
@@ -157,7 +157,18 @@ export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
});
|
||||
|
||||
const autoBootstrapWelcome = Effect.gen(function* () {
|
||||
export const resolveWelcomeBase = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
return {
|
||||
cwd: serverConfig.cwd,
|
||||
projectName,
|
||||
} as const;
|
||||
});
|
||||
|
||||
export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
@@ -221,12 +232,7 @@ const autoBootstrapWelcome = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
return {
|
||||
cwd: serverConfig.cwd,
|
||||
projectName,
|
||||
...(bootstrapProjectId ? { bootstrapProjectId } : {}),
|
||||
...(bootstrapThreadId ? { bootstrapThreadId } : {}),
|
||||
} as const;
|
||||
@@ -271,7 +277,7 @@ const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>)
|
||||
Effect.withSpan(`server.startup.${phase}`),
|
||||
);
|
||||
|
||||
const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
export const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const keybindings = yield* Keybindings;
|
||||
const orchestrationReactor = yield* OrchestrationReactor;
|
||||
@@ -322,15 +328,13 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
|
||||
);
|
||||
|
||||
yield* Effect.logDebug("startup phase: preparing welcome payload");
|
||||
const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome);
|
||||
const welcomeBase = yield* resolveWelcomeBase;
|
||||
const environment = yield* serverEnvironment.getDescriptor;
|
||||
yield* Effect.logDebug("startup phase: preparing welcome payload");
|
||||
yield* Effect.logDebug("startup phase: publishing welcome event", {
|
||||
environmentId: environment.environmentId,
|
||||
cwd: welcome.cwd,
|
||||
projectName: welcome.projectName,
|
||||
bootstrapProjectId: welcome.bootstrapProjectId,
|
||||
bootstrapThreadId: welcome.bootstrapThreadId,
|
||||
cwd: welcomeBase.cwd,
|
||||
projectName: welcomeBase.projectName,
|
||||
});
|
||||
yield* runStartupPhase(
|
||||
"welcome.publish",
|
||||
@@ -339,10 +343,47 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
type: "welcome",
|
||||
payload: {
|
||||
environment,
|
||||
...welcome,
|
||||
...welcomeBase,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
if (serverConfig.autoBootstrapProjectFromCwd) {
|
||||
yield* Effect.forkScoped(
|
||||
runStartupPhase(
|
||||
"welcome.autobootstrap",
|
||||
Effect.gen(function* () {
|
||||
const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets;
|
||||
if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.logDebug("startup phase: publishing bootstrapped welcome event", {
|
||||
environmentId: environment.environmentId,
|
||||
cwd: welcomeBase.cwd,
|
||||
projectName: welcomeBase.projectName,
|
||||
bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
|
||||
bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
|
||||
});
|
||||
yield* lifecycleEvents.publish({
|
||||
version: 1,
|
||||
type: "welcome",
|
||||
payload: {
|
||||
environment,
|
||||
...welcomeBase,
|
||||
...bootstrapTargets,
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("startup auto-bootstrap welcome failed", {
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.annotateSpans({
|
||||
"server.mode": serverConfig.mode,
|
||||
|
||||
@@ -129,6 +129,18 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prioritizes exact basename matches ahead of broader path matches", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-exact-ranking-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "docs/composer.tsx-notes.md");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "Composer.tsx", limit: 5 });
|
||||
|
||||
expect(result.entries[0]?.path).toBe("src/components/Composer.tsx");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("tracks truncation without sorting every fuzzy match", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-limit-" });
|
||||
|
||||
@@ -4,6 +4,12 @@ import type { Dirent } from "node:fs";
|
||||
import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect";
|
||||
|
||||
import { type ProjectEntry } from "@t3tools/contracts";
|
||||
import {
|
||||
insertRankedSearchResult,
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
type RankedSearchResult,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
@@ -40,10 +46,7 @@ interface SearchableWorkspaceEntry extends ProjectEntry {
|
||||
normalizedName: string;
|
||||
}
|
||||
|
||||
interface RankedWorkspaceEntry {
|
||||
entry: SearchableWorkspaceEntry;
|
||||
score: number;
|
||||
}
|
||||
type RankedWorkspaceEntry = RankedSearchResult<SearchableWorkspaceEntry>;
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
@@ -74,45 +77,6 @@ function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEnt
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreSubsequenceMatch(value: string, query: string): number | null {
|
||||
if (!query) return 0;
|
||||
|
||||
let queryIndex = 0;
|
||||
let firstMatchIndex = -1;
|
||||
let previousMatchIndex = -1;
|
||||
let gapPenalty = 0;
|
||||
|
||||
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
|
||||
if (value[valueIndex] !== query[queryIndex]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (firstMatchIndex === -1) {
|
||||
firstMatchIndex = valueIndex;
|
||||
}
|
||||
if (previousMatchIndex !== -1) {
|
||||
gapPenalty += valueIndex - previousMatchIndex - 1;
|
||||
}
|
||||
|
||||
previousMatchIndex = valueIndex;
|
||||
queryIndex += 1;
|
||||
if (queryIndex === query.length) {
|
||||
const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
|
||||
const lengthPenalty = Math.min(64, value.length - query.length);
|
||||
return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
@@ -120,81 +84,32 @@ function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | nu
|
||||
|
||||
const { normalizedPath, normalizedName } = entry;
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
if (normalizedName.includes(query)) return 5;
|
||||
if (normalizedPath.includes(query)) return 6;
|
||||
const scores = [
|
||||
scoreQueryMatch({
|
||||
value: normalizedName,
|
||||
query,
|
||||
exactBase: 0,
|
||||
prefixBase: 2,
|
||||
includesBase: 5,
|
||||
fuzzyBase: 100,
|
||||
}),
|
||||
scoreQueryMatch({
|
||||
value: normalizedPath,
|
||||
query,
|
||||
exactBase: 1,
|
||||
prefixBase: 3,
|
||||
boundaryBase: 4,
|
||||
includesBase: 6,
|
||||
fuzzyBase: 200,
|
||||
boundaryMarkers: ["/"],
|
||||
}),
|
||||
].filter((score): score is number => score !== null);
|
||||
|
||||
const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query);
|
||||
if (nameFuzzyScore !== null) {
|
||||
return 100 + nameFuzzyScore;
|
||||
if (scores.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query);
|
||||
if (pathFuzzyScore !== null) {
|
||||
return 200 + pathFuzzyScore;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function compareRankedWorkspaceEntries(
|
||||
left: RankedWorkspaceEntry,
|
||||
right: RankedWorkspaceEntry,
|
||||
): number {
|
||||
const scoreDelta = left.score - right.score;
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.entry.path.localeCompare(right.entry.path);
|
||||
}
|
||||
|
||||
function findInsertionIndex(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
): number {
|
||||
let low = 0;
|
||||
let high = rankedEntries.length;
|
||||
|
||||
while (low < high) {
|
||||
const middle = low + Math.floor((high - low) / 2);
|
||||
const current = rankedEntries[middle];
|
||||
if (!current) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (compareRankedWorkspaceEntries(candidate, current) < 0) {
|
||||
high = middle;
|
||||
} else {
|
||||
low = middle + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
function insertRankedEntry(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
limit: number,
|
||||
): void {
|
||||
if (limit <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertionIndex = findInsertionIndex(rankedEntries, candidate);
|
||||
if (rankedEntries.length < limit) {
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
return;
|
||||
}
|
||||
|
||||
if (insertionIndex >= limit) {
|
||||
return;
|
||||
}
|
||||
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
rankedEntries.pop();
|
||||
return Math.min(...scores);
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
@@ -469,7 +384,9 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
|
||||
return yield* Cache.get(workspaceIndexCache, normalizedCwd).pipe(
|
||||
Effect.map((index) => {
|
||||
const normalizedQuery = normalizeQuery(input.query);
|
||||
const normalizedQuery = normalizeSearchQuery(input.query, {
|
||||
trimLeadingPattern: /^[@./]+/,
|
||||
});
|
||||
const limit = Math.max(0, Math.floor(input.limit));
|
||||
const rankedEntries: RankedWorkspaceEntry[] = [];
|
||||
let matchedEntryCount = 0;
|
||||
@@ -481,11 +398,15 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
matchedEntryCount += 1;
|
||||
insertRankedEntry(rankedEntries, { entry, score }, limit);
|
||||
insertRankedSearchResult(
|
||||
rankedEntries,
|
||||
{ item: entry, score, tieBreaker: entry.path },
|
||||
limit,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
entries: rankedEntries.map((candidate) => candidate.entry),
|
||||
entries: rankedEntries.map((candidate) => candidate.item),
|
||||
truncated: index.truncated || matchedEntryCount > limit,
|
||||
};
|
||||
}),
|
||||
|
||||
+164
-67
@@ -1,4 +1,4 @@
|
||||
import { Cause, Effect, Layer, Queue, Ref, Schema, Stream } from "effect";
|
||||
import { Cause, Duration, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import {
|
||||
type AuthAccessStreamEvent,
|
||||
AuthSessionId,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type GitManagerServiceError,
|
||||
OrchestrationDispatchCommandError,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationShellStreamEvent,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
@@ -62,6 +63,30 @@ import {
|
||||
} from "./auth/Services/SessionCredentialService";
|
||||
import { respondToAuthError } from "./auth/http";
|
||||
|
||||
function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
OrchestrationEvent,
|
||||
{
|
||||
type:
|
||||
| "thread.message-sent"
|
||||
| "thread.proposed-plan-upserted"
|
||||
| "thread.activity-appended"
|
||||
| "thread.turn-diff-completed"
|
||||
| "thread.reverted"
|
||||
| "thread.session-set";
|
||||
}
|
||||
> {
|
||||
return (
|
||||
event.type === "thread.message-sent" ||
|
||||
event.type === "thread.proposed-plan-upserted" ||
|
||||
event.type === "thread.activity-appended" ||
|
||||
event.type === "thread.turn-diff-completed" ||
|
||||
event.type === "thread.reverted" ||
|
||||
event.type === "thread.session-set"
|
||||
);
|
||||
}
|
||||
|
||||
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
|
||||
|
||||
function toAuthAccessStreamEvent(
|
||||
change: BootstrapCredentialChange | SessionCredentialChange,
|
||||
revision: number,
|
||||
@@ -222,6 +247,57 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const enrichOrchestrationEvents = (events: ReadonlyArray<OrchestrationEvent>) =>
|
||||
Effect.forEach(events, enrichProjectEvent, { concurrency: 4 });
|
||||
|
||||
const toShellStreamEvent = (
|
||||
event: OrchestrationEvent,
|
||||
): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
case "project.meta-updated":
|
||||
return projectionSnapshotQuery.getProjectShellById(event.payload.projectId).pipe(
|
||||
Effect.map((project) =>
|
||||
Option.map(project, (nextProject) => ({
|
||||
kind: "project-upserted" as const,
|
||||
sequence: event.sequence,
|
||||
project: nextProject,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
case "project.deleted":
|
||||
return Effect.succeed(
|
||||
Option.some({
|
||||
kind: "project-removed" as const,
|
||||
sequence: event.sequence,
|
||||
projectId: event.payload.projectId,
|
||||
}),
|
||||
);
|
||||
case "thread.deleted":
|
||||
return Effect.succeed(
|
||||
Option.some({
|
||||
kind: "thread-removed" as const,
|
||||
sequence: event.sequence,
|
||||
threadId: event.payload.threadId,
|
||||
}),
|
||||
);
|
||||
default:
|
||||
if (event.aggregateKind !== "thread") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return projectionSnapshotQuery
|
||||
.getThreadShellById(ThreadId.make(event.aggregateId))
|
||||
.pipe(
|
||||
Effect.map((thread) =>
|
||||
Option.map(thread, (nextThread) => ({
|
||||
kind: "thread-upserted" as const,
|
||||
sequence: event.sequence,
|
||||
thread: nextThread,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const dispatchBootstrapTurnStart = (
|
||||
command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
|
||||
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
|
||||
@@ -390,6 +466,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
branch: worktree.worktree.branch,
|
||||
worktreePath: targetWorktreePath,
|
||||
});
|
||||
yield* refreshGitStatus(targetWorktreePath);
|
||||
}
|
||||
|
||||
yield* runSetupProgram();
|
||||
@@ -467,20 +544,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
|
||||
|
||||
return WsRpcGroup.of({
|
||||
[ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_WS_METHODS.getSnapshot,
|
||||
projectionSnapshotQuery.getSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_WS_METHODS.dispatchCommand,
|
||||
@@ -561,65 +624,85 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
|
||||
[ORCHESTRATION_WS_METHODS.subscribeShell]: (_input) =>
|
||||
observeRpcStreamEffect(
|
||||
WS_METHODS.subscribeOrchestrationDomainEvents,
|
||||
ORCHESTRATION_WS_METHODS.subscribeShell,
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* orchestrationEngine.getReadModel();
|
||||
const fromSequenceExclusive = snapshot.snapshotSequence;
|
||||
const replayEvents: Array<OrchestrationEvent> = yield* Stream.runCollect(
|
||||
orchestrationEngine.readEvents(fromSequenceExclusive),
|
||||
).pipe(
|
||||
Effect.map((events) => Array.from(events)),
|
||||
Effect.flatMap(enrichOrchestrationEvents),
|
||||
Effect.catch(() => Effect.succeed([] as Array<OrchestrationEvent>)),
|
||||
const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration shell snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const replayStream = Stream.fromIterable(replayEvents);
|
||||
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.mapEffect(enrichProjectEvent),
|
||||
Stream.mapEffect(toShellStreamEvent),
|
||||
Stream.flatMap((event) =>
|
||||
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
|
||||
),
|
||||
);
|
||||
const source = Stream.merge(replayStream, liveStream);
|
||||
type SequenceState = {
|
||||
readonly nextSequence: number;
|
||||
readonly pendingBySequence: Map<number, OrchestrationEvent>;
|
||||
};
|
||||
const state = yield* Ref.make<SequenceState>({
|
||||
nextSequence: fromSequenceExclusive + 1,
|
||||
pendingBySequence: new Map<number, OrchestrationEvent>(),
|
||||
});
|
||||
|
||||
return source.pipe(
|
||||
Stream.mapEffect((event) =>
|
||||
Ref.modify(
|
||||
state,
|
||||
({
|
||||
nextSequence,
|
||||
pendingBySequence,
|
||||
}): [Array<OrchestrationEvent>, SequenceState] => {
|
||||
if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) {
|
||||
return [[], { nextSequence, pendingBySequence }];
|
||||
}
|
||||
|
||||
const updatedPending = new Map(pendingBySequence);
|
||||
updatedPending.set(event.sequence, event);
|
||||
|
||||
const emit: Array<OrchestrationEvent> = [];
|
||||
let expected = nextSequence;
|
||||
for (;;) {
|
||||
const expectedEvent = updatedPending.get(expected);
|
||||
if (!expectedEvent) {
|
||||
break;
|
||||
}
|
||||
emit.push(expectedEvent);
|
||||
updatedPending.delete(expected);
|
||||
expected += 1;
|
||||
}
|
||||
|
||||
return [emit, { nextSequence: expected, pendingBySequence: updatedPending }];
|
||||
},
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot,
|
||||
}),
|
||||
liveStream,
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>
|
||||
observeRpcStreamEffect(
|
||||
ORCHESTRATION_WS_METHODS.subscribeThread,
|
||||
Effect.gen(function* () {
|
||||
const [threadDetail, snapshotSequence] = yield* Effect.all([
|
||||
projectionSnapshotQuery.getThreadDetailById(input.threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: `Failed to load thread ${input.threadId}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Stream.flatMap((events) => Stream.fromIterable(events)),
|
||||
orchestrationEngine
|
||||
.getReadModel()
|
||||
.pipe(Effect.map((readModel) => readModel.snapshotSequence)),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadDetail)) {
|
||||
return yield* new OrchestrationGetSnapshotError({
|
||||
message: `Thread ${input.threadId} was not found`,
|
||||
cause: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.filter(
|
||||
(event) =>
|
||||
event.aggregateKind === "thread" &&
|
||||
event.aggregateId === input.threadId &&
|
||||
isThreadDetailEvent(event),
|
||||
),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event,
|
||||
})),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot: {
|
||||
snapshotSequence,
|
||||
thread: threadDetail.value,
|
||||
},
|
||||
}),
|
||||
liveStream,
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
@@ -838,6 +921,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
type: "providerStatuses" as const,
|
||||
payload: { providers },
|
||||
})),
|
||||
Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)),
|
||||
);
|
||||
const settingsUpdates = serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => ({
|
||||
@@ -847,13 +931,26 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
})),
|
||||
);
|
||||
|
||||
yield* Effect.all(
|
||||
[providerRegistry.refresh("codex"), providerRegistry.refresh("claudeAgent")],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
|
||||
|
||||
const liveUpdates = Stream.merge(
|
||||
keybindingsUpdates,
|
||||
Stream.merge(providerStatuses, settingsUpdates),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
version: 1 as const,
|
||||
type: "snapshot" as const,
|
||||
config: yield* loadServerConfig,
|
||||
}),
|
||||
Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
|
||||
liveUpdates,
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
@@ -29,7 +30,6 @@
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
|
||||
@@ -424,7 +424,7 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3773/api/auth/session");
|
||||
});
|
||||
|
||||
it("revalidates the server session state after a previous authenticated result", async () => {
|
||||
it("memoizes the authenticated gate state after the first successful read", async () => {
|
||||
const fetchMock = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(
|
||||
@@ -459,15 +459,9 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
status: "authenticated",
|
||||
});
|
||||
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
|
||||
status: "requires-auth",
|
||||
auth: {
|
||||
policy: "loopback-browser",
|
||||
bootstrapMethods: ["one-time-token"],
|
||||
sessionMethods: ["browser-session-cookie"],
|
||||
sessionCookieName: "t3_session",
|
||||
},
|
||||
status: "authenticated",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("creates a pairing credential from the authenticated auth endpoint", async () => {
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
|
||||
|
||||
describe("isScrollContainerNearBottom", () => {
|
||||
it("returns true when already at bottom", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 600,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true when within the auto-scroll threshold", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 540,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when the user is meaningfully above the bottom", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 520,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("clamps negative thresholds to zero", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom(
|
||||
{
|
||||
scrollTop: 539,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
},
|
||||
-1,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the default threshold for non-finite values", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom(
|
||||
{
|
||||
scrollTop: 540,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
},
|
||||
Number.NaN,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(AUTO_SCROLL_BOTTOM_THRESHOLD_PX).toBe(64);
|
||||
});
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
export const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 64;
|
||||
|
||||
interface ScrollPosition {
|
||||
scrollTop: number;
|
||||
clientHeight: number;
|
||||
scrollHeight: number;
|
||||
}
|
||||
|
||||
export function isScrollContainerNearBottom(
|
||||
position: ScrollPosition,
|
||||
thresholdPx = AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
|
||||
): boolean {
|
||||
const threshold = Number.isFinite(thresholdPx)
|
||||
? Math.max(0, thresholdPx)
|
||||
: AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
|
||||
|
||||
const { scrollTop, clientHeight, scrollHeight } = position;
|
||||
if (![scrollTop, clientHeight, scrollHeight].every(Number.isFinite)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const distanceFromBottom = scrollHeight - clientHeight - scrollTop;
|
||||
return distanceFromBottom <= threshold;
|
||||
}
|
||||
@@ -77,4 +77,54 @@ describe("clientPersistenceStorage", () => {
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reads and writes workspace documents as JSON blobs", async () => {
|
||||
const testWindow = getTestWindow();
|
||||
const {
|
||||
WORKSPACE_DOCUMENT_STORAGE_KEY,
|
||||
readBrowserWorkspaceDocument,
|
||||
writeBrowserWorkspaceDocument,
|
||||
} = await import("./clientPersistenceStorage");
|
||||
const workspaceDocument = {
|
||||
version: 1 as const,
|
||||
layoutEngine: "split" as const,
|
||||
rootNodeId: "node-1",
|
||||
nodesById: {
|
||||
"node-1": {
|
||||
id: "node-1",
|
||||
kind: "window" as const,
|
||||
windowId: "window-1",
|
||||
},
|
||||
},
|
||||
windowsById: {
|
||||
"window-1": {
|
||||
id: "window-1",
|
||||
tabIds: ["surface-1"],
|
||||
activeTabId: "surface-1",
|
||||
},
|
||||
},
|
||||
surfacesById: {
|
||||
"surface-1": {
|
||||
id: "surface-1",
|
||||
kind: "thread" as const,
|
||||
input: {
|
||||
scope: "server" as const,
|
||||
threadRef: {
|
||||
environmentId: testEnvironmentId,
|
||||
threadId: "thread-1",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
focusedWindowId: "window-1",
|
||||
mobileActiveWindowId: "window-1",
|
||||
};
|
||||
|
||||
writeBrowserWorkspaceDocument(workspaceDocument);
|
||||
|
||||
expect(readBrowserWorkspaceDocument<typeof workspaceDocument>()).toEqual(workspaceDocument);
|
||||
expect(JSON.parse(testWindow.localStorage.getItem(WORKSPACE_DOCUMENT_STORAGE_KEY)!)).toEqual(
|
||||
workspaceDocument,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorag
|
||||
|
||||
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
|
||||
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
|
||||
export const WORKSPACE_DOCUMENT_STORAGE_KEY = "t3code:workspace-document:v1";
|
||||
|
||||
const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
@@ -34,6 +35,34 @@ function hasWindow(): boolean {
|
||||
return typeof window !== "undefined";
|
||||
}
|
||||
|
||||
function readBrowserJsonDocument<T>(storageKey: string): T | null {
|
||||
if (!hasWindow()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeBrowserJsonDocument<T>(storageKey: string, document: T): void {
|
||||
if (!hasWindow()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(storageKey, JSON.stringify(document));
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking the app.
|
||||
}
|
||||
}
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
record: PersistedSavedEnvironmentRecord,
|
||||
): PersistedSavedEnvironmentRecord {
|
||||
@@ -192,3 +221,11 @@ export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentId
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export function readBrowserWorkspaceDocument<T>(): T | null {
|
||||
return readBrowserJsonDocument<T>(WORKSPACE_DOCUMENT_STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function writeBrowserWorkspaceDocument<T>(document: T): void {
|
||||
writeBrowserJsonDocument(WORKSPACE_DOCUMENT_STORAGE_KEY, document);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
export interface CommandPaletteWorkspaceTarget {
|
||||
disposition: "split-right" | "split-down";
|
||||
}
|
||||
|
||||
interface CommandPaletteStore {
|
||||
open: boolean;
|
||||
workspaceTarget: CommandPaletteWorkspaceTarget | null;
|
||||
setOpen: (open: boolean) => void;
|
||||
toggleOpen: () => void;
|
||||
openWorkspaceTarget: (target: CommandPaletteWorkspaceTarget) => void;
|
||||
clearWorkspaceTarget: () => void;
|
||||
}
|
||||
|
||||
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
|
||||
open: false,
|
||||
workspaceTarget: null,
|
||||
setOpen: (open) => set({ open, ...(open ? {} : { workspaceTarget: null }) }),
|
||||
toggleOpen: () =>
|
||||
set((state) => ({
|
||||
open: !state.open,
|
||||
...(!state.open ? {} : { workspaceTarget: null }),
|
||||
})),
|
||||
openWorkspaceTarget: (target) => set({ open: true, workspaceTarget: target }),
|
||||
clearWorkspaceTarget: () => set({ workspaceTarget: null }),
|
||||
}));
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
resolveEffectiveEnvMode,
|
||||
resolveEnvModeLabel,
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
@@ -157,6 +158,16 @@ describe("resolveCurrentWorkspaceLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveLockedWorkspaceLabel", () => {
|
||||
it("uses a shorter label for the main repo checkout", () => {
|
||||
expect(resolveLockedWorkspaceLabel(null)).toBe("Local checkout");
|
||||
});
|
||||
|
||||
it("uses a shorter label for an attached worktree", () => {
|
||||
expect(resolveLockedWorkspaceLabel("/repo/.t3/worktrees/feature-a")).toBe("Worktree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
it("strips the remote prefix from a remote ref", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
|
||||
|
||||
@@ -50,6 +50,10 @@ export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null):
|
||||
return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
|
||||
}
|
||||
|
||||
export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): string {
|
||||
return activeWorktreePath ? "Worktree" : "Local checkout";
|
||||
}
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
hasServerThread: boolean;
|
||||
|
||||
@@ -20,6 +20,9 @@ interface BranchToolbarProps {
|
||||
threadId: ThreadId;
|
||||
draftId?: DraftId;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
effectiveEnvModeOverride?: EnvMode;
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
envLocked: boolean;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
@@ -32,6 +35,9 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
threadId,
|
||||
draftId,
|
||||
onEnvModeChange,
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
envLocked,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
@@ -44,7 +50,9 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
);
|
||||
const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]);
|
||||
const serverThread = useStore(serverThreadSelector);
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
const activeProjectRef = serverThread
|
||||
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
|
||||
: draftThread
|
||||
@@ -57,11 +65,13 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
const activeProject = useStore(activeProjectSelector);
|
||||
const hasActiveThread = serverThread !== undefined || draftThread !== null;
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: serverThread !== undefined,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const effectiveEnvMode =
|
||||
effectiveEnvModeOverride ??
|
||||
resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: serverThread !== undefined,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const envModeLocked = envLocked || (serverThread !== undefined && activeWorktreePath !== null);
|
||||
|
||||
const showEnvironmentPicker =
|
||||
@@ -96,6 +106,9 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
threadId={threadId}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
envLocked={envLocked}
|
||||
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
|
||||
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
|
||||
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
|
||||
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import {
|
||||
type CSSProperties,
|
||||
useCallback,
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
@@ -38,6 +37,7 @@ import {
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxListVirtualized,
|
||||
ComboboxPopup,
|
||||
ComboboxStatus,
|
||||
ComboboxTrigger,
|
||||
@@ -49,6 +49,9 @@ interface BranchToolbarBranchSelectorProps {
|
||||
threadId: ThreadId;
|
||||
draftId?: DraftId;
|
||||
envLocked: boolean;
|
||||
effectiveEnvModeOverride?: "local" | "worktree";
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
@@ -77,6 +80,9 @@ export function BranchToolbarBranchSelector({
|
||||
threadId,
|
||||
draftId,
|
||||
envLocked,
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
@@ -91,7 +97,9 @@ export function BranchToolbarBranchSelector({
|
||||
const serverThread = useStore(serverThreadSelector);
|
||||
const serverSession = serverThread?.session ?? null;
|
||||
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
|
||||
const activeProjectRef = serverThread
|
||||
@@ -106,16 +114,21 @@ export function BranchToolbarBranchSelector({
|
||||
const activeProject = useStore(activeProjectSelector);
|
||||
|
||||
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
|
||||
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
|
||||
const activeThreadBranch =
|
||||
activeThreadBranchOverride !== undefined
|
||||
? activeThreadBranchOverride
|
||||
: (serverThread?.branch ?? draftThread?.branch ?? null);
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const branchCwd = activeWorktreePath ?? activeProjectCwd;
|
||||
const hasServerThread = serverThread !== undefined;
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const effectiveEnvMode =
|
||||
effectiveEnvModeOverride ??
|
||||
resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread branch mutation (colocated — only this component calls it)
|
||||
@@ -144,6 +157,7 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
onActiveThreadBranchOverrideChange?.(branch);
|
||||
setThreadBranchAction(threadRef, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
@@ -165,6 +179,7 @@ export function BranchToolbarBranchSelector({
|
||||
serverSession,
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
setThreadBranchAction,
|
||||
setDraftThreadContext,
|
||||
draftId,
|
||||
@@ -388,7 +403,7 @@ export function BranchToolbarBranchSelector({
|
||||
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combobox / virtualizer plumbing
|
||||
// Combobox / list plumbing
|
||||
// ---------------------------------------------------------------------------
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
@@ -423,49 +438,22 @@ export function BranchToolbarBranchSelector({
|
||||
|
||||
void fetchNextPage().catch(() => undefined);
|
||||
}, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
|
||||
const branchListVirtualizer = useVirtualizer({
|
||||
count: filteredBranchPickerItems.length,
|
||||
estimateSize: (index) =>
|
||||
filteredBranchPickerItems[index] === checkoutPullRequestItemValue ? 44 : 28,
|
||||
getScrollElement: () => branchListScrollElementRef.current,
|
||||
overscan: 12,
|
||||
enabled: isBranchMenuOpen && shouldVirtualizeBranchList,
|
||||
initialRect: {
|
||||
height: 224,
|
||||
width: 0,
|
||||
},
|
||||
});
|
||||
const virtualBranchRows = branchListVirtualizer.getVirtualItems();
|
||||
const setBranchListRef = useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
branchListScrollElementRef.current =
|
||||
(element?.parentElement as HTMLDivElement | null) ?? null;
|
||||
if (element) {
|
||||
branchListVirtualizer.measure();
|
||||
}
|
||||
},
|
||||
[branchListVirtualizer],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isBranchMenuOpen || !shouldVirtualizeBranchList) return;
|
||||
queueMicrotask(() => {
|
||||
branchListVirtualizer.measure();
|
||||
});
|
||||
}, [
|
||||
branchListVirtualizer,
|
||||
filteredBranchPickerItems.length,
|
||||
isBranchMenuOpen,
|
||||
shouldVirtualizeBranchList,
|
||||
]);
|
||||
const branchListRef = useRef<LegendListRef | null>(null);
|
||||
const setBranchListRef = useCallback((element: HTMLDivElement | null) => {
|
||||
branchListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isBranchMenuOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
branchListScrollElementRef.current?.scrollTo({ top: 0 });
|
||||
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
|
||||
if (shouldVirtualizeBranchList) {
|
||||
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
|
||||
} else {
|
||||
branchListScrollElementRef.current?.scrollTo({ top: 0 });
|
||||
}
|
||||
}, [deferredTrimmedBranchQuery, isBranchMenuOpen, shouldVirtualizeBranchList]);
|
||||
|
||||
useEffect(() => {
|
||||
const scrollElement = branchListScrollElementRef.current;
|
||||
@@ -485,8 +473,9 @@ export function BranchToolbarBranchSelector({
|
||||
}, [isBranchMenuOpen, maybeFetchNextBranchPage]);
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldVirtualizeBranchList) return;
|
||||
maybeFetchNextBranchPage();
|
||||
}, [branches.length, maybeFetchNextBranchPage]);
|
||||
}, [branches.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
|
||||
|
||||
const triggerLabel = getBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
@@ -494,7 +483,7 @@ export function BranchToolbarBranchSelector({
|
||||
resolvedActiveBranch,
|
||||
});
|
||||
|
||||
function renderPickerItem(itemValue: string, index: number, style?: CSSProperties) {
|
||||
function renderPickerItem(itemValue: string, index: number) {
|
||||
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
|
||||
return (
|
||||
<ComboboxItem
|
||||
@@ -502,7 +491,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
style={style}
|
||||
onClick={() => {
|
||||
if (!prReference || !onCheckoutPullRequestRequest) {
|
||||
return;
|
||||
@@ -527,7 +515,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
style={style}
|
||||
onClick={() => createBranch(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||
@@ -555,7 +542,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
style={style}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
@@ -573,8 +559,13 @@ export function BranchToolbarBranchSelector({
|
||||
autoHighlight
|
||||
virtualized={shouldVirtualizeBranchList}
|
||||
onItemHighlighted={(_value, eventDetails) => {
|
||||
if (!isBranchMenuOpen || eventDetails.index < 0) return;
|
||||
branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
|
||||
if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
|
||||
return;
|
||||
}
|
||||
branchListRef.current?.scrollIndexIntoView?.({
|
||||
index: eventDetails.index,
|
||||
animated: false,
|
||||
});
|
||||
}}
|
||||
onOpenChange={handleOpenChange}
|
||||
open={isBranchMenuOpen}
|
||||
@@ -602,30 +593,30 @@ export function BranchToolbarBranchSelector({
|
||||
</div>
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
<ComboboxList ref={setBranchListRef} className="max-h-56">
|
||||
{shouldVirtualizeBranchList ? (
|
||||
<div
|
||||
className="relative"
|
||||
style={{
|
||||
height: `${branchListVirtualizer.getTotalSize()}px`,
|
||||
{shouldVirtualizeBranchList ? (
|
||||
<ComboboxListVirtualized>
|
||||
<LegendList<string>
|
||||
ref={branchListRef}
|
||||
data={filteredBranchPickerItems}
|
||||
keyExtractor={(item) => item}
|
||||
renderItem={({ item, index }) => renderPickerItem(item, index)}
|
||||
estimatedItemSize={28}
|
||||
drawDistance={336}
|
||||
onEndReached={() => {
|
||||
if (hasNextPage && !isFetchingNextPage) {
|
||||
void fetchNextPage().catch(() => undefined);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{virtualBranchRows.map((virtualRow) => {
|
||||
const itemValue = filteredBranchPickerItems[virtualRow.index];
|
||||
if (!itemValue) return null;
|
||||
return renderPickerItem(itemValue, virtualRow.index, {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
});
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))
|
||||
)}
|
||||
</ComboboxList>
|
||||
style={{ maxHeight: "14rem" }}
|
||||
/>
|
||||
</ComboboxListVirtualized>
|
||||
) : (
|
||||
<ComboboxList ref={setBranchListRef} className="max-h-56">
|
||||
{filteredBranchPickerItems.map((itemValue, index) =>
|
||||
renderPickerItem(itemValue, index),
|
||||
)}
|
||||
</ComboboxList>
|
||||
)}
|
||||
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
|
||||
</ComboboxPopup>
|
||||
</Combobox>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { memo, useMemo } from "react";
|
||||
import {
|
||||
resolveCurrentWorkspaceLabel,
|
||||
resolveEnvModeLabel,
|
||||
resolveLockedWorkspaceLabel,
|
||||
type EnvMode,
|
||||
} from "./BranchToolbar.logic";
|
||||
import {
|
||||
@@ -43,12 +44,12 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
{activeWorktreePath ? (
|
||||
<>
|
||||
<FolderGitIcon className="size-3" />
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FolderIcon className="size-3" />
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,7 @@ import {
|
||||
deriveComposerSendState,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
resolveSendEnvMode,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
waitForStartedServerThread,
|
||||
} from "./ChatView.logic";
|
||||
@@ -82,6 +83,17 @@ describe("buildExpiredTerminalContextToastCopy", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSendEnvMode", () => {
|
||||
it("keeps worktree mode for git repositories", () => {
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");
|
||||
});
|
||||
|
||||
it("forces local mode for non-git repositories", () => {
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: false })).toBe("local");
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "local", isGitRepo: false })).toBe("local");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileMountedTerminalThreadIds", () => {
|
||||
it("keeps previously mounted open threads and adds the active open thread", () => {
|
||||
expect(
|
||||
@@ -530,6 +542,142 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not clear local dispatch while the session is running a newer turn than latestTurn", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: previousLatestTurn,
|
||||
session: {
|
||||
...previousSession,
|
||||
status: "running",
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.make("turn-2"),
|
||||
updatedAt: "2026-03-29T00:01:00.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not clear local dispatch while the session is running but latestTurn has not advanced yet", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: previousLatestTurn,
|
||||
session: {
|
||||
...previousSession,
|
||||
status: "running",
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: undefined,
|
||||
updatedAt: "2026-03-29T00:01:00.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("clears local dispatch once the running latestTurn matches the active session turn", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: {
|
||||
...previousLatestTurn,
|
||||
turnId: TurnId.make("turn-2"),
|
||||
state: "running",
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: null,
|
||||
},
|
||||
session: {
|
||||
...previousSession,
|
||||
status: "running",
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.make("turn-2"),
|
||||
updatedAt: "2026-03-29T00:01:01.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("clears local dispatch when the session changes without an observed running phase", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import { Schema } from "effect";
|
||||
import { selectThreadByRef, useStore } from "../store";
|
||||
@@ -17,10 +16,10 @@ import {
|
||||
stripInlineTerminalContextPlaceholders,
|
||||
type TerminalContextDraft,
|
||||
} from "../lib/terminalContext";
|
||||
import type { DraftThreadEnvMode } from "../composerDraftStore";
|
||||
|
||||
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
|
||||
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
|
||||
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
|
||||
|
||||
@@ -157,10 +156,11 @@ export function readFileAsDataUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
export function buildTemporaryWorktreeBranchName(): string {
|
||||
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||
const token = randomUUID().slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
export function resolveSendEnvMode(input: {
|
||||
requestedEnvMode: DraftThreadEnvMode;
|
||||
isGitRepo: boolean;
|
||||
}): DraftThreadEnvMode {
|
||||
return input.isGitRepo ? input.requestedEnvMode : "local";
|
||||
}
|
||||
|
||||
export function cloneComposerImageForRetry(
|
||||
@@ -322,23 +322,37 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
if (!input.localDispatch) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
input.phase === "running" ||
|
||||
input.hasPendingApproval ||
|
||||
input.hasPendingUserInput ||
|
||||
Boolean(input.threadError)
|
||||
) {
|
||||
if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const latestTurn = input.latestTurn ?? null;
|
||||
const session = input.session ?? null;
|
||||
|
||||
return (
|
||||
const latestTurnChanged =
|
||||
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
|
||||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
|
||||
|
||||
if (input.phase === "running") {
|
||||
if (!latestTurnChanged) {
|
||||
return false;
|
||||
}
|
||||
if (latestTurn?.startedAt === null || latestTurn === null) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
session?.activeTurnId !== undefined &&
|
||||
session.activeTurnId !== null &&
|
||||
latestTurn?.turnId !== session.activeTurnId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
latestTurnChanged ||
|
||||
input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) ||
|
||||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,166 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import type { Thread } from "../types";
|
||||
import {
|
||||
buildThreadActionItems,
|
||||
filterCommandPaletteGroups,
|
||||
type CommandPaletteGroup,
|
||||
} from "./CommandPalette.logic";
|
||||
|
||||
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
codexThreadId: null,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadActionItems", () => {
|
||||
it("orders threads by most recent activity and formats timestamps from updatedAt", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-03-25T12:00:00.000Z"));
|
||||
|
||||
try {
|
||||
const items = buildThreadActionItems({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-older"),
|
||||
title: "Older thread",
|
||||
updatedAt: "2026-03-24T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-newer"),
|
||||
title: "Newer thread",
|
||||
createdAt: "2026-03-20T00:00:00.000Z",
|
||||
updatedAt: "2026-03-20T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
projectTitleById: new Map([[PROJECT_ID, "Project"]]),
|
||||
sortOrder: "updated_at",
|
||||
icon: null,
|
||||
runThread: async (_thread) => undefined,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.value)).toEqual([
|
||||
"thread:thread-older",
|
||||
"thread:thread-newer",
|
||||
]);
|
||||
expect(items[0]?.timestamp).toBe("1d ago");
|
||||
expect(items[1]?.timestamp).toBe("5d ago");
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("ranks thread title matches ahead of contextual project-name matches", () => {
|
||||
const threadItems = buildThreadActionItems({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-context-match"),
|
||||
title: "Fix navbar spacing",
|
||||
updatedAt: "2026-03-20T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-title-match"),
|
||||
title: "Project kickoff notes",
|
||||
createdAt: "2026-03-02T00:00:00.000Z",
|
||||
updatedAt: "2026-03-19T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
projectTitleById: new Map([[PROJECT_ID, "Project"]]),
|
||||
sortOrder: "updated_at",
|
||||
icon: null,
|
||||
runThread: async (_thread) => undefined,
|
||||
});
|
||||
|
||||
const groups = filterCommandPaletteGroups({
|
||||
activeGroups: [],
|
||||
query: "project",
|
||||
isInSubmenu: false,
|
||||
projectSearchItems: [],
|
||||
threadSearchItems: threadItems,
|
||||
});
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.value).toBe("threads-search");
|
||||
expect(groups[0]?.items.map((item) => item.value)).toEqual([
|
||||
"thread:thread-title-match",
|
||||
"thread:thread-context-match",
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves thread project-name matches when there is no stronger title match", () => {
|
||||
const group: CommandPaletteGroup = {
|
||||
value: "threads-search",
|
||||
label: "Threads",
|
||||
items: [
|
||||
{
|
||||
kind: "action",
|
||||
value: "thread:project-context-only",
|
||||
searchTerms: ["Fix navbar spacing", "Project"],
|
||||
title: "Fix navbar spacing",
|
||||
description: "Project",
|
||||
icon: null,
|
||||
run: async () => undefined,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const groups = filterCommandPaletteGroups({
|
||||
activeGroups: [group],
|
||||
query: "project",
|
||||
isInSubmenu: false,
|
||||
projectSearchItems: [],
|
||||
threadSearchItems: [],
|
||||
});
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.items.map((item) => item.value)).toEqual(["thread:project-context-only"]);
|
||||
});
|
||||
|
||||
it("filters archived threads out of thread search items", () => {
|
||||
const items = buildThreadActionItems({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-active"),
|
||||
title: "Active thread",
|
||||
createdAt: "2026-03-02T00:00:00.000Z",
|
||||
updatedAt: "2026-03-19T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-archived"),
|
||||
title: "Archived thread",
|
||||
archivedAt: "2026-03-20T00:00:00.000Z",
|
||||
updatedAt: "2026-03-20T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
projectTitleById: new Map([[PROJECT_ID, "Project"]]),
|
||||
sortOrder: "updated_at",
|
||||
icon: null,
|
||||
runThread: async (_thread) => undefined,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.value)).toEqual(["thread:thread-active"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import { type KeybindingCommand } from "@t3tools/contracts";
|
||||
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import { type ReactNode } from "react";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
import { type Project, type SidebarThreadSummary, type Thread } from "../types";
|
||||
|
||||
export const RECENT_THREAD_LIMIT = 12;
|
||||
export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80";
|
||||
export const ADDON_ICON_CLASS = "size-4";
|
||||
|
||||
export interface CommandPaletteItem {
|
||||
readonly kind: "action" | "submenu";
|
||||
readonly value: string;
|
||||
readonly searchTerms: ReadonlyArray<string>;
|
||||
readonly title: ReactNode;
|
||||
readonly description?: string;
|
||||
readonly timestamp?: string;
|
||||
readonly icon: ReactNode;
|
||||
readonly shortcutCommand?: KeybindingCommand;
|
||||
}
|
||||
|
||||
export interface CommandPaletteActionItem extends CommandPaletteItem {
|
||||
readonly kind: "action";
|
||||
readonly keepOpen?: boolean;
|
||||
readonly run: () => Promise<void>;
|
||||
}
|
||||
|
||||
export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
|
||||
readonly kind: "submenu";
|
||||
readonly addonIcon: ReactNode;
|
||||
readonly groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
readonly initialQuery?: string;
|
||||
}
|
||||
|
||||
export interface CommandPaletteGroup {
|
||||
readonly value: string;
|
||||
readonly label: string;
|
||||
readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
|
||||
}
|
||||
|
||||
export interface CommandPaletteView {
|
||||
readonly addonIcon: ReactNode;
|
||||
readonly groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
readonly initialQuery?: string;
|
||||
}
|
||||
|
||||
export type CommandPaletteMode = "root" | "submenu";
|
||||
|
||||
export function normalizeSearchText(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
export function buildProjectActionItems(input: {
|
||||
projects: ReadonlyArray<Project>;
|
||||
valuePrefix: string;
|
||||
icon: (project: Project) => ReactNode;
|
||||
runProject: (project: Project) => Promise<void>;
|
||||
}): CommandPaletteActionItem[] {
|
||||
return input.projects.map((project) => ({
|
||||
kind: "action",
|
||||
value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
|
||||
searchTerms: [project.name, project.cwd],
|
||||
title: project.name,
|
||||
description: project.cwd,
|
||||
icon: input.icon(project),
|
||||
run: async () => {
|
||||
await input.runProject(project);
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildThreadActionItems(input: {
|
||||
threads: ReadonlyArray<
|
||||
Pick<
|
||||
SidebarThreadSummary,
|
||||
"archivedAt" | "branch" | "createdAt" | "environmentId" | "id" | "projectId" | "title"
|
||||
> & {
|
||||
updatedAt?: string | undefined;
|
||||
latestUserMessageAt?: string | null;
|
||||
}
|
||||
>;
|
||||
activeThreadId?: Thread["id"];
|
||||
projectTitleById: ReadonlyMap<Project["id"], string>;
|
||||
sortOrder: SidebarThreadSortOrder;
|
||||
icon: ReactNode;
|
||||
runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
|
||||
limit?: number;
|
||||
}): CommandPaletteActionItem[] {
|
||||
const sortedThreads = sortThreads(
|
||||
input.threads.filter((thread) => thread.archivedAt === null),
|
||||
input.sortOrder,
|
||||
);
|
||||
const visibleThreads =
|
||||
input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
|
||||
|
||||
return visibleThreads.map((thread) => {
|
||||
const projectTitle = input.projectTitleById.get(thread.projectId);
|
||||
const descriptionParts: string[] = [];
|
||||
|
||||
if (projectTitle) {
|
||||
descriptionParts.push(projectTitle);
|
||||
}
|
||||
if (thread.branch) {
|
||||
descriptionParts.push(`#${thread.branch}`);
|
||||
}
|
||||
if (thread.id === input.activeThreadId) {
|
||||
descriptionParts.push("Current thread");
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "action",
|
||||
value: `thread:${thread.id}`,
|
||||
searchTerms: [thread.title, projectTitle ?? "", thread.branch ?? ""],
|
||||
title: thread.title,
|
||||
description: descriptionParts.join(" · "),
|
||||
timestamp: formatRelativeTimeLabel(
|
||||
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
|
||||
),
|
||||
icon: input.icon,
|
||||
run: async () => {
|
||||
await input.runThread(thread);
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
|
||||
const normalizedField = normalizeSearchText(field);
|
||||
if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
|
||||
return Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
if (normalizedField === normalizedQuery) {
|
||||
return 3;
|
||||
}
|
||||
if (normalizedField.startsWith(normalizedQuery)) {
|
||||
return 2;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function rankCommandPaletteItemMatch(
|
||||
item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
|
||||
normalizedQuery: string,
|
||||
): number {
|
||||
const terms = item.searchTerms.filter((term) => term.length > 0);
|
||||
if (terms.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (const [index, field] of terms.entries()) {
|
||||
const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
|
||||
if (fieldRank !== Number.NEGATIVE_INFINITY) {
|
||||
return 1_000 - index * 100 + fieldRank;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function filterCommandPaletteGroups(input: {
|
||||
activeGroups: ReadonlyArray<CommandPaletteGroup>;
|
||||
query: string;
|
||||
isInSubmenu: boolean;
|
||||
projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
|
||||
threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
|
||||
}): CommandPaletteGroup[] {
|
||||
const isActionsFilter = input.query.startsWith(">");
|
||||
const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
|
||||
const normalizedQuery = normalizeSearchText(searchQuery);
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
if (isActionsFilter) {
|
||||
return input.activeGroups.filter((group) => group.value === "actions");
|
||||
}
|
||||
return [...input.activeGroups];
|
||||
}
|
||||
|
||||
let baseGroups = [...input.activeGroups];
|
||||
if (isActionsFilter) {
|
||||
baseGroups = baseGroups.filter((group) => group.value === "actions");
|
||||
} else if (!input.isInSubmenu) {
|
||||
baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
|
||||
}
|
||||
|
||||
const searchableGroups = [...baseGroups];
|
||||
if (!input.isInSubmenu && !isActionsFilter) {
|
||||
if (input.projectSearchItems.length > 0) {
|
||||
searchableGroups.push({
|
||||
value: "projects-search",
|
||||
label: "Projects",
|
||||
items: input.projectSearchItems,
|
||||
});
|
||||
}
|
||||
if (input.threadSearchItems.length > 0) {
|
||||
searchableGroups.push({
|
||||
value: "threads-search",
|
||||
label: "Threads",
|
||||
items: input.threadSearchItems,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return searchableGroups.flatMap((group) => {
|
||||
const items = group.items
|
||||
.map((item, index) => {
|
||||
const haystack = normalizeSearchText(item.searchTerms.join(" "));
|
||||
if (!haystack.includes(normalizedQuery)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
item,
|
||||
index,
|
||||
rank: rankCommandPaletteItemMatch(item, normalizedQuery),
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(entry): entry is { item: (typeof group.items)[number]; index: number; rank: number } =>
|
||||
entry !== null,
|
||||
)
|
||||
.toSorted((left, right) => right.rank - left.rank || left.index - right.index)
|
||||
.map((entry) => entry.item);
|
||||
|
||||
if (items.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [{ value: group.value, label: group.label, items }];
|
||||
});
|
||||
}
|
||||
|
||||
export function getCommandPaletteMode(input: {
|
||||
currentView: CommandPaletteView | null;
|
||||
}): CommandPaletteMode {
|
||||
return input.currentView ? "submenu" : "root";
|
||||
}
|
||||
|
||||
export function buildRootGroups(input: {
|
||||
actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
|
||||
recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
|
||||
}): CommandPaletteGroup[] {
|
||||
const groups: CommandPaletteGroup[] = [];
|
||||
if (input.actionItems.length > 0) {
|
||||
groups.push({ value: "actions", label: "Actions", items: input.actionItems });
|
||||
}
|
||||
if (input.recentThreadItems.length > 0) {
|
||||
groups.push({
|
||||
value: "recent-threads",
|
||||
label: "Recent Threads",
|
||||
items: input.recentThreadItems,
|
||||
});
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
|
||||
switch (mode) {
|
||||
case "root":
|
||||
return "Search commands, projects, and threads...";
|
||||
case "submenu":
|
||||
return "Search...";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
"use client";
|
||||
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { ProjectId } from "@t3tools/contracts";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
ArrowDownIcon,
|
||||
ArrowLeftIcon,
|
||||
ArrowRightIcon,
|
||||
ArrowUpIcon,
|
||||
Columns2Icon,
|
||||
MessageSquareIcon,
|
||||
Rows2Icon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
TerminalSquareIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import {
|
||||
WORKSPACE_COMMAND_METADATA,
|
||||
useWorkspaceCommandExecutor,
|
||||
} from "../hooks/useWorkspaceCommandExecutor";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
startNewThreadInProjectFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { cn } from "../lib/utils";
|
||||
import {
|
||||
selectProjectsAcrossEnvironments,
|
||||
selectSidebarThreadsAcrossEnvironments,
|
||||
useStore,
|
||||
} from "../store";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import { useWorkspaceStore, useWorkspaceThreadTerminalOpen } from "../workspace/store";
|
||||
import { serverThreadSurfaceInput } from "../workspace/types";
|
||||
import {
|
||||
ADDON_ICON_CLASS,
|
||||
buildProjectActionItems,
|
||||
buildRootGroups,
|
||||
buildThreadActionItems,
|
||||
type CommandPaletteActionItem,
|
||||
type CommandPaletteSubmenuItem,
|
||||
type CommandPaletteView,
|
||||
filterCommandPaletteGroups,
|
||||
getCommandPaletteInputPlaceholder,
|
||||
getCommandPaletteMode,
|
||||
ITEM_ICON_CLASS,
|
||||
RECENT_THREAD_LIMIT,
|
||||
} from "./CommandPalette.logic";
|
||||
import { CommandPaletteResults } from "./CommandPaletteResults";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandDialogPopup,
|
||||
CommandFooter,
|
||||
CommandInput,
|
||||
CommandPanel,
|
||||
} from "./ui/command";
|
||||
import { Kbd, KbdGroup } from "./ui/kbd";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
|
||||
export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
const toggleOpen = useCommandPaletteStore((store) => store.toggleOpen);
|
||||
const keybindings = useServerKeybindings();
|
||||
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
|
||||
const routeTarget = useParams({
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
|
||||
const terminalOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
context: {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen,
|
||||
},
|
||||
});
|
||||
if (command !== "commandPalette.toggle") {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleOpen();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
return (
|
||||
<ComposerHandleContext.Provider value={composerHandleRef}>
|
||||
{children}
|
||||
<CommandDialog open={open} onOpenChange={setOpen}>
|
||||
<CommandPaletteDialog />
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandPaletteDialog() {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setOpen(false);
|
||||
};
|
||||
}, [setOpen]);
|
||||
|
||||
if (!open) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <OpenCommandPaletteDialog />;
|
||||
}
|
||||
|
||||
function OpenCommandPaletteDialog() {
|
||||
const navigate = useNavigate();
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
const workspaceTarget = useCommandPaletteStore((store) => store.workspaceTarget);
|
||||
const clearWorkspaceTarget = useCommandPaletteStore((store) => store.clearWorkspaceTarget);
|
||||
const composerHandleRef = useComposerHandleContext();
|
||||
const [query, setQuery] = useState("");
|
||||
const deferredQuery = useDeferredValue(query);
|
||||
const isActionsOnly = deferredQuery.startsWith(">");
|
||||
const settings = useSettings();
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
|
||||
useHandleNewThread();
|
||||
const projects = useStore(useShallow(selectProjectsAcrossEnvironments));
|
||||
const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments));
|
||||
const keybindings = useServerKeybindings();
|
||||
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
|
||||
const currentView = viewStack.at(-1) ?? null;
|
||||
const paletteMode = getCommandPaletteMode({ currentView });
|
||||
const { canOpenTerminalSurface, canSplitFocusedPane, executeWorkspaceCommand } =
|
||||
useWorkspaceCommandExecutor();
|
||||
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
|
||||
const workspaceWindowCount = useWorkspaceStore(
|
||||
(state) => Object.keys(state.document.windowsById).length,
|
||||
);
|
||||
const canUseSpatialWorkspaceCommands = workspaceWindowCount > 1;
|
||||
|
||||
const projectTitleById = useMemo(
|
||||
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.name])),
|
||||
[projects],
|
||||
);
|
||||
|
||||
const activeThreadId = activeThread?.id;
|
||||
const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null;
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
() => async (project: (typeof projects)[number]) => {
|
||||
const latestThread = getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === project.environmentId),
|
||||
project.id,
|
||||
settings.sidebarThreadSortOrder,
|
||||
);
|
||||
if (latestThread) {
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(
|
||||
scopeThreadRef(latestThread.environmentId, latestThread.id),
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await handleNewThread(scopeProjectRef(project.environmentId, project.id), {
|
||||
envMode: settings.defaultThreadEnvMode,
|
||||
});
|
||||
},
|
||||
[
|
||||
handleNewThread,
|
||||
navigate,
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.sidebarThreadSortOrder,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
const projectSearchItems = useMemo(
|
||||
() =>
|
||||
buildProjectActionItems({
|
||||
projects,
|
||||
valuePrefix: "project",
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.cwd}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
),
|
||||
runProject: openProjectFromSearch,
|
||||
}),
|
||||
[openProjectFromSearch, projects],
|
||||
);
|
||||
|
||||
const projectThreadItems = useMemo(
|
||||
() =>
|
||||
buildProjectActionItems({
|
||||
projects,
|
||||
valuePrefix: "new-thread-in",
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.cwd}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
),
|
||||
runProject: async (project) => {
|
||||
await startNewThreadInProjectFromContext(
|
||||
{
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
defaultThreadEnvMode: settings.defaultThreadEnvMode,
|
||||
handleNewThread,
|
||||
},
|
||||
scopeProjectRef(project.environmentId, project.id),
|
||||
);
|
||||
},
|
||||
}),
|
||||
[
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
projects,
|
||||
settings.defaultThreadEnvMode,
|
||||
],
|
||||
);
|
||||
|
||||
const allThreadItems = useMemo(
|
||||
() =>
|
||||
buildThreadActionItems({
|
||||
threads,
|
||||
...(activeThreadId ? { activeThreadId } : {}),
|
||||
projectTitleById,
|
||||
sortOrder: settings.sidebarThreadSortOrder,
|
||||
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
runThread: async (thread) => {
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
|
||||
});
|
||||
},
|
||||
}),
|
||||
[activeThreadId, navigate, projectTitleById, settings.sidebarThreadSortOrder, threads],
|
||||
);
|
||||
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
|
||||
const workspaceTargetThreadItems = useMemo(() => {
|
||||
if (!workspaceTarget) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return buildThreadActionItems({
|
||||
threads,
|
||||
...(activeThreadId ? { activeThreadId } : {}),
|
||||
projectTitleById,
|
||||
sortOrder: settings.sidebarThreadSortOrder,
|
||||
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
runThread: async (thread) => {
|
||||
openThreadSurface(
|
||||
serverThreadSurfaceInput(scopeThreadRef(thread.environmentId, thread.id)),
|
||||
workspaceTarget.disposition,
|
||||
);
|
||||
},
|
||||
});
|
||||
}, [
|
||||
activeThreadId,
|
||||
openThreadSurface,
|
||||
projectTitleById,
|
||||
settings.sidebarThreadSortOrder,
|
||||
threads,
|
||||
workspaceTarget,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!workspaceTarget) {
|
||||
return;
|
||||
}
|
||||
setViewStack([]);
|
||||
setQuery("");
|
||||
}, [workspaceTarget]);
|
||||
|
||||
function pushView(item: CommandPaletteSubmenuItem): void {
|
||||
setViewStack((previousViews) => [
|
||||
...previousViews,
|
||||
{
|
||||
addonIcon: item.addonIcon,
|
||||
groups: item.groups,
|
||||
...(item.initialQuery ? { initialQuery: item.initialQuery } : {}),
|
||||
},
|
||||
]);
|
||||
setQuery(item.initialQuery ?? "");
|
||||
}
|
||||
|
||||
function popView(): void {
|
||||
setViewStack((previousViews) => previousViews.slice(0, -1));
|
||||
setQuery("");
|
||||
}
|
||||
|
||||
function leaveSubmenu(): void {
|
||||
if (currentView) {
|
||||
popView();
|
||||
return;
|
||||
}
|
||||
clearWorkspaceTarget();
|
||||
setQuery("");
|
||||
}
|
||||
|
||||
function handleQueryChange(nextQuery: string): void {
|
||||
setQuery(nextQuery);
|
||||
if (nextQuery === "" && currentView?.initialQuery) {
|
||||
popView();
|
||||
}
|
||||
}
|
||||
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (projects.length > 0) {
|
||||
const activeProjectTitle = currentProjectId
|
||||
? (projectTitleById.get(currentProjectId) ?? null)
|
||||
: null;
|
||||
|
||||
if (activeProjectTitle) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:new-thread",
|
||||
searchTerms: ["new thread", "chat", "create", "draft"],
|
||||
title: (
|
||||
<>
|
||||
New thread in <span className="font-semibold">{activeProjectTitle}</span>
|
||||
</>
|
||||
),
|
||||
icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "chat.new",
|
||||
run: async () => {
|
||||
await startNewThreadFromContext({
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
defaultThreadEnvMode: settings.defaultThreadEnvMode,
|
||||
handleNewThread,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
actionItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:new-thread-in",
|
||||
searchTerms: ["new thread", "project", "pick", "choose", "select"],
|
||||
title: "New thread in...",
|
||||
icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
|
||||
});
|
||||
}
|
||||
|
||||
if (canOpenTerminalSurface) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-terminal-split-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitRight"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitRight"].title,
|
||||
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.terminal.splitRight",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.terminal.splitRight");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-terminal-split-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitDown"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitDown"].title,
|
||||
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.terminal.splitDown",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.terminal.splitDown");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-terminal-tab",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.newTab"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.newTab"].title,
|
||||
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.terminal.newTab",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.terminal.newTab");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (canSplitFocusedPane) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-split-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.splitRight"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.splitRight"].title,
|
||||
icon: <Columns2Icon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.splitRight",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.splitRight");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-split-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.splitDown"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.splitDown"].title,
|
||||
icon: <Rows2Icon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.splitDown",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.splitDown");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-close",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.close"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.close"].title,
|
||||
icon: <XIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.close",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.close");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (canUseSpatialWorkspaceCommands) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-left",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.left"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.left"].title,
|
||||
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.left",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.left");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.right"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.right"].title,
|
||||
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.right",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.right");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-up",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.up"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.up"].title,
|
||||
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.up",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.up");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-focus-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.down"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.focus.down"].title,
|
||||
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.focus.down",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.focus.down");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-move-left",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveLeft"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveLeft"].title,
|
||||
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.moveLeft",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.moveLeft");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-move-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveRight"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveRight"].title,
|
||||
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.moveRight",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.moveRight");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-move-up",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveUp"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveUp"].title,
|
||||
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.moveUp",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.moveUp");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-pane-move-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveDown"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveDown"].title,
|
||||
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.pane.moveDown",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.pane.moveDown");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-tab-move-left",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveLeft"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveLeft"].title,
|
||||
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.tab.moveLeft",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.tab.moveLeft");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-tab-move-right",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveRight"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveRight"].title,
|
||||
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.tab.moveRight",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.tab.moveRight");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-tab-move-up",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveUp"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveUp"].title,
|
||||
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.tab.moveUp",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.tab.moveUp");
|
||||
},
|
||||
});
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:workspace-tab-move-down",
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveDown"].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveDown"].title,
|
||||
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "workspace.tab.moveDown",
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand("workspace.tab.moveDown");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:settings",
|
||||
searchTerms: ["settings", "preferences", "configuration", "keybindings"],
|
||||
title: "Open settings",
|
||||
icon: <SettingsIcon className={ITEM_ICON_CLASS} />,
|
||||
run: async () => {
|
||||
await navigate({ to: "/settings" });
|
||||
},
|
||||
});
|
||||
|
||||
const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
|
||||
const workspaceTargetGroups = useMemo(() => {
|
||||
if (!workspaceTarget) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const items: CommandPaletteActionItem[] = [];
|
||||
if (canOpenTerminalSurface) {
|
||||
const targetCommand =
|
||||
workspaceTarget.disposition === "split-right"
|
||||
? "workspace.terminal.splitRight"
|
||||
: "workspace.terminal.splitDown";
|
||||
items.push({
|
||||
kind: "action",
|
||||
value: `action:workspace-target:${targetCommand}`,
|
||||
searchTerms: WORKSPACE_COMMAND_METADATA[targetCommand].searchTerms,
|
||||
title: WORKSPACE_COMMAND_METADATA[targetCommand].title,
|
||||
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: targetCommand,
|
||||
run: async () => {
|
||||
await executeWorkspaceCommand(targetCommand);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return [
|
||||
...(items.length > 0 ? [{ value: "actions", label: "Actions", items }] : []),
|
||||
...(workspaceTargetThreadItems.length > 0
|
||||
? [{ value: "threads", label: "Threads", items: workspaceTargetThreadItems }]
|
||||
: []),
|
||||
];
|
||||
}, [
|
||||
canOpenTerminalSurface,
|
||||
executeWorkspaceCommand,
|
||||
workspaceTarget,
|
||||
workspaceTargetThreadItems,
|
||||
]);
|
||||
const activeGroups = currentView
|
||||
? currentView.groups
|
||||
: workspaceTarget
|
||||
? workspaceTargetGroups
|
||||
: rootGroups;
|
||||
|
||||
const displayedGroups = filterCommandPaletteGroups({
|
||||
activeGroups,
|
||||
query: deferredQuery,
|
||||
isInSubmenu: currentView !== null || workspaceTarget !== null,
|
||||
projectSearchItems: projectSearchItems,
|
||||
threadSearchItems: allThreadItems,
|
||||
});
|
||||
|
||||
const isSubmenu = paletteMode === "submenu" || workspaceTarget !== null;
|
||||
const inputPlaceholder = workspaceTarget
|
||||
? "Open in split..."
|
||||
: getCommandPaletteInputPlaceholder(paletteMode);
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
|
||||
if (event.key === "Backspace" && query === "" && isSubmenu) {
|
||||
event.preventDefault();
|
||||
leaveSubmenu();
|
||||
}
|
||||
}
|
||||
|
||||
function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void {
|
||||
if (item.kind === "submenu") {
|
||||
pushView(item);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!item.keepOpen) {
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
void item.run().catch((error: unknown) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to run command",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<CommandDialogPopup
|
||||
aria-label="Command palette"
|
||||
className="overflow-hidden p-0"
|
||||
data-testid="command-palette"
|
||||
finalFocus={() => {
|
||||
composerHandleRef?.current?.focusAtEnd();
|
||||
return false;
|
||||
}}
|
||||
>
|
||||
<Command
|
||||
key={`${viewStack.length}-${workspaceTarget?.disposition ?? "root"}`}
|
||||
aria-label="Command palette"
|
||||
autoHighlight="always"
|
||||
mode="none"
|
||||
onValueChange={handleQueryChange}
|
||||
value={query}
|
||||
>
|
||||
<CommandInput
|
||||
placeholder={inputPlaceholder}
|
||||
wrapperClassName={
|
||||
isSubmenu
|
||||
? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto [&_[data-slot=autocomplete-start-addon]]:cursor-pointer"
|
||||
: undefined
|
||||
}
|
||||
{...(isSubmenu
|
||||
? {
|
||||
startAddon: (
|
||||
<button
|
||||
type="button"
|
||||
className="flex cursor-pointer items-center"
|
||||
aria-label="Back"
|
||||
onClick={leaveSubmenu}
|
||||
>
|
||||
<ArrowLeftIcon />
|
||||
</button>
|
||||
),
|
||||
}
|
||||
: {})}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
<CommandPanel className="max-h-[min(28rem,70vh)]">
|
||||
<CommandPaletteResults
|
||||
groups={displayedGroups}
|
||||
isActionsOnly={isActionsOnly}
|
||||
keybindings={keybindings}
|
||||
onExecuteItem={executeItem}
|
||||
/>
|
||||
</CommandPanel>
|
||||
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
|
||||
<div className="flex items-center gap-3">
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>
|
||||
<ArrowUpIcon />
|
||||
</Kbd>
|
||||
<Kbd>
|
||||
<ArrowDownIcon />
|
||||
</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Navigate</span>
|
||||
</KbdGroup>
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Select</span>
|
||||
</KbdGroup>
|
||||
{isSubmenu ? (
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Backspace</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Back</span>
|
||||
</KbdGroup>
|
||||
) : null}
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Esc</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Close</span>
|
||||
</KbdGroup>
|
||||
</div>
|
||||
</CommandFooter>
|
||||
</Command>
|
||||
</CommandDialogPopup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { type ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { ChevronRightIcon } from "lucide-react";
|
||||
import { shortcutLabelForCommand } from "../keybindings";
|
||||
import {
|
||||
type CommandPaletteActionItem,
|
||||
type CommandPaletteGroup,
|
||||
type CommandPaletteSubmenuItem,
|
||||
} from "./CommandPalette.logic";
|
||||
import {
|
||||
CommandCollection,
|
||||
CommandGroup,
|
||||
CommandGroupLabel,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandShortcut,
|
||||
} from "./ui/command";
|
||||
|
||||
interface CommandPaletteResultsProps {
|
||||
emptyStateMessage?: string;
|
||||
groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
isActionsOnly: boolean;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
|
||||
}
|
||||
|
||||
export function CommandPaletteResults(props: CommandPaletteResultsProps) {
|
||||
if (props.groups.length === 0) {
|
||||
return (
|
||||
<div className="py-10 text-center text-sm text-muted-foreground">
|
||||
{props.emptyStateMessage ??
|
||||
(props.isActionsOnly
|
||||
? "No matching actions."
|
||||
: "No matching commands, projects, or threads.")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CommandList>
|
||||
{props.groups.map((group) => (
|
||||
<CommandGroup items={group.items} key={group.value}>
|
||||
<CommandGroupLabel>{group.label}</CommandGroupLabel>
|
||||
<CommandCollection>
|
||||
{(item) => (
|
||||
<CommandPaletteResultRow
|
||||
item={item}
|
||||
key={item.value}
|
||||
keybindings={props.keybindings}
|
||||
onExecuteItem={props.onExecuteItem}
|
||||
/>
|
||||
)}
|
||||
</CommandCollection>
|
||||
</CommandGroup>
|
||||
))}
|
||||
</CommandList>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandPaletteResultRow(props: {
|
||||
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
|
||||
}) {
|
||||
const shortcutLabel = props.item.shortcutCommand
|
||||
? shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
value={props.item.value}
|
||||
className="cursor-pointer gap-2"
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
props.onExecuteItem(props.item);
|
||||
}}
|
||||
>
|
||||
{props.item.icon}
|
||||
{props.item.description ? (
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-sm text-foreground">{props.item.title}</span>
|
||||
<span className="truncate text-muted-foreground/70 text-xs">
|
||||
{props.item.description}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex min-w-0 items-center gap-1.5 truncate text-sm text-foreground">
|
||||
<span className="truncate">{props.item.title}</span>
|
||||
</span>
|
||||
)}
|
||||
{props.item.timestamp ? (
|
||||
<span className="min-w-12 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground/70">
|
||||
{props.item.timestamp}
|
||||
</span>
|
||||
) : null}
|
||||
{shortcutLabel ? <CommandShortcut>{shortcutLabel}</CommandShortcut> : null}
|
||||
{props.item.kind === "submenu" ? (
|
||||
<ChevronRightIcon className="ml-auto size-4 shrink-0 text-muted-foreground/50" />
|
||||
) : null}
|
||||
</CommandItem>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
|
||||
import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
|
||||
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
|
||||
import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
|
||||
import { type ServerProviderSkill } from "@t3tools/contracts";
|
||||
import {
|
||||
$applyNodeReplacement,
|
||||
$createRangeSelection,
|
||||
@@ -73,8 +74,11 @@ import {
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME,
|
||||
} from "./composerInlineChip";
|
||||
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
|
||||
import { formatProviderSkillDisplayName } from "~/providerSkillPresentation";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||
const SURROUND_SYMBOLS: [string, string][] = [
|
||||
@@ -102,6 +106,17 @@ type SerializedComposerMentionNode = Spread<
|
||||
SerializedTextNode
|
||||
>;
|
||||
|
||||
type SerializedComposerSkillNode = Spread<
|
||||
{
|
||||
skillName: string;
|
||||
skillLabel?: string;
|
||||
skillDescription?: string;
|
||||
type: "composer-skill";
|
||||
version: 1;
|
||||
},
|
||||
SerializedLexicalNode
|
||||
>;
|
||||
|
||||
type SerializedComposerTerminalContextNode = Spread<
|
||||
{
|
||||
context: TerminalContextDraft;
|
||||
@@ -189,6 +204,155 @@ function $createComposerMentionNode(path: string): ComposerMentionNode {
|
||||
return $applyNodeReplacement(new ComposerMentionNode(path));
|
||||
}
|
||||
|
||||
const SKILL_CHIP_ICON_SVG = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>`;
|
||||
|
||||
function resolveSkillDescription(
|
||||
skill: Pick<ServerProviderSkill, "shortDescription" | "description">,
|
||||
): string | null {
|
||||
const shortDescription = skill.shortDescription?.trim();
|
||||
if (shortDescription) {
|
||||
return shortDescription;
|
||||
}
|
||||
const description = skill.description?.trim();
|
||||
return description || null;
|
||||
}
|
||||
|
||||
type ComposerSkillMetadata = {
|
||||
label: string;
|
||||
description: string | null;
|
||||
};
|
||||
|
||||
function skillMetadataByName(
|
||||
skills: ReadonlyArray<ServerProviderSkill>,
|
||||
): ReadonlyMap<string, ComposerSkillMetadata> {
|
||||
return new Map(
|
||||
skills.map((skill) => [
|
||||
skill.name,
|
||||
{
|
||||
label: formatProviderSkillDisplayName(skill),
|
||||
description: resolveSkillDescription(skill),
|
||||
},
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function ComposerSkillDecorator(props: { skillLabel: string; skillDescription: string | null }) {
|
||||
const chip = (
|
||||
<span
|
||||
className={COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME}
|
||||
contentEditable={false}
|
||||
spellCheck={false}
|
||||
data-composer-skill-chip="true"
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
|
||||
dangerouslySetInnerHTML={{ __html: SKILL_CHIP_ICON_SVG }}
|
||||
/>
|
||||
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{props.skillLabel}</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
if (!props.skillDescription) {
|
||||
return chip;
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={chip} />
|
||||
<TooltipPopup side="top" className="max-w-[30rem] whitespace-normal leading-tight">
|
||||
{props.skillDescription}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
class ComposerSkillNode extends DecoratorNode<ReactElement> {
|
||||
__skillName: string;
|
||||
__skillLabel: string;
|
||||
__skillDescription: string | null;
|
||||
|
||||
static override getType(): string {
|
||||
return "composer-skill";
|
||||
}
|
||||
|
||||
static override clone(node: ComposerSkillNode): ComposerSkillNode {
|
||||
return new ComposerSkillNode(
|
||||
node.__skillName,
|
||||
node.__skillLabel,
|
||||
node.__skillDescription,
|
||||
node.__key,
|
||||
);
|
||||
}
|
||||
|
||||
static override importJSON(serializedNode: SerializedComposerSkillNode): ComposerSkillNode {
|
||||
return $createComposerSkillNode(
|
||||
serializedNode.skillName,
|
||||
serializedNode.skillLabel ?? serializedNode.skillName,
|
||||
serializedNode.skillDescription ?? null,
|
||||
).updateFromJSON(serializedNode);
|
||||
}
|
||||
|
||||
constructor(
|
||||
skillName: string,
|
||||
skillLabel: string,
|
||||
skillDescription: string | null,
|
||||
key?: NodeKey,
|
||||
) {
|
||||
super(key);
|
||||
const normalizedSkillName = skillName.startsWith("$") ? skillName.slice(1) : skillName;
|
||||
this.__skillName = normalizedSkillName;
|
||||
this.__skillLabel = skillLabel;
|
||||
this.__skillDescription = skillDescription;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerSkillNode {
|
||||
return {
|
||||
...super.exportJSON(),
|
||||
skillName: this.__skillName,
|
||||
skillLabel: this.__skillLabel,
|
||||
...(this.__skillDescription ? { skillDescription: this.__skillDescription } : {}),
|
||||
type: "composer-skill",
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = "inline-flex align-middle leading-none";
|
||||
return dom;
|
||||
}
|
||||
|
||||
override updateDOM(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override getTextContent(): string {
|
||||
return `$${this.__skillName}`;
|
||||
}
|
||||
|
||||
override isInline(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
return (
|
||||
<ComposerSkillDecorator
|
||||
skillLabel={this.__skillLabel}
|
||||
skillDescription={this.__skillDescription}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function $createComposerSkillNode(
|
||||
skillName: string,
|
||||
skillLabel: string,
|
||||
skillDescription: string | null,
|
||||
): ComposerSkillNode {
|
||||
return $applyNodeReplacement(new ComposerSkillNode(skillName, skillLabel, skillDescription));
|
||||
}
|
||||
|
||||
function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) {
|
||||
return <ComposerPendingTerminalContextChip context={props.context} />;
|
||||
}
|
||||
@@ -253,11 +417,16 @@ function $createComposerTerminalContextNode(
|
||||
return $applyNodeReplacement(new ComposerTerminalContextNode(context));
|
||||
}
|
||||
|
||||
type ComposerInlineTokenNode = ComposerMentionNode | ComposerTerminalContextNode;
|
||||
type ComposerInlineTokenNode =
|
||||
| ComposerMentionNode
|
||||
| ComposerSkillNode
|
||||
| ComposerTerminalContextNode;
|
||||
|
||||
function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode {
|
||||
return (
|
||||
candidate instanceof ComposerMentionNode || candidate instanceof ComposerTerminalContextNode
|
||||
candidate instanceof ComposerMentionNode ||
|
||||
candidate instanceof ComposerSkillNode ||
|
||||
candidate instanceof ComposerTerminalContextNode
|
||||
);
|
||||
}
|
||||
|
||||
@@ -302,6 +471,22 @@ function terminalContextSignature(contexts: ReadonlyArray<TerminalContextDraft>)
|
||||
.join("\u001e");
|
||||
}
|
||||
|
||||
function skillSignature(skills: ReadonlyArray<ServerProviderSkill>): string {
|
||||
return skills
|
||||
.map((skill) =>
|
||||
[
|
||||
skill.name,
|
||||
skill.displayName ?? "",
|
||||
skill.shortDescription ?? "",
|
||||
skill.description ?? "",
|
||||
skill.path,
|
||||
skill.scope ?? "",
|
||||
skill.enabled ? "1" : "0",
|
||||
].join("\u001f"),
|
||||
)
|
||||
.join("\u001e");
|
||||
}
|
||||
|
||||
function clampExpandedCursor(value: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return value.length;
|
||||
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
|
||||
@@ -415,7 +600,7 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
@@ -462,7 +647,7 @@ function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: numbe
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
@@ -488,7 +673,7 @@ function findSelectionPointAtOffset(
|
||||
node: LexicalNode,
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
if (node instanceof ComposerMentionNode || node instanceof ComposerSkillNode) {
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
@@ -657,6 +842,7 @@ function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||
function $setComposerEditorPrompt(
|
||||
prompt: string,
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>,
|
||||
skillMetadata: ReadonlyMap<string, ComposerSkillMetadata>,
|
||||
): void {
|
||||
const root = $getRoot();
|
||||
root.clear();
|
||||
@@ -669,6 +855,17 @@ function $setComposerEditorPrompt(
|
||||
paragraph.append($createComposerMentionNode(segment.path));
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "skill") {
|
||||
const metadata = skillMetadata.get(segment.name);
|
||||
paragraph.append(
|
||||
$createComposerSkillNode(
|
||||
segment.name,
|
||||
metadata?.label ?? formatProviderSkillDisplayName({ name: segment.name }),
|
||||
metadata?.description ?? null,
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "terminal-context") {
|
||||
if (segment.context) {
|
||||
paragraph.append($createComposerTerminalContextNode(segment.context));
|
||||
@@ -705,6 +902,7 @@ interface ComposerPromptEditorProps {
|
||||
value: string;
|
||||
cursor: number;
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
skills: ReadonlyArray<ServerProviderSkill>;
|
||||
disabled: boolean;
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
@@ -946,9 +1144,11 @@ function ComposerInlineTokenBackspacePlugin() {
|
||||
|
||||
function ComposerSurroundSelectionPlugin(props: {
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
skills: ReadonlyArray<ServerProviderSkill>;
|
||||
}) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const terminalContextsRef = useRef(props.terminalContexts);
|
||||
const skillMetadataRef = useRef(skillMetadataByName(props.skills));
|
||||
const pendingSurroundSelectionRef = useRef<{
|
||||
value: string;
|
||||
expandedStart: number;
|
||||
@@ -964,6 +1164,10 @@ function ComposerSurroundSelectionPlugin(props: {
|
||||
terminalContextsRef.current = props.terminalContexts;
|
||||
}, [props.terminalContexts]);
|
||||
|
||||
useEffect(() => {
|
||||
skillMetadataRef.current = skillMetadataByName(props.skills);
|
||||
}, [props.skills]);
|
||||
|
||||
const applySurroundInsertion = useCallback(
|
||||
(inputData: string): boolean => {
|
||||
const surroundCloseSymbol = SURROUND_SYMBOLS_MAP.get(inputData);
|
||||
@@ -1009,7 +1213,7 @@ function ComposerSurroundSelectionPlugin(props: {
|
||||
selectionSnapshot.expandedEnd,
|
||||
);
|
||||
const nextValue = `${selectionSnapshot.value.slice(0, selectionSnapshot.expandedStart)}${inputData}${selectedText}${surroundCloseSymbol}${selectionSnapshot.value.slice(selectionSnapshot.expandedEnd)}`;
|
||||
$setComposerEditorPrompt(nextValue, terminalContextsRef.current);
|
||||
$setComposerEditorPrompt(nextValue, terminalContextsRef.current, skillMetadataRef.current);
|
||||
const selectionStart = collapseExpandedComposerCursor(
|
||||
nextValue,
|
||||
selectionSnapshot.expandedStart,
|
||||
@@ -1211,6 +1415,7 @@ function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
skills,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
@@ -1225,6 +1430,9 @@ function ComposerPromptEditorInner({
|
||||
const initialCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const terminalContextsSignature = terminalContextSignature(terminalContexts);
|
||||
const terminalContextsSignatureRef = useRef(terminalContextsSignature);
|
||||
const skillsSignature = skillSignature(skills);
|
||||
const skillsSignatureRef = useRef(skillsSignature);
|
||||
const skillMetadataRef = useRef(skillMetadataByName(skills));
|
||||
const snapshotRef = useRef({
|
||||
value,
|
||||
cursor: initialCursor,
|
||||
@@ -1241,6 +1449,10 @@ function ComposerPromptEditorInner({
|
||||
onChangeRef.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
skillMetadataRef.current = skillMetadataByName(skills);
|
||||
}, [skills]);
|
||||
|
||||
useEffect(() => {
|
||||
editor.setEditable(!disabled);
|
||||
}, [disabled, editor]);
|
||||
@@ -1249,10 +1461,12 @@ function ComposerPromptEditorInner({
|
||||
const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
const contextsChanged = terminalContextsSignatureRef.current !== terminalContextsSignature;
|
||||
const skillsChanged = skillsSignatureRef.current !== skillsSignature;
|
||||
if (
|
||||
previousSnapshot.value === value &&
|
||||
previousSnapshot.cursor === normalizedCursor &&
|
||||
!contextsChanged
|
||||
!contextsChanged &&
|
||||
!skillsChanged
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -1264,18 +1478,20 @@ function ComposerPromptEditorInner({
|
||||
terminalContextIds: terminalContexts.map((context) => context.id),
|
||||
};
|
||||
terminalContextsSignatureRef.current = terminalContextsSignature;
|
||||
skillsSignatureRef.current = skillsSignature;
|
||||
|
||||
const rootElement = editor.getRootElement();
|
||||
const isFocused = Boolean(rootElement && document.activeElement === rootElement);
|
||||
if (previousSnapshot.value === value && !contextsChanged && !isFocused) {
|
||||
if (previousSnapshot.value === value && !contextsChanged && !skillsChanged && !isFocused) {
|
||||
return;
|
||||
}
|
||||
|
||||
isApplyingControlledUpdateRef.current = true;
|
||||
editor.update(() => {
|
||||
const shouldRewriteEditorState = previousSnapshot.value !== value || contextsChanged;
|
||||
const shouldRewriteEditorState =
|
||||
previousSnapshot.value !== value || contextsChanged || skillsChanged;
|
||||
if (shouldRewriteEditorState) {
|
||||
$setComposerEditorPrompt(value, terminalContexts);
|
||||
$setComposerEditorPrompt(value, terminalContexts, skillMetadataRef.current);
|
||||
}
|
||||
if (shouldRewriteEditorState || isFocused) {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
@@ -1284,7 +1500,7 @@ function ComposerPromptEditorInner({
|
||||
queueMicrotask(() => {
|
||||
isApplyingControlledUpdateRef.current = false;
|
||||
});
|
||||
}, [cursor, editor, terminalContexts, terminalContextsSignature, value]);
|
||||
}, [cursor, editor, skillsSignature, terminalContexts, terminalContextsSignature, value]);
|
||||
|
||||
const focusAt = useCallback(
|
||||
(nextCursor: number) => {
|
||||
@@ -1442,7 +1658,7 @@ function ComposerPromptEditorInner({
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerSurroundSelectionPlugin terminalContexts={terminalContexts} />
|
||||
<ComposerSurroundSelectionPlugin terminalContexts={terminalContexts} skills={skills} />
|
||||
<ComposerInlineTokenArrowPlugin />
|
||||
<ComposerInlineTokenSelectionNormalizePlugin />
|
||||
<ComposerInlineTokenBackspacePlugin />
|
||||
@@ -1460,6 +1676,7 @@ export const ComposerPromptEditor = forwardRef<
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
skills,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
@@ -1472,13 +1689,18 @@ export const ComposerPromptEditor = forwardRef<
|
||||
) {
|
||||
const initialValueRef = useRef(value);
|
||||
const initialTerminalContextsRef = useRef(terminalContexts);
|
||||
const initialSkillMetadataRef = useRef(skillMetadataByName(skills));
|
||||
const initialConfig = useMemo<InitialConfigType>(
|
||||
() => ({
|
||||
namespace: "t3tools-composer-editor",
|
||||
editable: true,
|
||||
nodes: [ComposerMentionNode, ComposerTerminalContextNode],
|
||||
nodes: [ComposerMentionNode, ComposerSkillNode, ComposerTerminalContextNode],
|
||||
editorState: () => {
|
||||
$setComposerEditorPrompt(initialValueRef.current, initialTerminalContextsRef.current);
|
||||
$setComposerEditorPrompt(
|
||||
initialValueRef.current,
|
||||
initialTerminalContextsRef.current,
|
||||
initialSkillMetadataRef.current,
|
||||
);
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
@@ -1493,6 +1715,7 @@ export const ComposerPromptEditor = forwardRef<
|
||||
value={value}
|
||||
cursor={cursor}
|
||||
terminalContexts={terminalContexts}
|
||||
skills={skills}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onRemoveTerminalContext={onRemoveTerminalContext}
|
||||
|
||||
@@ -429,12 +429,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const headerRow = (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
|
||||
{canScrollTurnStripLeft && (
|
||||
<div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-linear-to-r from-card to-transparent" />
|
||||
)}
|
||||
{canScrollTurnStripRight && (
|
||||
<div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-linear-to-l from-card to-transparent" />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
@@ -466,6 +460,13 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div
|
||||
ref={turnStripRef}
|
||||
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
|
||||
style={
|
||||
canScrollTurnStripLeft || canScrollTurnStripRight
|
||||
? {
|
||||
maskImage: `linear-gradient(to right, ${canScrollTurnStripLeft ? "transparent 24px, black 72px" : "black"}, ${canScrollTurnStripRight ? "black calc(100% - 72px), transparent calc(100% - 24px)" : "black"})`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onWheel={onTurnStripWheel}
|
||||
>
|
||||
<button
|
||||
|
||||
@@ -10,8 +10,10 @@ export type DiffPanelMode = "inline" | "sheet" | "sidebar";
|
||||
function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) {
|
||||
const shouldUseDragRegion = isElectron && mode !== "sheet";
|
||||
return cn(
|
||||
"flex items-center justify-between gap-2 px-4",
|
||||
shouldUseDragRegion ? "drag-region h-[52px] border-b border-border" : "h-12",
|
||||
"flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
|
||||
shouldUseDragRegion
|
||||
? "drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]"
|
||||
: "h-12 wco:max-h-[env(titlebar-area-height)]",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -426,4 +426,37 @@ describe("GitActionsControl thread-scoped progress toast", () => {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not overwrite a selected base branch while a new worktree draft is being configured", async () => {
|
||||
hasServerThreadRef.current = false;
|
||||
activeDraftThreadRef.current = {
|
||||
threadId: SHARED_THREAD_ID,
|
||||
environmentId: ENVIRONMENT_A,
|
||||
branch: "feature/base-branch",
|
||||
worktreePath: null,
|
||||
envMode: "worktree",
|
||||
};
|
||||
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(
|
||||
<GitActionsControl
|
||||
gitCwd={GIT_CWD}
|
||||
activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
|
||||
/>,
|
||||
{
|
||||
container: host,
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(setDraftThreadContextSpy).not.toHaveBeenCalled();
|
||||
expect(setThreadBranchSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1020,6 +1020,15 @@ describe("resolveLiveThreadBranchUpdate", () => {
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
|
||||
it("does not regress a semantic thread branch back to a temporary worktree branch", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "t3code/github-query-rate-limit",
|
||||
gitStatus: status({ branch: "t3code/bda76797" }),
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAutoFeatureBranchName", () => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
GitStackedAction,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
|
||||
export type GitActionIconName = "commit" | "push" | "pr";
|
||||
|
||||
@@ -354,6 +355,15 @@ export function resolveLiveThreadBranchUpdate(input: {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
input.threadBranch !== null &&
|
||||
input.gitStatus.branch !== null &&
|
||||
!isTemporaryWorktreeBranch(input.threadBranch) &&
|
||||
isTemporaryWorktreeBranch(input.gitStatus.branch)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
branch: input.gitStatus.branch,
|
||||
};
|
||||
|
||||
@@ -49,7 +49,7 @@ import {
|
||||
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
|
||||
import { newCommandId, randomUUID } from "~/lib/utils";
|
||||
import { resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { useComposerDraftStore } from "~/composerDraftStore";
|
||||
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
|
||||
import { readEnvironmentApi } from "~/environmentApi";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { useStore } from "~/store";
|
||||
@@ -58,6 +58,7 @@ import { createThreadSelectorByRef } from "~/storeSelectors";
|
||||
interface GitActionsControlProps {
|
||||
gitCwd: string | null;
|
||||
activeThreadRef: ScopedThreadRef | null;
|
||||
draftId?: DraftId;
|
||||
}
|
||||
|
||||
interface PendingDefaultBranchAction {
|
||||
@@ -209,7 +210,11 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
return <InfoIcon className={iconClassName} />;
|
||||
}
|
||||
|
||||
export default function GitActionsControl({ gitCwd, activeThreadRef }: GitActionsControlProps) {
|
||||
export default function GitActionsControl({
|
||||
gitCwd,
|
||||
activeThreadRef,
|
||||
draftId,
|
||||
}: GitActionsControlProps) {
|
||||
const activeEnvironmentId = activeThreadRef?.environmentId ?? null;
|
||||
const threadToastData = useMemo(
|
||||
() => (activeThreadRef ? { threadRef: activeThreadRef } : undefined),
|
||||
@@ -221,7 +226,11 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
);
|
||||
const activeServerThread = useStore(activeServerThreadSelector);
|
||||
const activeDraftThread = useComposerDraftStore((store) =>
|
||||
activeThreadRef ? store.getDraftThreadByRef(activeThreadRef) : null,
|
||||
draftId
|
||||
? store.getDraftSession(draftId)
|
||||
: activeThreadRef
|
||||
? store.getDraftThreadByRef(activeThreadRef)
|
||||
: null,
|
||||
);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const setThreadBranch = useStore((store) => store.setThreadBranch);
|
||||
@@ -282,7 +291,7 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
return;
|
||||
}
|
||||
|
||||
setDraftThreadContext(activeThreadRef, {
|
||||
setDraftThreadContext(draftId ?? activeThreadRef, {
|
||||
branch,
|
||||
worktreePath: activeDraftThread.worktreePath,
|
||||
});
|
||||
@@ -291,6 +300,7 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
activeDraftThread,
|
||||
activeServerThread,
|
||||
activeThreadRef,
|
||||
draftId,
|
||||
setDraftThreadContext,
|
||||
setThreadBranch,
|
||||
],
|
||||
@@ -344,14 +354,18 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
const isPullRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.pull(activeEnvironmentId, gitCwd) }) > 0;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
||||
const isSelectingWorktreeBase =
|
||||
!activeServerThread &&
|
||||
activeDraftThread?.envMode === "worktree" &&
|
||||
activeDraftThread.worktreePath === null;
|
||||
|
||||
useEffect(() => {
|
||||
if (isGitActionRunning) {
|
||||
if (isGitActionRunning || isSelectingWorktreeBase) {
|
||||
return;
|
||||
}
|
||||
|
||||
const branchUpdate = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: activeServerThread?.branch ?? null,
|
||||
threadBranch: activeServerThread?.branch ?? activeDraftThread?.branch ?? null,
|
||||
gitStatus: gitStatusForActions,
|
||||
});
|
||||
if (!branchUpdate) {
|
||||
@@ -361,8 +375,10 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
persistThreadBranchSync(branchUpdate.branch);
|
||||
}, [
|
||||
activeServerThread?.branch,
|
||||
activeDraftThread?.branch,
|
||||
gitStatusForActions,
|
||||
isGitActionRunning,
|
||||
isSelectingWorktreeBase,
|
||||
persistThreadBranchSync,
|
||||
]);
|
||||
|
||||
|
||||
@@ -34,6 +34,24 @@ export const TraeIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const KiroIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 1200 1200" fill="none">
|
||||
<rect width="1200" height="1200" rx="260" fill="#9046FF" />
|
||||
<path
|
||||
d="M398.554 818.914C316.315 1001.03 491.477 1046.74 620.672 940.156C658.687 1059.66 801.052 970.473 852.234 877.795C964.787 673.567 919.318 465.357 907.64 422.374C827.637 129.443 427.623 128.946 358.8 423.865C342.651 475.544 342.402 534.18 333.458 595.051C328.986 625.86 325.507 645.488 313.83 677.785C306.873 696.424 297.68 712.819 282.773 740.645C259.915 783.881 269.604 867.113 387.87 823.883L399.051 818.914H398.554Z"
|
||||
fill="#fff"
|
||||
/>
|
||||
<path
|
||||
d="M636.123 549.353C603.328 549.353 598.359 510.097 598.359 486.742C598.359 465.623 602.086 448.977 609.293 438.293C615.504 428.852 624.697 424.131 636.123 424.131C647.555 424.131 657.492 428.852 664.447 438.541C672.398 449.474 676.623 466.12 676.623 486.742C676.623 525.998 661.471 549.353 636.375 549.353H636.123Z"
|
||||
fill="#000"
|
||||
/>
|
||||
<path
|
||||
d="M771.24 549.353C738.445 549.353 733.477 510.097 733.477 486.742C733.477 465.623 737.203 448.977 744.41 438.293C750.621 428.852 759.814 424.131 771.24 424.131C782.672 424.131 792.609 428.852 799.564 438.541C807.516 449.474 811.74 466.12 811.74 486.742C811.74 525.998 796.588 549.353 771.492 549.353H771.24Z"
|
||||
fill="#000"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const VisualStudioCode: Icon = (props) => {
|
||||
const id = useId();
|
||||
const maskId = `${id}-vscode-a`;
|
||||
|
||||
@@ -80,6 +80,8 @@ function createBaseServerConfig(): ServerConfig {
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: NOW_ISO,
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
],
|
||||
availableEditors: [],
|
||||
@@ -167,6 +169,43 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
};
|
||||
}
|
||||
|
||||
function toShellSnapshot(snapshot: OrchestrationReadModel) {
|
||||
return {
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
projects: snapshot.projects.map((project) => ({
|
||||
id: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
repositoryIdentity: project.repositoryIdentity ?? null,
|
||||
defaultModelSelection: project.defaultModelSelection,
|
||||
scripts: project.scripts,
|
||||
createdAt: project.createdAt,
|
||||
updatedAt: project.updatedAt,
|
||||
})),
|
||||
threads: snapshot.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: thread.modelSelection,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
latestTurn: thread.latestTurn,
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
session: thread.session,
|
||||
latestUserMessageAt:
|
||||
thread.messages.findLast((message) => message.role === "user")?.createdAt ?? null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
})),
|
||||
updatedAt: snapshot.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFixture(): TestFixture {
|
||||
return {
|
||||
snapshot: createMinimalSnapshot(),
|
||||
@@ -188,9 +227,6 @@ function buildFixture(): TestFixture {
|
||||
}
|
||||
|
||||
function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
}
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
@@ -427,6 +463,28 @@ describe("Keybindings update toast", () => {
|
||||
},
|
||||
];
|
||||
}
|
||||
if (request._tag === ORCHESTRATION_WS_METHODS.subscribeShell) {
|
||||
return [
|
||||
{
|
||||
kind: "snapshot",
|
||||
snapshot: toShellSnapshot(fixture.snapshot),
|
||||
},
|
||||
];
|
||||
}
|
||||
if (
|
||||
request._tag === ORCHESTRATION_WS_METHODS.subscribeThread &&
|
||||
request.threadId === THREAD_ID
|
||||
) {
|
||||
return [
|
||||
{
|
||||
kind: "snapshot",
|
||||
snapshot: {
|
||||
snapshotSequence: fixture.snapshot.snapshotSequence,
|
||||
thread: fixture.snapshot.threads[0],
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
});
|
||||
|
||||
@@ -10,11 +10,15 @@ export function NoActiveThreadState() {
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border px-3 sm:px-5",
|
||||
isElectron ? "drag-region flex h-[52px] items-center" : "py-2 sm:py-3",
|
||||
isElectron
|
||||
? "drag-region flex h-[52px] items-center wco:h-[env(titlebar-area-height)]"
|
||||
: "py-2 sm:py-3",
|
||||
)}
|
||||
>
|
||||
{isElectron ? (
|
||||
<span className="text-xs text-muted-foreground/50">No active thread</span>
|
||||
<span className="text-xs text-muted-foreground/50 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]">
|
||||
No active thread
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createThreadJumpHintVisibilityController,
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
getVisibleSidebarThreadIds,
|
||||
resolveAdjacentThreadId,
|
||||
getFallbackThreadIdAfterDelete,
|
||||
@@ -17,7 +18,6 @@ import {
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import { EnvironmentId, OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
@@ -122,6 +122,20 @@ describe("createThreadJumpHintVisibilityController", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSidebarThreadIdsToPrewarm", () => {
|
||||
it("returns only the first visible thread ids up to the prewarm limit", () => {
|
||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2", "t3"], 2)).toEqual(["t1", "t2"]);
|
||||
});
|
||||
|
||||
it("returns all visible thread ids when they fit within the limit", () => {
|
||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 10)).toEqual(["t1", "t2"]);
|
||||
});
|
||||
|
||||
it("returns no thread ids when the limit is zero", () => {
|
||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 0)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldClearThreadSelectionOnMouseDown", () => {
|
||||
it("preserves selection for thread items", () => {
|
||||
const child = {
|
||||
@@ -170,6 +184,28 @@ describe("resolveSidebarNewThreadEnvMode", () => {
|
||||
});
|
||||
|
||||
describe("resolveSidebarNewThreadSeedContext", () => {
|
||||
it("prefers the default worktree mode over active thread context", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "worktree",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/existing",
|
||||
worktreePath: "/repo/.t3/worktrees/existing",
|
||||
},
|
||||
activeDraftThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/draft",
|
||||
worktreePath: "/repo/.t3/worktrees/draft",
|
||||
envMode: "worktree",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
|
||||
it("inherits the active server thread context when creating a new thread in the same project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
@@ -667,133 +703,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
};
|
||||
}
|
||||
|
||||
describe("sortThreadsForSidebar", () => {
|
||||
it("sorts threads by the latest user message in recency mode", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older",
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:01:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer",
|
||||
createdAt: "2026-03-09T10:06:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:06:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-2"),
|
||||
ThreadId.make("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to thread timestamps when there is no user message", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "assistant",
|
||||
text: "assistant only",
|
||||
createdAt: "2026-03-09T10:02:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:02:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-2"),
|
||||
ThreadId.make("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to id ordering when threads have no sortable timestamps", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "" as never,
|
||||
updatedAt: undefined,
|
||||
messages: [],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "" as never,
|
||||
updatedAt: undefined,
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-2"),
|
||||
ThreadId.make("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("can sort threads by createdAt when configured", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
}),
|
||||
],
|
||||
"created_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-1"),
|
||||
ThreadId.make("thread-2"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFallbackThreadIdAfterDelete", () => {
|
||||
it("returns the top remaining thread in the deleted thread's project sidebar order", () => {
|
||||
const fallbackThreadId = getFallbackThreadIdAfterDelete({
|
||||
@@ -860,7 +769,6 @@ describe("getFallbackThreadIdAfterDelete", () => {
|
||||
expect(fallbackThreadId).toBe(ThreadId.make("thread-next"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortProjectsForSidebar", () => {
|
||||
it("sorts projects by the most recent user message across their threads", () => {
|
||||
const projects = [
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import * as React from "react";
|
||||
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import {
|
||||
getThreadSortTimestamp,
|
||||
sortThreads,
|
||||
toSortableTimestamp,
|
||||
type ThreadSortInput,
|
||||
} from "../lib/threadSort";
|
||||
import type { SidebarThreadSummary, Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
import { isLatestTurnSettled } from "../session-logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
|
||||
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
|
||||
// nearby thread usually reuses an already-hot subscription.
|
||||
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
@@ -13,10 +22,6 @@ type SidebarProject = {
|
||||
createdAt?: string | undefined;
|
||||
updatedAt?: string | undefined;
|
||||
};
|
||||
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
|
||||
latestUserMessageAt?: string | null;
|
||||
messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
|
||||
};
|
||||
|
||||
export type ThreadTraversalDirection = "previous" | "next";
|
||||
|
||||
@@ -181,6 +186,12 @@ export function resolveSidebarNewThreadSeedContext(input: {
|
||||
worktreePath?: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
} {
|
||||
if (input.defaultEnvMode === "worktree") {
|
||||
return {
|
||||
envMode: "worktree",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeDraftThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeDraftThread.branch,
|
||||
@@ -241,6 +252,13 @@ export function getVisibleSidebarThreadIds<TThreadId>(
|
||||
);
|
||||
}
|
||||
|
||||
export function getSidebarThreadIdsToPrewarm<TThreadId>(
|
||||
visibleThreadIds: readonly TThreadId[],
|
||||
limit = SIDEBAR_THREAD_PREWARM_LIMIT,
|
||||
): TThreadId[] {
|
||||
return visibleThreadIds.slice(0, Math.max(0, limit));
|
||||
}
|
||||
|
||||
export function resolveAdjacentThreadId<T>(input: {
|
||||
threadIds: readonly T[];
|
||||
currentThreadId: T | null;
|
||||
@@ -441,61 +459,8 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
|
||||
};
|
||||
}
|
||||
|
||||
function toSortableTimestamp(iso: string | undefined): number | null {
|
||||
if (!iso) return null;
|
||||
const ms = Date.parse(iso);
|
||||
return Number.isFinite(ms) ? ms : null;
|
||||
}
|
||||
|
||||
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
|
||||
if (thread.latestUserMessageAt) {
|
||||
return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
let latestUserMessageTimestamp: number | null = null;
|
||||
|
||||
for (const message of thread.messages ?? []) {
|
||||
if (message.role !== "user") continue;
|
||||
const messageTimestamp = toSortableTimestamp(message.createdAt);
|
||||
if (messageTimestamp === null) continue;
|
||||
latestUserMessageTimestamp =
|
||||
latestUserMessageTimestamp === null
|
||||
? messageTimestamp
|
||||
: Math.max(latestUserMessageTimestamp, messageTimestamp);
|
||||
}
|
||||
|
||||
if (latestUserMessageTimestamp !== null) {
|
||||
return latestUserMessageTimestamp;
|
||||
}
|
||||
|
||||
return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
function getThreadSortTimestamp(
|
||||
thread: SidebarThreadSortInput,
|
||||
sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
|
||||
): number {
|
||||
if (sortOrder === "created_at") {
|
||||
return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
return getLatestUserMessageTimestamp(thread);
|
||||
}
|
||||
|
||||
export function sortThreadsForSidebar<
|
||||
T extends Pick<Thread, "id" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
|
||||
return threads.toSorted((left, right) => {
|
||||
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
|
||||
const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
|
||||
const byTimestamp =
|
||||
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
|
||||
if (byTimestamp !== 0) return byTimestamp;
|
||||
return right.id.localeCompare(left.id);
|
||||
});
|
||||
}
|
||||
|
||||
export function getFallbackThreadIdAfterDelete<
|
||||
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
|
||||
>(input: {
|
||||
threads: readonly T[];
|
||||
deletedThreadId: T["id"];
|
||||
@@ -509,7 +474,7 @@ export function getFallbackThreadIdAfterDelete<
|
||||
}
|
||||
|
||||
return (
|
||||
sortThreadsForSidebar(
|
||||
sortThreads(
|
||||
threads.filter(
|
||||
(thread) =>
|
||||
thread.projectId === deletedThread.projectId &&
|
||||
@@ -520,10 +485,9 @@ export function getFallbackThreadIdAfterDelete<
|
||||
)[0]?.id ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function getProjectSortTimestamp(
|
||||
project: SidebarProject,
|
||||
projectThreads: readonly SidebarThreadSortInput[],
|
||||
projectThreads: readonly ThreadSortInput[],
|
||||
sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
|
||||
): number {
|
||||
if (projectThreads.length > 0) {
|
||||
@@ -541,7 +505,7 @@ export function getProjectSortTimestamp(
|
||||
|
||||
export function sortProjectsForSidebar<
|
||||
TProject extends SidebarProject,
|
||||
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
|
||||
>(
|
||||
projects: readonly TProject[],
|
||||
threads: readonly TThread[],
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
PlusIcon,
|
||||
SearchIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
@@ -42,6 +43,7 @@ import {
|
||||
type GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedProjectKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
@@ -80,6 +82,7 @@ import { useGitStatus } from "../lib/gitStatusState";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
|
||||
import { retainThreadDetailSubscription } from "../environments/runtime/service";
|
||||
|
||||
import { useThreadActions } from "../hooks/useThreadActions";
|
||||
import {
|
||||
@@ -90,6 +93,7 @@ import {
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
import { Kbd } from "./ui/kbd";
|
||||
import {
|
||||
getArm64IntelBuildWarningDescription,
|
||||
getDesktopUpdateActionError,
|
||||
@@ -120,6 +124,7 @@ import {
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
import {
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
resolveAdjacentThreadId,
|
||||
isContextMenuPointerDown,
|
||||
resolveProjectStatusIndicator,
|
||||
@@ -130,20 +135,23 @@ import {
|
||||
orderItemsByPreferredIds,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
useThreadJumpHintVisibility,
|
||||
ThreadStatusPill,
|
||||
} from "./Sidebar.logic";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { readEnvironmentApi } from "../environmentApi";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
import { deriveLogicalProjectKey } from "../logicalProject";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import {
|
||||
useSavedEnvironmentRegistryStore,
|
||||
useSavedEnvironmentRuntimeStore,
|
||||
} from "../environments/runtime";
|
||||
import { serverThreadSurfaceInput } from "../workspace/types";
|
||||
import { useWorkspaceStore, useWorkspaceThreadTerminalOpen } from "../workspace/store";
|
||||
import type { Project, SidebarThreadSummary } from "../types";
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
|
||||
@@ -644,7 +652,21 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
onClick={handleRenameInputClick}
|
||||
/>
|
||||
) : (
|
||||
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
className="min-w-0 flex-1 truncate text-xs"
|
||||
data-testid={`thread-title-${thread.id}`}
|
||||
>
|
||||
{thread.title}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-80 whitespace-normal leading-tight">
|
||||
{thread.title}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
@@ -742,7 +764,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
: "text-muted-foreground/40"
|
||||
}`}
|
||||
>
|
||||
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
|
||||
{formatRelativeTimeLabel(
|
||||
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
@@ -986,6 +1010,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const removeFromSelection = useThreadSelectionStore((state) => state.removeFromSelection);
|
||||
const setSelectionAnchor = useThreadSelectionStore((state) => state.setAnchor);
|
||||
const selectedThreadCount = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
|
||||
const openThreadInNewTab = useWorkspaceStore((state) => state.openThreadInNewTab);
|
||||
const openThreadInSplit = useWorkspaceStore((state) => state.openThreadInSplit);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((state) => state.clearDraftThread);
|
||||
const getDraftThreadByProjectRef = useComposerDraftStore(
|
||||
(state) => state.getDraftThreadByProjectRef,
|
||||
@@ -1098,6 +1124,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
),
|
||||
[allSidebarThreads],
|
||||
);
|
||||
// Keep a ref so callbacks can read the latest map without appearing in
|
||||
// dependency arrays (avoids invalidating every thread-row memo on each
|
||||
// thread-list change).
|
||||
const sidebarThreadByKeyRef = useRef(sidebarThreadByKey);
|
||||
sidebarThreadByKeyRef.current = sidebarThreadByKey;
|
||||
// All threads from the representative + other member environments are
|
||||
// already fetched into allSidebarThreads, so we can use them directly.
|
||||
const projectThreads = allSidebarThreads;
|
||||
@@ -1139,7 +1170,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
},
|
||||
});
|
||||
};
|
||||
const visibleProjectThreads = sortThreadsForSidebar(
|
||||
const visibleProjectThreads = sortThreads(
|
||||
projectThreads.filter((thread) => thread.archivedAt === null),
|
||||
threadSortOrder,
|
||||
);
|
||||
@@ -1441,7 +1472,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = sidebarThreadByKey.get(threadKey);
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey);
|
||||
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
|
||||
}
|
||||
clearSelection();
|
||||
@@ -1462,7 +1493,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
const deletedThreadKeys = new Set(threadKeys);
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = sidebarThreadByKey.get(threadKey);
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey);
|
||||
if (!thread) continue;
|
||||
await deleteThread(scopeThreadRef(thread.environmentId, thread.id), {
|
||||
deletedThreadKeys,
|
||||
@@ -1476,7 +1507,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
deleteThread,
|
||||
markThreadUnread,
|
||||
removeFromSelection,
|
||||
sidebarThreadByKey,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1605,16 +1635,14 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const api = readLocalApi();
|
||||
if (!api) return;
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const thread =
|
||||
projectThreads.find(
|
||||
(projectThread) =>
|
||||
projectThread.environmentId === threadRef.environmentId &&
|
||||
projectThread.id === threadRef.threadId,
|
||||
) ?? null;
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null;
|
||||
if (!thread) return;
|
||||
const threadWorkspacePath = thread.worktreePath ?? project.cwd ?? null;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "open-new-tab", label: "Open in new tab" },
|
||||
{ id: "open-split-right", label: "Open in split right" },
|
||||
{ id: "open-split-down", label: "Open in split down" },
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-path", label: "Copy Path" },
|
||||
@@ -1624,6 +1652,21 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
position,
|
||||
);
|
||||
|
||||
if (clicked === "open-new-tab") {
|
||||
openThreadInNewTab(serverThreadSurfaceInput(threadRef));
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "open-split-right") {
|
||||
openThreadInSplit(serverThreadSurfaceInput(threadRef), "x");
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "open-split-down") {
|
||||
openThreadInSplit(serverThreadSurfaceInput(threadRef), "y");
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "rename") {
|
||||
setRenamingThreadKey(threadKey);
|
||||
setRenamingTitle(thread.title);
|
||||
@@ -1671,8 +1714,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
markThreadUnread,
|
||||
openThreadInNewTab,
|
||||
openThreadInSplit,
|
||||
project.cwd,
|
||||
projectThreads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1971,7 +2015,7 @@ const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
);
|
||||
|
||||
return isElectron ? (
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px]">
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px] wco:h-[env(titlebar-area-height)] wco:pl-[calc(env(titlebar-area-x)+1em)]">
|
||||
{wordmark}
|
||||
</SidebarHeader>
|
||||
) : (
|
||||
@@ -2041,6 +2085,8 @@ interface SidebarProjectsContentProps {
|
||||
activeRouteProjectKey: string | null;
|
||||
routeThreadKey: string | null;
|
||||
newThreadShortcutLabel: string | null;
|
||||
commandPaletteShortcutLabel: string | null;
|
||||
onOpenCommandPalette: () => void;
|
||||
threadJumpLabelByKey: ReadonlyMap<string, string>;
|
||||
attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void;
|
||||
expandThreadListForProject: (projectKey: string) => void;
|
||||
@@ -2092,6 +2138,8 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
activeRouteProjectKey,
|
||||
routeThreadKey,
|
||||
newThreadShortcutLabel,
|
||||
commandPaletteShortcutLabel,
|
||||
onOpenCommandPalette,
|
||||
threadJumpLabelByKey,
|
||||
attachThreadListAutoAnimateRef,
|
||||
expandThreadListForProject,
|
||||
@@ -2138,6 +2186,27 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
|
||||
return (
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 pt-2 pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
type="button"
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground focus-visible:ring-0"
|
||||
data-testid="command-palette-trigger"
|
||||
onClick={onOpenCommandPalette}
|
||||
>
|
||||
<SearchIcon className="size-3.5" />
|
||||
<span className="flex-1 truncate text-left text-xs">Search</span>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
{showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? (
|
||||
<SidebarGroup className="px-2 pt-2 pb-0">
|
||||
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
|
||||
@@ -2345,7 +2414,9 @@ export default function Sidebar() {
|
||||
select: (params) => resolveThreadRouteRef(params),
|
||||
});
|
||||
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
|
||||
const routeThreadTerminalOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
|
||||
const keybindings = useServerKeybindings();
|
||||
const setCommandPaletteOpen = useCommandPaletteStore((state) => state.setOpen);
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
@@ -2507,14 +2578,9 @@ export default function Sidebar() {
|
||||
const getCurrentSidebarShortcutContext = useCallback(
|
||||
() => ({
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen: routeThreadRef
|
||||
? selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
routeThreadRef,
|
||||
).terminalOpen
|
||||
: false,
|
||||
terminalOpen: routeThreadTerminalOpen,
|
||||
}),
|
||||
[routeThreadRef],
|
||||
[routeThreadTerminalOpen],
|
||||
);
|
||||
const newThreadShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
@@ -2535,7 +2601,7 @@ export default function Sidebar() {
|
||||
scopeProjectRef(projectRef.environmentId, projectRef.projectId),
|
||||
);
|
||||
const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey;
|
||||
const latestThread = sortThreadsForSidebar(
|
||||
const latestThread = sortThreads(
|
||||
(threadsByProjectKey.get(logicalKey) ?? []).filter((thread) => thread.archivedAt === null),
|
||||
sidebarThreadSortOrder,
|
||||
)[0];
|
||||
@@ -2549,7 +2615,7 @@ export default function Sidebar() {
|
||||
[sidebarThreadSortOrder, navigate, threadsByProjectKey, physicalToLogicalKey],
|
||||
);
|
||||
|
||||
const addProjectFromPath = useCallback(
|
||||
const addProjectFromInput = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
const cwd = rawCwd.trim();
|
||||
if (!cwd || isAddingProject) return;
|
||||
@@ -2575,7 +2641,6 @@ export default function Sidebar() {
|
||||
}
|
||||
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
try {
|
||||
await api.orchestration.dispatchCommand({
|
||||
@@ -2588,7 +2653,7 @@ export default function Sidebar() {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
createdAt,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
if (activeEnvironmentId !== null) {
|
||||
await handleNewThread(scopeProjectRef(activeEnvironmentId, projectId), {
|
||||
@@ -2624,7 +2689,7 @@ export default function Sidebar() {
|
||||
);
|
||||
|
||||
const handleAddProject = () => {
|
||||
void addProjectFromPath(newCwd);
|
||||
void addProjectFromInput(newCwd);
|
||||
};
|
||||
|
||||
const canAddProject = newCwd.trim().length > 0 && !isAddingProject;
|
||||
@@ -2640,7 +2705,7 @@ export default function Sidebar() {
|
||||
// Ignore picker failures and leave the current thread selection unchanged.
|
||||
}
|
||||
if (pickedPath) {
|
||||
await addProjectFromPath(pickedPath);
|
||||
await addProjectFromInput(pickedPath);
|
||||
} else if (!shouldBrowseForProjectImmediately) {
|
||||
addProjectInputRef.current?.focus();
|
||||
}
|
||||
@@ -2696,7 +2761,9 @@ export default function Sidebar() {
|
||||
const activeProject = sidebarProjects.find((project) => project.projectKey === active.id);
|
||||
const overProject = sidebarProjects.find((project) => project.projectKey === over.id);
|
||||
if (!activeProject || !overProject) return;
|
||||
reorderProjects(activeProject.projectKey, overProject.projectKey);
|
||||
const activeMemberKeys = activeProject.memberProjectRefs.map(scopedProjectKey);
|
||||
const overMemberKeys = overProject.memberProjectRefs.map(scopedProjectKey);
|
||||
reorderProjects(activeMemberKeys, overMemberKeys);
|
||||
},
|
||||
[sidebarProjectSortOrder, reorderProjects, sidebarProjects],
|
||||
);
|
||||
@@ -2769,7 +2836,7 @@ export default function Sidebar() {
|
||||
const visibleSidebarThreadKeys = useMemo(
|
||||
() =>
|
||||
sortedProjects.flatMap((project) => {
|
||||
const projectThreads = sortThreadsForSidebar(
|
||||
const projectThreads = sortThreads(
|
||||
(threadsByProjectKey.get(project.projectKey) ?? []).filter(
|
||||
(thread) => thread.archivedAt === null,
|
||||
),
|
||||
@@ -2835,6 +2902,30 @@ export default function Sidebar() {
|
||||
? threadJumpLabelByKey
|
||||
: EMPTY_THREAD_JUMP_LABELS;
|
||||
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
|
||||
const prewarmedSidebarThreadKeys = useMemo(
|
||||
() => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys),
|
||||
[visibleSidebarThreadKeys],
|
||||
);
|
||||
const prewarmedSidebarThreadRefs = useMemo(
|
||||
() =>
|
||||
prewarmedSidebarThreadKeys.flatMap((threadKey) => {
|
||||
const ref = parseScopedThreadKey(threadKey);
|
||||
return ref ? [ref] : [];
|
||||
}),
|
||||
[prewarmedSidebarThreadKeys],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const releases = prewarmedSidebarThreadRefs.map((ref) =>
|
||||
retainThreadDetailSubscription(ref.environmentId, ref.threadId),
|
||||
);
|
||||
|
||||
return () => {
|
||||
for (const release of releases) {
|
||||
release();
|
||||
}
|
||||
};
|
||||
}, [prewarmedSidebarThreadRefs]);
|
||||
|
||||
useEffect(() => {
|
||||
const clearThreadJumpHints = () => {
|
||||
@@ -3040,6 +3131,11 @@ export default function Sidebar() {
|
||||
desktopUpdateState && showArm64IntelBuildWarning
|
||||
? getArm64IntelBuildWarningDescription(desktopUpdateState)
|
||||
: null;
|
||||
const commandPaletteShortcutLabel = shortcutLabelForCommand(
|
||||
keybindings,
|
||||
"commandPalette.toggle",
|
||||
newThreadShortcutLabelOptions,
|
||||
);
|
||||
const handleDesktopUpdateButtonClick = useCallback(() => {
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || !desktopUpdateState) return;
|
||||
@@ -3165,6 +3261,8 @@ export default function Sidebar() {
|
||||
activeRouteProjectKey={activeRouteProjectKey}
|
||||
routeThreadKey={routeThreadKey}
|
||||
newThreadShortcutLabel={newThreadShortcutLabel}
|
||||
commandPaletteShortcutLabel={commandPaletteShortcutLabel}
|
||||
onOpenCommandPalette={() => setCommandPaletteOpen(true)}
|
||||
threadJumpLabelByKey={visibleThreadJumpLabelByKey}
|
||||
attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef}
|
||||
expandThreadListForProject={expandThreadListForProject}
|
||||
|
||||
@@ -21,9 +21,12 @@ import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { type TerminalContextSelection } from "~/lib/terminalContext";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import {
|
||||
collectWrappedTerminalLinkLine,
|
||||
extractTerminalLinks,
|
||||
isTerminalLinkActivation,
|
||||
resolvePathLinkTarget,
|
||||
resolveWrappedTerminalLinkRange,
|
||||
wrappedTerminalLinkRangeIntersectsBufferLine,
|
||||
} from "../terminal-links";
|
||||
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
|
||||
import {
|
||||
@@ -419,26 +422,31 @@ export function TerminalViewport({
|
||||
return;
|
||||
}
|
||||
|
||||
const line = activeTerminal.buffer.active.getLine(bufferLineNumber - 1);
|
||||
if (!line) {
|
||||
const wrappedLine = collectWrappedTerminalLinkLine(bufferLineNumber, (bufferLineIndex) =>
|
||||
activeTerminal.buffer.active.getLine(bufferLineIndex),
|
||||
);
|
||||
if (!wrappedLine) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const lineText = line.translateToString(true);
|
||||
const matches = extractTerminalLinks(lineText);
|
||||
if (matches.length === 0) {
|
||||
const links = extractTerminalLinks(wrappedLine.text)
|
||||
.map((match) => ({
|
||||
match,
|
||||
range: resolveWrappedTerminalLinkRange(wrappedLine, match),
|
||||
}))
|
||||
.filter(({ range }) =>
|
||||
wrappedTerminalLinkRangeIntersectsBufferLine(range, bufferLineNumber),
|
||||
);
|
||||
if (links.length === 0) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(
|
||||
matches.map((match) => ({
|
||||
links.map(({ match, range }) => ({
|
||||
text: match.text,
|
||||
range: {
|
||||
start: { x: match.start + 1, y: bufferLineNumber },
|
||||
end: { x: match.end, y: bufferLineNumber },
|
||||
},
|
||||
range,
|
||||
activate: (event: MouseEvent) => {
|
||||
if (!isTerminalLinkActivation(event)) return;
|
||||
|
||||
@@ -775,6 +783,7 @@ interface ThreadTerminalDrawerProps {
|
||||
onCloseTerminal: (terminalId: string) => void;
|
||||
onHeightChange: (height: number) => void;
|
||||
onAddTerminalContext: (selection: TerminalContextSelection) => void;
|
||||
showResizeHandle?: boolean;
|
||||
}
|
||||
|
||||
interface TerminalActionButtonProps {
|
||||
@@ -828,6 +837,7 @@ export default function ThreadTerminalDrawer({
|
||||
onCloseTerminal,
|
||||
onHeightChange,
|
||||
onAddTerminalContext,
|
||||
showResizeHandle = true,
|
||||
}: ThreadTerminalDrawerProps) {
|
||||
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
|
||||
const [resizeEpoch, setResizeEpoch] = useState(0);
|
||||
@@ -1064,16 +1074,20 @@ export default function ThreadTerminalDrawer({
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
className={`thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden bg-background ${
|
||||
showResizeHandle ? "border-t border-border/80" : ""
|
||||
}`}
|
||||
style={{ height: `${drawerHeight}px` }}
|
||||
>
|
||||
<div
|
||||
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
|
||||
onPointerDown={handleResizePointerDown}
|
||||
onPointerMove={handleResizePointerMove}
|
||||
onPointerUp={handleResizePointerEnd}
|
||||
onPointerCancel={handleResizePointerEnd}
|
||||
/>
|
||||
{showResizeHandle ? (
|
||||
<div
|
||||
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
|
||||
onPointerDown={handleResizePointerDown}
|
||||
onPointerMove={handleResizePointerMove}
|
||||
onPointerUp={handleResizePointerEnd}
|
||||
onPointerCancel={handleResizePointerEnd}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!hasTerminalSidebar && (
|
||||
<div className="pointer-events-none absolute right-2 top-2 z-20">
|
||||
|
||||
@@ -55,8 +55,6 @@ import {
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
} from "../../lib/terminalContext";
|
||||
import {
|
||||
resolveComposerFooterContentWidth,
|
||||
shouldForceCompactComposerFooterForFit,
|
||||
shouldUseCompactComposerPrimaryActions,
|
||||
shouldUseCompactComposerFooter,
|
||||
} from "../composerFooterLayout";
|
||||
@@ -69,6 +67,8 @@ import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
|
||||
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
|
||||
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
|
||||
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
|
||||
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
|
||||
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
|
||||
import {
|
||||
getComposerProviderState,
|
||||
renderProviderTraitsMenuContent,
|
||||
@@ -100,6 +100,8 @@ import type { SessionPhase, Thread } from "../../types";
|
||||
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
|
||||
import type { PendingApproval, PendingUserInput } from "../../session-logic";
|
||||
import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";
|
||||
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
|
||||
import { searchProviderSkills } from "../../providerSkillSearch";
|
||||
|
||||
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
|
||||
|
||||
@@ -560,6 +562,10 @@ export const ChatComposer = memo(
|
||||
});
|
||||
|
||||
const selectedProviderModels = getProviderModels(providerStatuses, selectedProvider);
|
||||
const selectedProviderStatus = useMemo(
|
||||
() => providerStatuses.find((provider) => provider.provider === selectedProvider),
|
||||
[providerStatuses, selectedProvider],
|
||||
);
|
||||
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
@@ -636,6 +642,9 @@ export const ChatComposer = memo(
|
||||
detectComposerTrigger(prompt, prompt.length),
|
||||
);
|
||||
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
|
||||
const [composerHighlightedSearchKey, setComposerHighlightedSearchKey] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
||||
const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false);
|
||||
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
|
||||
@@ -646,9 +655,6 @@ export const ChatComposer = memo(
|
||||
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
|
||||
const composerFormRef = useRef<HTMLFormElement>(null);
|
||||
const composerFormHeightRef = useRef(0);
|
||||
const composerFooterRef = useRef<HTMLDivElement>(null);
|
||||
const composerFooterLeadingRef = useRef<HTMLDivElement>(null);
|
||||
const composerFooterActionsRef = useRef<HTMLDivElement>(null);
|
||||
const composerSelectLockRef = useRef(false);
|
||||
const composerMenuOpenRef = useRef(false);
|
||||
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
|
||||
@@ -704,7 +710,7 @@ export const ChatComposer = memo(
|
||||
}));
|
||||
}
|
||||
if (composerTrigger.kind === "slash-command") {
|
||||
const slashCommandItems = [
|
||||
const builtInSlashCommandItems = [
|
||||
{
|
||||
id: "slash:model",
|
||||
type: "slash-command",
|
||||
@@ -727,13 +733,38 @@ export const ChatComposer = memo(
|
||||
description: "Switch this thread back to normal build mode",
|
||||
},
|
||||
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
if (!query) {
|
||||
return [...slashCommandItems];
|
||||
}
|
||||
return slashCommandItems.filter(
|
||||
(item) => item.command.includes(query) || item.label.slice(1).includes(query),
|
||||
const providerSlashCommandItems = (selectedProviderStatus?.slashCommands ?? []).map(
|
||||
(command) => ({
|
||||
id: `provider-slash-command:${selectedProvider}:${command.name}`,
|
||||
type: "provider-slash-command" as const,
|
||||
provider: selectedProvider,
|
||||
command,
|
||||
label: `/${command.name}`,
|
||||
description: command.description ?? command.input?.hint ?? "Run provider command",
|
||||
}),
|
||||
);
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
const slashCommandItems = [...builtInSlashCommandItems, ...providerSlashCommandItems];
|
||||
if (!query) {
|
||||
return slashCommandItems;
|
||||
}
|
||||
return searchSlashCommandItems(slashCommandItems, query);
|
||||
}
|
||||
if (composerTrigger.kind === "skill") {
|
||||
return searchProviderSkills(
|
||||
selectedProviderStatus?.skills ?? [],
|
||||
composerTrigger.query,
|
||||
).map((skill) => ({
|
||||
id: `skill:${selectedProvider}:${skill.name}`,
|
||||
type: "skill" as const,
|
||||
provider: selectedProvider,
|
||||
skill,
|
||||
label: formatProviderSkillDisplayName(skill),
|
||||
description:
|
||||
skill.shortDescription ??
|
||||
skill.description ??
|
||||
(skill.scope ? `${skill.scope} skill` : "Run provider skill"),
|
||||
}));
|
||||
}
|
||||
return searchableModelOptions
|
||||
.filter(({ searchSlug, searchName, searchProvider }) => {
|
||||
@@ -753,16 +784,32 @@ export const ChatComposer = memo(
|
||||
label: name,
|
||||
description: `${providerLabel} · ${slug}`,
|
||||
}));
|
||||
}, [composerTrigger, searchableModelOptions, workspaceEntries]);
|
||||
}, [
|
||||
composerTrigger,
|
||||
searchableModelOptions,
|
||||
selectedProvider,
|
||||
selectedProviderStatus,
|
||||
workspaceEntries,
|
||||
]);
|
||||
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const activeComposerMenuItem = useMemo(
|
||||
() =>
|
||||
composerMenuItems.find((item) => item.id === composerHighlightedItemId) ??
|
||||
composerMenuItems[0] ??
|
||||
null,
|
||||
[composerHighlightedItemId, composerMenuItems],
|
||||
);
|
||||
const composerMenuSearchKey = composerTrigger
|
||||
? `${composerTrigger.kind}:${composerTrigger.query.trim().toLowerCase()}`
|
||||
: null;
|
||||
const activeComposerMenuItem = useMemo(() => {
|
||||
const activeItemId = resolveComposerMenuActiveItemId({
|
||||
items: composerMenuItems,
|
||||
highlightedItemId: composerHighlightedItemId,
|
||||
currentSearchKey: composerMenuSearchKey,
|
||||
highlightedSearchKey: composerHighlightedSearchKey,
|
||||
});
|
||||
return composerMenuItems.find((item) => item.id === activeItemId) ?? null;
|
||||
}, [
|
||||
composerHighlightedItemId,
|
||||
composerHighlightedSearchKey,
|
||||
composerMenuItems,
|
||||
composerMenuSearchKey,
|
||||
]);
|
||||
|
||||
composerMenuOpenRef.current = composerMenuOpen;
|
||||
composerMenuItemsRef.current = composerMenuItems;
|
||||
@@ -810,14 +857,21 @@ export const ChatComposer = memo(
|
||||
((pathTriggerQuery.length > 0 && composerPathQueryDebouncer.state.isPending) ||
|
||||
workspaceEntriesQuery.isLoading ||
|
||||
workspaceEntriesQuery.isFetching);
|
||||
const composerMenuEmptyState = useMemo(() => {
|
||||
if (composerTriggerKind === "skill") {
|
||||
return "No skills found. Try / to browse provider commands.";
|
||||
}
|
||||
return composerTriggerKind === "path"
|
||||
? "No matching files or folders."
|
||||
: "No matching command.";
|
||||
}, [composerTriggerKind]);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Provider traits UI
|
||||
// ------------------------------------------------------------------
|
||||
const setPromptFromTraits = useCallback(
|
||||
(nextPrompt: string) => {
|
||||
const currentPrompt = promptRef.current;
|
||||
if (nextPrompt === currentPrompt) {
|
||||
if (nextPrompt === promptRef.current) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
@@ -941,14 +995,28 @@ export const ChatComposer = memo(
|
||||
useEffect(() => {
|
||||
if (!composerMenuOpen) {
|
||||
setComposerHighlightedItemId(null);
|
||||
setComposerHighlightedSearchKey(null);
|
||||
return;
|
||||
}
|
||||
const nextActiveItemId = resolveComposerMenuActiveItemId({
|
||||
items: composerMenuItems,
|
||||
highlightedItemId: composerHighlightedItemId,
|
||||
currentSearchKey: composerMenuSearchKey,
|
||||
highlightedSearchKey: composerHighlightedSearchKey,
|
||||
});
|
||||
setComposerHighlightedItemId((existing) =>
|
||||
existing && composerMenuItems.some((item) => item.id === existing)
|
||||
? existing
|
||||
: (composerMenuItems[0]?.id ?? null),
|
||||
existing === nextActiveItemId ? existing : nextActiveItemId,
|
||||
);
|
||||
}, [composerMenuItems, composerMenuOpen]);
|
||||
setComposerHighlightedSearchKey((existing) =>
|
||||
existing === composerMenuSearchKey ? existing : composerMenuSearchKey,
|
||||
);
|
||||
}, [
|
||||
composerHighlightedItemId,
|
||||
composerHighlightedSearchKey,
|
||||
composerMenuItems,
|
||||
composerMenuOpen,
|
||||
composerMenuSearchKey,
|
||||
]);
|
||||
|
||||
const lastSyncedPendingInputRef = useRef<{
|
||||
requestId: string | null;
|
||||
@@ -1017,31 +1085,17 @@ export const ChatComposer = memo(
|
||||
const measureComposerFormWidth = () => composerForm.clientWidth;
|
||||
const measureFooterCompactness = () => {
|
||||
const composerFormWidth = measureComposerFormWidth();
|
||||
const heuristicFooterCompact = shouldUseCompactComposerFooter(composerFormWidth, {
|
||||
const footerCompact = shouldUseCompactComposerFooter(composerFormWidth, {
|
||||
hasWideActions: composerFooterHasWideActions,
|
||||
});
|
||||
const footer = composerFooterRef.current;
|
||||
const footerStyle = footer ? window.getComputedStyle(footer) : null;
|
||||
const footerContentWidth = resolveComposerFooterContentWidth({
|
||||
footerWidth: footer?.clientWidth ?? null,
|
||||
paddingLeft: footerStyle ? Number.parseFloat(footerStyle.paddingLeft) : null,
|
||||
paddingRight: footerStyle ? Number.parseFloat(footerStyle.paddingRight) : null,
|
||||
});
|
||||
const fitInput = {
|
||||
footerContentWidth,
|
||||
leadingContentWidth: composerFooterLeadingRef.current?.scrollWidth ?? null,
|
||||
actionsWidth: composerFooterActionsRef.current?.scrollWidth ?? null,
|
||||
};
|
||||
const nextFooterCompact =
|
||||
heuristicFooterCompact || shouldForceCompactComposerFooterForFit(fitInput);
|
||||
const nextPrimaryActionsCompact =
|
||||
nextFooterCompact &&
|
||||
const primaryActionsCompact =
|
||||
footerCompact &&
|
||||
shouldUseCompactComposerPrimaryActions(composerFormWidth, {
|
||||
hasWideActions: composerFooterHasWideActions,
|
||||
});
|
||||
return {
|
||||
primaryActionsCompact: nextPrimaryActionsCompact,
|
||||
footerCompact: nextFooterCompact,
|
||||
primaryActionsCompact,
|
||||
footerCompact,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1333,6 +1387,42 @@ export const ChatComposer = memo(
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (item.type === "provider-slash-command") {
|
||||
const replacement = `/${item.command.name} `;
|
||||
const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
|
||||
snapshot.value,
|
||||
trigger.rangeEnd,
|
||||
replacement,
|
||||
);
|
||||
const applied = applyPromptReplacement(
|
||||
trigger.rangeStart,
|
||||
replacementRangeEnd,
|
||||
replacement,
|
||||
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
|
||||
);
|
||||
if (applied) {
|
||||
setComposerHighlightedItemId(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (item.type === "skill") {
|
||||
const replacement = `$${item.skill.name} `;
|
||||
const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
|
||||
snapshot.value,
|
||||
trigger.rangeEnd,
|
||||
replacement,
|
||||
);
|
||||
const applied = applyPromptReplacement(
|
||||
trigger.rangeStart,
|
||||
replacementRangeEnd,
|
||||
replacement,
|
||||
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
|
||||
);
|
||||
if (applied) {
|
||||
setComposerHighlightedItemId(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
onProviderModelSelect(item.provider, item.model);
|
||||
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
|
||||
expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
|
||||
@@ -1349,9 +1439,13 @@ export const ChatComposer = memo(
|
||||
],
|
||||
);
|
||||
|
||||
const onComposerMenuItemHighlighted = useCallback((itemId: string | null) => {
|
||||
setComposerHighlightedItemId(itemId);
|
||||
}, []);
|
||||
const onComposerMenuItemHighlighted = useCallback(
|
||||
(itemId: string | null) => {
|
||||
setComposerHighlightedItemId(itemId);
|
||||
setComposerHighlightedSearchKey(composerMenuSearchKey);
|
||||
},
|
||||
[composerMenuSearchKey],
|
||||
);
|
||||
|
||||
const nudgeComposerMenuHighlight = useCallback(
|
||||
(key: "ArrowDown" | "ArrowUp") => {
|
||||
@@ -1676,6 +1770,11 @@ export const ChatComposer = memo(
|
||||
resolvedTheme={resolvedTheme}
|
||||
isLoading={isComposerMenuLoading}
|
||||
triggerKind={composerTriggerKind}
|
||||
groupSlashCommandSections={
|
||||
composerTrigger?.kind === "slash-command" &&
|
||||
composerTrigger.query.trim().length === 0
|
||||
}
|
||||
emptyStateText={composerMenuEmptyState}
|
||||
activeItemId={activeComposerMenuItem?.id ?? null}
|
||||
onHighlightedItemChange={onComposerMenuItemHighlighted}
|
||||
onSelect={onSelectComposerItem}
|
||||
@@ -1765,6 +1864,7 @@ export const ChatComposer = memo(
|
||||
? composerTerminalContexts
|
||||
: []
|
||||
}
|
||||
skills={selectedProviderStatus?.skills ?? []}
|
||||
onRemoveTerminalContext={removeComposerTerminalContextFromDraft}
|
||||
onChange={onPromptChange}
|
||||
onCommandKeyDown={onComposerCommandKey}
|
||||
@@ -1795,7 +1895,6 @@ export const ChatComposer = memo(
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
ref={composerFooterRef}
|
||||
data-chat-composer-footer="true"
|
||||
data-chat-composer-footer-compact={isComposerFooterCompact ? "true" : "false"}
|
||||
className={cn(
|
||||
@@ -1803,15 +1902,7 @@ export const ChatComposer = memo(
|
||||
isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
ref={composerFooterLeadingRef}
|
||||
className={cn(
|
||||
"flex min-w-0 flex-1 items-center",
|
||||
isComposerFooterCompact
|
||||
? "gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||
: "gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:min-w-max sm:overflow-visible",
|
||||
)}
|
||||
>
|
||||
<div className="-m-1 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<ProviderModelPicker
|
||||
compact={isComposerFooterCompact}
|
||||
provider={selectedProvider}
|
||||
@@ -1865,7 +1956,6 @@ export const ChatComposer = memo(
|
||||
|
||||
{/* Right side: send / stop button */}
|
||||
<div
|
||||
ref={composerFooterActionsRef}
|
||||
data-chat-composer-actions="right"
|
||||
data-chat-composer-primary-actions-compact={
|
||||
isComposerPrimaryActionsCompact ? "true" : "false"
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import { memo } from "react";
|
||||
import GitActionsControl from "../GitActionsControl";
|
||||
import { type DraftId } from "~/composerDraftStore";
|
||||
import { DiffIcon, TerminalSquareIcon } from "lucide-react";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
@@ -19,6 +20,7 @@ import { OpenInPicker } from "./OpenInPicker";
|
||||
interface ChatHeaderProps {
|
||||
activeThreadEnvironmentId: EnvironmentId;
|
||||
activeThreadId: ThreadId;
|
||||
draftId?: DraftId;
|
||||
activeThreadTitle: string;
|
||||
activeProjectName: string | undefined;
|
||||
isGitRepo: boolean;
|
||||
@@ -44,6 +46,7 @@ interface ChatHeaderProps {
|
||||
export const ChatHeader = memo(function ChatHeader({
|
||||
activeThreadEnvironmentId,
|
||||
activeThreadId,
|
||||
draftId,
|
||||
activeThreadTitle,
|
||||
activeProjectName,
|
||||
isGitRepo,
|
||||
@@ -109,6 +112,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
<GitActionsControl
|
||||
gitCwd={gitCwd}
|
||||
activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
/>
|
||||
)}
|
||||
<Tooltip>
|
||||
@@ -118,7 +122,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
className="shrink-0"
|
||||
pressed={terminalOpen}
|
||||
onPressedChange={onToggleTerminal}
|
||||
aria-label="Toggle terminal drawer"
|
||||
aria-label="Toggle terminal split"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!terminalAvailable}
|
||||
@@ -131,8 +135,8 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
{!terminalAvailable
|
||||
? "Terminal is unavailable until this thread has an active project."
|
||||
: terminalToggleShortcutLabel
|
||||
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
|
||||
: "Toggle terminal drawer"}
|
||||
? `Toggle terminal split (${terminalToggleShortcutLabel})`
|
||||
: "Toggle terminal split"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts";
|
||||
import { memo, useLayoutEffect, useRef } from "react";
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import {
|
||||
type ProjectEntry,
|
||||
type ProviderKind,
|
||||
type ServerProviderSkill,
|
||||
type ServerProviderSlashCommand,
|
||||
} from "@t3tools/contracts";
|
||||
import { BotIcon } from "lucide-react";
|
||||
import { memo, useLayoutEffect, useMemo, useRef } from "react";
|
||||
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import { formatProviderSkillInstallSource } from "~/providerSkillPresentation";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Command, CommandItem, CommandList } from "../ui/command";
|
||||
import {
|
||||
Command,
|
||||
CommandGroup,
|
||||
CommandGroupLabel,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "../ui/command";
|
||||
import { VscodeEntryIcon } from "./VscodeEntryIcon";
|
||||
|
||||
export type ComposerCommandItem =
|
||||
@@ -23,6 +37,14 @@ export type ComposerCommandItem =
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "provider-slash-command";
|
||||
provider: ProviderKind;
|
||||
command: ServerProviderSlashCommand;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "model";
|
||||
@@ -30,18 +52,83 @@ export type ComposerCommandItem =
|
||||
model: string;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "skill";
|
||||
provider: ProviderKind;
|
||||
skill: ServerProviderSkill;
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
type ComposerCommandGroup = {
|
||||
id: string;
|
||||
label: string | null;
|
||||
items: ComposerCommandItem[];
|
||||
};
|
||||
|
||||
function SkillGlyph(props: { className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.85"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={props.className}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z" />
|
||||
<path d="m3.3 7 8.7 5 8.7-5" />
|
||||
<path d="M12 22V12" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function groupCommandItems(
|
||||
items: ComposerCommandItem[],
|
||||
triggerKind: ComposerTriggerKind | null,
|
||||
groupSlashCommandSections: boolean,
|
||||
): ComposerCommandGroup[] {
|
||||
if (triggerKind === "skill") {
|
||||
return items.length > 0 ? [{ id: "skills", label: "Skills", items }] : [];
|
||||
}
|
||||
if (triggerKind !== "slash-command" || !groupSlashCommandSections) {
|
||||
return [{ id: "default", label: null, items }];
|
||||
}
|
||||
|
||||
const builtInItems = items.filter((item) => item.type === "slash-command");
|
||||
const providerItems = items.filter((item) => item.type === "provider-slash-command");
|
||||
|
||||
const groups: ComposerCommandGroup[] = [];
|
||||
if (builtInItems.length > 0) {
|
||||
groups.push({ id: "built-in", label: "Built-in", items: builtInItems });
|
||||
}
|
||||
if (providerItems.length > 0) {
|
||||
groups.push({ id: "provider", label: "Provider", items: providerItems });
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
items: ComposerCommandItem[];
|
||||
resolvedTheme: "light" | "dark";
|
||||
isLoading: boolean;
|
||||
triggerKind: ComposerTriggerKind | null;
|
||||
groupSlashCommandSections?: boolean;
|
||||
emptyStateText?: string;
|
||||
activeItemId: string | null;
|
||||
onHighlightedItemChange: (itemId: string | null) => void;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
}) {
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
groupCommandItems(props.items, props.triggerKind, props.groupSlashCommandSections ?? true),
|
||||
[props.groupSlashCommandSections, props.items, props.triggerKind],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!props.activeItemId || !listRef.current) return;
|
||||
@@ -65,27 +152,56 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
ref={listRef}
|
||||
className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
|
||||
>
|
||||
<CommandList className="max-h-64">
|
||||
{props.items.map((item) => (
|
||||
<ComposerCommandMenuItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
resolvedTheme={props.resolvedTheme}
|
||||
isActive={props.activeItemId === item.id}
|
||||
onHighlight={props.onHighlightedItemChange}
|
||||
onSelect={props.onSelect}
|
||||
/>
|
||||
<CommandList className="max-h-72">
|
||||
{groups.map((group, groupIndex) => (
|
||||
<div key={group.id}>
|
||||
{groupIndex > 0 ? <CommandSeparator className="my-0.5" /> : null}
|
||||
<CommandGroup>
|
||||
{group.label ? (
|
||||
<CommandGroupLabel className="px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
|
||||
{group.label}
|
||||
</CommandGroupLabel>
|
||||
) : null}
|
||||
{group.items.map((item) => (
|
||||
<ComposerCommandMenuItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
resolvedTheme={props.resolvedTheme}
|
||||
isActive={props.activeItemId === item.id}
|
||||
onHighlight={props.onHighlightedItemChange}
|
||||
onSelect={props.onSelect}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</div>
|
||||
))}
|
||||
</CommandList>
|
||||
{props.items.length === 0 && (
|
||||
<p className="px-3 py-2 text-muted-foreground/70 text-xs">
|
||||
{props.isLoading
|
||||
? "Searching workspace files..."
|
||||
: props.triggerKind === "path"
|
||||
? "No matching files or folders."
|
||||
: "No matching command."}
|
||||
</p>
|
||||
)}
|
||||
{props.items.length === 0 ? (
|
||||
<div className="px-3 py-2">
|
||||
{props.triggerKind === "skill" ? (
|
||||
<CommandGroup>
|
||||
<CommandGroupLabel className="px-0 pt-0 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
|
||||
Skills
|
||||
</CommandGroupLabel>
|
||||
<p className="text-muted-foreground/70 text-xs">
|
||||
{props.isLoading
|
||||
? "Searching workspace skills..."
|
||||
: (props.emptyStateText ??
|
||||
"No skills found. Try / to browse provider commands.")}
|
||||
</p>
|
||||
</CommandGroup>
|
||||
) : (
|
||||
<p className="text-muted-foreground/70 text-xs">
|
||||
{props.isLoading
|
||||
? "Searching workspace files..."
|
||||
: (props.emptyStateText ??
|
||||
(props.triggerKind === "path"
|
||||
? "No matching files or folders."
|
||||
: "No matching command."))}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Command>
|
||||
);
|
||||
@@ -98,6 +214,9 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
onHighlight: (itemId: string | null) => void;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
}) {
|
||||
const skillSourceLabel =
|
||||
props.item.type === "skill" ? formatProviderSkillInstallSource(props.item.skill) : null;
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
value={props.item.id}
|
||||
@@ -124,17 +243,32 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
/>
|
||||
) : null}
|
||||
{props.item.type === "slash-command" ? (
|
||||
<BotIcon className="size-4 text-muted-foreground/80" />
|
||||
<BotIcon className="size-4 shrink-0 text-muted-foreground/80" />
|
||||
) : null}
|
||||
{props.item.type === "provider-slash-command" ? (
|
||||
<span className="inline-flex size-4 shrink-0 items-center justify-center text-muted-foreground/80">
|
||||
<SkillGlyph className="size-3.5" />
|
||||
</span>
|
||||
) : null}
|
||||
{props.item.type === "skill" ? (
|
||||
<span className="inline-flex size-4 shrink-0 items-center justify-center text-muted-foreground/80">
|
||||
<SkillGlyph className="size-3.5" />
|
||||
</span>
|
||||
) : null}
|
||||
{props.item.type === "model" ? (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
model
|
||||
</Badge>
|
||||
) : null}
|
||||
<span className="flex min-w-0 items-center gap-1.5 truncate">
|
||||
<span className="truncate">{props.item.label}</span>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<span className="shrink-0">{props.item.label}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-muted-foreground/70 text-xs">
|
||||
{props.item.description}
|
||||
</span>
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground/70 text-xs">{props.item.description}</span>
|
||||
{skillSourceLabel ? (
|
||||
<span className="shrink-0 pl-2 text-muted-foreground/70 text-xs">{skillSourceLabel}</span>
|
||||
) : null}
|
||||
</CommandItem>
|
||||
);
|
||||
});
|
||||
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user