Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8580032a5f | ||
|
|
ebe8afb1df | ||
|
|
bf76535fe4 | ||
|
|
5c66110e26 | ||
|
|
da3c2030f7 | ||
|
|
0506508e9b | ||
|
|
b859a575d1 | ||
|
|
e63403fe92 | ||
|
|
c0e161af06 | ||
|
|
d0b9f8d40d | ||
|
|
d8b12ae801 | ||
|
|
31caa5652b | ||
|
|
e350c0a07b | ||
|
|
38e0bb07bb | ||
|
|
765e1b5fc0 | ||
|
|
03e20c875c | ||
|
|
2318e00270 | ||
|
|
4cfec8c128 | ||
|
|
1bd2fa25e2 | ||
|
|
5ca32661b7 | ||
|
|
8b33799523 | ||
|
|
24f9c2a08e | ||
|
|
31ca9e5531 | ||
|
|
73bf127d71 | ||
|
|
43e2aeab38 | ||
|
|
b655a9f183 | ||
|
|
4e3f2f04d5 | ||
|
|
1047dac0c5 | ||
|
|
143b9c9280 | ||
|
|
cf58cadd02 | ||
|
|
6a17629670 | ||
|
|
7b8d12618b | ||
|
|
bcd640bf4d | ||
|
|
b49a2e677c | ||
|
|
ed81c156da | ||
|
|
7dc75127c2 | ||
|
|
e057e2e985 |
No files matched your search
@@ -20,7 +20,7 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 12;
|
||||
const LAUNCHER_VERSION = 14;
|
||||
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = NodePath.join(
|
||||
repoRoot,
|
||||
@@ -220,11 +220,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
|
||||
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
|
||||
{
|
||||
@@ -277,11 +278,25 @@ function readJson(path) {
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
|
||||
const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
|
||||
const launcherExecutableName = `${displayName} Launcher`;
|
||||
return {
|
||||
launcherExecutableName,
|
||||
launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
|
||||
runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
|
||||
};
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
|
||||
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
|
||||
const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
|
||||
const launcherBinaryPath = isDevelopment
|
||||
? developmentPaths.launcherBinaryPath
|
||||
: runtimeElectronBinaryPath;
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
|
||||
|
||||
@@ -298,7 +313,8 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
NodeFS.existsSync(targetBinaryPath) &&
|
||||
NodeFS.existsSync(launcherBinaryPath) &&
|
||||
(!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
@@ -306,10 +322,10 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
return launcherBinaryPath;
|
||||
}
|
||||
|
||||
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
@@ -321,15 +337,24 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
recursive: true,
|
||||
verbatimSymlinks: true,
|
||||
});
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchMainBundleInfoPlist(
|
||||
targetAppBundlePath,
|
||||
iconPath,
|
||||
isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
|
||||
);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
// Keep Electron's native executable inside the branded bundle. Launching the
|
||||
// node_modules copy makes macOS associate the process (and Dock label) with
|
||||
// Electron.app even though this bundle's Info.plist has the T3 Code name.
|
||||
// Its conventional executable name also keeps Electron's default-app runtime
|
||||
// in development mode instead of making app.isPackaged report true.
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
}
|
||||
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
|
||||
return targetBinaryPath;
|
||||
return launcherBinaryPath;
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
|
||||
import {
|
||||
makeDevelopmentLauncherScript,
|
||||
resolveElectronBinaryPath,
|
||||
resolveMacLauncherPaths,
|
||||
} from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
@@ -45,4 +49,33 @@ describe("electron development launcher", () => {
|
||||
);
|
||||
assert.deepEqual(calls, ["ensure", "require:electron"]);
|
||||
});
|
||||
|
||||
it("keeps the native Electron executable name inside the branded macOS bundle", () => {
|
||||
const paths = resolveMacLauncherPaths(
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
|
||||
"T3 Code (Dev)",
|
||||
);
|
||||
|
||||
assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
|
||||
assert.equal(
|
||||
paths.launcherBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
|
||||
);
|
||||
assert.equal(
|
||||
paths.runtimeElectronBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
|
||||
);
|
||||
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: paths.runtimeElectronBinaryPath,
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {},
|
||||
});
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
|
||||
);
|
||||
assert.notInclude(script, "node_modules/electron");
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,12 @@ const TestLayer = ElectronMenu.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
const makeWindow = (zoomFactor = 1): Electron.BrowserWindow =>
|
||||
({
|
||||
id: 7,
|
||||
webContents: { getZoomFactor: () => zoomFactor },
|
||||
}) as unknown as Electron.BrowserWindow;
|
||||
|
||||
describe("ElectronMenu", () => {
|
||||
beforeEach(() => {
|
||||
buildFromTemplateMock.mockReset();
|
||||
@@ -70,7 +76,7 @@ describe("ElectronMenu", () => {
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const selectedItemId = yield* electronMenu.showContextMenu({
|
||||
window: {} as Electron.BrowserWindow,
|
||||
window: makeWindow(),
|
||||
items: [{ id: "copy", label: "Copy" }],
|
||||
position: Option.none(),
|
||||
});
|
||||
@@ -81,20 +87,24 @@ describe("ElectronMenu", () => {
|
||||
|
||||
it.effect("resolves with none when the menu closes without a click", () =>
|
||||
Effect.gen(function* () {
|
||||
let popupOptions: Electron.PopupOptions | undefined;
|
||||
buildFromTemplateMock.mockImplementation(() => ({
|
||||
popup: (options: Electron.PopupOptions) => {
|
||||
popupOptions = options;
|
||||
options.callback?.();
|
||||
},
|
||||
}));
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const selectedItemId = yield* electronMenu.showContextMenu({
|
||||
window: {} as Electron.BrowserWindow,
|
||||
window: makeWindow(2),
|
||||
items: [{ id: "copy", label: "Copy" }],
|
||||
position: Option.some({ x: 10.8, y: 20.2 }),
|
||||
});
|
||||
|
||||
assert.isTrue(Option.isNone(selectedItemId));
|
||||
assert.equal(popupOptions?.x, 21);
|
||||
assert.equal(popupOptions?.y, 40);
|
||||
assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], {
|
||||
label: "Copy",
|
||||
enabled: true,
|
||||
|
||||
@@ -94,13 +94,20 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
|
||||
return normalizedItems;
|
||||
}
|
||||
|
||||
// Renderer positions arrive in CSS pixels; popup() expects window points, so
|
||||
// page zoom must be factored in or menus drift proportionally to their
|
||||
// distance from the window origin.
|
||||
const normalizePosition = (
|
||||
position: Option.Option<ElectronMenuPosition>,
|
||||
zoomFactor: number,
|
||||
): Option.Option<ElectronMenuPosition> =>
|
||||
Option.filter(
|
||||
position,
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
({ x, y }) =>
|
||||
Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
|
||||
).pipe(
|
||||
Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
@@ -214,7 +221,10 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
try {
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupPosition = normalizePosition(
|
||||
input.position,
|
||||
input.window.webContents.getZoomFactor(),
|
||||
);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
formatNodePtyProbeFailureReason,
|
||||
formatWslShellTransportFailureReason,
|
||||
parseNodePath,
|
||||
parseNodeVersion,
|
||||
parseResolvedPath,
|
||||
parseToolchainReport,
|
||||
probeWslDistros,
|
||||
@@ -173,6 +174,29 @@ describe("parseNodePath", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseNodeVersion", () => {
|
||||
it("extracts the node version from a nodeVersion: line", () => {
|
||||
expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
|
||||
});
|
||||
|
||||
it("returns null when the version value is empty", () => {
|
||||
expect(parseNodeVersion("nodeVersion:")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when there is no nodeVersion line at all", () => {
|
||||
expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores surrounding noise and trims whitespace", () => {
|
||||
const stdout = [
|
||||
"some preamble noise",
|
||||
" nodeVersion:22.16.0 ",
|
||||
"nodePath:/usr/bin/node",
|
||||
].join("\n");
|
||||
expect(parseNodeVersion(stdout)).toBe("22.16.0");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseResolvedPath", () => {
|
||||
it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
|
||||
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
|
||||
|
||||
@@ -32,7 +32,11 @@ export interface EnsureWslNodePtyOptions {
|
||||
}
|
||||
|
||||
export type EnsureWslNodePtyResult =
|
||||
| { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly nodePath: string;
|
||||
readonly resolvedPath: string;
|
||||
}
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly reason: string;
|
||||
@@ -222,6 +226,7 @@ export const formatNodePtyProbeFailureReason = (exitCode: number): string | null
|
||||
const NODE_PTY_PROBE_SCRIPT = (
|
||||
linuxServerDir: string,
|
||||
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
|
||||
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
|
||||
printf 'resolvedPath:%s\\n' "$PATH"
|
||||
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
|
||||
// The server bundle externalizes its deps to node_modules, and the WSL Node
|
||||
@@ -318,6 +323,16 @@ export const parseNodePath = (stdout: string): string | null => {
|
||||
return path ?? null;
|
||||
};
|
||||
|
||||
export const parseNodeVersion = (stdout: string): string | null => {
|
||||
const version = stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.startsWith("nodeVersion:"))
|
||||
.map((line) => line.slice("nodeVersion:".length).trim())
|
||||
.find((value) => value.length > 0);
|
||||
return version ?? null;
|
||||
};
|
||||
|
||||
// Captures the login-shell PATH after the shared resolver has loaded version
|
||||
// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
|
||||
// paths containing spaces or apostrophes can be forwarded as one env argv.
|
||||
@@ -404,7 +419,11 @@ const ensureNodePtyImpl = (
|
||||
|
||||
const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
|
||||
if (transportFailureReason !== null) {
|
||||
return { ok: false, reason: transportFailureReason, fatal: false } as const;
|
||||
return {
|
||||
ok: false,
|
||||
reason: transportFailureReason,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
// No node at all, even after the shared resolver repaired PATH. Surface
|
||||
@@ -457,12 +476,31 @@ const ensureNodePtyImpl = (
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
|
||||
if (probe.exitCode === 0) {
|
||||
const rawVersion = parseNodeVersion(probe.stdout);
|
||||
if (
|
||||
rawVersion !== null &&
|
||||
options.nodeEngineRange &&
|
||||
!satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
|
||||
) {
|
||||
const range = options.nodeEngineRange.trim();
|
||||
return {
|
||||
ok: false,
|
||||
reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
return { ok: true, nodePath, resolvedPath } as const;
|
||||
}
|
||||
|
||||
if (options.allowBuild !== true) {
|
||||
const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
|
||||
if (packagedProbeFailure !== null) {
|
||||
return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
|
||||
return {
|
||||
ok: false,
|
||||
reason: packagedProbeFailure,
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path fill="#F5F5F5" d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861" />
|
||||
<path fill="#F5F5F5" d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 948 B |
@@ -33,6 +33,9 @@ const mobileEndorsementRows = [
|
||||
<span class="hero-float-mark hf-cursor" title="Cursor">
|
||||
<img src="/harnesses/cursor_light.svg" alt="" />
|
||||
</span>
|
||||
<span class="hero-float-mark hf-grok" title="Grok">
|
||||
<img src="/harnesses/grok-dark.svg" alt="" />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="container hero-inner">
|
||||
@@ -41,7 +44,7 @@ const mobileEndorsementRows = [
|
||||
</h1>
|
||||
|
||||
<p class="hero-sub">
|
||||
Orchestrate Claude Code, Codex, OpenCode and Cursor from one surface.
|
||||
Orchestrate Claude Code, Codex, OpenCode, Cursor, and Grok from one surface.
|
||||
Bring your own subscription. Fork the whole thing.
|
||||
</p>
|
||||
|
||||
@@ -173,7 +176,7 @@ const mobileEndorsementRows = [
|
||||
<h2>Bring your own sub</h2>
|
||||
<p>
|
||||
T3 Code doesn't resell tokens. Plug in Claude Code, Codex, OpenCode,
|
||||
or Cursor with the credentials you already have — we orchestrate
|
||||
Cursor, or Grok with the credentials you already have — we orchestrate
|
||||
them, you keep your plan.
|
||||
</p>
|
||||
</div>
|
||||
@@ -207,6 +210,13 @@ const mobileEndorsementRows = [
|
||||
<div class="harness-tag">cursor-agent</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="harness">
|
||||
<div class="harness-mark"><img src="/harnesses/grok-dark.svg" alt="" /></div>
|
||||
<div class="harness-meta">
|
||||
<div class="harness-name">Grok CLI</div>
|
||||
<div class="harness-tag">grok login</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="harness-footer">
|
||||
@@ -615,8 +625,9 @@ const mobileEndorsementRows = [
|
||||
|
||||
.hero-float-mark.hf-claude { background: radial-gradient(circle at 30% 25%, rgba(217, 119, 87, 0.22), rgba(20, 20, 24, 0.92) 65%); top: 8%; left: 7%; animation-delay: 0s; transform: rotate(-8deg); }
|
||||
.hero-float-mark.hf-codex { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 6%; right: 7%; animation-delay: -2.5s; transform: rotate(6deg); }
|
||||
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 32%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
|
||||
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 30%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
|
||||
.hero-float-mark.hf-cursor { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 30%; right: 5%; animation-delay: -7s; transform: rotate(-5deg); }
|
||||
.hero-float-mark.hf-grok { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 52%; left: 6%; animation-delay: -1.2s; transform: rotate(3deg); }
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.hero-float-mark { width: 76px; height: 76px; border-radius: 20px; }
|
||||
@@ -625,6 +636,7 @@ const mobileEndorsementRows = [
|
||||
.hero-float-mark.hf-codex { top: 2%; right: 3%; }
|
||||
.hero-float-mark.hf-opencode { top: 26%; left: 2%; }
|
||||
.hero-float-mark.hf-cursor { top: 24%; right: 2%; }
|
||||
.hero-float-mark.hf-grok { top: 48%; left: 2%; transform: rotate(3deg); }
|
||||
}
|
||||
|
||||
@media (max-width: 820px) {
|
||||
@@ -659,17 +671,18 @@ const mobileEndorsementRows = [
|
||||
height: 44px;
|
||||
}
|
||||
|
||||
/* Two above the title, two flanking the call-to-action area. */
|
||||
/* Three stacked on the left, two on the right — keeps the center CTA clear. */
|
||||
.hero-float-mark.hf-claude {
|
||||
top: 44px;
|
||||
left: 10px;
|
||||
transform: rotate(-10deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-codex {
|
||||
top: 44px;
|
||||
right: 10px;
|
||||
transform: rotate(8deg);
|
||||
.hero-float-mark.hf-grok {
|
||||
top: 240px;
|
||||
left: 4px;
|
||||
right: auto;
|
||||
transform: rotate(-4deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode {
|
||||
@@ -679,6 +692,12 @@ const mobileEndorsementRows = [
|
||||
transform: rotate(-6deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-codex {
|
||||
top: 44px;
|
||||
right: 10px;
|
||||
transform: rotate(8deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-cursor {
|
||||
top: 474px;
|
||||
right: 4px;
|
||||
@@ -688,6 +707,14 @@ const mobileEndorsementRows = [
|
||||
}
|
||||
|
||||
@media (max-width: 340px) {
|
||||
.hero-float-mark.hf-grok {
|
||||
top: 220px;
|
||||
left: 0;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode,
|
||||
.hero-float-mark.hf-cursor {
|
||||
top: 580px;
|
||||
@@ -704,6 +731,7 @@ const mobileEndorsementRows = [
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-grok img,
|
||||
.hero-float-mark.hf-opencode img,
|
||||
.hero-float-mark.hf-cursor img {
|
||||
width: 30px;
|
||||
@@ -750,7 +778,7 @@ const mobileEndorsementRows = [
|
||||
|
||||
.harness-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-template-columns: repeat(5, 1fr);
|
||||
gap: 0;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
@@ -1205,6 +1233,10 @@ const mobileEndorsementRows = [
|
||||
.harness-grid { grid-template-columns: 1fr 1fr; }
|
||||
.harness { border-right: 0; border-bottom: 1px solid var(--border); }
|
||||
.harness:nth-child(odd) { border-right: 1px solid var(--border); }
|
||||
.harness:nth-child(5):last-child {
|
||||
grid-column: 1 / -1;
|
||||
border-right: 0;
|
||||
}
|
||||
.git-inner { grid-template-columns: 1fr; gap: 40px; }
|
||||
.open-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "re
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
import { renderCompactBrandTitle } from "./components/CompactBrandTitle";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
@@ -377,7 +378,8 @@ export const RootStack = createNativeStackNavigator({
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerBackVisible: false,
|
||||
title: "Threads",
|
||||
headerTitle: renderCompactBrandTitle,
|
||||
title: "T3 Code",
|
||||
},
|
||||
}),
|
||||
Thread: createNativeStackScreen({
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { T3Wordmark } from "./T3Wordmark";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
/**
|
||||
* Compact brand lockup sized for native navigation bars.
|
||||
*/
|
||||
export function CompactBrandTitle() {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
|
||||
return (
|
||||
<View
|
||||
aria-level={1}
|
||||
accessibilityLabel="T3 Code"
|
||||
accessible
|
||||
role="heading"
|
||||
style={{ alignItems: "center", flexDirection: "row", gap: 6 }}
|
||||
>
|
||||
<T3Wordmark color={iconColor} height={11} />
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Medium",
|
||||
fontSize: 14,
|
||||
letterSpacing: -0.35,
|
||||
}}
|
||||
>
|
||||
Code
|
||||
</Text>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 2,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Bold",
|
||||
fontSize: 9,
|
||||
letterSpacing: 0.9,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
Alpha
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function renderCompactBrandTitle() {
|
||||
return <CompactBrandTitle />;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { renderCompactBrandTitle } from "../../components/CompactBrandTitle";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -86,7 +87,9 @@ export function HomeRouteScreen() {
|
||||
>
|
||||
<>
|
||||
{/* Restore the compact title in case the split branch blanked it. */}
|
||||
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
|
||||
<NativeStackScreenOptions
|
||||
options={{ title: "T3 Code", headerTitle: renderCompactBrandTitle }}
|
||||
/>
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
searchQuery={searchQuery}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import type { ReactNode } from "react";
|
||||
import { Platform, useColorScheme } from "react-native";
|
||||
|
||||
import { renderCompactBrandTitle } from "../../components/CompactBrandTitle";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
|
||||
|
||||
const SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
@@ -34,10 +35,11 @@ const SIDEBAR_SCREEN_OPTIONS: SidebarScreenOptions = {
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerTitle: renderCompactBrandTitle,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: true,
|
||||
scrollEdgeEffects: SCROLL_EDGE_EFFECTS,
|
||||
title: "Threads",
|
||||
title: "T3 Code",
|
||||
unstable_navigationItemStyle: "editor",
|
||||
};
|
||||
|
||||
|
||||
@@ -32,6 +32,63 @@ describe("imageMime", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects payload with characters outside the base64 alphabet", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull();
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects structurally malformed base64", () => {
|
||||
// '=' before the trailing padding position
|
||||
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
|
||||
// more than two padding characters
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull();
|
||||
// length not a multiple of 4
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts base64 with one or two trailing padding characters", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbA==",
|
||||
});
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8h",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects empty and whitespace-only payloads", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
|
||||
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();
|
||||
});
|
||||
|
||||
it("parses a case-insensitive scheme and mime type", () => {
|
||||
expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses a multi-megabyte payload from a deep call stack", () => {
|
||||
// Regression: matching the payload with a regex borrowed the JS call
|
||||
// stack, so a ~10 MB image parsed inside fiber execution threw
|
||||
// "RangeError: Maximum call stack size exceeded".
|
||||
const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`;
|
||||
const atDepth = (depth: number): ReturnType<typeof parseBase64DataUrl> =>
|
||||
depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1);
|
||||
const findMaxDepth = (depth: number): number => {
|
||||
try {
|
||||
return findMaxDepth(depth + 1);
|
||||
} catch {
|
||||
return depth;
|
||||
}
|
||||
};
|
||||
const result = atDepth(Math.floor(findMaxDepth(0) * 0.85));
|
||||
expect(result?.mimeType).toBe("image/png");
|
||||
expect(result?.base64.length).toBe(14_000_000);
|
||||
});
|
||||
|
||||
it("does not read inherited keys from mime extension map", () => {
|
||||
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
|
||||
});
|
||||
|
||||
@@ -29,17 +29,43 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
||||
".webp",
|
||||
]);
|
||||
|
||||
// Whether `code` is a character the base64 payload may contain, aside from
|
||||
// the whitespace handled separately below.
|
||||
function isBase64Char(code: number): boolean {
|
||||
return (
|
||||
(code >= 0x61 && code <= 0x7a) || // a-z
|
||||
(code >= 0x41 && code <= 0x5a) || // A-Z
|
||||
(code >= 0x30 && code <= 0x39) || // 0-9
|
||||
code === 0x2b || // +
|
||||
code === 0x2f || // /
|
||||
code === 0x3d // =
|
||||
);
|
||||
}
|
||||
|
||||
function isBase64Whitespace(code: number): boolean {
|
||||
return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space
|
||||
}
|
||||
|
||||
// Data URLs carry the full image payload, so this parser must never run a
|
||||
// regex across the payload: V8's regex engine borrows the JS call stack, and
|
||||
// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
|
||||
// execution) throws "Maximum call stack size exceeded".
|
||||
export function parseBase64DataUrl(
|
||||
dataUrl: string,
|
||||
): { readonly mimeType: string; readonly base64: string } | null {
|
||||
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
|
||||
if (!match) return null;
|
||||
const trimmed = dataUrl.trim();
|
||||
if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
|
||||
|
||||
const commaIndex = trimmed.indexOf(",");
|
||||
if (commaIndex === -1) return null;
|
||||
const header = trimmed.slice(5, commaIndex);
|
||||
if (header.length === 0) return null;
|
||||
|
||||
const headerParts: Array<string> = [];
|
||||
for (const part of (match[1] ?? "").split(";")) {
|
||||
const trimmed = part.trim();
|
||||
if (trimmed.length > 0) {
|
||||
headerParts.push(trimmed);
|
||||
for (const part of header.split(";")) {
|
||||
const partTrimmed = part.trim();
|
||||
if (partTrimmed.length > 0) {
|
||||
headerParts.push(partTrimmed);
|
||||
}
|
||||
}
|
||||
if (headerParts.length < 2) {
|
||||
@@ -51,8 +77,37 @@ export function parseBase64DataUrl(
|
||||
}
|
||||
|
||||
const mimeType = headerParts[0]?.toLowerCase();
|
||||
const base64 = match[2]?.replace(/\s+/g, "");
|
||||
if (!mimeType || !base64) return null;
|
||||
if (!mimeType) return null;
|
||||
|
||||
const payload = trimmed.slice(commaIndex + 1);
|
||||
const runs: Array<string> = [];
|
||||
let runStart = -1;
|
||||
for (let index = 0; index < payload.length; index += 1) {
|
||||
const code = payload.charCodeAt(index);
|
||||
if (isBase64Char(code)) {
|
||||
if (runStart === -1) runStart = index;
|
||||
continue;
|
||||
}
|
||||
if (!isBase64Whitespace(code)) return null;
|
||||
if (runStart !== -1) {
|
||||
runs.push(payload.slice(runStart, index));
|
||||
runStart = -1;
|
||||
}
|
||||
}
|
||||
if (runStart !== -1) {
|
||||
runs.push(payload.slice(runStart));
|
||||
}
|
||||
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
|
||||
if (base64.length === 0 || base64.length % 4 !== 0) return null;
|
||||
const firstPad = base64.indexOf("=");
|
||||
if (firstPad !== -1) {
|
||||
// '=' is only valid as one or two trailing padding characters; Node's
|
||||
// decoder would otherwise silently truncate at the first '='.
|
||||
if (base64.length - firstPad > 2) return null;
|
||||
for (let index = firstPad; index < base64.length; index += 1) {
|
||||
if (base64.charCodeAt(index) !== 0x3d) return null;
|
||||
}
|
||||
}
|
||||
|
||||
return { mimeType, base64 };
|
||||
}
|
||||
|
||||
@@ -411,6 +411,28 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("replacing with a rule that already exists elsewhere does not duplicate it", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+alt+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings.Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+alt+r",
|
||||
command: "script.run-tests.run",
|
||||
replace: { key: "mod+r", command: "script.run-tests.run" },
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [{ key: "mod+alt+r", command: "script.run-tests.run" }]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("removes only the targeted custom keybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
|
||||
|
||||
@@ -644,7 +644,9 @@ const make = Effect.gen(function* () {
|
||||
const nextConfig = [
|
||||
...customConfig.filter((entry) => {
|
||||
if (replaceTarget) {
|
||||
return !isSameKeybindingRule(entry, replaceTarget);
|
||||
return (
|
||||
!isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)
|
||||
);
|
||||
}
|
||||
return !isSameKeybindingRule(entry, rule);
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
CommandId,
|
||||
type ClientOrchestrationCommand,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { canonicalizeClientCommandTimestamps } from "./Normalizer.ts";
|
||||
|
||||
const clientCreatedAt = "2031-01-01T00:00:00.000Z";
|
||||
const serverReceivedAt = "2026-07-18T00:00:00.000Z";
|
||||
|
||||
describe("canonicalizeClientCommandTimestamps", () => {
|
||||
it("replaces a client command timestamp with the server receipt timestamp", () => {
|
||||
const command: ClientOrchestrationCommand = {
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("command-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Clock-safe project",
|
||||
workspaceRoot: "/tmp/clock-safe-project",
|
||||
createdAt: clientCreatedAt,
|
||||
};
|
||||
|
||||
expect(canonicalizeClientCommandTimestamps(command, serverReceivedAt)).toEqual({
|
||||
...command,
|
||||
createdAt: serverReceivedAt,
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces both timestamps when the first turn bootstraps a thread", () => {
|
||||
const command: ClientOrchestrationCommand = {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("command-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-1"),
|
||||
role: "user",
|
||||
text: "Start a thread",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
createThread: {
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Clock-safe thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: clientCreatedAt,
|
||||
},
|
||||
},
|
||||
createdAt: clientCreatedAt,
|
||||
};
|
||||
|
||||
const result = canonicalizeClientCommandTimestamps(command, serverReceivedAt);
|
||||
|
||||
expect(result.type).toBe("thread.turn.start");
|
||||
if (result.type !== "thread.turn.start") {
|
||||
throw new Error("Expected a thread.turn.start command");
|
||||
}
|
||||
expect(result.createdAt).toBe(serverReceivedAt);
|
||||
expect(result.bootstrap?.createThread?.createdAt).toBe(serverReceivedAt);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
type IsoDateTime,
|
||||
type OrchestrationCommand,
|
||||
OrchestrationDispatchCommandError,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
@@ -13,8 +15,38 @@ import { ServerConfig } from "../config.ts";
|
||||
import { parseBase64DataUrl } from "../imageMime.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
|
||||
export const canonicalizeClientCommandTimestamps = (
|
||||
command: ClientOrchestrationCommand,
|
||||
receivedAt: IsoDateTime,
|
||||
): ClientOrchestrationCommand => {
|
||||
const canonicalCommand =
|
||||
"createdAt" in command
|
||||
? {
|
||||
...command,
|
||||
createdAt: receivedAt,
|
||||
}
|
||||
: command;
|
||||
|
||||
if (canonicalCommand.type !== "thread.turn.start" || !canonicalCommand.bootstrap?.createThread) {
|
||||
return canonicalCommand;
|
||||
}
|
||||
|
||||
return {
|
||||
...canonicalCommand,
|
||||
bootstrap: {
|
||||
...canonicalCommand.bootstrap,
|
||||
createThread: {
|
||||
...canonicalCommand.bootstrap.createThread,
|
||||
createdAt: receivedAt,
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
Effect.gen(function* () {
|
||||
const receivedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
@@ -47,30 +79,33 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
),
|
||||
);
|
||||
|
||||
if (command.type === "project.create") {
|
||||
if (canonicalCommand.type === "project.create") {
|
||||
return {
|
||||
...command,
|
||||
...canonicalCommand,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
|
||||
command.workspaceRoot,
|
||||
command.createWorkspaceRootIfMissing,
|
||||
canonicalCommand.workspaceRoot,
|
||||
canonicalCommand.createWorkspaceRootIfMissing,
|
||||
),
|
||||
createWorkspaceRootIfMissing: command.createWorkspaceRootIfMissing === true,
|
||||
createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (command.type === "project.meta.update" && command.workspaceRoot !== undefined) {
|
||||
if (
|
||||
canonicalCommand.type === "project.meta.update" &&
|
||||
canonicalCommand.workspaceRoot !== undefined
|
||||
) {
|
||||
return {
|
||||
...command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
|
||||
...canonicalCommand,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (command.type !== "thread.turn.start") {
|
||||
return command as OrchestrationCommand;
|
||||
if (canonicalCommand.type !== "thread.turn.start") {
|
||||
return canonicalCommand as OrchestrationCommand;
|
||||
}
|
||||
|
||||
const normalizedAttachments = yield* Effect.forEach(
|
||||
command.message.attachments,
|
||||
canonicalCommand.message.attachments,
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
@@ -87,7 +122,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
});
|
||||
}
|
||||
|
||||
const attachmentId = createAttachmentId(command.threadId);
|
||||
const attachmentId = createAttachmentId(canonicalCommand.threadId);
|
||||
if (!attachmentId) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: "Failed to create a safe attachment id.",
|
||||
@@ -135,9 +170,9 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
);
|
||||
|
||||
return {
|
||||
...command,
|
||||
...canonicalCommand,
|
||||
message: {
|
||||
...command.message,
|
||||
...canonicalCommand.message,
|
||||
attachments: normalizedAttachments,
|
||||
},
|
||||
} satisfies OrchestrationCommand;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Struct from "effect/Struct";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -280,18 +282,30 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
Effect.flatMap((rows) =>
|
||||
// Skip rows that no longer decode (e.g. written by an older build)
|
||||
// instead of failing the whole list — one stale row must not disable
|
||||
// every consumer that enumerates sessions, such as the reaper.
|
||||
Effect.forEach(rows, (row) =>
|
||||
decodeRuntimeRow(row).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
PersistenceDecodeError.fromSchemaError(
|
||||
"ProviderSessionRuntimeRepository.list:decodeRows",
|
||||
cause,
|
||||
{ threadId: row.threadId },
|
||||
),
|
||||
Effect.map(Option.some),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("provider.session.runtime.row-skipped", {
|
||||
threadId: row.threadId,
|
||||
error: PersistenceDecodeError.fromSchemaError(
|
||||
"ProviderSessionRuntimeRepository.list:decodeRows",
|
||||
cause,
|
||||
{ threadId: row.threadId },
|
||||
).message,
|
||||
}).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((decoded) =>
|
||||
Arr.filterMap(decoded, (row) =>
|
||||
Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
|
||||
|
||||
@@ -182,7 +182,7 @@ describe("persistence error correlation", () => {
|
||||
}).pipe(Effect.provide(authPairingLinkLayer)),
|
||||
);
|
||||
|
||||
it.effect("correlates provider runtime SQL and per-row decode failures by thread", () =>
|
||||
it.effect("skips undecodable provider runtime rows and correlates SQL failures by thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
@@ -215,16 +215,24 @@ describe("persistence error correlation", () => {
|
||||
)
|
||||
`;
|
||||
|
||||
const decodeError = yield* Effect.flip(runtimes.list());
|
||||
assert.instanceOf(decodeError, PersistenceErrors.PersistenceDecodeError);
|
||||
assert.deepStrictEqual(decodeError.correlation, { threadId });
|
||||
assert.equal(
|
||||
decodeError.message,
|
||||
`Decode error in ProviderSessionRuntimeRepository.list:decodeRows: ${decodeError.issue}`,
|
||||
const validThreadId = ThreadId.make("thread-valid");
|
||||
yield* runtimes.upsert({
|
||||
threadId: validThreadId,
|
||||
providerName: "codex",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt,
|
||||
resumeCursor: null,
|
||||
runtimePayload: null,
|
||||
});
|
||||
|
||||
const listed = yield* runtimes.list();
|
||||
assert.deepStrictEqual(
|
||||
listed.map((runtime) => runtime.threadId),
|
||||
[validThreadId],
|
||||
);
|
||||
assert.notInclude(decodeError.issue, runtimePayload);
|
||||
assert.notInclude(decodeError.message, runtimePayload);
|
||||
assert.notInclude(decodeError.message, lastSeenAt);
|
||||
|
||||
yield* sql`DROP TABLE provider_session_runtime`;
|
||||
const sqlFailure = yield* Effect.flip(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ProviderInteractionMode } from "@t3tools/contracts";
|
||||
|
||||
const T3_CODE_BROWSER_TOOL_INSTRUCTIONS = `
|
||||
|
||||
## T3 Code collaborative browser
|
||||
@@ -145,3 +147,26 @@ The \`request_user_input\` tool is unavailable in Default mode. If you call it w
|
||||
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
|
||||
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
|
||||
</collaboration_mode>`;
|
||||
|
||||
export interface CodexRuntimeInfo {
|
||||
readonly model: string;
|
||||
readonly reasoningEffort: string;
|
||||
}
|
||||
|
||||
// Values come from trusted config, but keep the block single-line regardless.
|
||||
function toSingleLine(value: string): string {
|
||||
return value.replaceAll(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
export function buildCodexDeveloperInstructions(
|
||||
interactionMode: ProviderInteractionMode,
|
||||
runtime: CodexRuntimeInfo,
|
||||
): string {
|
||||
const base =
|
||||
interactionMode === "plan"
|
||||
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
|
||||
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS;
|
||||
return `${base}
|
||||
|
||||
<runtime_info>In case you're asked: you are running in T3 Code through the Codex harness, as ${toSingleLine(runtime.model)} with ${toSingleLine(runtime.reasoningEffort)} reasoning effort. No need to mention this otherwise.</runtime_info>`;
|
||||
}
|
||||
@@ -119,6 +119,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
const { cwd } = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
@@ -154,11 +155,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
capacity: 1,
|
||||
timeToLive: CAPABILITIES_PROBE_TTL,
|
||||
lookup: () =>
|
||||
probeClaudeCapabilities(effectiveConfig, processEnv).pipe(
|
||||
probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
),
|
||||
});
|
||||
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig);
|
||||
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig, cwd);
|
||||
|
||||
const checkProvider = checkClaudeProviderStatus(
|
||||
effectiveConfig,
|
||||
|
||||
@@ -34,11 +34,20 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => {
|
||||
expect((yield* makeClaudeEnvironment({ homePath })).CLAUDE_CONFIG_DIR).toBe(resolved);
|
||||
expect(yield* makeClaudeContinuationGroupKey({ homePath })).toBe(`claude:home:${resolved}`);
|
||||
expect(yield* makeClaudeCapabilitiesCacheKey({ binaryPath: "claude", homePath })).toBe(
|
||||
`claude\0${resolved}`,
|
||||
`claude\0${resolved}\0`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("separates capability probes by cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = { binaryPath: "claude", homePath: "" };
|
||||
const first = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-a");
|
||||
const second = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-b");
|
||||
expect(first).not.toBe(second);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps continuation compatible across instances with the same Claude HOME", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
|
||||
@@ -44,8 +44,9 @@ export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationG
|
||||
export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesCacheKey")(
|
||||
function* (
|
||||
config: Pick<ClaudeSettings, "binaryPath" | "homePath">,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<string, never, Path.Path> {
|
||||
const resolvedHomePath = yield* resolveClaudeHomePath(config);
|
||||
return `${config.binaryPath}\0${resolvedHomePath}`;
|
||||
return `${config.binaryPath}\0${resolvedHomePath}\0${cwd ?? ""}`;
|
||||
},
|
||||
);
|
||||
@@ -114,6 +114,9 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {
|
||||
|
||||
const sessionsTarget = yield* fileSystem.readLink(path.join(shadowHome, "sessions"));
|
||||
const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml"));
|
||||
const mcpOauthLocksTarget = yield* fileSystem.readLink(
|
||||
path.join(shadowHome, "mcp-oauth-locks"),
|
||||
);
|
||||
const modelsCacheExists = yield* fileSystem.exists(
|
||||
path.join(shadowHome, "models_cache.json"),
|
||||
);
|
||||
@@ -124,12 +127,45 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {
|
||||
|
||||
expect(sessionsTarget).toBe(path.join(sharedHome, "sessions"));
|
||||
expect(configTarget).toBe(path.join(sharedHome, "config.toml"));
|
||||
expect(mcpOauthLocksTarget).toBe(path.join(sharedHome, "mcp-oauth-locks"));
|
||||
expect(modelsCacheExists).toBe(false);
|
||||
expect(authLinkResult._tag).toBe("Failure");
|
||||
expect(authContents).toContain("shadow");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("replaces Codex-created local MCP OAuth locks with the shared lock directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sharedHome = yield* makeTempDir("t3code-codex-shared-");
|
||||
const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");
|
||||
const shadowHome = path.join(shadowRoot, "shadow");
|
||||
const sharedLocks = path.join(sharedHome, "mcp-oauth-locks");
|
||||
const shadowLocks = path.join(shadowHome, "mcp-oauth-locks");
|
||||
|
||||
yield* writeTextFile(path.join(sharedLocks, "file-store.lock"), "");
|
||||
yield* writeTextFile(path.join(shadowLocks, "file-store.lock"), "");
|
||||
|
||||
const layout = yield* resolveCodexHomeLayout(
|
||||
decodeCodexSettings({
|
||||
homePath: sharedHome,
|
||||
shadowHomePath: shadowHome,
|
||||
}),
|
||||
);
|
||||
|
||||
yield* materializeCodexShadowHome(layout);
|
||||
|
||||
const locksTarget = yield* fileSystem.readLink(shadowLocks);
|
||||
const sharedLockExists = yield* fileSystem.exists(
|
||||
path.join(sharedLocks, "file-store.lock"),
|
||||
);
|
||||
|
||||
expect(locksTarget).toBe(sharedLocks);
|
||||
expect(sharedLockExists).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts Codex-created shadow-local runtime directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -26,10 +26,12 @@ const KNOWN_SHARED_DIRECTORIES = [
|
||||
"plugins",
|
||||
"cache",
|
||||
"logs",
|
||||
"mcp-oauth-locks",
|
||||
] as const;
|
||||
|
||||
const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]);
|
||||
const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp"]);
|
||||
const REPLACEABLE_SHARED_RUNTIME_DIRECTORIES = new Set(["mcp-oauth-locks"]);
|
||||
|
||||
function resolveHomePath(path: Path.Path, value: string | undefined): string {
|
||||
const expanded =
|
||||
@@ -225,16 +227,6 @@ const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (inpu
|
||||
linkPath: link,
|
||||
});
|
||||
|
||||
if (state._tag === "NotSymlink") {
|
||||
return yield* new CodexShadowHomeEntryConflictError({
|
||||
sharedHomePath: input.sharedHomePath,
|
||||
effectiveHomePath: input.effectiveHomePath,
|
||||
entryName: input.entryName,
|
||||
linkPath: link,
|
||||
targetPath: target,
|
||||
});
|
||||
}
|
||||
|
||||
const createLink = input.fileSystem.symlink(target, link).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
@@ -250,6 +242,33 @@ const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (inpu
|
||||
}),
|
||||
);
|
||||
|
||||
if (state._tag === "NotSymlink") {
|
||||
if (!REPLACEABLE_SHARED_RUNTIME_DIRECTORIES.has(input.entryName)) {
|
||||
return yield* new CodexShadowHomeEntryConflictError({
|
||||
sharedHomePath: input.sharedHomePath,
|
||||
effectiveHomePath: input.effectiveHomePath,
|
||||
entryName: input.entryName,
|
||||
linkPath: link,
|
||||
targetPath: target,
|
||||
});
|
||||
}
|
||||
|
||||
yield* input.fileSystem.remove(link, { recursive: true }).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
new CodexShadowHomeFileSystemError({
|
||||
sharedHomePath: input.sharedHomePath,
|
||||
effectiveHomePath: input.effectiveHomePath,
|
||||
operation: "remove",
|
||||
path: link,
|
||||
entryName: input.entryName,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
return yield* createLink;
|
||||
}
|
||||
|
||||
if (state._tag === "Missing") {
|
||||
return yield* createLink;
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
defaultConfig: (): CursorSettings => decodeCursorSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -133,6 +134,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
|
||||
const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
|
||||
@@ -84,6 +84,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
defaultConfig: (): GrokSettings => decodeGrokSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
@@ -114,6 +115,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
|
||||
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
|
||||
|
||||
@@ -583,6 +583,7 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {
|
||||
const probeClaudeCapabilities = (
|
||||
claudeSettings: ClaudeSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
cwd?: string,
|
||||
) => {
|
||||
const abort = new AbortController();
|
||||
return Effect.gen(function* () {
|
||||
@@ -602,6 +603,7 @@ const probeClaudeCapabilities = (
|
||||
settingSources: ["user", "project", "local"],
|
||||
allowedTools: [],
|
||||
env: claudeEnvironment,
|
||||
...(cwd ? { cwd } : {}),
|
||||
stderr: () => {},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -4,11 +4,12 @@ import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { describe } from "vite-plus/test";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { DEFAULT_MODEL, ThreadId } from "@t3tools/contracts";
|
||||
import * as CodexErrors from "effect-codex-app-server/errors";
|
||||
import * as CodexRpc from "effect-codex-app-server/rpc";
|
||||
|
||||
import {
|
||||
buildCodexDeveloperInstructions,
|
||||
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
} from "../CodexDeveloperInstructions.ts";
|
||||
@@ -118,7 +119,10 @@ describe("buildTurnStartParams", () => {
|
||||
settings: {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
developer_instructions: buildCodexDeveloperInstructions("plan", {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoningEffort: "medium",
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -163,12 +167,31 @@ describe("buildTurnStartParams", () => {
|
||||
settings: {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
developer_instructions: buildCodexDeveloperInstructions("default", {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoningEffort: "medium",
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reports the same fallback model and effort in settings and instructions", () => {
|
||||
const params = Effect.runSync(
|
||||
buildTurnStartParams({
|
||||
threadId: "provider-thread-1",
|
||||
runtimeMode: "full-access",
|
||||
prompt: "Go",
|
||||
interactionMode: "default",
|
||||
}),
|
||||
);
|
||||
|
||||
const settings = params.collaborationMode?.settings;
|
||||
NodeAssert.equal(settings?.model, DEFAULT_MODEL);
|
||||
NodeAssert.equal(settings?.reasoning_effort, "medium");
|
||||
NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`));
|
||||
});
|
||||
|
||||
it("omits collaboration mode when interaction mode is absent", () => {
|
||||
const params = Effect.runSync(
|
||||
buildTurnStartParams({
|
||||
@@ -194,6 +217,53 @@ describe("buildTurnStartParams", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCodexDeveloperInstructions", () => {
|
||||
it("appends runtime info after the mode instructions", () => {
|
||||
const instructions = buildCodexDeveloperInstructions("default", {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoningEffort: "high",
|
||||
});
|
||||
|
||||
NodeAssert.ok(instructions.startsWith(CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS));
|
||||
NodeAssert.match(instructions, /T3 Code/);
|
||||
NodeAssert.match(instructions, /Codex harness/);
|
||||
NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/);
|
||||
});
|
||||
|
||||
it("includes runtime info alongside plan mode instructions", () => {
|
||||
const instructions = buildCodexDeveloperInstructions("plan", {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoningEffort: "medium",
|
||||
});
|
||||
|
||||
NodeAssert.ok(instructions.startsWith(CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS));
|
||||
NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/);
|
||||
});
|
||||
|
||||
it("varies with the model and effort of each turn", () => {
|
||||
const first = buildCodexDeveloperInstructions("default", {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoningEffort: "medium",
|
||||
});
|
||||
const second = buildCodexDeveloperInstructions("default", {
|
||||
model: "gpt-5.4",
|
||||
reasoningEffort: "high",
|
||||
});
|
||||
|
||||
NodeAssert.notEqual(first, second);
|
||||
});
|
||||
|
||||
it("flattens multiline metadata into single-line runtime info", () => {
|
||||
const instructions = buildCodexDeveloperInstructions("default", {
|
||||
model: "gpt\n5.3\ncodex",
|
||||
reasoningEffort: " high\neffort ",
|
||||
});
|
||||
|
||||
NodeAssert.match(instructions, /as gpt 5\.3 codex with high effort reasoning effort/);
|
||||
NodeAssert.doesNotMatch(instructions, /<runtime_info>[^<]*\n/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("T3 browser developer instructions", () => {
|
||||
it("prefers the product-native preview tools in both collaboration modes", () => {
|
||||
for (const instructions of [
|
||||
|
||||
@@ -37,10 +37,7 @@ import * as EffectCodexSchema from "effect-codex-app-server/schema";
|
||||
|
||||
import { buildCodexInitializeParams } from "./CodexProvider.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import {
|
||||
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
} from "../CodexDeveloperInstructions.ts";
|
||||
import { buildCodexDeveloperInstructions } from "../CodexDeveloperInstructions.ts";
|
||||
const decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse);
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("codex");
|
||||
@@ -331,15 +328,16 @@ function buildCodexCollaborationMode(input: {
|
||||
return undefined;
|
||||
}
|
||||
const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL;
|
||||
const reasoningEffort = input.effort ?? "medium";
|
||||
return {
|
||||
mode: input.interactionMode,
|
||||
settings: {
|
||||
model,
|
||||
reasoning_effort: input.effort ?? "medium",
|
||||
developer_instructions:
|
||||
input.interactionMode === "plan"
|
||||
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
|
||||
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
reasoning_effort: reasoningEffort,
|
||||
developer_instructions: buildCodexDeveloperInstructions(input.interactionMode, {
|
||||
model,
|
||||
reasoningEffort,
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -228,7 +228,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
assert.isDefined(delta);
|
||||
if (delta?.type === "content.delta") {
|
||||
assert.equal(delta.payload.delta, "hello from mock");
|
||||
assert.match(String(delta.itemId), /^assistant:mock-session-1:segment:0$/);
|
||||
assert.match(String(delta.itemId), /^assistant:mock-session-1:runtime:[^:]+:segment:0$/);
|
||||
}
|
||||
|
||||
const assistantCompleted = runtimeEvents.find(
|
||||
@@ -687,7 +687,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
if (contentDelta?.type === "content.delta") {
|
||||
assert.equal(String(contentDelta.turnId), String(turn.turnId));
|
||||
assert.equal(contentDelta.payload.delta, "hello from mock");
|
||||
assert.equal(String(contentDelta.itemId), "assistant:mock-session-1:segment:0");
|
||||
assert.match(
|
||||
String(contentDelta.itemId),
|
||||
/^assistant:mock-session-1:runtime:[^:]+:segment:0$/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -558,6 +558,7 @@ export function makeCursorAdapter(
|
||||
: {}),
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.provideService(Scope.Scope, sessionScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -28,7 +29,7 @@ const runNode = <A, E>(
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
|
||||
>,
|
||||
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -992,7 +993,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const fallbackModels = getCursorFallbackModels(cursorSettings);
|
||||
|
||||
@@ -596,6 +596,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
: {}),
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.provideService(Scope.Scope, sessionScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -167,7 +168,11 @@ const runGrokVersionCommand = (
|
||||
export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
|
||||
grokSettings: GrokSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
|
||||
> {
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const fallbackModels = grokModelsFromSettings(grokSettings.customModels);
|
||||
|
||||
|
||||
@@ -248,6 +248,38 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails sendTurn for missing sessions through the typed error channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const result = yield* adapter
|
||||
.sendTurn({
|
||||
threadId: asThreadId("thread-opencode-missing-send"),
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
NodeAssert.equal(result._tag, "Failure");
|
||||
NodeAssert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
|
||||
NodeAssert.equal(result.failure.provider, "opencode");
|
||||
NodeAssert.equal(result.failure.threadId, "thread-opencode-missing-send");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails stopSession for missing sessions through the typed error channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const result = yield* adapter
|
||||
.stopSession(asThreadId("thread-opencode-missing-stop"))
|
||||
.pipe(Effect.result);
|
||||
|
||||
NodeAssert.equal(result._tag, "Failure");
|
||||
NodeAssert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
|
||||
NodeAssert.equal(result.failure.provider, "opencode");
|
||||
NodeAssert.equal(result.failure.threadId, "thread-opencode-missing-stop");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops a configured-server session without trying to own server lifecycle", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
|
||||
@@ -228,28 +228,25 @@ function appendTurnItem(
|
||||
resolveTurnSnapshot(context, turnId).items.push(item);
|
||||
}
|
||||
|
||||
function ensureSessionContext(
|
||||
const ensureSessionContext = Effect.fn("ensureSessionContext")(function* (
|
||||
sessions: ReadonlyMap<ThreadId, OpenCodeSessionContext>,
|
||||
threadId: ThreadId,
|
||||
): OpenCodeSessionContext {
|
||||
) {
|
||||
const session = sessions.get(threadId);
|
||||
if (!session) {
|
||||
throw new ProviderAdapterSessionNotFoundError({
|
||||
return yield* new ProviderAdapterSessionNotFoundError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
});
|
||||
}
|
||||
// `ensureSessionContext` is a sync gate used from both sync helpers and
|
||||
// Effect bodies. `Ref.getUnsafe` is an atomic read of the backing cell —
|
||||
// no fiber suspension required, which keeps this callable everywhere.
|
||||
if (Ref.getUnsafe(session.stopped)) {
|
||||
throw new ProviderAdapterSessionClosedError({
|
||||
if (yield* Ref.get(session.stopped)) {
|
||||
return yield* new ProviderAdapterSessionClosedError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
});
|
||||
}
|
||||
return session;
|
||||
}
|
||||
});
|
||||
|
||||
function normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray<UserInputQuestion> {
|
||||
return request.questions.map((question, index) => ({
|
||||
@@ -1167,7 +1164,7 @@ export function makeOpenCodeAdapter(
|
||||
);
|
||||
|
||||
const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
|
||||
const context = ensureSessionContext(sessions, input.threadId);
|
||||
const context = yield* ensureSessionContext(sessions, input.threadId);
|
||||
// A sendTurn while a turn is active is a steer: OpenCode queues the
|
||||
// prompt into the busy session and the work continues as one turn, so
|
||||
// the active turn id is reused instead of opening a new turn.
|
||||
@@ -1291,7 +1288,7 @@ export function makeOpenCodeAdapter(
|
||||
|
||||
const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
|
||||
function* (threadId, turnId) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
const context = yield* ensureSessionContext(sessions, threadId);
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
context.client.session.abort({ sessionID: context.openCodeSessionId }),
|
||||
).pipe(Effect.mapError(toRequestError));
|
||||
@@ -1313,7 +1310,7 @@ export function makeOpenCodeAdapter(
|
||||
const respondToRequest: OpenCodeAdapterShape["respondToRequest"] = Effect.fn(
|
||||
"respondToRequest",
|
||||
)(function* (threadId, requestId, decision) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
const context = yield* ensureSessionContext(sessions, threadId);
|
||||
if (!context.pendingPermissions.has(requestId)) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
@@ -1333,7 +1330,7 @@ export function makeOpenCodeAdapter(
|
||||
const respondToUserInput: OpenCodeAdapterShape["respondToUserInput"] = Effect.fn(
|
||||
"respondToUserInput",
|
||||
)(function* (threadId, requestId, answers) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
const context = yield* ensureSessionContext(sessions, threadId);
|
||||
const request = context.pendingQuestions.get(requestId);
|
||||
if (!request) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
@@ -1355,7 +1352,7 @@ export function makeOpenCodeAdapter(
|
||||
function* (threadId) {
|
||||
const context = sessions.get(threadId);
|
||||
if (!context) {
|
||||
throw new ProviderAdapterSessionNotFoundError({
|
||||
return yield* new ProviderAdapterSessionNotFoundError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
});
|
||||
@@ -1385,7 +1382,7 @@ export function makeOpenCodeAdapter(
|
||||
|
||||
const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")(
|
||||
function* (threadId) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
const context = yield* ensureSessionContext(sessions, threadId);
|
||||
const messages = yield* runOpenCodeSdk("session.messages", () =>
|
||||
context.client.session.messages({
|
||||
sessionID: context.openCodeSessionId,
|
||||
@@ -1411,7 +1408,7 @@ export function makeOpenCodeAdapter(
|
||||
|
||||
const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(
|
||||
function* (threadId, numTurns) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
const context = yield* ensureSessionContext(sessions, threadId);
|
||||
const messages = yield* runOpenCodeSdk("session.messages", () =>
|
||||
context.client.session.messages({
|
||||
sessionID: context.openCodeSessionId,
|
||||
|
||||
@@ -116,6 +116,43 @@ describe("AcpSessionRuntime", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps assistant item IDs unique when a provider session restarts", () => {
|
||||
const collectFirstAssistantItemId = Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
const started = yield* runtime.start();
|
||||
expect(started.sessionId).toBe("mock-session-1");
|
||||
|
||||
yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
|
||||
const events = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
|
||||
const assistantStart = events.find((event) => event._tag === "AssistantItemStarted");
|
||||
expect(assistantStart?._tag).toBe("AssistantItemStarted");
|
||||
return assistantStart?._tag === "AssistantItemStarted" ? assistantStart.itemId : "";
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const beforeRestart = yield* collectFirstAssistantItemId;
|
||||
const afterRestart = yield* collectFirstAssistantItemId;
|
||||
|
||||
expect(afterRestart).not.toBe(beforeRestart);
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
});
|
||||
|
||||
it.effect("drops session updates emitted for a child ACP session", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -270,14 +271,24 @@ export const make = (
|
||||
): Effect.Effect<
|
||||
AcpSessionRuntime["Service"],
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
|
||||
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
|
||||
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
|
||||
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
|
||||
const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EffectAcpErrors.AcpTransportError({
|
||||
detail: "Failed to generate an ACP assistant item runtime identifier.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
|
||||
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
|
||||
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
|
||||
@@ -387,6 +398,7 @@ export const make = (
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
assistantItemRuntimeId,
|
||||
params: notification,
|
||||
});
|
||||
}),
|
||||
@@ -802,7 +814,7 @@ export const layer = (
|
||||
): Layer.Layer<
|
||||
AcpSessionRuntime,
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
|
||||
> => Layer.effect(AcpSessionRuntime, make(options));
|
||||
|
||||
function sessionConfigOptionsFromSetup(
|
||||
@@ -834,12 +846,14 @@ const handleSessionUpdate = ({
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
assistantItemRuntimeId,
|
||||
params,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
|
||||
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly assistantItemRuntimeId: string;
|
||||
readonly params: EffectAcpSchema.SessionNotification;
|
||||
}): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
@@ -887,6 +901,7 @@ const handleSessionUpdate = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
sessionId: params.sessionId,
|
||||
assistantItemRuntimeId,
|
||||
});
|
||||
yield* Queue.offer(queue, {
|
||||
...event,
|
||||
@@ -924,17 +939,19 @@ function shouldEmitToolCallUpdate(
|
||||
return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
|
||||
}
|
||||
|
||||
const assistantItemId = (sessionId: string, segmentIndex: number) =>
|
||||
`assistant:${sessionId}:segment:${segmentIndex}`;
|
||||
const assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) =>
|
||||
`assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`;
|
||||
|
||||
const ensureActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
sessionId,
|
||||
assistantItemRuntimeId,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly sessionId: string;
|
||||
readonly assistantItemRuntimeId: string;
|
||||
}) =>
|
||||
Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
|
||||
assistantSegmentRef,
|
||||
@@ -942,7 +959,7 @@ const ensureActiveAssistantSegment = ({
|
||||
if (current.activeItemId) {
|
||||
return [{ itemId: current.activeItemId }, current] as const;
|
||||
}
|
||||
const itemId = assistantItemId(sessionId, current.nextSegmentIndex);
|
||||
const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex);
|
||||
return [
|
||||
{
|
||||
itemId,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -50,7 +51,7 @@ export const makeCursorAcpRuntime = (
|
||||
): Effect.Effect<
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
EffectAcpErrors.AcpError,
|
||||
Scope.Scope
|
||||
Crypto.Crypto | Scope.Scope
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const acpContext = yield* Layer.build(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -55,7 +56,7 @@ export const makeGrokAcpRuntime = (
|
||||
): Effect.Effect<
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
EffectAcpErrors.AcpError,
|
||||
Scope.Scope
|
||||
Crypto.Crypto | Scope.Scope
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const acpContext = yield* Layer.build(
|
||||
|
||||
@@ -1334,6 +1334,63 @@ it.layer(
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("strips AppImage runtime env from terminal sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const appDir = "/tmp/.mount_T3Codeabc123";
|
||||
const { manager, ptyAdapter } = yield* createManager(5, {
|
||||
env: {
|
||||
APPIMAGE: "/home/user/T3-Code.AppImage",
|
||||
APPDIR: appDir,
|
||||
ARGV0: "/home/user/T3-Code.AppImage",
|
||||
OWD: "/home/user/project",
|
||||
PATH: `${appDir}/usr/bin:${appDir}:/usr/local/bin:/usr/bin:/bin`,
|
||||
LD_LIBRARY_PATH: `${appDir}/usr/lib:/home/user/.local/lib`,
|
||||
TEST_TERMINAL_KEEP: "keep-me",
|
||||
},
|
||||
});
|
||||
yield* manager.open(openInput());
|
||||
const spawnInput = ptyAdapter.spawnInputs[0];
|
||||
expect(spawnInput).toBeDefined();
|
||||
if (!spawnInput) return;
|
||||
|
||||
// AppImage runtime markers must never reach the PTY — tools inside the
|
||||
// terminal otherwise resolve against the AppImage mount (e.g. PHP_BINARY
|
||||
// reporting the AppImage path instead of the real binary).
|
||||
expect(spawnInput.env.APPIMAGE).toBeUndefined();
|
||||
expect(spawnInput.env.APPDIR).toBeUndefined();
|
||||
expect(spawnInput.env.ARGV0).toBeUndefined();
|
||||
expect(spawnInput.env.OWD).toBeUndefined();
|
||||
// PATH/LD_LIBRARY_PATH keep the user's real entries but drop the AppImage
|
||||
// mount segments that the runtime prepended.
|
||||
expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin");
|
||||
expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib");
|
||||
// Unrelated host vars still pass through untouched.
|
||||
expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("leaves the environment untouched when not launched from an AppImage", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter } = yield* createManager(5, {
|
||||
env: {
|
||||
PATH: "/usr/local/bin:/usr/bin:/bin",
|
||||
LD_LIBRARY_PATH: "/home/user/.local/lib",
|
||||
// Without APPIMAGE/APPDIR set, OWD is an ordinary variable and must
|
||||
// not be stripped — only an AppImage launch gives it special meaning.
|
||||
OWD: "/home/user/keep-this",
|
||||
},
|
||||
});
|
||||
yield* manager.open(openInput());
|
||||
const spawnInput = ptyAdapter.spawnInputs[0];
|
||||
expect(spawnInput).toBeDefined();
|
||||
if (!spawnInput) return;
|
||||
|
||||
expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin");
|
||||
expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib");
|
||||
expect(spawnInput.env.OWD).toBe("/home/user/keep-this");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("injects runtime env overrides into spawned terminals", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter } = yield* createManager();
|
||||
|
||||
@@ -1065,6 +1065,53 @@ function shouldExcludeTerminalEnvKey(key: string): boolean {
|
||||
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
|
||||
}
|
||||
|
||||
// Marker variables the AppImage runtime injects into the process it launches.
|
||||
// They describe the AppImage itself, not the user's session, so terminals must
|
||||
// not inherit them.
|
||||
const APPIMAGE_RUNTIME_ENV_KEYS = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"] as const;
|
||||
// PATH-style variables the AppImage runtime prepends with its temporary mount
|
||||
// (e.g. /tmp/.mount_T3-XXXX/usr/bin). Only the mount segments are dropped; the
|
||||
// user's real entries are preserved.
|
||||
const APPIMAGE_PATH_LIKE_ENV_KEYS = ["PATH", "LD_LIBRARY_PATH"] as const;
|
||||
|
||||
function isPathSegmentUnderAppDir(segment: string, appDir: string): boolean {
|
||||
return segment === appDir || segment.startsWith(`${appDir}/`);
|
||||
}
|
||||
|
||||
// On Linux AppImage builds the runtime mounts the app under a temporary dir and
|
||||
// injects APPIMAGE/APPDIR/ARGV0/OWD plus mount entries on PATH/LD_LIBRARY_PATH.
|
||||
// The integrated terminal inherits the server process environment, so without
|
||||
// this scrub those leak into the PTY and tools resolve against the AppImage
|
||||
// mount instead of the user's real environment (e.g. `php` reporting
|
||||
// PHP_BINARY as the AppImage path). See issue #1699. The scrub is gated on an
|
||||
// actual AppImage launch so non-AppImage environments are left untouched.
|
||||
function stripAppImageRuntimeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
if (env.APPIMAGE === undefined && env.APPDIR === undefined) return env;
|
||||
|
||||
const scrubbed: NodeJS.ProcessEnv = { ...env };
|
||||
for (const key of APPIMAGE_RUNTIME_ENV_KEYS) {
|
||||
delete scrubbed[key];
|
||||
}
|
||||
|
||||
const appDir = env.APPDIR?.replace(/\/+$/, "");
|
||||
if (appDir) {
|
||||
for (const key of APPIMAGE_PATH_LIKE_ENV_KEYS) {
|
||||
const value = scrubbed[key];
|
||||
if (value === undefined) continue;
|
||||
const kept = value
|
||||
.split(":")
|
||||
.filter((segment) => segment.length > 0 && !isPathSegmentUnderAppDir(segment, appDir));
|
||||
if (kept.length > 0) {
|
||||
scrubbed[key] = kept.join(":");
|
||||
} else {
|
||||
delete scrubbed[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return scrubbed;
|
||||
}
|
||||
|
||||
function createTerminalSpawnEnv(
|
||||
baseEnv: NodeJS.ProcessEnv,
|
||||
runtimeEnv?: Record<string, string> | null,
|
||||
@@ -1080,7 +1127,7 @@ function createTerminalSpawnEnv(
|
||||
spawnEnv[key] = value;
|
||||
}
|
||||
}
|
||||
return spawnEnv;
|
||||
return stripAppImageRuntimeEnv(spawnEnv);
|
||||
}
|
||||
|
||||
function normalizedRuntimeEnv(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -38,6 +39,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
cursorSettings: CursorSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
|
||||
@@ -66,7 +68,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
childProcessSpawner: commandSpawner,
|
||||
cwd,
|
||||
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
|
||||
});
|
||||
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
|
||||
|
||||
yield* runtime.handleSessionUpdate((notification) => {
|
||||
const update = notification.update;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -37,6 +38,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
grokSettings: GrokSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
) {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const runGrokJson = <S extends Schema.Top>({
|
||||
@@ -65,7 +67,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
childProcessSpawner: commandSpawner,
|
||||
cwd,
|
||||
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
|
||||
});
|
||||
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
|
||||
|
||||
yield* runtime.handleSessionUpdate((notification) => {
|
||||
const update = notification.update;
|
||||
|
||||
|
Before Width: | Height: | Size: 74 KiB After Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 1003 B After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 204 KiB After Width: | Height: | Size: 277 KiB |
@@ -1,6 +1,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
@@ -55,6 +55,7 @@ function SidebarControl() {
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
|
||||
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
|
||||
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
|
||||
@@ -92,14 +93,17 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
|
||||
const unsubscribe = onMenuAction((action) => {
|
||||
if (action === "open-settings") {
|
||||
void navigate({ to: "/settings" });
|
||||
const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
|
||||
if (!isSettingsRoute) {
|
||||
void navigate({ to: "/settings" });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribe?.();
|
||||
};
|
||||
}, [navigate]);
|
||||
}, [navigate, pathname]);
|
||||
|
||||
return (
|
||||
<SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={macosWindowControlsStyle}>
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { Thread } from "../types";
|
||||
@@ -359,6 +366,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: completedTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: readySession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -384,6 +392,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: newerTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: { ...readySession, updatedAt: newerTurn.completedAt },
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -410,6 +419,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
@@ -425,6 +435,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
@@ -437,12 +448,56 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("acknowledges a steering message projected onto the current running turn", () => {
|
||||
const runningTurn = {
|
||||
...completedTurn,
|
||||
state: "running" as const,
|
||||
completedAt: null,
|
||||
};
|
||||
const runningSession = {
|
||||
...readySession,
|
||||
status: "running" as const,
|
||||
activeTurnId: runningTurn.turnId,
|
||||
};
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({
|
||||
latestTurn: runningTurn,
|
||||
session: runningSession,
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("message-before-steer"),
|
||||
role: "user",
|
||||
text: "Initial prompt",
|
||||
turnId: runningTurn.turnId,
|
||||
createdAt: runningTurn.requestedAt,
|
||||
updatedAt: runningTurn.requestedAt,
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: MessageId.make("message-steer"),
|
||||
session: runningSession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("acknowledges pending user interaction and errors immediately", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(makeThread());
|
||||
const common = {
|
||||
localDispatch,
|
||||
phase: "ready" as const,
|
||||
latestTurn: null,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: null,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
|
||||
@@ -387,6 +387,7 @@ export async function waitForStartedServerThread(
|
||||
export interface LocalDispatchSnapshot {
|
||||
startedAt: string;
|
||||
preparingWorktree: boolean;
|
||||
latestUserMessageId: ChatMessage["id"] | null;
|
||||
latestTurnTurnId: TurnId | null;
|
||||
latestTurnRequestedAt: string | null;
|
||||
latestTurnStartedAt: string | null;
|
||||
@@ -401,9 +402,11 @@ export function createLocalDispatchSnapshot(
|
||||
): LocalDispatchSnapshot {
|
||||
const latestTurn = activeThread?.latestTurn ?? null;
|
||||
const session = activeThread?.session ?? null;
|
||||
const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
|
||||
return {
|
||||
startedAt: new Date().toISOString(),
|
||||
preparingWorktree: Boolean(options?.preparingWorktree),
|
||||
latestUserMessageId: latestUserMessage?.id ?? null,
|
||||
latestTurnTurnId: latestTurn?.turnId ?? null,
|
||||
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
|
||||
latestTurnStartedAt: latestTurn?.startedAt ?? null,
|
||||
@@ -417,6 +420,7 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
localDispatch: LocalDispatchSnapshot | null;
|
||||
phase: SessionPhase;
|
||||
latestTurn: Thread["latestTurn"] | null;
|
||||
latestUserMessageId: ChatMessage["id"] | null;
|
||||
session: Thread["session"] | null;
|
||||
hasPendingApproval: boolean;
|
||||
hasPendingUserInput: boolean;
|
||||
@@ -431,6 +435,8 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
|
||||
const latestTurn = input.latestTurn ?? null;
|
||||
const session = input.session ?? null;
|
||||
const latestUserMessageChanged =
|
||||
input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
|
||||
const latestTurnChanged =
|
||||
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
|
||||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
|
||||
@@ -438,6 +444,13 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
|
||||
|
||||
if (input.phase === "running") {
|
||||
// Steering adds a user message to the current running turn without
|
||||
// necessarily changing any of the turn timestamps. Treat that projected
|
||||
// message as the server acknowledgment so the composer does not remain
|
||||
// stuck in its local "Sending" state until the turn settles.
|
||||
if (latestUserMessageChanged) {
|
||||
return true;
|
||||
}
|
||||
if (!latestTurnChanged) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -53,6 +53,7 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import {
|
||||
@@ -201,6 +202,7 @@ import {
|
||||
} from "../state/entities";
|
||||
import { environmentShell } from "../state/shell";
|
||||
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
|
||||
import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";
|
||||
import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
|
||||
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
|
||||
import { MessagesTimeline } from "./chat/MessagesTimeline";
|
||||
@@ -212,6 +214,14 @@ import { resolveEffectiveEnvMode } from "./BranchToolbar.logic";
|
||||
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
|
||||
import {
|
||||
DRAFT_HERO_TRANSITION_ANIMATION_ID,
|
||||
DRAFT_HERO_TRANSITION_DURATION_MS,
|
||||
DRAFT_HERO_TRANSITION_EASING,
|
||||
MOBILE_COMPOSER_VIEW_TRANSITION_NAME,
|
||||
MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
|
||||
runMobileComposerTransition,
|
||||
} from "./chat/draftHeroTransition";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
@@ -256,6 +266,78 @@ const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
|
||||
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
|
||||
function useDraftHeroLayoutTransition(isDraftHeroState: boolean) {
|
||||
const transitionGroupRef = useRef<HTMLDivElement | null>(null);
|
||||
const composerAnchorRef = useRef<HTMLDivElement | null>(null);
|
||||
const previousStateRef = useRef(isDraftHeroState);
|
||||
const previousComposerRectRef = useRef<DOMRect | null>(null);
|
||||
const animationRef = useRef<Animation | null>(null);
|
||||
const attachTransitionGroupRef = (element: HTMLDivElement | null) => {
|
||||
transitionGroupRef.current = element;
|
||||
};
|
||||
const attachComposerAnchorRef = (element: HTMLDivElement | null) => {
|
||||
composerAnchorRef.current = element;
|
||||
};
|
||||
const captureComposerRect = () => {
|
||||
previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null;
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const transitionGroup = transitionGroupRef.current;
|
||||
const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null;
|
||||
const stateChanged = previousStateRef.current !== isDraftHeroState;
|
||||
const prefersReducedMotion =
|
||||
typeof window !== "undefined" &&
|
||||
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
|
||||
const mobileComposerTransitionActive =
|
||||
typeof document !== "undefined" &&
|
||||
document.documentElement.dataset.mobileComposerRouteTransition === "true";
|
||||
|
||||
animationRef.current?.cancel();
|
||||
animationRef.current = null;
|
||||
|
||||
const previousComposerRect = previousComposerRectRef.current;
|
||||
if (
|
||||
stateChanged &&
|
||||
!prefersReducedMotion &&
|
||||
!mobileComposerTransitionActive &&
|
||||
transitionGroup &&
|
||||
previousComposerRect &&
|
||||
nextComposerRect &&
|
||||
typeof transitionGroup.animate === "function"
|
||||
) {
|
||||
const translateX = previousComposerRect.left - nextComposerRect.left;
|
||||
const translateY = previousComposerRect.top - nextComposerRect.top;
|
||||
if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) {
|
||||
const animation = transitionGroup.animate(
|
||||
[
|
||||
{ transform: `translate3d(${translateX}px, ${translateY}px, 0)` },
|
||||
{ transform: "translate3d(0, 0, 0)" },
|
||||
],
|
||||
{
|
||||
duration: DRAFT_HERO_TRANSITION_DURATION_MS,
|
||||
easing: DRAFT_HERO_TRANSITION_EASING,
|
||||
},
|
||||
);
|
||||
animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID;
|
||||
animationRef.current = animation;
|
||||
void animation.finished
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
if (animationRef.current !== animation) {
|
||||
return;
|
||||
}
|
||||
animationRef.current = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
previousStateRef.current = isDraftHeroState;
|
||||
previousComposerRectRef.current = nextComposerRect;
|
||||
}, [isDraftHeroState]);
|
||||
|
||||
return [attachTransitionGroupRef, attachComposerAnchorRef, captureComposerRect] as const;
|
||||
}
|
||||
const PreviewPanel = lazy(() =>
|
||||
import("./preview/PreviewPanel").then((module) => ({ default: module.PreviewPanel })),
|
||||
);
|
||||
@@ -339,6 +421,7 @@ type ChatViewProps =
|
||||
threadId: ThreadId;
|
||||
onDiffPanelOpen?: () => void;
|
||||
reserveTitleBarControlInset?: boolean;
|
||||
forceExpandedMobileComposer?: boolean;
|
||||
routeKind: "server";
|
||||
draftId?: never;
|
||||
}
|
||||
@@ -347,6 +430,7 @@ type ChatViewProps =
|
||||
threadId: ThreadId;
|
||||
onDiffPanelOpen?: () => void;
|
||||
reserveTitleBarControlInset?: boolean;
|
||||
forceExpandedMobileComposer?: boolean;
|
||||
routeKind: "draft";
|
||||
draftId: DraftId;
|
||||
};
|
||||
@@ -368,6 +452,8 @@ function useLocalDispatchState(input: {
|
||||
threadError: string | null | undefined;
|
||||
}) {
|
||||
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
|
||||
const latestUserMessageId =
|
||||
input.activeThread?.messages.findLast((message) => message.role === "user")?.id ?? null;
|
||||
|
||||
const resetLocalDispatch = useCallback(() => {
|
||||
setLocalDispatch(null);
|
||||
@@ -379,6 +465,7 @@ function useLocalDispatchState(input: {
|
||||
localDispatch,
|
||||
phase: input.phase,
|
||||
latestTurn: input.activeLatestTurn,
|
||||
latestUserMessageId,
|
||||
session: input.activeThread?.session ?? null,
|
||||
hasPendingApproval: input.activePendingApproval !== null,
|
||||
hasPendingUserInput: input.activePendingUserInput !== null,
|
||||
@@ -391,6 +478,7 @@ function useLocalDispatchState(input: {
|
||||
input.activeThread?.session,
|
||||
input.phase,
|
||||
input.threadError,
|
||||
latestUserMessageId,
|
||||
localDispatch,
|
||||
],
|
||||
);
|
||||
@@ -979,6 +1067,14 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane
|
||||
);
|
||||
});
|
||||
|
||||
// Errors surface through two maps (draft-keyed and thread-keyed) whose entries
|
||||
// can race around promotion, so each write carries its time to let the latest
|
||||
// one win when they collide.
|
||||
type LocalThreadErrorEntry = {
|
||||
readonly message: string | null;
|
||||
readonly at: number;
|
||||
};
|
||||
|
||||
function ChatViewContent(props: ChatViewProps) {
|
||||
const {
|
||||
environmentId,
|
||||
@@ -986,6 +1082,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
routeKind,
|
||||
onDiffPanelOpen,
|
||||
reserveTitleBarControlInset = true,
|
||||
forceExpandedMobileComposer = false,
|
||||
} = props;
|
||||
const draftId = routeKind === "draft" ? props.draftId : null;
|
||||
const routeThreadRef = useMemo(
|
||||
@@ -1035,10 +1132,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
);
|
||||
const composerDraftTarget: ScopedThreadRef | DraftId =
|
||||
routeKind === "server" ? routeThreadRef : props.draftId;
|
||||
const serverThread = useThread(routeKind === "server" ? routeThreadRef : null);
|
||||
const serverThread = useThread(routeThreadRef);
|
||||
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
|
||||
const activeThreadLastVisitedAt = useUiStateStore((store) =>
|
||||
routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined,
|
||||
const activeThreadLastVisitedAt = useUiStateStore(
|
||||
(store) => store.threadLastVisitedAtById[routeThreadKey],
|
||||
);
|
||||
const settings = useEnvironmentSettings(environmentId);
|
||||
const setStickyComposerModelSelection = useComposerDraftStore(
|
||||
@@ -1103,10 +1200,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
|
||||
optimisticUserMessagesRef.current = optimisticUserMessages;
|
||||
const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState<
|
||||
Record<string, string | null>
|
||||
Record<string, LocalThreadErrorEntry>
|
||||
>({});
|
||||
const [localServerErrorsByThreadKey, setLocalServerErrorsByThreadKey] = useState<
|
||||
Record<string, string | null>
|
||||
Record<string, LocalThreadErrorEntry>
|
||||
>({});
|
||||
const [isConnecting, _setIsConnecting] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
@@ -1218,11 +1315,45 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
|
||||
: null;
|
||||
const fallbackDraftProject = useProject(fallbackDraftProjectRef);
|
||||
const localDraftError =
|
||||
routeKind === "server" && serverThread
|
||||
? null
|
||||
: ((draftId ? localDraftErrorsByDraftId[draftId] : null) ?? null);
|
||||
const localServerError = localServerErrorsByThreadKey[routeThreadKey] ?? null;
|
||||
const localDraftError = serverThread
|
||||
? null
|
||||
: ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null);
|
||||
const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null;
|
||||
// Draft errors are keyed by draftId while server errors are keyed by thread
|
||||
// key, so a pending draft entry must migrate when the server thread loads or
|
||||
// a failed send would silently disappear on promotion. When both keys hold
|
||||
// an entry, the most recent write wins.
|
||||
useEffect(() => {
|
||||
if (!serverThread || !draftId) {
|
||||
return;
|
||||
}
|
||||
const pendingDraftEntry = localDraftErrorsByDraftId[draftId];
|
||||
if (pendingDraftEntry === undefined) {
|
||||
return;
|
||||
}
|
||||
setLocalDraftErrorsByDraftId((existing) => {
|
||||
if (existing[draftId] === undefined) {
|
||||
return existing;
|
||||
}
|
||||
const next = { ...existing };
|
||||
delete next[draftId];
|
||||
return next;
|
||||
});
|
||||
setLocalServerErrorsByThreadKey((existing) => {
|
||||
const currentEntry = existing[routeThreadKey];
|
||||
if (
|
||||
currentEntry !== undefined &&
|
||||
(currentEntry.at > pendingDraftEntry.at ||
|
||||
currentEntry.message === pendingDraftEntry.message)
|
||||
) {
|
||||
return existing;
|
||||
}
|
||||
return {
|
||||
...existing,
|
||||
[routeThreadKey]: pendingDraftEntry,
|
||||
};
|
||||
});
|
||||
}, [draftId, localDraftErrorsByDraftId, routeThreadKey, serverThread]);
|
||||
const localDraftThread = useMemo(
|
||||
() =>
|
||||
draftThread
|
||||
@@ -1237,7 +1368,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: undefined,
|
||||
[draftThread, fallbackDraftProject?.defaultModelSelection, threadId],
|
||||
);
|
||||
const isServerThread = routeKind === "server" && serverThread !== null;
|
||||
// Promotion is data-driven: the draft route keeps rendering while the
|
||||
// server thread (same pre-allocated ref) starts, so live state must not
|
||||
// depend on which route is mounted.
|
||||
const isServerThread = serverThread !== null;
|
||||
const activeThread = isServerThread ? serverThread : localDraftThread;
|
||||
const threadError = isServerThread
|
||||
? (localServerError ?? serverThread?.session?.lastError ?? null)
|
||||
@@ -2063,6 +2197,16 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),
|
||||
[activeThread?.proposedPlans, timelineMessages, workLogEntries],
|
||||
);
|
||||
const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);
|
||||
const draftHeroDockRequested =
|
||||
activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;
|
||||
const isDraftHeroState =
|
||||
isLocalDraftThread && timelineEntries.length === 0 && !isWorking && !draftHeroDockRequested;
|
||||
const [
|
||||
attachDraftHeroTransitionGroupRef,
|
||||
attachDraftHeroComposerAnchorRef,
|
||||
captureDraftHeroComposerRect,
|
||||
] = useDraftHeroLayoutTransition(isDraftHeroState);
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const turnDiffSummaryByAssistantMessageId = useMemo(() => {
|
||||
@@ -2112,12 +2256,13 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
worktreePath: activeThread?.worktreePath ?? null,
|
||||
})
|
||||
: null;
|
||||
const gitStatusCwd = activeThread?.worktreePath ?? gitCwd;
|
||||
const gitStatusQuery = useEnvironmentQuery(
|
||||
gitCwd === null
|
||||
gitStatusCwd === null
|
||||
? null
|
||||
: vcsEnvironment.status({
|
||||
environmentId,
|
||||
input: { cwd: gitCwd },
|
||||
input: { cwd: gitStatusCwd },
|
||||
}),
|
||||
);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
@@ -2151,6 +2296,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null;
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const initialDiffPanelGitScope =
|
||||
gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch";
|
||||
const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending";
|
||||
const terminalShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
context: {
|
||||
@@ -2226,6 +2374,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
(targetThreadId: ThreadId | null, error: string | null) => {
|
||||
if (!targetThreadId) return;
|
||||
const nextError = sanitizeThreadErrorMessage(error);
|
||||
const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };
|
||||
if (
|
||||
serverThread &&
|
||||
targetThreadId === routeThreadRef.threadId &&
|
||||
@@ -2233,24 +2382,24 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
serverThread.id === targetThreadId
|
||||
) {
|
||||
setLocalServerErrorsByThreadKey((existing) => {
|
||||
if ((existing[routeThreadKey] ?? null) === nextError) {
|
||||
if ((existing[routeThreadKey]?.message ?? null) === nextError) {
|
||||
return existing;
|
||||
}
|
||||
return {
|
||||
...existing,
|
||||
[routeThreadKey]: nextError,
|
||||
[routeThreadKey]: nextEntry,
|
||||
};
|
||||
});
|
||||
return;
|
||||
}
|
||||
const localDraftErrorKey = draftId ?? targetThreadId;
|
||||
setLocalDraftErrorsByDraftId((existing) => {
|
||||
if ((existing[localDraftErrorKey] ?? null) === nextError) {
|
||||
if ((existing[localDraftErrorKey]?.message ?? null) === nextError) {
|
||||
return existing;
|
||||
}
|
||||
return {
|
||||
...existing,
|
||||
[localDraftErrorKey]: nextError,
|
||||
[localDraftErrorKey]: nextEntry,
|
||||
};
|
||||
});
|
||||
},
|
||||
@@ -2771,9 +2920,19 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}, [activeThreadRef, openPreview]);
|
||||
const addDiffSurface = useCallback(() => {
|
||||
if (!activeThreadRef || !isServerThread || !isGitRepo) return;
|
||||
if (planSidebarOpen) {
|
||||
dismissPlanSidebarForCurrentTurn();
|
||||
}
|
||||
useRightPanelStore.getState().open(activeThreadRef, "diff");
|
||||
onDiffPanelOpen?.();
|
||||
}, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]);
|
||||
}, [
|
||||
activeThreadRef,
|
||||
dismissPlanSidebarForCurrentTurn,
|
||||
isGitRepo,
|
||||
isServerThread,
|
||||
onDiffPanelOpen,
|
||||
planSidebarOpen,
|
||||
]);
|
||||
const addFilesSurface = useCallback(() => {
|
||||
if (!activeThreadRef || !activeProject) return;
|
||||
useRightPanelStore.getState().open(activeThreadRef, "files");
|
||||
@@ -3963,7 +4122,16 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!activeProject) return;
|
||||
if (!activeProject) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: "Choose a project first",
|
||||
description: "This draft no longer points to an available project.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const threadIdForSend = activeThread.id;
|
||||
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
|
||||
const baseBranchForWorktree =
|
||||
@@ -3981,6 +4149,21 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
if (isDraftHeroState && activeThreadKey) {
|
||||
let resolveDockStarted: (() => void) | undefined;
|
||||
const dockStarted = new Promise<void>((resolve) => {
|
||||
resolveDockStarted = resolve;
|
||||
});
|
||||
const dockTransition = runMobileComposerTransition(() => {
|
||||
flushSync(() => {
|
||||
captureDraftHeroComposerRect();
|
||||
setDockedDraftHeroThreadKey(activeThreadKey);
|
||||
});
|
||||
resolveDockStarted?.();
|
||||
});
|
||||
void dockTransition.catch(() => resolveDockStarted?.());
|
||||
await dockStarted;
|
||||
}
|
||||
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
|
||||
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
@@ -4234,6 +4417,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
sendInFlightRef.current = false;
|
||||
if (!turnStartSucceeded) {
|
||||
setDockedDraftHeroThreadKey((currentThreadKey) =>
|
||||
currentThreadKey === activeThreadKey ? null : currentThreadKey,
|
||||
);
|
||||
resetLocalDispatch();
|
||||
}
|
||||
};
|
||||
@@ -4968,7 +5154,12 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
/>
|
||||
) : activeRightPanelSurface?.kind === "diff" ? (
|
||||
<Suspense fallback={null}>
|
||||
<DiffPanel mode="embedded" composerDraftTarget={composerDraftTarget} />
|
||||
<DiffPanel
|
||||
key={`${activeThreadKey}:${diffPanelGitStatusResolutionKey}`}
|
||||
mode="embedded"
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
initialGitScope={initialDiffPanelGitScope}
|
||||
/>
|
||||
</Suspense>
|
||||
) : activeRightPanelSurface?.kind === "plan" ? (
|
||||
<PlanSidebar
|
||||
@@ -5101,6 +5292,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
contentInsetEndAdjustment={composerOverlayHeight}
|
||||
onIsAtEndChange={onIsAtEndChange}
|
||||
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
|
||||
hideEmptyPlaceholder={isDraftHeroState}
|
||||
/>
|
||||
|
||||
{/* scroll to end pill — shown when user has scrolled away from the live edge */}
|
||||
@@ -5123,135 +5315,188 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Input bar */}
|
||||
{/* Input bar — centered hero while a draft has no messages, docked at the bottom otherwise */}
|
||||
<div
|
||||
ref={setComposerOverlayElement}
|
||||
data-chat-composer-overlay="true"
|
||||
className="pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
|
||||
className={
|
||||
isDraftHeroState
|
||||
? "pointer-events-none absolute inset-0 z-20 flex items-center"
|
||||
: "pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
|
||||
}
|
||||
>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"
|
||||
>
|
||||
<div className="relative mx-auto h-full w-full max-w-3xl overflow-clip rounded-t-[20px]">
|
||||
<div className="chat-composer-shared-blur absolute -inset-8" />
|
||||
{!isDraftHeroState ? (
|
||||
<div
|
||||
key="docked-composer-blur"
|
||||
aria-hidden="true"
|
||||
className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"
|
||||
>
|
||||
<div className="relative mx-auto h-full w-full max-w-3xl overflow-clip rounded-t-[20px]">
|
||||
<div className="chat-composer-shared-blur absolute -inset-8" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="chat-composer-horizontal-inset">
|
||||
) : null}
|
||||
<div
|
||||
ref={attachDraftHeroTransitionGroupRef}
|
||||
className="chat-composer-horizontal-inset w-full"
|
||||
>
|
||||
<div className="pointer-events-auto relative z-10 isolate">
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
<div className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
{isDraftHeroState ? (
|
||||
<div className="absolute inset-x-0 bottom-full z-0">
|
||||
<div
|
||||
className="pb-8"
|
||||
style={
|
||||
forceExpandedMobileComposer
|
||||
? {
|
||||
viewTransitionName: MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<DraftHeroHeadline
|
||||
activeProjectRef={activeProjectRef}
|
||||
activeProjectTitle={activeProject?.title ?? null}
|
||||
/>
|
||||
</div>
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
</div>
|
||||
) : (
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
)}
|
||||
<div
|
||||
className="relative"
|
||||
style={
|
||||
forceExpandedMobileComposer
|
||||
? { viewTransitionName: MOBILE_COMPOSER_VIEW_TRANSITION_NAME }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div
|
||||
ref={attachDraftHeroComposerAnchorRef}
|
||||
className="relative z-10 mx-auto w-full max-w-3xl"
|
||||
>
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
|
||||
projectSelectionRequired={isLocalDraftThread && activeProject === null}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"min-h-0",
|
||||
isDraftHeroState ? "absolute inset-x-0 top-full" : null,
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"chat-composer-lower-chrome relative z-10",
|
||||
isGitRepo
|
||||
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
|
||||
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
|
||||
)}
|
||||
>
|
||||
{isGitRepo && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange:
|
||||
setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"chat-composer-horizontal-inset chat-composer-lower-chrome relative z-10",
|
||||
isGitRepo
|
||||
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
|
||||
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
|
||||
)}
|
||||
>
|
||||
{isGitRepo && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{pullRequestDialogState ? (
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
$createParagraphNode,
|
||||
$createTextNode,
|
||||
$getRoot,
|
||||
$getSelection,
|
||||
$isRangeSelection,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
createEditor,
|
||||
PASTE_COMMAND,
|
||||
} from "lexical";
|
||||
|
||||
import { registerComposerInlineTokenPaste } from "./composerInlineTokenPaste";
|
||||
|
||||
class TestClipboardEvent extends Event {
|
||||
readonly clipboardData: DataTransfer;
|
||||
|
||||
constructor(text: string) {
|
||||
super("paste", { cancelable: true });
|
||||
this.clipboardData = {
|
||||
files: [],
|
||||
getData: (type: string) => (type === "text/plain" ? text : ""),
|
||||
} as unknown as DataTransfer;
|
||||
}
|
||||
}
|
||||
|
||||
describe("registerComposerInlineTokenPaste", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("handles a copied mention without also running the plain-text paste fallback", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createEditor();
|
||||
const mention = "[improve-deploy-error-logging.md](.changeset/improve-deploy-error-logging.md)";
|
||||
const plainTextFallback = vi.fn(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) return false;
|
||||
selection.insertText(mention);
|
||||
return true;
|
||||
});
|
||||
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $createParagraphNode();
|
||||
$getRoot().append(paragraph);
|
||||
paragraph.selectEnd();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
|
||||
getExpandedAbsoluteOffsetForPoint: () => 0,
|
||||
});
|
||||
editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
|
||||
|
||||
const event = new TestClipboardEvent(mention);
|
||||
let handled = false;
|
||||
editor.update(
|
||||
() => {
|
||||
handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
expect(handled).toBe(true);
|
||||
expect(plainTextFallback).not.toHaveBeenCalled();
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
"<mention:.changeset/improve-deploy-error-logging.md> ",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import { type ServerProviderSkill } from "@t3tools/contracts";
|
||||
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
|
||||
import {
|
||||
$applyNodeReplacement,
|
||||
$createRangeSelectionFromDom,
|
||||
$createRangeSelection,
|
||||
$getSelection,
|
||||
$setSelection,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
KEY_ARROW_LEFT_COMMAND,
|
||||
KEY_ARROW_RIGHT_COMMAND,
|
||||
KEY_ARROW_UP_COMMAND,
|
||||
KEY_DOWN_COMMAND,
|
||||
KEY_ENTER_COMMAND,
|
||||
KEY_TAB_COMMAND,
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
@@ -63,7 +65,7 @@ import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "~/lib/terminalContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { cn, isMacPlatform } from "~/lib/utils";
|
||||
import { basenameOfPath } from "~/pierre-icons";
|
||||
import {
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
@@ -75,6 +77,7 @@ import { FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip
|
||||
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
|
||||
import { formatProviderSkillDisplayName } from "~/providerSkillPresentation";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { registerComposerInlineTokenPaste } from "./composerInlineTokenPaste";
|
||||
|
||||
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||
const SURROUND_SYMBOLS: [string, string][] = [
|
||||
@@ -1022,6 +1025,53 @@ function ComposerInlineTokenArrowPlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerHomeEndKeyPlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerCommand(
|
||||
KEY_DOWN_COMMAND,
|
||||
(event) => {
|
||||
if (!isMacPlatform(navigator.platform)) {
|
||||
return false;
|
||||
}
|
||||
if (event.key !== "Home" && event.key !== "End") {
|
||||
return false;
|
||||
}
|
||||
if (event.altKey || event.metaKey || event.ctrlKey || event.isComposing) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const rootElement = editor.getRootElement();
|
||||
const selection = window.getSelection();
|
||||
const anchorNode = selection?.anchorNode;
|
||||
if (!rootElement || !selection || !anchorNode || !rootElement.contains(anchorNode)) {
|
||||
return false;
|
||||
}
|
||||
if (selection.rangeCount === 0 || typeof selection.modify !== "function") {
|
||||
return false;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
selection.modify(
|
||||
event.shiftKey ? "extend" : "move",
|
||||
event.key === "Home" ? "backward" : "forward",
|
||||
"lineboundary",
|
||||
);
|
||||
editor.update(() => {
|
||||
$setSelection($createRangeSelectionFromDom(selection, editor));
|
||||
});
|
||||
return true;
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
}, [editor]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerInlineTokenSelectionNormalizePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
@@ -1117,6 +1167,21 @@ function ComposerInlineTokenBackspacePlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerInlineTokenPastePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: $createComposerMentionNode,
|
||||
getExpandedAbsoluteOffsetForPoint,
|
||||
}),
|
||||
[editor],
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerSurroundSelectionPlugin(props: {
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
skills: ReadonlyArray<ServerProviderSkill>;
|
||||
@@ -1631,9 +1696,11 @@ function ComposerPromptEditorInner({
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerSurroundSelectionPlugin terminalContexts={terminalContexts} skills={skills} />
|
||||
<ComposerHomeEndKeyPlugin />
|
||||
<ComposerInlineTokenArrowPlugin />
|
||||
<ComposerInlineTokenSelectionNormalizePlugin />
|
||||
<ComposerInlineTokenBackspacePlugin />
|
||||
<ComposerInlineTokenPastePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
</ComposerTerminalContextActionsContext>
|
||||
|
||||
@@ -178,13 +178,19 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
interface DiffPanelProps {
|
||||
mode?: DiffPanelMode;
|
||||
composerDraftTarget: ScopedThreadRef | DraftId;
|
||||
initialGitScope: "branch" | "unstaged";
|
||||
}
|
||||
|
||||
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
|
||||
export default function DiffPanel({ mode = "inline", composerDraftTarget }: DiffPanelProps) {
|
||||
export default function DiffPanel({
|
||||
mode = "inline",
|
||||
composerDraftTarget,
|
||||
initialGitScope: initialGitScopeProp,
|
||||
}: DiffPanelProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const settings = useClientSettings();
|
||||
const [initialGitScope] = useState(initialGitScopeProp);
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
@@ -199,9 +205,6 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteRef(params),
|
||||
});
|
||||
const diffSelection = useDiffPanelStore((state) =>
|
||||
selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef),
|
||||
);
|
||||
const activeThreadId = routeThreadRef?.threadId ?? null;
|
||||
const activeThread = useThread(routeThreadRef);
|
||||
const activeProjectId = activeThread?.projectId ?? null;
|
||||
@@ -229,6 +232,13 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const diffSelection = useDiffPanelStore((state) =>
|
||||
selectThreadDiffPanelSelection(
|
||||
state.byThreadKey,
|
||||
routeThreadRef,
|
||||
initialGitScope === "unstaged",
|
||||
),
|
||||
);
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
|
||||
@@ -15,10 +15,12 @@ import {
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveSidebarThreadRowTransientProps,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortScopedProjectsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import {
|
||||
@@ -37,6 +39,51 @@ import {
|
||||
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
|
||||
describe("resolveSidebarThreadRowTransientProps", () => {
|
||||
it("only publishes rename state to the row being edited", () => {
|
||||
expect(
|
||||
resolveSidebarThreadRowTransientProps({
|
||||
threadKey: "thread-1",
|
||||
renamingThreadKey: "thread-1",
|
||||
renamingTitle: "Edited title",
|
||||
confirmingArchiveThreadKey: null,
|
||||
}),
|
||||
).toEqual({
|
||||
isRenaming: true,
|
||||
renamingTitle: "Edited title",
|
||||
isConfirmingArchive: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveSidebarThreadRowTransientProps({
|
||||
threadKey: "thread-2",
|
||||
renamingThreadKey: "thread-1",
|
||||
renamingTitle: "Edited title",
|
||||
confirmingArchiveThreadKey: null,
|
||||
}),
|
||||
).toEqual({
|
||||
isRenaming: false,
|
||||
renamingTitle: "",
|
||||
isConfirmingArchive: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("only publishes archive confirmation state to its target row", () => {
|
||||
expect(
|
||||
resolveSidebarThreadRowTransientProps({
|
||||
threadKey: "thread-2",
|
||||
renamingThreadKey: null,
|
||||
renamingTitle: "",
|
||||
confirmingArchiveThreadKey: "thread-2",
|
||||
}),
|
||||
).toEqual({
|
||||
isRenaming: false,
|
||||
renamingTitle: "",
|
||||
isConfirmingArchive: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarStageBadgeLabel", () => {
|
||||
it("returns Nightly for nightly primary server versions", () => {
|
||||
expect(
|
||||
@@ -1066,3 +1113,73 @@ describe("sortProjectsForSidebar", () => {
|
||||
expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortScopedProjectsForSidebar", () => {
|
||||
it("keeps identical project ids in different environments separate", () => {
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const sharedProjectId = ProjectId.make("shared-project");
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: sharedProjectId,
|
||||
title: "Local project",
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: sharedProjectId,
|
||||
title: "Remote project",
|
||||
}),
|
||||
];
|
||||
const threads = [
|
||||
makeThread({
|
||||
environmentId: localEnvironmentId,
|
||||
projectId: sharedProjectId,
|
||||
updatedAt: "2026-03-09T10:02:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
projectId: sharedProjectId,
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
|
||||
|
||||
expect(sorted.map((project) => project.title)).toEqual(["Remote project", "Local project"]);
|
||||
});
|
||||
|
||||
it("does not use archived threads as project activity", () => {
|
||||
const projects = [
|
||||
makeProject({
|
||||
id: ProjectId.make("project-visible"),
|
||||
title: "Visible project",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
id: ProjectId.make("project-archived"),
|
||||
title: "Archived-only project",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
const threads = [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-visible"),
|
||||
projectId: ProjectId.make("project-visible"),
|
||||
updatedAt: "2026-03-09T10:02:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-archived"),
|
||||
projectId: ProjectId.make("project-archived"),
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
archivedAt: "2026-03-09T10:11:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
|
||||
|
||||
expect(sorted.map((project) => project.title)).toEqual([
|
||||
"Visible project",
|
||||
"Archived-only project",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,25 @@ export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
|
||||
// nearby thread usually reuses an already-hot subscription.
|
||||
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
|
||||
export function resolveSidebarThreadRowTransientProps(input: {
|
||||
threadKey: string;
|
||||
renamingThreadKey: string | null;
|
||||
renamingTitle: string;
|
||||
confirmingArchiveThreadKey: string | null;
|
||||
}): {
|
||||
isRenaming: boolean;
|
||||
renamingTitle: string;
|
||||
isConfirmingArchive: boolean;
|
||||
} {
|
||||
const isRenaming = input.renamingThreadKey === input.threadKey;
|
||||
return {
|
||||
isRenaming,
|
||||
renamingTitle: isRenaming ? input.renamingTitle : "",
|
||||
isConfirmingArchive: input.confirmingArchiveThreadKey === input.threadKey,
|
||||
};
|
||||
}
|
||||
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -24,6 +43,16 @@ type SidebarProject = {
|
||||
updatedAt?: string | undefined;
|
||||
};
|
||||
|
||||
type ScopedSidebarProject = SidebarProject & {
|
||||
environmentId: string;
|
||||
};
|
||||
|
||||
type ScopedSidebarThread = ThreadSortInput & {
|
||||
environmentId: string;
|
||||
projectId: string;
|
||||
archivedAt: string | null;
|
||||
};
|
||||
|
||||
export type ThreadTraversalDirection = "previous" | "next";
|
||||
|
||||
export interface ThreadStatusPill {
|
||||
@@ -534,6 +563,25 @@ export function getProjectSortTimestamp(
|
||||
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
function sortProjectsByActivity<TProject extends SidebarProject>(
|
||||
projects: readonly TProject[],
|
||||
sortOrder: SidebarProjectSortOrder,
|
||||
getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
|
||||
compareTies: (left: TProject, right: TProject) => number,
|
||||
): TProject[] {
|
||||
if (sortOrder === "manual") {
|
||||
return [...projects];
|
||||
}
|
||||
|
||||
return [...projects].toSorted((left, right) => {
|
||||
const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
|
||||
const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
|
||||
const byTimestamp =
|
||||
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
|
||||
return byTimestamp || compareTies(left, right);
|
||||
});
|
||||
}
|
||||
|
||||
export function sortProjectsForSidebar<
|
||||
TProject extends SidebarProject,
|
||||
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
|
||||
@@ -542,10 +590,6 @@ export function sortProjectsForSidebar<
|
||||
threads: readonly TThread[],
|
||||
sortOrder: SidebarProjectSortOrder,
|
||||
): TProject[] {
|
||||
if (sortOrder === "manual") {
|
||||
return [...projects];
|
||||
}
|
||||
|
||||
const threadsByProjectId = new Map<string, TThread[]>();
|
||||
for (const thread of threads) {
|
||||
const existing = threadsByProjectId.get(thread.projectId) ?? [];
|
||||
@@ -553,20 +597,47 @@ export function sortProjectsForSidebar<
|
||||
threadsByProjectId.set(thread.projectId, existing);
|
||||
}
|
||||
|
||||
return [...projects].toSorted((left, right) => {
|
||||
const rightTimestamp = getProjectSortTimestamp(
|
||||
right,
|
||||
threadsByProjectId.get(right.id) ?? [],
|
||||
sortOrder,
|
||||
);
|
||||
const leftTimestamp = getProjectSortTimestamp(
|
||||
left,
|
||||
threadsByProjectId.get(left.id) ?? [],
|
||||
sortOrder,
|
||||
);
|
||||
const byTimestamp =
|
||||
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
|
||||
if (byTimestamp !== 0) return byTimestamp;
|
||||
return left.title.localeCompare(right.title) || left.id.localeCompare(right.id);
|
||||
});
|
||||
return sortProjectsByActivity(
|
||||
projects,
|
||||
sortOrder,
|
||||
(project) => threadsByProjectId.get(project.id) ?? [],
|
||||
(left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts the cross-environment project collection used by landing surfaces.
|
||||
* Project ids are only unique within an environment, and archived threads
|
||||
* must not make a project appear recently active.
|
||||
*/
|
||||
export function sortScopedProjectsForSidebar<
|
||||
TProject extends ScopedSidebarProject,
|
||||
TThread extends ScopedSidebarThread,
|
||||
>(
|
||||
projects: readonly TProject[],
|
||||
threads: readonly TThread[],
|
||||
sortOrder: SidebarProjectSortOrder,
|
||||
): TProject[] {
|
||||
const scopedKey = (environmentId: string, projectId: string) =>
|
||||
`${environmentId}\u0000${projectId}`;
|
||||
const threadsByProject = new Map<string, TThread[]>();
|
||||
for (const thread of threads) {
|
||||
if (thread.archivedAt !== null) {
|
||||
continue;
|
||||
}
|
||||
const key = scopedKey(thread.environmentId, thread.projectId);
|
||||
const existing = threadsByProject.get(key) ?? [];
|
||||
existing.push(thread);
|
||||
threadsByProject.set(key, existing);
|
||||
}
|
||||
|
||||
return sortProjectsByActivity(
|
||||
projects,
|
||||
sortOrder,
|
||||
(project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
|
||||
(left, right) =>
|
||||
left.title.localeCompare(right.title) ||
|
||||
left.environmentId.localeCompare(right.environmentId) ||
|
||||
left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
@@ -192,6 +192,7 @@ import {
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveSidebarThreadRowTransientProps,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
orderItemsByPreferredIds,
|
||||
@@ -324,13 +325,13 @@ interface SidebarThreadRowProps {
|
||||
isActive: boolean;
|
||||
jumpLabel: string | null;
|
||||
appSettingsConfirmThreadArchive: boolean;
|
||||
renamingThreadKey: string | null;
|
||||
isRenaming: boolean;
|
||||
renamingTitle: string;
|
||||
setRenamingTitle: (title: string) => void;
|
||||
startThreadRename: (threadKey: string, title: string) => void;
|
||||
renamingInputRef: React.RefObject<HTMLInputElement | null>;
|
||||
renamingCommittedRef: React.RefObject<boolean>;
|
||||
confirmingArchiveThreadKey: string | null;
|
||||
isConfirmingArchive: boolean;
|
||||
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
|
||||
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
|
||||
handleThreadClick: (
|
||||
@@ -361,13 +362,13 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
isActive,
|
||||
jumpLabel,
|
||||
appSettingsConfirmThreadArchive,
|
||||
renamingThreadKey,
|
||||
isRenaming,
|
||||
renamingTitle,
|
||||
setRenamingTitle,
|
||||
startThreadRename,
|
||||
renamingInputRef,
|
||||
renamingCommittedRef,
|
||||
confirmingArchiveThreadKey,
|
||||
isConfirmingArchive,
|
||||
setConfirmingArchiveThreadKey,
|
||||
confirmArchiveButtonRefs,
|
||||
handleThreadClick,
|
||||
@@ -468,8 +469,8 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
|
||||
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
|
||||
const threadMetaClassName = isConfirmingArchive
|
||||
const showArchiveConfirmation = isConfirmingArchive && !isThreadRunning;
|
||||
const threadMetaClassName = showArchiveConfirmation
|
||||
? "pointer-events-none opacity-0"
|
||||
: !isThreadRunning
|
||||
? "pointer-events-none transition-opacity duration-150 max-sm:pr-6 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
|
||||
@@ -502,7 +503,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
(event: React.MouseEvent) => {
|
||||
// Already renaming this row: a double-click on the row chrome (outside the
|
||||
// input) must not restart and discard the in-progress edit.
|
||||
if (renamingThreadKey === threadKey) return;
|
||||
if (isRenaming) return;
|
||||
// On mobile the first tap navigates and closes the sidebar sheet, so the
|
||||
// inline rename can't be shown. Renaming there stays on the context menu.
|
||||
if (isMobile) return;
|
||||
@@ -514,7 +515,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
event.preventDefault();
|
||||
startThreadRename(threadKey, thread.title);
|
||||
},
|
||||
[isMobile, renamingThreadKey, startThreadRename, threadKey, thread.title],
|
||||
[isMobile, isRenaming, startThreadRename, threadKey, thread.title],
|
||||
);
|
||||
const handleRowKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent) => {
|
||||
@@ -709,7 +710,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
</Tooltip>
|
||||
)}
|
||||
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
|
||||
{renamingThreadKey === threadKey ? (
|
||||
{isRenaming ? (
|
||||
<input
|
||||
ref={handleRenameInputRef}
|
||||
className="min-w-0 flex-1 truncate text-base sm:text-xs bg-transparent outline-none border border-ring rounded px-0.5"
|
||||
@@ -783,7 +784,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
isRemoteThread ? "max-sm:min-w-24" : "max-sm:min-w-20"
|
||||
}`}
|
||||
>
|
||||
{isConfirmingArchive ? (
|
||||
{showArchiveConfirmation ? (
|
||||
<button
|
||||
ref={handleConfirmArchiveRef}
|
||||
type="button"
|
||||
@@ -995,6 +996,12 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
|
||||
{shouldShowThreadPanel &&
|
||||
renderedThreads.map((thread) => {
|
||||
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
|
||||
const transientProps = resolveSidebarThreadRowTransientProps({
|
||||
threadKey,
|
||||
renamingThreadKey,
|
||||
renamingTitle,
|
||||
confirmingArchiveThreadKey,
|
||||
});
|
||||
return (
|
||||
<SidebarThreadRow
|
||||
key={threadKey}
|
||||
@@ -1004,13 +1011,13 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
|
||||
isActive={activeRouteThreadKey === threadKey}
|
||||
jumpLabel={threadJumpLabelByKey.get(threadKey) ?? null}
|
||||
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
|
||||
renamingThreadKey={renamingThreadKey}
|
||||
renamingTitle={renamingTitle}
|
||||
isRenaming={transientProps.isRenaming}
|
||||
renamingTitle={transientProps.renamingTitle}
|
||||
setRenamingTitle={setRenamingTitle}
|
||||
startThreadRename={startThreadRename}
|
||||
renamingInputRef={renamingInputRef}
|
||||
renamingCommittedRef={renamingCommittedRef}
|
||||
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
|
||||
isConfirmingArchive={transientProps.isConfirmingArchive}
|
||||
setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey}
|
||||
confirmArchiveButtonRefs={confirmArchiveButtonRefs}
|
||||
handleThreadClick={handleThreadClick}
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
detectComposerTrigger,
|
||||
expandCollapsedComposerCursor,
|
||||
replaceTextRange,
|
||||
shouldSubmitComposerOnEnter,
|
||||
} from "../../composer-logic";
|
||||
import { deriveComposerSendState, readFileAsDataUrl } from "../ChatView.logic";
|
||||
import {
|
||||
@@ -94,6 +95,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { toastManager } from "../ui/toast";
|
||||
import {
|
||||
BotIcon,
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
ListTodoIcon,
|
||||
PencilRulerIcon,
|
||||
@@ -272,16 +274,25 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
{runtimeModeOptions.map((mode) => {
|
||||
const option = runtimeModeConfig[mode];
|
||||
const OptionIcon = option.icon;
|
||||
const isSelected = props.runtimeMode === mode;
|
||||
return (
|
||||
<SelectItem key={mode} value={mode} className="min-w-64 py-2">
|
||||
<div className="grid min-w-0 gap-0.5">
|
||||
<span className="inline-flex items-center gap-1.5 font-medium text-foreground">
|
||||
<OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
{option.label}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-xs leading-4">
|
||||
{option.description}
|
||||
</span>
|
||||
<SelectItem key={mode} value={mode} hideIndicator className="min-w-64 py-2">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<div className="grid min-w-0 flex-1 gap-0.5">
|
||||
<span className="inline-flex items-center gap-1.5 font-medium text-foreground">
|
||||
<OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
{option.label}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-xs leading-4">
|
||||
{option.description}
|
||||
</span>
|
||||
</div>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"size-4 text-blue-400",
|
||||
isSelected ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</SelectItem>
|
||||
);
|
||||
@@ -389,7 +400,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
|
||||
export interface ChatComposerHandle {
|
||||
focusAtEnd: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
insertTextAtEnd: (text: string) => boolean;
|
||||
insertTextAtEnd: (text: string, options?: { ensureLeadingBoundary?: boolean }) => boolean;
|
||||
openModelPicker: () => void;
|
||||
toggleModelPicker: () => void;
|
||||
isModelPickerOpen: () => boolean;
|
||||
@@ -441,6 +452,8 @@ export interface ChatComposerProps {
|
||||
activeThread: Thread | undefined;
|
||||
isServerThread: boolean;
|
||||
isLocalDraftThread: boolean;
|
||||
forceExpandedOnMobile: boolean;
|
||||
projectSelectionRequired: boolean;
|
||||
|
||||
// Session phase
|
||||
phase: SessionPhase;
|
||||
@@ -552,6 +565,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
activeThread,
|
||||
isServerThread: _isServerThread,
|
||||
isLocalDraftThread: _isLocalDraftThread,
|
||||
forceExpandedOnMobile,
|
||||
projectSelectionRequired,
|
||||
phase,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
@@ -882,7 +897,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
|
||||
const [isComposerFocused, setIsComposerFocused] = useState(false);
|
||||
const isMobileViewport = useMediaQuery("max-sm");
|
||||
const isComposerCollapsedMobile = isMobileViewport && !isComposerFocused;
|
||||
const isComposerCollapsedMobile =
|
||||
isMobileViewport && !forceExpandedOnMobile && !isComposerFocused;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Refs
|
||||
@@ -1135,7 +1151,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
[activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers],
|
||||
);
|
||||
const collapsedComposerPrimaryActionDisabled =
|
||||
phase === "running" || isSendBusy || isConnecting || !composerSendState.hasSendableContent;
|
||||
phase === "running" ||
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
projectSelectionRequired ||
|
||||
!composerSendState.hasSendableContent;
|
||||
const collapsedComposerPrimaryActionLabel = "Send message";
|
||||
const showMobilePendingAnswerActions =
|
||||
isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null;
|
||||
@@ -1750,7 +1770,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (key === "Enter" && !event.shiftKey) {
|
||||
if (
|
||||
key === "Enter" &&
|
||||
shouldSubmitComposerOnEnter({ isMobileViewport, shiftKey: event.shiftKey })
|
||||
) {
|
||||
submitComposer();
|
||||
return true;
|
||||
}
|
||||
@@ -1918,18 +1941,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
focusAt: (cursor: number) => {
|
||||
composerEditorRef.current?.focusAt(cursor);
|
||||
},
|
||||
insertTextAtEnd: (text: string) => {
|
||||
insertTextAtEnd: (text: string, options?: { ensureLeadingBoundary?: boolean }) => {
|
||||
if (
|
||||
text.length === 0 ||
|
||||
isConnecting ||
|
||||
isComposerApprovalState ||
|
||||
pendingUserInputs.length > 0 ||
|
||||
projectSelectionRequired ||
|
||||
(environmentUnavailable !== null && activePendingProgress === null)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const rangeEnd = promptRef.current.length;
|
||||
return applyPromptReplacement(rangeEnd, rangeEnd, text);
|
||||
const prompt = promptRef.current;
|
||||
const needsLeadingSpace =
|
||||
(options?.ensureLeadingBoundary ?? false) && prompt.length > 0 && !/\s$/.test(prompt);
|
||||
return applyPromptReplacement(
|
||||
prompt.length,
|
||||
prompt.length,
|
||||
needsLeadingSpace ? ` ${text}` : text,
|
||||
);
|
||||
},
|
||||
openModelPicker: () => {
|
||||
setIsComposerModelPickerOpen(true);
|
||||
@@ -2024,6 +2054,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isConnecting,
|
||||
isComposerApprovalState,
|
||||
pendingUserInputs.length,
|
||||
projectSelectionRequired,
|
||||
environmentUnavailable,
|
||||
activePendingProgress,
|
||||
applyPromptReplacement,
|
||||
@@ -2061,9 +2092,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
ref={composerSurfaceRef}
|
||||
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
|
||||
className={cn(
|
||||
"chat-composer-glass rounded-[20px] border transition-colors duration-200 has-focus-visible:border-ring/45",
|
||||
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
|
||||
environmentUnavailable ? "opacity-75" : null,
|
||||
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
onFocusCapture={(event) => {
|
||||
@@ -2175,7 +2206,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
promptHasText={false}
|
||||
isSendBusy={isSendBusy}
|
||||
isConnecting={isConnecting}
|
||||
isEnvironmentUnavailable={environmentUnavailable !== null}
|
||||
isEnvironmentUnavailable={
|
||||
environmentUnavailable !== null || projectSelectionRequired
|
||||
}
|
||||
isPreparingWorktree={false}
|
||||
hasSendableContent={false}
|
||||
preserveComposerFocusOnPointerDown
|
||||
@@ -2409,17 +2442,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
? "Type your own answer, or leave this blank to use the selected option"
|
||||
: showPlanFollowUpPrompt && activeProposedPlan
|
||||
? "Add feedback to refine the plan, or leave this blank to implement it"
|
||||
: environmentUnavailable
|
||||
? `${environmentUnavailable.label}: ${connectionStatusText(
|
||||
environmentUnavailable.connection,
|
||||
)}`
|
||||
: phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
: projectSelectionRequired
|
||||
? "Choose a project above to start a thread"
|
||||
: environmentUnavailable
|
||||
? `${environmentUnavailable.label}: ${connectionStatusText(
|
||||
environmentUnavailable.connection,
|
||||
)}`
|
||||
: phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
}
|
||||
disabled={
|
||||
isConnecting ||
|
||||
isComposerApprovalState ||
|
||||
projectSelectionRequired ||
|
||||
(environmentUnavailable !== null && activePendingProgress === null)
|
||||
}
|
||||
/>
|
||||
@@ -2436,7 +2472,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
promptHasText={false}
|
||||
isSendBusy={isSendBusy}
|
||||
isConnecting={isConnecting}
|
||||
isEnvironmentUnavailable={environmentUnavailable !== null}
|
||||
isEnvironmentUnavailable={
|
||||
environmentUnavailable !== null || projectSelectionRequired
|
||||
}
|
||||
isPreparingWorktree={false}
|
||||
hasSendableContent={false}
|
||||
preserveComposerFocusOnPointerDown
|
||||
@@ -2547,7 +2585,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
promptHasText={prompt.trim().length > 0}
|
||||
isSendBusy={isSendBusy}
|
||||
isConnecting={isConnecting}
|
||||
isEnvironmentUnavailable={environmentUnavailable !== null}
|
||||
isEnvironmentUnavailable={
|
||||
environmentUnavailable !== null || projectSelectionRequired
|
||||
}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
hasSendableContent={composerSendState.hasSendableContent}
|
||||
preserveComposerFocusOnPointerDown={isMobileViewport}
|
||||
|
||||
@@ -190,7 +190,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
<div className="min-w-0 flex-1 flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium">{option.label}</span>
|
||||
{option.description && option.description !== option.label ? (
|
||||
<span className="text-xs text-muted-foreground/50">{option.description}</span>
|
||||
<span className="text-xs text-muted-foreground">{option.description}</span>
|
||||
) : null}
|
||||
</div>
|
||||
{isSelected ? (
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { ScopedProjectRef } from "@t3tools/contracts";
|
||||
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { FolderPlusIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useOpenAddProjectCommandPalette } from "~/commandPaletteContext";
|
||||
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
|
||||
import { useProjects, useThreadShells } from "~/state/entities";
|
||||
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
|
||||
import {
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
|
||||
interface DraftHeroHeadlineProps {
|
||||
readonly activeProjectRef: ScopedProjectRef | null;
|
||||
readonly activeProjectTitle: string | null;
|
||||
}
|
||||
|
||||
export function DraftHeroHeadline({
|
||||
activeProjectRef,
|
||||
activeProjectTitle,
|
||||
}: DraftHeroHeadlineProps) {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const handleNewThread = useNewThreadHandler();
|
||||
const openAddProject = useOpenAddProjectCommandPalette();
|
||||
|
||||
const orderedProjects = useMemo(
|
||||
() => sortScopedProjectsForSidebar(projects, threads, "updated_at"),
|
||||
[projects, threads],
|
||||
);
|
||||
const projectByKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
orderedProjects.map(
|
||||
(project) =>
|
||||
[
|
||||
scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
|
||||
project,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
[orderedProjects],
|
||||
);
|
||||
const activeProjectKey = activeProjectRef === null ? "" : scopedProjectKey(activeProjectRef);
|
||||
const hasResolvedProject = activeProjectTitle !== null;
|
||||
const canChooseProject = orderedProjects.length > 0;
|
||||
const shouldShowProjectMenu = canChooseProject;
|
||||
|
||||
const projectSelector = shouldShowProjectMenu ? (
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
|
||||
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-foreground underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{activeProjectTitle ?? "Choose a project"}
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">
|
||||
<MenuRadioGroup
|
||||
value={activeProjectKey}
|
||||
onValueChange={(value) => {
|
||||
const project = projectByKey.get(value as string);
|
||||
if (!project || value === activeProjectKey) {
|
||||
return;
|
||||
}
|
||||
void handleNewThread(scopeProjectRef(project.environmentId, project.id), {
|
||||
replace: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
{orderedProjects.map((project) => {
|
||||
const key = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
|
||||
return (
|
||||
<MenuRadioItem key={key} value={key} closeOnClick>
|
||||
<span className="min-w-0 truncate">{project.title}</span>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
})}
|
||||
</MenuRadioGroup>
|
||||
<MenuSeparator />
|
||||
<MenuItem onClick={openAddProject}>
|
||||
<FolderPlusIcon />
|
||||
New project
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={openAddProject}
|
||||
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-muted-foreground/60 underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{activeProjectTitle ?? "Add a project"}
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<h1 className="mx-auto w-full max-w-5xl text-center font-normal text-3xl text-foreground tracking-tight sm:text-5xl">
|
||||
{hasResolvedProject ? (
|
||||
<>What should we build in {projectSelector}?</>
|
||||
) : canChooseProject ? (
|
||||
<>{projectSelector} to start</>
|
||||
) : (
|
||||
<>Add a project to start</>
|
||||
)}
|
||||
</h1>
|
||||
);
|
||||
}
|
||||
@@ -179,6 +179,7 @@ interface MessagesTimelineProps {
|
||||
contentInsetEndAdjustment: number;
|
||||
onIsAtEndChange: (isAtEnd: boolean) => void;
|
||||
onManualNavigation: () => void;
|
||||
hideEmptyPlaceholder?: boolean;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -212,6 +213,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
contentInsetEndAdjustment,
|
||||
onIsAtEndChange,
|
||||
onManualNavigation,
|
||||
hideEmptyPlaceholder = false,
|
||||
}: MessagesTimelineProps) {
|
||||
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
|
||||
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
|
||||
@@ -458,6 +460,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
);
|
||||
|
||||
if (rows.length === 0 && !isWorking) {
|
||||
if (hideEmptyPlaceholder) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground/30">
|
||||
|
||||
@@ -31,111 +31,138 @@ import {
|
||||
RustRoverIcon,
|
||||
WebStormIcon,
|
||||
} from "../JetBrainsIcons";
|
||||
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { shellEnvironment } from "~/state/shell";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
|
||||
type OpenInOption = {
|
||||
label: string;
|
||||
Icon: Icon;
|
||||
value: EditorId;
|
||||
kind: "brand" | "generic";
|
||||
};
|
||||
|
||||
const resolveOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
|
||||
const baseOptions: ReadonlyArray<{ label: string; Icon: Icon; value: EditorId }> = [
|
||||
const baseOptions: ReadonlyArray<OpenInOption> = [
|
||||
{
|
||||
label: "Cursor",
|
||||
Icon: CursorIcon,
|
||||
value: "cursor",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "Trae",
|
||||
Icon: TraeIcon,
|
||||
value: "trae",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "Kiro",
|
||||
Icon: KiroIcon,
|
||||
value: "kiro",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "VS Code",
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscode",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "VS Code Insiders",
|
||||
Icon: VisualStudioCodeInsiders,
|
||||
value: "vscode-insiders",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "VSCodium",
|
||||
Icon: VSCodium,
|
||||
value: "vscodium",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "Zed",
|
||||
Icon: Zed,
|
||||
value: "zed",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "Antigravity",
|
||||
Icon: AntigravityIcon,
|
||||
value: "antigravity",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "IntelliJ IDEA",
|
||||
Icon: IntelliJIdeaIcon,
|
||||
value: "idea",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "Aqua",
|
||||
Icon: AquaIcon,
|
||||
value: "aqua",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "CLion",
|
||||
Icon: CLionIcon,
|
||||
value: "clion",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "DataGrip",
|
||||
Icon: DataGripIcon,
|
||||
value: "datagrip",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "DataSpell",
|
||||
Icon: DataSpellIcon,
|
||||
value: "dataspell",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "GoLand",
|
||||
Icon: GoLandIcon,
|
||||
value: "goland",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "PhpStorm",
|
||||
Icon: PhpStormIcon,
|
||||
value: "phpstorm",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "PyCharm",
|
||||
Icon: PyCharmIcon,
|
||||
value: "pycharm",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "Rider",
|
||||
Icon: RiderIcon,
|
||||
value: "rider",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "RubyMine",
|
||||
Icon: RubyMineIcon,
|
||||
value: "rubymine",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "RustRover",
|
||||
Icon: RustRoverIcon,
|
||||
value: "rustrover",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: "WebStorm",
|
||||
Icon: WebStormIcon,
|
||||
value: "webstorm",
|
||||
kind: "brand",
|
||||
},
|
||||
{
|
||||
label: isMacPlatform(platform)
|
||||
@@ -145,12 +172,17 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
: "Files",
|
||||
Icon: FolderClosedIcon,
|
||||
value: "file-manager",
|
||||
kind: "generic",
|
||||
},
|
||||
];
|
||||
const availableEditorSet = new Set(availableEditors);
|
||||
return baseOptions.filter((option) => availableEditorSet.has(option.value));
|
||||
};
|
||||
|
||||
function getOpenInIconClass(kind: OpenInOption["kind"]) {
|
||||
return cn(kind === "brand" ? "text-foreground opacity-100" : "text-muted-foreground");
|
||||
}
|
||||
|
||||
export const OpenInPicker = memo(function OpenInPicker({
|
||||
environmentId,
|
||||
keybindings,
|
||||
@@ -233,7 +265,12 @@ export const OpenInPicker = memo(function OpenInPicker({
|
||||
disabled={!preferredEditor || !openInCwd}
|
||||
onClick={() => openInEditor(preferredEditor)}
|
||||
>
|
||||
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
|
||||
{primaryOption?.Icon && (
|
||||
<primaryOption.Icon
|
||||
aria-hidden="true"
|
||||
className={cn("size-3.5", getOpenInIconClass(primaryOption.kind))}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
className={
|
||||
compact
|
||||
@@ -259,9 +296,9 @@ export const OpenInPicker = memo(function OpenInPicker({
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
{options.length === 0 && <MenuItem disabled>No installed editors found</MenuItem>}
|
||||
{options.map(({ label, Icon, value }) => (
|
||||
{options.map(({ label, Icon, value, kind }) => (
|
||||
<MenuItem key={value} onClick={() => openInEditor(value)}>
|
||||
<Icon aria-hidden="true" className="text-muted-foreground" />
|
||||
<Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
|
||||
{label}
|
||||
{value === preferredEditor && openFavoriteEditorShortcutLabel && (
|
||||
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { CheckIcon, ChevronDownIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
|
||||
import { getProviderModelCapabilities } from "../../providerModels";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
|
||||
type ProviderOptions = ReadonlyArray<ProviderOptionSelection>;
|
||||
|
||||
@@ -46,6 +47,17 @@ type TraitsPersistence =
|
||||
|
||||
const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
|
||||
|
||||
function DefaultBadge() {
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="inline-flex h-4 w-fit min-w-0 items-center justify-center gap-0 border-border/70 bg-muted/60 px-1.5 py-0 font-semibold text-[10px] text-muted-foreground leading-none sm:h-4"
|
||||
>
|
||||
Default
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
function replaceDescriptorCurrentValue(
|
||||
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
|
||||
descriptorId: string,
|
||||
@@ -285,62 +297,90 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
|
||||
return (
|
||||
<>
|
||||
{selectDescriptors.map((descriptor, index) => (
|
||||
<div key={descriptor.id}>
|
||||
{index > 0 ? <MenuDivider /> : null}
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">
|
||||
{descriptor.label}
|
||||
</div>
|
||||
{ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id ? (
|
||||
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
|
||||
Your prompt contains "ultrathink" in the text. Remove it to change this
|
||||
option.
|
||||
{selectDescriptors.map((descriptor, index) => {
|
||||
const selectedValue =
|
||||
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
|
||||
? "ultrathink"
|
||||
: (getDescriptorStringValue(descriptor) ?? "");
|
||||
|
||||
return (
|
||||
<div key={descriptor.id}>
|
||||
{index > 0 ? <MenuDivider /> : null}
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">
|
||||
{descriptor.label}
|
||||
</div>
|
||||
) : null}
|
||||
<MenuRadioGroup
|
||||
value={
|
||||
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
|
||||
? "ultrathink"
|
||||
: (getDescriptorStringValue(descriptor) ?? "")
|
||||
}
|
||||
onValueChange={(value) => handleSelectChange(descriptor, value)}
|
||||
>
|
||||
{descriptor.options.map((option) => (
|
||||
<MenuRadioItem
|
||||
key={option.id}
|
||||
value={option.id}
|
||||
disabled={ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id}
|
||||
>
|
||||
{option.label}
|
||||
{option.isDefault ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</div>
|
||||
))}
|
||||
{booleanDescriptors.map((descriptor, index) => (
|
||||
<div key={descriptor.id}>
|
||||
{index > 0 || selectDescriptors.length > 0 ? <MenuDivider /> : null}
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
{descriptor.label}
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={descriptor.currentValue === true ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
updateDescriptors(
|
||||
replaceDescriptorCurrentValue(descriptors, descriptor.id, value === "on"),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="on">On</MenuRadioItem>
|
||||
<MenuRadioItem value="off">Off</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</div>
|
||||
))}
|
||||
{ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id ? (
|
||||
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
|
||||
Your prompt contains "ultrathink" in the text. Remove it to change this
|
||||
option.
|
||||
</div>
|
||||
) : null}
|
||||
<MenuRadioGroup
|
||||
value={selectedValue}
|
||||
onValueChange={(value) => handleSelectChange(descriptor, value)}
|
||||
>
|
||||
{descriptor.options.map((option) => (
|
||||
<MenuRadioItem
|
||||
key={option.id}
|
||||
value={option.id}
|
||||
hideIndicator
|
||||
disabled={ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id}
|
||||
>
|
||||
<span className="flex w-full min-w-0 items-center justify-between gap-3">
|
||||
<span className="min-w-0 truncate">
|
||||
{option.label}
|
||||
{option.isDefault ? (
|
||||
<>
|
||||
{" "}
|
||||
<DefaultBadge />
|
||||
</>
|
||||
) : null}
|
||||
</span>
|
||||
{option.id === selectedValue ? (
|
||||
<CheckIcon className="size-3.5 shrink-0 text-blue-400" />
|
||||
) : null}
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{booleanDescriptors.map((descriptor, index) => {
|
||||
const selectedValue = descriptor.currentValue === true ? "on" : "off";
|
||||
|
||||
return (
|
||||
<div key={descriptor.id}>
|
||||
{index > 0 || selectDescriptors.length > 0 ? <MenuDivider /> : null}
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
{descriptor.label}
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={selectedValue}
|
||||
onValueChange={(value) => {
|
||||
updateDescriptors(
|
||||
replaceDescriptorCurrentValue(descriptors, descriptor.id, value === "on"),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{(["on", "off"] as const).map((value) => (
|
||||
<MenuRadioItem key={value} value={value} hideIndicator>
|
||||
<span className="flex w-full min-w-0 items-center justify-between gap-3">
|
||||
<span>{value === "on" ? "On" : "Off"}</span>
|
||||
{value === selectedValue ? (
|
||||
<CheckIcon className="size-3.5 shrink-0 text-blue-400" />
|
||||
) : null}
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
DRAFT_HERO_TRANSITION_ANIMATION_ID,
|
||||
runMobileComposerTransition,
|
||||
waitForDraftHeroTransition,
|
||||
} from "./draftHeroTransition";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("waitForDraftHeroTransition", () => {
|
||||
it("waits for active draft hero animations and ignores unrelated animations", async () => {
|
||||
let finishTransition: (() => void) | undefined;
|
||||
const transitionFinished = new Promise<void>((resolve) => {
|
||||
finishTransition = resolve;
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
getAnimations: () => [
|
||||
{ id: "unrelated-animation", finished: new Promise<void>(() => undefined) },
|
||||
{ id: DRAFT_HERO_TRANSITION_ANIMATION_ID, finished: transitionFinished },
|
||||
],
|
||||
});
|
||||
|
||||
let handoffComplete = false;
|
||||
const handoff = waitForDraftHeroTransition().then(() => {
|
||||
handoffComplete = true;
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(handoffComplete).toBe(false);
|
||||
|
||||
finishTransition?.();
|
||||
await handoff;
|
||||
expect(handoffComplete).toBe(true);
|
||||
});
|
||||
|
||||
it("allows the handoff when an active transition is cancelled", async () => {
|
||||
vi.stubGlobal("document", {
|
||||
getAnimations: () => [
|
||||
{
|
||||
id: DRAFT_HERO_TRANSITION_ANIMATION_ID,
|
||||
finished: Promise.reject(new Error("cancelled")),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(waitForDraftHeroTransition()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("runMobileComposerTransition", () => {
|
||||
it("keeps the route handoff waiting while the mobile composer morph is active", async () => {
|
||||
let finishTransition: (() => void) | undefined;
|
||||
const transitionFinished = new Promise<void>((resolve) => {
|
||||
finishTransition = resolve;
|
||||
});
|
||||
const dataset: Record<string, string> = {};
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: { dataset },
|
||||
getAnimations: () => [],
|
||||
startViewTransition: (update: () => void | Promise<void>) => {
|
||||
void update();
|
||||
return { finished: transitionFinished };
|
||||
},
|
||||
});
|
||||
vi.stubGlobal("window", {
|
||||
matchMedia: (query: string) => ({ matches: query === "(max-width: 639px)" }),
|
||||
});
|
||||
|
||||
const transition = runMobileComposerTransition(() => undefined);
|
||||
await Promise.resolve();
|
||||
|
||||
let handoffComplete = false;
|
||||
const handoff = waitForDraftHeroTransition().then(() => {
|
||||
handoffComplete = true;
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(handoffComplete).toBe(false);
|
||||
|
||||
finishTransition?.();
|
||||
await Promise.all([transition, handoff]);
|
||||
expect(handoffComplete).toBe(true);
|
||||
});
|
||||
|
||||
it("uses a scoped view transition on mobile", async () => {
|
||||
const dataset: Record<string, string> = {};
|
||||
const startViewTransition = vi.fn((update: () => void | Promise<void>) => ({
|
||||
finished: Promise.resolve(update()).then(() => undefined),
|
||||
}));
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: { dataset },
|
||||
startViewTransition,
|
||||
});
|
||||
vi.stubGlobal("window", {
|
||||
matchMedia: (query: string) => ({ matches: query === "(max-width: 639px)" }),
|
||||
});
|
||||
const update = vi.fn();
|
||||
|
||||
await runMobileComposerTransition(update);
|
||||
|
||||
expect(startViewTransition).toHaveBeenCalledOnce();
|
||||
expect(update).toHaveBeenCalledOnce();
|
||||
expect(dataset).not.toHaveProperty("mobileComposerRouteTransition");
|
||||
});
|
||||
|
||||
it("updates without a view transition when reduced motion is preferred", async () => {
|
||||
const startViewTransition = vi.fn();
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: { dataset: {} },
|
||||
startViewTransition,
|
||||
});
|
||||
vi.stubGlobal("window", {
|
||||
matchMedia: () => ({ matches: true }),
|
||||
});
|
||||
const update = vi.fn();
|
||||
|
||||
await runMobileComposerTransition(update);
|
||||
|
||||
expect(startViewTransition).not.toHaveBeenCalled();
|
||||
expect(update).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
export const DRAFT_HERO_TRANSITION_ANIMATION_ID = "t3-draft-hero-transition";
|
||||
export const DRAFT_HERO_TRANSITION_DURATION_MS = 180;
|
||||
export const DRAFT_HERO_TRANSITION_EASING = "cubic-bezier(0.4, 0, 0.2, 1)";
|
||||
export const MOBILE_COMPOSER_VIEW_TRANSITION_NAME = "t3-mobile-composer";
|
||||
export const MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME = "t3-mobile-draft-headline";
|
||||
|
||||
type ComposerViewTransition = {
|
||||
readonly finished: Promise<void>;
|
||||
};
|
||||
|
||||
let activeMobileComposerTransition: Promise<void> | null = null;
|
||||
|
||||
type ComposerViewTransitionDocument = Document & {
|
||||
startViewTransition?: (update: () => void | Promise<void>) => ComposerViewTransition;
|
||||
};
|
||||
|
||||
export async function waitForDraftHeroTransition(): Promise<void> {
|
||||
const mobileComposerTransition = activeMobileComposerTransition;
|
||||
if (typeof document === "undefined" || typeof document.getAnimations !== "function") {
|
||||
await mobileComposerTransition;
|
||||
return;
|
||||
}
|
||||
|
||||
const activeTransitions = document
|
||||
.getAnimations()
|
||||
.filter((animation) => animation.id === DRAFT_HERO_TRANSITION_ANIMATION_ID);
|
||||
|
||||
await Promise.all([
|
||||
mobileComposerTransition,
|
||||
...activeTransitions.map(async (animation) => {
|
||||
try {
|
||||
await animation.finished;
|
||||
} catch {
|
||||
// A cancelled transition is already safe to hand off.
|
||||
}
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
export async function runMobileComposerTransition(
|
||||
update: () => void | Promise<void>,
|
||||
): Promise<void> {
|
||||
if (typeof document === "undefined" || typeof window === "undefined") {
|
||||
await update();
|
||||
return;
|
||||
}
|
||||
|
||||
const transitionDocument = document as ComposerViewTransitionDocument;
|
||||
const mobileViewport = window.matchMedia?.("(max-width: 639px)").matches ?? false;
|
||||
const prefersReducedMotion =
|
||||
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
|
||||
if (!mobileViewport || prefersReducedMotion || !transitionDocument.startViewTransition) {
|
||||
await update();
|
||||
return;
|
||||
}
|
||||
|
||||
let updateStarted = false;
|
||||
const runUpdate = async () => {
|
||||
if (updateStarted) return;
|
||||
updateStarted = true;
|
||||
await update();
|
||||
};
|
||||
let transitionFinished: Promise<void> | null = null;
|
||||
transitionDocument.documentElement.dataset.mobileComposerRouteTransition = "true";
|
||||
try {
|
||||
const transition = transitionDocument.startViewTransition(runUpdate);
|
||||
transitionFinished = transition.finished.catch(() => undefined);
|
||||
activeMobileComposerTransition = transitionFinished;
|
||||
try {
|
||||
await transition.finished;
|
||||
} catch {
|
||||
await runUpdate();
|
||||
}
|
||||
} catch {
|
||||
await runUpdate();
|
||||
} finally {
|
||||
if (activeMobileComposerTransition === transitionFinished) {
|
||||
activeMobileComposerTransition = null;
|
||||
}
|
||||
delete transitionDocument.documentElement.dataset.mobileComposerRouteTransition;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
|
||||
import {
|
||||
$createLineBreakNode,
|
||||
$createTextNode,
|
||||
$getRoot,
|
||||
$getSelection,
|
||||
$isRangeSelection,
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
PASTE_COMMAND,
|
||||
type LexicalEditor,
|
||||
type LexicalNode,
|
||||
} from "lexical";
|
||||
|
||||
interface ComposerInlineTokenPasteOptions {
|
||||
createMentionNode: (path: string) => LexicalNode;
|
||||
getExpandedAbsoluteOffsetForPoint: (node: LexicalNode, pointOffset: number) => number;
|
||||
}
|
||||
|
||||
export function registerComposerInlineTokenPaste(
|
||||
editor: LexicalEditor,
|
||||
options: ComposerInlineTokenPasteOptions,
|
||||
): () => void {
|
||||
return editor.registerCommand(
|
||||
PASTE_COMMAND,
|
||||
(event) => {
|
||||
if (!(event instanceof ClipboardEvent) || event.clipboardData === null) {
|
||||
return false;
|
||||
}
|
||||
if (event.clipboardData.files.length > 0) {
|
||||
return false;
|
||||
}
|
||||
const text = event.clipboardData.getData("text/plain");
|
||||
if (text.length === 0) {
|
||||
return false;
|
||||
}
|
||||
// Token grammar requires trailing whitespace; a virtual newline lets a
|
||||
// mention at the very end of the pasted text still parse.
|
||||
const mentions = collectComposerInlineTokens(`${text}\n`).filter(
|
||||
(token) => token.type === "mention" && token.end <= text.length,
|
||||
);
|
||||
if (mentions.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Lexical command listeners already run inside an editor update. Starting
|
||||
// a nested update here queues the mention insertion until after this
|
||||
// listener returns, which lets the plain-text paste handler run as well.
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) {
|
||||
return false;
|
||||
}
|
||||
const nodes: LexicalNode[] = [];
|
||||
const appendText = (value: string) => {
|
||||
const lines = value.split("\n");
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
const line = lines[index] ?? "";
|
||||
if (line.length > 0) {
|
||||
nodes.push($createTextNode(line));
|
||||
}
|
||||
if (index < lines.length - 1) {
|
||||
nodes.push($createLineBreakNode());
|
||||
}
|
||||
}
|
||||
};
|
||||
const firstMention = mentions[0];
|
||||
if (firstMention && firstMention.start === 0) {
|
||||
const startPoint = selection.isBackward() ? selection.focus : selection.anchor;
|
||||
const insertionOffset = options.getExpandedAbsoluteOffsetForPoint(
|
||||
startPoint.getNode(),
|
||||
startPoint.offset,
|
||||
);
|
||||
const precedingChar = $getRoot()
|
||||
.getTextContent()
|
||||
.slice(insertionOffset - 1, insertionOffset);
|
||||
if (precedingChar.length > 0 && !/\s/.test(precedingChar)) {
|
||||
nodes.push($createTextNode(" "));
|
||||
}
|
||||
}
|
||||
let cursor = 0;
|
||||
for (const mention of mentions) {
|
||||
if (mention.start < cursor) {
|
||||
continue;
|
||||
}
|
||||
if (mention.start > cursor) {
|
||||
appendText(text.slice(cursor, mention.start));
|
||||
}
|
||||
nodes.push(options.createMentionNode(mention.value));
|
||||
cursor = mention.end;
|
||||
}
|
||||
if (cursor < text.length) {
|
||||
appendText(text.slice(cursor));
|
||||
} else {
|
||||
// Keep the serialized prompt valid: mention tokens need trailing
|
||||
// whitespace, so a paste ending in a mention gets the same
|
||||
// trailing space the autocomplete inserts.
|
||||
nodes.push($createTextNode(" "));
|
||||
}
|
||||
selection.insertNodes(nodes);
|
||||
event.preventDefault();
|
||||
return true;
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,19 @@
|
||||
import type {
|
||||
ContextMenuItem as TreeContextMenuItem,
|
||||
ContextMenuOpenContext as TreeContextMenuOpenContext,
|
||||
} from "@pierre/trees";
|
||||
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
|
||||
import { FileTree, useFileTree } from "@pierre/trees/react";
|
||||
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
|
||||
import { RefreshCw, Search } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import { toastManager } from "~/components/ui/toast";
|
||||
import { useComposerHandleContext } from "~/composerHandleContext";
|
||||
import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useTheme } from "~/hooks/useTheme";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { T3_PIERRE_ICONS } from "~/pierre-icons";
|
||||
|
||||
import { useProjectEntriesQuery } from "./projectFilesQueryState";
|
||||
@@ -39,6 +48,7 @@ export default function FileBrowserPanel({
|
||||
onOpenFile,
|
||||
}: FileBrowserPanelProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const composerRef = useComposerHandleContext();
|
||||
const entriesQuery = useProjectEntriesQuery(environmentId, cwd);
|
||||
const entries = entriesQuery.data?.entries ?? [];
|
||||
const entryKinds = useMemo(
|
||||
@@ -49,7 +59,93 @@ export default function FileBrowserPanel({
|
||||
const treePaths = useMemo(() => entries.map(treePath), [entries]);
|
||||
const previousTreePathsRef = useRef<readonly string[]>([]);
|
||||
|
||||
// The tree renders rows in shadow DOM and its anchor rect is unreliable, so
|
||||
// capture the right-click position ourselves; contextmenu is a composed
|
||||
// event, so a capture-phase listener sees it with viewport coordinates.
|
||||
const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null);
|
||||
useEffect(() => {
|
||||
const capturePointer = (event: MouseEvent) => {
|
||||
contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
|
||||
};
|
||||
document.addEventListener("contextmenu", capturePointer, true);
|
||||
return () => document.removeEventListener("contextmenu", capturePointer, true);
|
||||
}, []);
|
||||
|
||||
const showEntryContextMenu = async (
|
||||
item: TreeContextMenuItem,
|
||||
context: TreeContextMenuOpenContext,
|
||||
) => {
|
||||
const api = readLocalApi();
|
||||
if (!api) {
|
||||
context.close();
|
||||
return;
|
||||
}
|
||||
const relativePath = item.path.replace(/\/$/, "");
|
||||
const mention = serializeComposerFileLink(relativePath);
|
||||
const pointer = contextMenuPointerRef.current;
|
||||
const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
|
||||
const anchorRect = context.anchorElement.getBoundingClientRect();
|
||||
const position = pointerIsFresh
|
||||
? { x: pointer.x, y: pointer.y }
|
||||
: { x: anchorRect.left, y: anchorRect.bottom };
|
||||
try {
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "copy-mention", label: "Copy mention" },
|
||||
{ id: "add-to-chat", label: "Add to chat" },
|
||||
],
|
||||
position,
|
||||
);
|
||||
if (clicked === "copy-mention") {
|
||||
try {
|
||||
await writeTextToClipboard(mention);
|
||||
toastManager.add({ type: "success", title: "Mention copied", description: relativePath });
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to copy mention",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (clicked === "add-to-chat") {
|
||||
const composer = composerRef?.current;
|
||||
if (!composer) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to add to chat",
|
||||
description: "Open a chat for this project and try again.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
|
||||
if (!inserted) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to add to chat",
|
||||
description: "The chat isn't ready to accept input right now.",
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
context.close();
|
||||
}
|
||||
};
|
||||
const showEntryContextMenuRef = useRef(showEntryContextMenu);
|
||||
useEffect(() => {
|
||||
showEntryContextMenuRef.current = showEntryContextMenu;
|
||||
});
|
||||
|
||||
const { model } = useFileTree({
|
||||
composition: {
|
||||
contextMenu: {
|
||||
triggerMode: "right-click",
|
||||
onOpen: (item, context) => {
|
||||
void showEntryContextMenuRef.current(item, context);
|
||||
},
|
||||
},
|
||||
},
|
||||
density: "compact",
|
||||
fileTreeSearchMode: "hide-non-matches",
|
||||
flattenEmptyDirectories: true,
|
||||
|
||||
@@ -17,7 +17,7 @@ interface Props {
|
||||
export function PreviewUnreachable({ url, code, description, onReload }: Props) {
|
||||
const [showDetails, setShowDetails] = useState(false);
|
||||
const host = safeHost(url) ?? url;
|
||||
const friendly = describePreviewError(code, description);
|
||||
const friendly = describePreviewError(description);
|
||||
const errorLabel = description.length > 0 ? description : `ERR_${Math.abs(code) || "FAILED"}`;
|
||||
|
||||
return (
|
||||
|
||||
@@ -2,11 +2,11 @@ import { PREVIEW_ERROR_CODE_MESSAGES } from "./previewConstants";
|
||||
|
||||
/**
|
||||
* Resolve a friendly description for a Chromium / network error. Falls back
|
||||
* to the description string passed in when the code isn't in our table.
|
||||
* to the description string passed in when it isn't in our table.
|
||||
*/
|
||||
export function describePreviewError(code: number, description: string): string {
|
||||
export function describePreviewError(description: string): string {
|
||||
const friendly = PREVIEW_ERROR_CODE_MESSAGES[description];
|
||||
if (friendly) return friendly;
|
||||
if (description.length > 0) return description;
|
||||
return `Network error (${code})`;
|
||||
return "Network error";
|
||||
}
|
||||
@@ -1461,22 +1461,34 @@ function SavedBackendListRow({
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isConnecting || removingEnvironmentId === environmentId}
|
||||
onClick={() =>
|
||||
void (isConnected ? onRemove(environmentId) : onConnect(environmentId))
|
||||
}
|
||||
>
|
||||
{isConnected
|
||||
? removingEnvironmentId === environmentId
|
||||
? "Disconnecting…"
|
||||
: "Disconnect"
|
||||
: isConnecting
|
||||
? "Connecting…"
|
||||
: "Connect"}
|
||||
</Button>
|
||||
<>
|
||||
{!isConnected ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={removingEnvironmentId === environmentId}
|
||||
onClick={() => void onRemove(environmentId)}
|
||||
>
|
||||
{removingEnvironmentId === environmentId ? "Removing…" : "Remove"}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isConnecting || removingEnvironmentId === environmentId}
|
||||
onClick={() =>
|
||||
void (isConnected ? onRemove(environmentId) : onConnect(environmentId))
|
||||
}
|
||||
>
|
||||
{isConnected
|
||||
? removingEnvironmentId === environmentId
|
||||
? "Disconnecting…"
|
||||
: "Disconnect"
|
||||
: isConnecting
|
||||
? "Connecting…"
|
||||
: "Connect"}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -23,7 +23,7 @@ import * as Option from "effect/Option";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
|
||||
import { formatRelativeTime } from "../../timestampFormat";
|
||||
import { formatRelativeTimeLabel, getRelativeTimeState } from "../../timestampFormat";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import {
|
||||
primaryServerAvailableEditorsAtom,
|
||||
@@ -65,8 +65,7 @@ function formatBytes(value: number): string {
|
||||
|
||||
function formatRelative(value: DateTime.Utc | null): string {
|
||||
if (!value) return "No trace records";
|
||||
const relative = formatRelativeTime(DateTime.formatIso(value));
|
||||
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
|
||||
return formatRelativeTimeLabel(DateTime.formatIso(value));
|
||||
}
|
||||
|
||||
function formatRelativeNoWrap(value: DateTime.Utc | null): string {
|
||||
@@ -755,12 +754,16 @@ function ProcessResourceHistoryTable({
|
||||
|
||||
function DiagnosticsLastChecked({ checkedAt }: { checkedAt: DateTime.Utc | null }) {
|
||||
useRelativeTimeTick();
|
||||
const relative = checkedAt ? formatRelativeTime(DateTime.formatIso(checkedAt)) : null;
|
||||
const relative = getRelativeTimeState(checkedAt ? DateTime.formatIso(checkedAt) : null);
|
||||
|
||||
if (!relative) {
|
||||
if (relative.status === "missing") {
|
||||
return <span className="text-[11px] text-muted-foreground/50">Checking</span>;
|
||||
}
|
||||
|
||||
if (relative.status === "invalid") {
|
||||
return <span className="text-[11px] text-muted-foreground/50">Checked unavailable</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="text-[11px] text-muted-foreground/60">
|
||||
{relative.suffix ? (
|
||||
|
||||
@@ -58,7 +58,7 @@ import {
|
||||
import { usePrimaryEnvironment } from "../../state/environments";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
|
||||
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
|
||||
import { formatRelativeTimeLabel, getRelativeTimeState } from "../../timestampFormat";
|
||||
import { Button } from "../ui/button";
|
||||
import { DraftInput } from "../ui/draft-input";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
@@ -134,12 +134,16 @@ const PROVIDER_SETTINGS = DRIVER_OPTIONS.map((definition) => ({
|
||||
|
||||
function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
|
||||
useRelativeTimeTick();
|
||||
const lastCheckedRelative = lastCheckedAt ? formatRelativeTime(lastCheckedAt) : null;
|
||||
const lastCheckedRelative = getRelativeTimeState(lastCheckedAt);
|
||||
|
||||
if (!lastCheckedRelative) {
|
||||
if (lastCheckedRelative.status === "missing") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (lastCheckedRelative.status === "invalid") {
|
||||
return <span className="text-[11px] text-muted-foreground/50">Checked unavailable</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="text-[11px] text-muted-foreground/60">
|
||||
{lastCheckedRelative.suffix ? (
|
||||
@@ -401,6 +405,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
|
||||
? ["Assistant output"]
|
||||
: []),
|
||||
...(settings.enableProviderUpdateChecks !==
|
||||
DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks
|
||||
? ["Provider update checks"]
|
||||
: []),
|
||||
...(Duration.toMillis(settings.automaticGitFetchInterval) !==
|
||||
Duration.toMillis(DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval)
|
||||
? ["Automatic Git fetch interval"]
|
||||
@@ -434,6 +442,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.automaticGitFetchInterval,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.enableProviderUpdateChecks,
|
||||
settings.sidebarThreadPreviewCount,
|
||||
settings.timestampFormat,
|
||||
settings.wordWrap,
|
||||
@@ -459,6 +468,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
|
||||
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
|
||||
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
|
||||
newWorktreesStartFromOrigin: DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin,
|
||||
|
||||
@@ -147,32 +147,42 @@ function MenuRadioGroup(props: MenuPrimitive.RadioGroup.Props) {
|
||||
return <MenuPrimitive.RadioGroup data-slot="menu-radio-group" {...props} />;
|
||||
}
|
||||
|
||||
function MenuRadioItem({ className, children, ...props }: MenuPrimitive.RadioItem.Props) {
|
||||
function MenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
hideIndicator = false,
|
||||
...props
|
||||
}: MenuPrimitive.RadioItem.Props & {
|
||||
hideIndicator?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.RadioItem
|
||||
className={cn(
|
||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default items-center gap-2 rounded-sm py-1 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
hideIndicator ? "grid-cols-[1fr] ps-3 pe-3" : "grid-cols-[1rem_1fr] ps-2 pe-4",
|
||||
className,
|
||||
)}
|
||||
data-slot="menu-radio-item"
|
||||
{...props}
|
||||
>
|
||||
<MenuPrimitive.RadioItemIndicator className="col-start-1">
|
||||
<svg
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
||||
</svg>
|
||||
</MenuPrimitive.RadioItemIndicator>
|
||||
<span className="col-start-2">{children}</span>
|
||||
{hideIndicator ? null : (
|
||||
<MenuPrimitive.RadioItemIndicator className="col-start-1">
|
||||
<svg
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
||||
</svg>
|
||||
</MenuPrimitive.RadioItemIndicator>
|
||||
)}
|
||||
<span className={hideIndicator ? "col-start-1" : "col-start-2"}>{children}</span>
|
||||
</MenuPrimitive.RadioItem>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,9 +8,24 @@ import {
|
||||
isCollapsedCursorAdjacentToInlineToken,
|
||||
parseStandaloneComposerSlashCommand,
|
||||
replaceTextRange,
|
||||
shouldSubmitComposerOnEnter,
|
||||
} from "./composer-logic";
|
||||
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
|
||||
|
||||
describe("shouldSubmitComposerOnEnter", () => {
|
||||
it("submits plain Enter on desktop", () => {
|
||||
expect(shouldSubmitComposerOnEnter({ isMobileViewport: false, shiftKey: false })).toBe(true);
|
||||
});
|
||||
|
||||
it("inserts a newline for plain Enter on mobile", () => {
|
||||
expect(shouldSubmitComposerOnEnter({ isMobileViewport: true, shiftKey: false })).toBe(false);
|
||||
});
|
||||
|
||||
it("inserts a newline for Shift+Enter", () => {
|
||||
expect(shouldSubmitComposerOnEnter({ isMobileViewport: false, shiftKey: true })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
const text = "Please check @src/com";
|
||||
|
||||
@@ -11,6 +11,13 @@ export interface ComposerTrigger {
|
||||
rangeEnd: number;
|
||||
}
|
||||
|
||||
export function shouldSubmitComposerOnEnter(input: {
|
||||
isMobileViewport: boolean;
|
||||
shiftKey: boolean;
|
||||
}): boolean {
|
||||
return !input.isMobileViewport && !input.shiftKey;
|
||||
}
|
||||
|
||||
const isInlineTokenSegment = (
|
||||
segment:
|
||||
| { type: "text"; text: string }
|
||||
|
||||
@@ -196,6 +196,23 @@ describe("showContextMenuFallback", () => {
|
||||
await expect(selectionPromise).resolves.toBe("rename");
|
||||
});
|
||||
|
||||
it("ignores a click from the gesture that opened the menu", async () => {
|
||||
let enablePointerSelection: ((time: number) => void) | undefined;
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: (time: number) => void) => {
|
||||
enablePointerSelection = callback;
|
||||
return 0;
|
||||
});
|
||||
|
||||
const selectionPromise = showContextMenuFallback([{ id: "rename", label: "Rename" }]);
|
||||
const renameButton = findButton("Rename");
|
||||
|
||||
renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
enablePointerSelection?.(0);
|
||||
renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
|
||||
await expect(selectionPromise).resolves.toBe("rename");
|
||||
});
|
||||
|
||||
it("opens nested submenus and resolves the clicked leaf id", async () => {
|
||||
const selectionPromise = showContextMenuFallback([
|
||||
{
|
||||
|
||||
@@ -272,7 +272,9 @@ export function showContextMenuFallback<T extends string>(
|
||||
button.addEventListener("mouseenter", () => {
|
||||
closeMenusFromLevel(level + 1);
|
||||
});
|
||||
button.addEventListener("click", () => cleanup(item.id));
|
||||
button.addEventListener("click", () => {
|
||||
if (canDismissFromPointer) cleanup(item.id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,12 +9,26 @@ const THREAD_REF = scopeThreadRef(EnvironmentId.make("environment-1"), ThreadId.
|
||||
describe("diffPanelStore", () => {
|
||||
beforeEach(() => useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {} }));
|
||||
|
||||
it("defaults each thread to branch changes with automatic base selection", () => {
|
||||
it("defaults each thread to branch changes when the working tree is clean", () => {
|
||||
expect(
|
||||
selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, THREAD_REF),
|
||||
).toEqual({ kind: "branch", baseRef: null });
|
||||
});
|
||||
|
||||
it("defaults each thread to working changes when the working tree is dirty", () => {
|
||||
expect(
|
||||
selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, THREAD_REF, true),
|
||||
).toEqual({ kind: "unstaged" });
|
||||
});
|
||||
|
||||
it("preserves an explicit scope selection when the working tree state changes", () => {
|
||||
useDiffPanelStore.getState().selectGitScope(THREAD_REF, "branch");
|
||||
|
||||
expect(
|
||||
selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, THREAD_REF, true),
|
||||
).toEqual({ kind: "branch", baseRef: null });
|
||||
});
|
||||
|
||||
it("clears incompatible selection fields when changing scopes", () => {
|
||||
const store = useDiffPanelStore.getState();
|
||||
store.selectTurn(THREAD_REF, TurnId.make("turn-1"), "src/app.ts");
|
||||
|
||||
@@ -11,6 +11,7 @@ export type DiffPanelSelection =
|
||||
| { kind: "turn"; turnId: TurnId; filePath: string | null; revealRequestId: number };
|
||||
|
||||
const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null };
|
||||
const DEFAULT_WORKING_TREE_SELECTION: DiffPanelSelection = { kind: "unstaged" };
|
||||
|
||||
interface DiffPanelStoreState {
|
||||
byThreadKey: Record<string, DiffPanelSelection>;
|
||||
@@ -133,7 +134,11 @@ export const useDiffPanelStore = create<DiffPanelStoreState>()(
|
||||
export function selectThreadDiffPanelSelection(
|
||||
byThreadKey: Record<string, DiffPanelSelection>,
|
||||
ref: ScopedThreadRef | null | undefined,
|
||||
hasWorkingTreeChanges = false,
|
||||
): DiffPanelSelection {
|
||||
if (!ref) return DEFAULT_SELECTION;
|
||||
return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_SELECTION;
|
||||
return (
|
||||
byThreadKey[scopedThreadKey(ref)] ??
|
||||
(hasWorkingTreeChanges ? DEFAULT_WORKING_TREE_SELECTION : DEFAULT_SELECTION)
|
||||
);
|
||||
}
|
||||
@@ -47,6 +47,7 @@ export function useNewThreadHandler() {
|
||||
worktreePath?: string | null;
|
||||
envMode?: DraftThreadEnvMode;
|
||||
startFromOrigin?: boolean;
|
||||
replace?: boolean;
|
||||
},
|
||||
): Promise<void> => {
|
||||
const {
|
||||
@@ -120,6 +121,7 @@ export function useNewThreadHandler() {
|
||||
await router.navigate({
|
||||
to: "/draft/$draftId",
|
||||
params: { draftId: reusableStoredDraftThread.draftId },
|
||||
replace: options?.replace ?? false,
|
||||
});
|
||||
})();
|
||||
}
|
||||
@@ -180,6 +182,7 @@ export function useNewThreadHandler() {
|
||||
await router.navigate({
|
||||
to: "/draft/$draftId",
|
||||
params: { draftId },
|
||||
replace: options?.replace ?? false,
|
||||
});
|
||||
})();
|
||||
},
|
||||
|
||||
@@ -4,8 +4,80 @@
|
||||
/* Window Controls Overlay: active when Electron exposes native titlebar control geometry. */
|
||||
@custom-variant wco (&:is(.wco, .wco *));
|
||||
|
||||
/* On mobile, morph the expanded hero composer into the compact docked
|
||||
composer while it moves; the rest of the app remains visually stationary. */
|
||||
html[data-mobile-composer-route-transition="true"]::view-transition-old(root),
|
||||
html[data-mobile-composer-route-transition="true"]::view-transition-new(root) {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
html[data-mobile-composer-route-transition="true"]::view-transition-group(t3-mobile-composer) {
|
||||
animation-duration: 180ms;
|
||||
animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
html[data-mobile-composer-route-transition="true"]::view-transition-image-pair(t3-mobile-composer) {
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobile-composer) {
|
||||
animation: t3-mobile-composer-old 180ms linear both;
|
||||
mix-blend-mode: normal;
|
||||
}
|
||||
|
||||
html[data-mobile-composer-route-transition="true"]::view-transition-new(t3-mobile-composer) {
|
||||
animation: t3-mobile-composer-new 180ms linear both;
|
||||
mix-blend-mode: normal;
|
||||
}
|
||||
|
||||
/* The expanded and compact composers have different internal layouts. Use a
|
||||
brief crossfade while their shared wrapper moves so the layout change does
|
||||
not read as a single-frame cut. */
|
||||
@keyframes t3-mobile-composer-old {
|
||||
0%,
|
||||
35% {
|
||||
opacity: 1;
|
||||
}
|
||||
65%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes t3-mobile-composer-new {
|
||||
0%,
|
||||
35% {
|
||||
opacity: 0;
|
||||
}
|
||||
65%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
html[data-mobile-composer-route-transition="true"]::view-transition-group(t3-mobile-draft-headline) {
|
||||
animation-duration: 130ms;
|
||||
}
|
||||
|
||||
html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobile-draft-headline) {
|
||||
animation: t3-mobile-draft-headline-exit 130ms cubic-bezier(0.4, 0, 1, 1) both;
|
||||
mix-blend-mode: normal;
|
||||
}
|
||||
|
||||
@keyframes t3-mobile-draft-headline-exit {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
}
|
||||
|
||||
:root {
|
||||
--app-scrollbar-width: 6px;
|
||||
--desktop-window-right-resize-inset: 0px;
|
||||
--workspace-topbar-height: 52px;
|
||||
--workspace-controls-top: 0px;
|
||||
--workspace-controls-left: calc(env(safe-area-inset-left) + 0.75rem);
|
||||
@@ -375,6 +447,11 @@ body {
|
||||
overflow-y: hidden;
|
||||
overscroll-behavior-y: none;
|
||||
padding-top: max(env(safe-area-inset-top), 0px);
|
||||
padding-right: var(--desktop-window-right-resize-inset);
|
||||
}
|
||||
|
||||
.electron-windows {
|
||||
--desktop-window-right-resize-inset: 6px;
|
||||
}
|
||||
|
||||
/* App-chrome grain. Baked into each surface's own background (behind
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { isWindowsPlatform } from "./utils";
|
||||
|
||||
const WCO_CLASS_NAME = "wco";
|
||||
const ELECTRON_CLASS_NAME = "electron";
|
||||
const ELECTRON_WINDOWS_CLASS_NAME = "electron-windows";
|
||||
|
||||
interface WindowControlsOverlayLike {
|
||||
readonly visible: boolean;
|
||||
@@ -38,3 +42,25 @@ export function syncDocumentWindowControlsOverlayClass(): () => void {
|
||||
overlay.removeEventListener("geometrychange", update);
|
||||
};
|
||||
}
|
||||
|
||||
export function getElectronPlatformClassNames(
|
||||
platform: string,
|
||||
):
|
||||
| readonly [typeof ELECTRON_CLASS_NAME]
|
||||
| readonly [typeof ELECTRON_CLASS_NAME, typeof ELECTRON_WINDOWS_CLASS_NAME] {
|
||||
return isWindowsPlatform(platform)
|
||||
? [ELECTRON_CLASS_NAME, ELECTRON_WINDOWS_CLASS_NAME]
|
||||
: [ELECTRON_CLASS_NAME];
|
||||
}
|
||||
|
||||
export function syncDocumentElectronPlatformClasses(platform: string): () => void {
|
||||
if (typeof document === "undefined") {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const classNames = getElectronPlatformClassNames(platform);
|
||||
document.documentElement.classList.add(...classNames);
|
||||
return () => {
|
||||
document.documentElement.classList.remove(...classNames);
|
||||
};
|
||||
}
|
||||
@@ -15,7 +15,10 @@ import { isElectron } from "./env";
|
||||
import { ManagedRelayAuthProvider } from "./cloud/managedAuth";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig";
|
||||
import { getRouter } from "./router";
|
||||
import { syncDocumentWindowControlsOverlayClass } from "./lib/windowControlsOverlay";
|
||||
import {
|
||||
syncDocumentElectronPlatformClasses,
|
||||
syncDocumentWindowControlsOverlayClass,
|
||||
} from "./lib/windowControlsOverlay";
|
||||
import { AppRoot } from "./AppRoot";
|
||||
|
||||
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
|
||||
@@ -24,6 +27,7 @@ const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
const router = getRouter(history);
|
||||
|
||||
if (isElectron) {
|
||||
syncDocumentElectronPlatformClasses(navigator.platform);
|
||||
syncDocumentWindowControlsOverlayClass();
|
||||
}
|
||||
|
||||
|
||||
@@ -117,6 +117,21 @@ describe("rightPanelStore", () => {
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("reopening an inactive singleton activates its existing surface", () => {
|
||||
useRightPanelStore.getState().open(refA, "diff");
|
||||
useRightPanelStore.getState().open(refA, "plan");
|
||||
useRightPanelStore.getState().open(refA, "diff");
|
||||
|
||||
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
|
||||
isOpen: true,
|
||||
activeSurfaceId: "diff",
|
||||
surfaces: [
|
||||
{ id: "diff", kind: "diff" },
|
||||
{ id: "plan", kind: "plan" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps files as a singleton surface", () => {
|
||||
useRightPanelStore.getState().open(refA, "files");
|
||||
useRightPanelStore.getState().open(refA, "files");
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
useComposerDraftStore,
|
||||
} from "../composerDraftStore";
|
||||
import { SidebarInset } from "../components/ui/sidebar";
|
||||
import { waitForDraftHeroTransition } from "../components/chat/draftHeroTransition";
|
||||
import { buildThreadRouteParams } from "../threadRoutes";
|
||||
import { useThread, useThreadRefs } from "../state/entities";
|
||||
|
||||
@@ -40,11 +41,22 @@ function DraftChatThreadRouteView() {
|
||||
if (!canonicalThreadRef) {
|
||||
return;
|
||||
}
|
||||
void navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(canonicalThreadRef),
|
||||
replace: true,
|
||||
|
||||
let cancelled = false;
|
||||
void waitForDraftHeroTransition().then(() => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
void navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(canonicalThreadRef),
|
||||
replace: true,
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [canonicalThreadRef, navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -54,18 +66,6 @@ function DraftChatThreadRouteView() {
|
||||
void navigate({ to: "/", replace: true });
|
||||
}, [canonicalThreadRef, draftSession, navigate]);
|
||||
|
||||
if (canonicalThreadRef) {
|
||||
return (
|
||||
<SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground md:h-dvh">
|
||||
<ChatView
|
||||
environmentId={canonicalThreadRef.environmentId}
|
||||
threadId={canonicalThreadRef.threadId}
|
||||
routeKind="server"
|
||||
/>
|
||||
</SidebarInset>
|
||||
);
|
||||
}
|
||||
|
||||
if (!draftSession) {
|
||||
return null;
|
||||
}
|
||||
@@ -77,6 +77,7 @@ function DraftChatThreadRouteView() {
|
||||
environmentId={draftSession.environmentId}
|
||||
threadId={draftSession.threadId}
|
||||
routeKind="draft"
|
||||
forceExpandedMobileComposer
|
||||
/>
|
||||
</SidebarInset>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { createFileRoute, Link } from "@tanstack/react-router";
|
||||
import { LinkIcon, PlusIcon } from "lucide-react";
|
||||
import { LinkIcon, PlusIcon, RotateCcwIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { NoActiveThreadState } from "../components/NoActiveThreadState";
|
||||
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
|
||||
import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
|
||||
import { SidebarInset } from "../components/ui/sidebar";
|
||||
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
|
||||
import {
|
||||
useAllEnvironmentShellsBootstrapped,
|
||||
useProjects,
|
||||
useThreadShells,
|
||||
} from "../state/entities";
|
||||
import { useEnvironments } from "../state/environments";
|
||||
import { APP_DISPLAY_NAME } from "~/branding";
|
||||
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
|
||||
@@ -19,7 +28,109 @@ function ChatIndexRouteView() {
|
||||
return <HostedStaticOnboardingState />;
|
||||
}
|
||||
|
||||
return <NoActiveThreadState />;
|
||||
return <IndexDraftLanding />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Landing on the index route drops straight into a draft thread for the most
|
||||
* recently active project, so the first screen is a prompt instead of a dead
|
||||
* end. Falls back to an add-project hero when no project exists yet.
|
||||
*/
|
||||
function IndexDraftLanding() {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const bootstrapped = useAllEnvironmentShellsBootstrapped();
|
||||
const handleNewThread = useNewThreadHandler();
|
||||
const startingRef = useRef(false);
|
||||
const [startState, setStartState] = useState({ failed: false, retryRequest: 0 });
|
||||
|
||||
const mostRecentProject = useMemo(
|
||||
() =>
|
||||
bootstrapped
|
||||
? (sortScopedProjectsForSidebar(projects, threads, "updated_at")[0] ?? null)
|
||||
: null,
|
||||
[bootstrapped, projects, threads],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (mostRecentProject === null || startingRef.current) {
|
||||
return;
|
||||
}
|
||||
startingRef.current = true;
|
||||
void handleNewThread(scopeProjectRef(mostRecentProject.environmentId, mostRecentProject.id), {
|
||||
replace: true,
|
||||
}).catch(() => {
|
||||
startingRef.current = false;
|
||||
setStartState((state) => ({ ...state, failed: true }));
|
||||
});
|
||||
}, [handleNewThread, mostRecentProject, startState.retryRequest]);
|
||||
|
||||
if (!bootstrapped) {
|
||||
return null;
|
||||
}
|
||||
if (mostRecentProject !== null) {
|
||||
return startState.failed ? (
|
||||
<DraftStartError
|
||||
onRetry={() => {
|
||||
setStartState((state) => ({
|
||||
failed: false,
|
||||
retryRequest: state.retryRequest + 1,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
) : null;
|
||||
}
|
||||
return <NoProjectsHero />;
|
||||
}
|
||||
|
||||
function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<Empty className="flex-1">
|
||||
<EmptyHeader className="max-w-md">
|
||||
<EmptyTitle className="text-foreground text-xl">Couldn’t start a new thread</EmptyTitle>
|
||||
<EmptyDescription className="mt-2 text-sm text-muted-foreground/78">
|
||||
The project is still available. Try opening the draft again.
|
||||
</EmptyDescription>
|
||||
<div className="mt-5 flex justify-center">
|
||||
<Button size="sm" onClick={onRetry}>
|
||||
<RotateCcwIcon className="size-4" />
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
</SidebarInset>
|
||||
);
|
||||
}
|
||||
|
||||
function NoProjectsHero() {
|
||||
const openAddProject = useOpenAddProjectCommandPalette();
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
|
||||
<Empty className="flex-1">
|
||||
<div className="w-full max-w-lg px-8 py-12">
|
||||
<EmptyHeader className="max-w-none">
|
||||
<EmptyTitle className="text-foreground text-2xl sm:text-3xl">
|
||||
What should we work on?
|
||||
</EmptyTitle>
|
||||
<EmptyDescription className="mt-2 text-sm text-muted-foreground/78">
|
||||
Add a project to start your first thread.
|
||||
</EmptyDescription>
|
||||
<div className="mt-6 flex justify-center">
|
||||
<Button size="sm" onClick={openAddProject}>
|
||||
<PlusIcon className="size-4" />
|
||||
Add project
|
||||
</Button>
|
||||
</div>
|
||||
</EmptyHeader>
|
||||
</div>
|
||||
</Empty>
|
||||
</div>
|
||||
</SidebarInset>
|
||||
);
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/_chat/")({
|
||||
|
||||
@@ -20,6 +20,7 @@ import { useMemo } from "react";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
import { environmentProjects } from "./projects";
|
||||
import { environmentServerConfigsAtom } from "./server";
|
||||
import { allEnvironmentShellsBootstrappedAtom } from "./shell";
|
||||
import { environmentThreadDetails, environmentThreadShells } from "./threads";
|
||||
|
||||
const EMPTY_PROJECT_REFS: ReadonlyArray<ScopedProjectRef> = Object.freeze([]);
|
||||
@@ -113,6 +114,10 @@ export function useThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
|
||||
return useAtomValue(environmentThreadShells.threadShellsAtom);
|
||||
}
|
||||
|
||||
export function useAllEnvironmentShellsBootstrapped(): boolean {
|
||||
return useAtomValue(allEnvironmentShellsBootstrappedAtom);
|
||||
}
|
||||
|
||||
export function useThreadShellsForProjectRefs(
|
||||
refs: ReadonlyArray<ScopedProjectRef>,
|
||||
): ReadonlyArray<EnvironmentThreadShell> {
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import {
|
||||
AVAILABLE_CONNECTION_STATE,
|
||||
connectionProjectionPhase,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
createEnvironmentShellAtoms,
|
||||
createEnvironmentShellSummaryAtom,
|
||||
createEnvironmentSnapshotAtom,
|
||||
createShellEnvironmentAtoms,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { environmentCatalog } from "../connection/catalog";
|
||||
import { connectionAtomRuntime } from "../connection/runtime";
|
||||
@@ -15,3 +21,28 @@ export const environmentShellSummaryAtom = createEnvironmentShellSummaryAtom({
|
||||
catalogValueAtom: environmentCatalog.catalogValueAtom,
|
||||
shellStateValueAtom: environmentShell.stateValueAtom,
|
||||
});
|
||||
|
||||
export const allEnvironmentShellsBootstrappedAtom = Atom.make((get) => {
|
||||
const catalog = AsyncResult.value(get(environmentCatalog.catalogAtom));
|
||||
if (Option.isNone(catalog)) {
|
||||
return false;
|
||||
}
|
||||
for (const environmentId of catalog.value.entries.keys()) {
|
||||
if (Option.isSome(get(environmentShell.stateValueAtom(environmentId)).snapshot)) {
|
||||
continue;
|
||||
}
|
||||
const connection = Option.getOrElse(
|
||||
AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),
|
||||
() => AVAILABLE_CONNECTION_STATE,
|
||||
);
|
||||
if (connectionProjectionPhase(connection) !== "disconnected") {
|
||||
return false;
|
||||
}
|
||||
// A retrying environment is only transiently disconnected; give it its
|
||||
// first retries before letting the landing settle without its snapshot.
|
||||
if (connection.phase === "backoff" && connection.desired && connection.attempt <= 2) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}).pipe(Atom.withLabel("web-all-environment-shells-bootstrapped"));
|
||||
@@ -3,7 +3,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
|
||||
import {
|
||||
formatElapsedDurationLabel,
|
||||
formatExpiresInLabel,
|
||||
formatRelativeTime,
|
||||
formatRelativeTimeLabel,
|
||||
formatRelativeTimeUntil,
|
||||
formatRelativeTimeUntilLabel,
|
||||
formatShortTimestamp,
|
||||
formatTimestamp,
|
||||
getRelativeTimeState,
|
||||
getTimestampFormatOptions,
|
||||
} from "./timestampFormat";
|
||||
|
||||
@@ -90,6 +96,60 @@ describe("formatExpiresInLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("invalid timestamp inputs", () => {
|
||||
it("returns an empty timestamp instead of throwing", () => {
|
||||
expect(() => formatTimestamp("not-a-date", "12-hour")).not.toThrow();
|
||||
expect(formatTimestamp("not-a-date", "12-hour")).toBe("");
|
||||
});
|
||||
|
||||
it("returns an empty short timestamp instead of throwing", () => {
|
||||
expect(() => formatShortTimestamp("not-a-date", "12-hour")).not.toThrow();
|
||||
expect(formatShortTimestamp("not-a-date", "12-hour")).toBe("");
|
||||
});
|
||||
|
||||
it("returns an empty relative time label instead of a NaN label", () => {
|
||||
expect(formatRelativeTime("not-a-date")).toBeNull();
|
||||
expect(formatRelativeTimeLabel("not-a-date")).toBe("");
|
||||
});
|
||||
|
||||
it("distinguishes missing and invalid relative time state", () => {
|
||||
expect(getRelativeTimeState(null)).toEqual({ status: "missing" });
|
||||
expect(getRelativeTimeState("not-a-date")).toEqual({ status: "invalid" });
|
||||
});
|
||||
|
||||
it("returns an empty elapsed duration instead of a NaN label", () => {
|
||||
expect(formatElapsedDurationLabel("not-a-date")).toBe("");
|
||||
});
|
||||
|
||||
it("returns an empty relative time until label instead of a NaN label", () => {
|
||||
expect(formatRelativeTimeUntil("not-a-date")).toBeNull();
|
||||
expect(formatRelativeTimeUntilLabel("not-a-date")).toBe("");
|
||||
});
|
||||
|
||||
it("returns an empty expires-in label instead of a NaN label", () => {
|
||||
expect(formatExpiresInLabel("not-a-date")).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getRelativeTimeState", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-04-07T12:00:00.000Z"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("returns relative parts for valid timestamps", () => {
|
||||
expect(getRelativeTimeState("2026-04-07T11:45:00.000Z")).toEqual({
|
||||
status: "relative",
|
||||
value: "15m",
|
||||
suffix: "ago",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatElapsedDurationLabel", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
@@ -40,8 +40,15 @@ function getTimestampFormatter(
|
||||
return formatter;
|
||||
}
|
||||
|
||||
function parseTimestampDate(isoDate: string): Date | null {
|
||||
const date = new Date(isoDate);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
export function formatTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
|
||||
return getTimestampFormatter(timestampFormat, true).format(new Date(isoDate));
|
||||
const date = parseTimestampDate(isoDate);
|
||||
if (!date) return "";
|
||||
return getTimestampFormatter(timestampFormat, true).format(date);
|
||||
}
|
||||
|
||||
const monthNameFormatter = new Intl.DateTimeFormat(undefined, { month: "long" });
|
||||
@@ -69,8 +76,8 @@ export function formatChatTimestampTooltip(
|
||||
isoDate: string,
|
||||
timestampFormat: TimestampFormat,
|
||||
): string {
|
||||
const date = new Date(isoDate);
|
||||
if (Number.isNaN(date.getTime())) return "";
|
||||
const date = parseTimestampDate(isoDate);
|
||||
if (!date) return "";
|
||||
const time = formatShortTimestamp(isoDate, timestampFormat);
|
||||
const day = date.getDate();
|
||||
const month = monthNameFormatter.format(date);
|
||||
@@ -79,7 +86,9 @@ export function formatChatTimestampTooltip(
|
||||
}
|
||||
|
||||
export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
|
||||
return getTimestampFormatter(timestampFormat, false).format(new Date(isoDate));
|
||||
const date = parseTimestampDate(isoDate);
|
||||
if (!date) return "";
|
||||
return getTimestampFormatter(timestampFormat, false).format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,8 +96,16 @@ export function formatShortTimestamp(isoDate: string, timestampFormat: Timestamp
|
||||
* Returns `{ value: "20s", suffix: "ago" }` or `{ value: "just now", suffix: null }`
|
||||
* so callers can style the numeric portion independently.
|
||||
*/
|
||||
export function formatRelativeTime(isoDate: string): { value: string; suffix: string | null } {
|
||||
const diffMs = Date.now() - new Date(isoDate).getTime();
|
||||
type RelativeTimeParts = { value: string; suffix: string | null };
|
||||
export type RelativeTimeState =
|
||||
| { status: "missing" }
|
||||
| { status: "invalid" }
|
||||
| { status: "relative"; value: string; suffix: string | null };
|
||||
|
||||
export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
|
||||
const date = parseTimestampDate(isoDate);
|
||||
if (!date) return null;
|
||||
const diffMs = Date.now() - date.getTime();
|
||||
if (diffMs < 0) return { value: "just now", suffix: null };
|
||||
const seconds = Math.floor(diffMs / 1000);
|
||||
if (seconds < 60) return { value: "just now", suffix: null };
|
||||
@@ -102,15 +119,25 @@ export function formatRelativeTime(isoDate: string): { value: string; suffix: st
|
||||
|
||||
export function formatRelativeTimeLabel(isoDate: string) {
|
||||
const relative = formatRelativeTime(isoDate);
|
||||
if (!relative) return "";
|
||||
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
|
||||
}
|
||||
|
||||
export function getRelativeTimeState(isoDate: string | null): RelativeTimeState {
|
||||
if (!isoDate) return { status: "missing" };
|
||||
const relative = formatRelativeTime(isoDate);
|
||||
if (!relative) return { status: "invalid" };
|
||||
return { status: "relative", ...relative };
|
||||
}
|
||||
|
||||
/**
|
||||
* Relative elapsed duration since an ISO instant, without an "ago" suffix.
|
||||
* Useful for labels like "Connected for 3m".
|
||||
*/
|
||||
export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
|
||||
const diffMs = nowMs - new Date(isoDate).getTime();
|
||||
const date = parseTimestampDate(isoDate);
|
||||
if (!date) return "";
|
||||
const diffMs = nowMs - date.getTime();
|
||||
if (diffMs <= 0) return "just now";
|
||||
|
||||
const seconds = Math.floor(diffMs / 1000);
|
||||
@@ -130,8 +157,10 @@ export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date
|
||||
/**
|
||||
* Relative time until an ISO instant (e.g. expiry). Mirrors {@link formatRelativeTime} but for future times.
|
||||
*/
|
||||
export function formatRelativeTimeUntil(isoDate: string): { value: string; suffix: string | null } {
|
||||
const diffMs = new Date(isoDate).getTime() - Date.now();
|
||||
export function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
|
||||
const date = parseTimestampDate(isoDate);
|
||||
if (!date) return null;
|
||||
const diffMs = date.getTime() - Date.now();
|
||||
if (diffMs <= 0) return { value: "Expired", suffix: null };
|
||||
const seconds = Math.floor(diffMs / 1000);
|
||||
if (seconds < 5) return { value: "Soon", suffix: null };
|
||||
@@ -146,6 +175,7 @@ export function formatRelativeTimeUntil(isoDate: string): { value: string; suffi
|
||||
|
||||
export function formatRelativeTimeUntilLabel(isoDate: string): string {
|
||||
const relative = formatRelativeTimeUntil(isoDate);
|
||||
if (!relative) return "";
|
||||
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
|
||||
}
|
||||
|
||||
@@ -154,7 +184,9 @@ export function formatRelativeTimeUntilLabel(isoDate: string): string {
|
||||
* Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
|
||||
*/
|
||||
export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
|
||||
const diffMs = new Date(isoDate).getTime() - nowMs;
|
||||
const date = parseTimestampDate(isoDate);
|
||||
if (!date) return "";
|
||||
const diffMs = date.getTime() - nowMs;
|
||||
if (diffMs <= 0) return "Expired";
|
||||
|
||||
const totalSeconds = Math.floor(diffMs / 1000);
|
||||
|
||||
@@ -8,7 +8,7 @@ The three Icon Composer projects are the source of truth for full application ic
|
||||
|
||||
Each project uses `text.svg` for the T3 mark and `background.svg` when the background is a vector layer. Additional layers use semantic names that describe their role and placement.
|
||||
|
||||
Run `vp run icons:export` from the repository root to regenerate the tracked iOS, Linux, Windows, and web assets. Run `vp run icons:check` to verify that those generated assets match their sources without changing files.
|
||||
Run `vp run icons:export` from the repository root to regenerate the tracked iOS, Linux, Windows, and web assets. The development web exports are also copied to `apps/web/public` for the browser favicon and splash screen. Run `vp run icons:check` to verify that the generated assets and public copies match their sources without changing files.
|
||||
|
||||
Exporting requires Icon Composer 2 or newer on macOS. The script selects the newest compatible exporter from Xcode or a standalone Icon Composer installation and pins design generation 26. Set `ICON_COMPOSER_TOOL` to the full path of `Icon Composer.app/Contents/Executables/ictool` to override automatic discovery.
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { sortThreads, type ThreadSortInput } from "./threadSort.ts";
|
||||
|
||||
type TestThread = { readonly id: string } & ThreadSortInput;
|
||||
|
||||
function makeThread(overrides: Partial<TestThread> = {}): TestThread {
|
||||
return {
|
||||
id: "thread-1",
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
messages: [],
|
||||
latestUserMessageAt: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("sortThreads", () => {
|
||||
it("falls back to updatedAt and createdAt when latestUserMessageAt is invalid and there are no messages", () => {
|
||||
const sorted = sortThreads(
|
||||
[
|
||||
makeThread({
|
||||
id: "thread-1",
|
||||
latestUserMessageAt: "not-a-date",
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: "thread-2",
|
||||
latestUserMessageAt: "still-not-a-date",
|
||||
createdAt: "invalid-created-at",
|
||||
updatedAt: "invalid-updated-at",
|
||||
}),
|
||||
makeThread({
|
||||
id: "thread-3",
|
||||
latestUserMessageAt: "invalid-latest-user-message-at",
|
||||
createdAt: "2026-03-09T10:06:00.000Z",
|
||||
updatedAt: "invalid-updated-at",
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["thread-3", "thread-1", "thread-2"]);
|
||||
});
|
||||
|
||||
it("falls back to the latest valid user message when latestUserMessageAt is invalid", () => {
|
||||
const sorted = sortThreads(
|
||||
[
|
||||
makeThread({
|
||||
id: "thread-1",
|
||||
latestUserMessageAt: "invalid-latest-user-message-at",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
messages: [
|
||||
{ role: "user", createdAt: "2026-03-09T10:05:00.000Z" },
|
||||
{ role: "assistant", createdAt: "2026-03-09T10:30:00.000Z" },
|
||||
{ role: "user", createdAt: "2026-03-09T10:20:00.000Z" },
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: "thread-2",
|
||||
createdAt: "2026-03-09T10:15:00.000Z",
|
||||
updatedAt: "2026-03-09T10:15:00.000Z",
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["thread-1", "thread-2"]);
|
||||
});
|
||||
});
|
||||
@@ -32,7 +32,10 @@ function getFirstSortableTimestamp(...values: Array<string | null | undefined>):
|
||||
|
||||
function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
|
||||
if (thread.latestUserMessageAt) {
|
||||
return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
|
||||
const latestUserMessageTimestamp = toSortableTimestamp(thread.latestUserMessageAt);
|
||||
if (latestUserMessageTimestamp !== null) {
|
||||
return latestUserMessageTimestamp;
|
||||
}
|
||||
}
|
||||
|
||||
let latestUserMessageTimestamp: number | null = null;
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadDetailSnapshot,
|
||||
type OrchestrationThreadStreamItem,
|
||||
@@ -74,6 +75,26 @@ const BASE_THREAD: OrchestrationThread = {
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
};
|
||||
const ACTIVE_THREAD: OrchestrationThread = {
|
||||
...BASE_THREAD,
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:01:00.000Z",
|
||||
startedAt: "2026-04-01T00:01:00.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: TurnId.make("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-04-01T00:01:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
type TestThreadInput = OrchestrationThreadStreamItem | Error;
|
||||
|
||||
@@ -308,6 +329,31 @@ describe("EnvironmentThreads", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not persist active thread snapshots during streaming or teardown", () =>
|
||||
Effect.gen(function* () {
|
||||
const savedThreads = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({ cached: ACTIVE_THREAD });
|
||||
yield* awaitThreadState(
|
||||
harness.observed,
|
||||
(value) =>
|
||||
value.status === "live" &&
|
||||
Option.isSome(value.data) &&
|
||||
value.data.value.session?.status === "running",
|
||||
);
|
||||
|
||||
yield* TestClock.adjust("500 millis");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* Ref.get(harness.savedThreads)).toEqual([]);
|
||||
return harness.savedThreads;
|
||||
}),
|
||||
);
|
||||
|
||||
expect(yield* Ref.get(savedThreads)).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
|
||||
Effect.gen(function* () {
|
||||
const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" };
|
||||
|
||||
@@ -41,6 +41,11 @@ function formatThreadError(cause: Cause.Cause<unknown>): string {
|
||||
: "Could not synchronize the thread.";
|
||||
}
|
||||
|
||||
function shouldPersistThread(thread: OrchestrationThread): boolean {
|
||||
const status = thread.session?.status;
|
||||
return status !== "starting" && status !== "running";
|
||||
}
|
||||
|
||||
export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
|
||||
threadId: ThreadIdType,
|
||||
) {
|
||||
@@ -128,10 +133,13 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
status: "live",
|
||||
error: Option.none(),
|
||||
});
|
||||
// Persist the thread together with the sequence it reflects so the next warm
|
||||
// cache can resume from exactly here.
|
||||
const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
|
||||
yield* Queue.offer(persistence, { snapshotSequence, thread });
|
||||
// Active threads can update many times per second and retain large tool
|
||||
// payloads. The server remains the source of truth while a turn is active;
|
||||
// persist once it settles so cache encoding stays off the streaming path.
|
||||
if (shouldPersistThread(thread)) {
|
||||
const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
|
||||
yield* Queue.offer(persistence, { snapshotSequence, thread });
|
||||
}
|
||||
});
|
||||
|
||||
const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
|
||||
@@ -246,7 +254,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
Effect.flatMap(([current, snapshotSequence]) =>
|
||||
Option.match(current.data, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (thread) => persist({ snapshotSequence, thread }),
|
||||
onSome: (thread) =>
|
||||
shouldPersistThread(thread) ? persist({ snapshotSequence, thread }) : Effect.void,
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
resolveDesktopBuildIconAssets,
|
||||
resolveDesktopProductName,
|
||||
resolveDesktopUpdateChannel,
|
||||
resolveDesktopWebAssetBrand,
|
||||
resolveGitHubPublishConfig,
|
||||
resolveMockUpdateServerPort,
|
||||
resolveMockUpdateServerUrl,
|
||||
@@ -102,6 +103,11 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
});
|
||||
});
|
||||
|
||||
it("switches the bundled splash and favicon branding for nightly versions", () => {
|
||||
assert.equal(resolveDesktopWebAssetBrand("0.0.17"), "production");
|
||||
assert.equal(resolveDesktopWebAssetBrand("0.0.17-nightly.20260413.42"), "nightly");
|
||||
});
|
||||
|
||||
it.effect("resolves GitHub desktop publish config from Effect config", () =>
|
||||
Effect.gen(function* () {
|
||||
const latestConfig = yield* resolveGitHubPublishConfig("latest").pipe(
|
||||
|
||||