Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 61bfbce047 format workspace filesystem tests
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 16:06:38 +00:00
Cursor AgentandJulius Marminge 217fbf1b9c refactor workspace reads to Effect FileSystem
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 16:04:58 +00:00
Julius Marminge ebe8afb1df Refresh splash screen and favicon branding (#4120) 2026-07-18 15:44:06 +02:00
Utkarsh PatilandJulius Marminge bf76535fe4 fix(desktop): Validate WSL node version against engine range after probe success (#3621)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 11:54:13 +00:00
5c66110e26 [fix/feat:ui] Make selected menu checks blue (#3234)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-18 13:50:33 +02:00
Maxwell Young da3c2030f7 [codex] canonicalize client timestamps (#4112) 2026-07-18 13:40:34 +02:00
Noah ZepnerandJulius Marminge 0506508e9b Allow failed remote environments to be removed (#4084)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:31:10 +02:00
Guilherme VieiraandJulius Marminge b859a575d1 fix(web): handle macOS Home and End in composer (#2508)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:23:57 +02:00
ssandJulius Marminge e63403fe92 [fix/feat:ui] Preserve open-in editor brand colors (#3225)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:22:37 +02:00
ssandJulius Marminge c0e161af06 [fix/feat:ui] Show default option badge (#3232)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:21:50 +02:00
d0b9f8d40d [codex] Route OpenCode missing-session errors through Effect (#3608)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:19:52 +02:00
Jake LeventhalandJulius Marminge d8b12ae801 Fix sending messages during active turns (#3919)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:19:14 +02:00
Jake LeventhalandJulius Marminge 31caa5652b Fix reopening existing Diff tab (#3973)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:18:18 +02:00
Aditya Mer e350c0a07b Add Grok to marketing site provider list (#3484) 2026-07-18 11:18:17 +00:00
Jake LeventhalandJulius Marminge 38e0bb07bb Default diffs to working changes (#3974)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:17:30 +02:00
Chris Michael Guzman 765e1b5fc0 perf(client): defer active thread cache writes (#4006) 2026-07-18 13:16:38 +02:00
AlexandJulius Marminge 03e20c875c fix(mobile): restore iOS home screen branding (#4025)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:14:59 +02:00
Julius Marmingeandcodex 2318e00270 fix(web): avoid duplicate mention text on paste
Co-authored-by: codex <[email protected]>
2026-07-18 13:05:45 +02:00
Yordis PrietoandJulius Marminge 4cfec8c128 feat: file explorer mention actions and zoom-aware context menus (#4054)
Signed-off-by: Yordis Prieto <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:05:26 +02:00
1bd2fa25e2 feat: draft hero landing on the index route (#4055)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Signed-off-by: Yordis Prieto <[email protected]>
2026-07-18 12:45:45 +02:00
5ca32661b7 fix(web): increase contrast of question option descriptions (#3867)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:53:50 +02:00
Julius Marminge 8b33799523 Preserve T3 Code identity in macOS development launcher (#4102) 2026-07-17 23:39:29 +02:00
Julius Marminge 24f9c2a08e Share MCP OAuth locks across Codex shadow homes (#4104) 2026-07-17 23:26:53 +02:00
31ca9e5531 fix(server): skip undecodable provider runtime rows when listing sessions (#3951)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 21:26:22 +00:00
73bf127d71 [codex] Fix provider update checks restore defaults (#3531)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:25:21 +02:00
43e2aeab38 [codex] fix: tolerate invalid latest user message timestamps (#3521)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:24:52 +02:00
b655a9f183 [codex] fix: guard invalid web timestamps (#3515)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:24:10 +02:00
Matt Van HornandJulius Marminge 4e3f2f04d5 fix(server): thread cwd through Claude capability probe (#2048) (#2124)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:22:19 +02:00
1047dac0c5 fix(terminal): strip AppImage runtime env from spawned terminals (#3108)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 23:21:19 +02:00
JamesandJulius Marminge 143b9c9280 fix(ux): spamming cmd + , no longer stack opening settings (#2757)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:20:28 +02:00
cf58cadd02 feat(server): include runtime model and effort in Codex developer instructions (#3948)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:15:53 +02:00
6a17629670 [codex] fix mobile composer Enter behavior (#3930)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 23:14:45 +02:00
7b8d12618b fix(web): inset Windows desktop scrollbars from resize edge (#4097)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 19:52:42 +00:00
Maxwell YoungandJulius Marminge bcd640bf4d [codex] prevent ACP assistant ID collisions after restarts (#3932)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:51:16 +02:00
b49a2e677c Remove unused code parameter from describePreviewError (#3970)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 19:50:33 +00:00
ed81c156da fix(server): image upload crashed dispatchCommand with a stack overflow (#3952)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:47:52 +02:00
Kriday DaveandJulius Marminge 7dc75127c2 Fix duplicate keybinding rule when replacing with an existing rule (#3969)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:47:35 +02:00
Fazal Kadivar e057e2e985 fix: prevent initial right-click from selecting a context menu item (#3877) 2026-07-17 21:42:13 +02:00
Olivier Melcher a7f6d97b94 Allow preview panel to grow on wide displays (#4044) 2026-07-17 18:40:24 +00:00
Kriday DaveandJulius Marminge f9a4f59930 Fix documented task-runner commands (bun run -> vp) (#3965)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 20:35:24 +02:00
BunnyGamezsc 7f1cb61031 fix(cursor): default binary path to cursor-agent (avoid path conflict w/ grok) (#4094) 2026-07-17 18:01:02 +00:00
Kriday Dave c49d424e3a Normalize protocol-relative remote host input as https (#3971) 2026-07-17 18:59:42 +02:00
Manuel De Ceglie 4804a9824f fix(marketing): correct Cursor icon color (#4090) 2026-07-17 18:56:59 +02:00
Manuel De Ceglie 0748134cec Update marketing GitHub star count (#4088) 2026-07-17 18:56:35 +02:00
Julius Marmingeandcodex 6e9987cf17 Refresh app icons across release variants (#4080)
Co-authored-by: codex <[email protected]>
2026-07-17 18:51:14 +02:00
177 changed files with 4825 additions and 735 deletions

No files matched your search

+34 -9
View File
@@ -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");
});
});
+12 -2
View File
@@ -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,
+13 -3
View File
@@ -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";
+42 -4
View File
@@ -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;
}
}
@@ -1 +1 @@
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" fill="#EDECEC" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>

Before

Width:  |  Height:  |  Size: 649 B

After

Width:  |  Height:  |  Size: 665 B

@@ -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

+1 -1
View File
@@ -1,6 +1,6 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const MARKETING_STATS = {
githubStars: "12k+",
githubStars: "14k+",
users: "100,000",
} as const;
+41 -9
View File
@@ -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; }
}
+22 -8
View File
@@ -1,5 +1,6 @@
import type { ExpoConfig } from "expo/config";
import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
type AppVariant = "development" | "preview" | "production";
@@ -13,6 +14,8 @@ const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
const fromRepoRoot = (relativePath: string) => `../../${relativePath}`;
if (
isIosPersonalTeamBuild &&
(!personalTeamBundleIdentifier ||
@@ -24,20 +27,31 @@ if (
}
const DEVELOPMENT_ASSETS = {
appIcon: "./assets/splash-icon-dev.png",
iosIcon: "./assets/icon-composer-dev.icon",
splashIcon: "./assets/splash-icon-dev.png",
androidAdaptiveForeground: "./assets/android-icon-dev-foreground.png",
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIconComposerProject),
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.developmentUniversalIconPng),
androidAdaptiveBackgroundColor: "#00639B",
androidMonochromeIcon: "./assets/android-icon-mark.png",
androidNotificationIcon: "./assets/android-notification-icon.png",
androidNotificationColor: "#00639B",
} as const;
const PREVIEW_ASSETS = {
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIconComposerProject),
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.nightlyLinuxIconPng),
androidAdaptiveBackgroundColor: "#111533",
androidMonochromeIcon: "./assets/android-icon-mark.png",
androidNotificationIcon: "./assets/android-notification-icon.png",
androidNotificationColor: "#7565C7",
} as const;
const RELEASE_ASSETS = {
appIcon: "./assets/splash-icon-prod.png",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIconComposerProject),
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
androidAdaptiveForeground: "./assets/android-icon-mark.png",
androidAdaptiveBackgroundColor: "#000000",
androidMonochromeIcon: "./assets/android-icon-mark.png",
@@ -60,7 +74,7 @@ const VARIANT_CONFIG = {
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
assets: RELEASE_ASSETS,
assets: PREVIEW_ASSETS,
},
production: {
appName: "T3 Code",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

@@ -1,3 +0,0 @@
<svg width="77" height="47" viewBox="0 0 77 47" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.56 45.5V8.58H1.69082e-06V-3.09944e-06H39.65V8.58H25.09V45.5H14.56ZM57.8454 46.28C54.6821 46.28 51.5404 45.8683 48.4204 45.045C45.3004 44.1783 42.6571 42.965 40.4904 41.405L44.5854 33.345C46.3188 34.6017 48.3338 35.5983 50.6304 36.335C52.9271 37.0717 55.2454 37.44 57.5854 37.44C60.2288 37.44 62.3088 36.92 63.8254 35.88C65.3421 34.84 66.1004 33.41 66.1004 31.59C66.1004 29.8567 65.4288 28.4917 64.0854 27.495C62.7421 26.4983 60.5754 26 57.5854 26H52.7754V19.045L65.4504 4.68L66.6204 8.45H42.7654V-3.09944e-06H74.6154V6.825L62.0054 21.19L56.6754 18.135H59.7304C65.3204 18.135 69.5454 19.3917 72.4054 21.905C75.2654 24.4183 76.6954 27.6467 76.6954 31.59C76.6954 34.1467 76.0238 36.5517 74.6804 38.805C73.3371 41.015 71.2788 42.8133 68.5054 44.2C65.7321 45.5867 62.1788 46.28 57.8454 46.28Z" fill="white"/>
</svg>

Before

Width:  |  Height:  |  Size: 920 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 302 KiB

+3 -1
View File
@@ -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({
+13 -3
View File
@@ -1,13 +1,23 @@
import { Image, View } from "react-native";
import Constants from "expo-constants";
import { Image } from "expo-image";
import { View } from "react-native";
import { AppText as Text } from "./AppText";
const BRAND_MARK_SOURCE = require("../../../../assets/dev/blueprint-ios-1024.png");
const appVariant = Constants.expoConfig?.extra?.appVariant;
const BRAND_MARK_SOURCE =
appVariant === "development"
? require("../../../../assets/dev/blueprint-ios-1024.png")
: appVariant === "preview"
? require("../../../../assets/nightly/nightly-ios-1024.png")
: require("../../../../assets/prod/black-ios-1024.png");
const DEFAULT_STAGE_LABEL =
appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha";
export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) {
const compact = props.compact ?? false;
const iconSize = compact ? 32 : 44;
const stageLabel = props.stageLabel ?? "Alpha";
const stageLabel = props.stageLabel ?? DEFAULT_STAGE_LABEL;
return (
<View className="flex-row items-center gap-3">
@@ -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",
};
@@ -62,7 +62,7 @@ const promptText = NodeProcess.argv[4] ?? "helo";
const targetReasoning = NodeProcess.env.CURSOR_REASONING ?? "";
const targetContext = NodeProcess.env.CURSOR_CONTEXT ?? "";
const targetFast = NodeProcess.env.CURSOR_FAST ?? "";
const agentBin = NodeProcess.env.CURSOR_AGENT_BIN ?? "agent";
const agentBin = NodeProcess.env.CURSOR_AGENT_BIN ?? "cursor-agent";
const promptWaitMs = Number(NodeProcess.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
const requestTimeoutMs = Number(NodeProcess.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
+57
View File
@@ -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");
});
+63 -8
View File
@@ -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 };
}
+22
View File
@@ -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;
+3 -1
View File
@@ -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);
});
});
+49 -14
View File
@@ -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;
}
@@ -1,5 +1,5 @@
/**
* CursorDriver — `ProviderDriver` for the Cursor Agent (`agent`) runtime.
* CursorDriver — `ProviderDriver` for the Cursor Agent (`cursor-agent`) runtime.
*
* Cursor exposes an ACP-based CLI. Model catalog and capability refreshes
* happen during the managed provider status check via Cursor's
@@ -42,7 +42,7 @@ import type { ServerProviderDraft } from "../providerSnapshot.ts";
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
import {
makeProviderMaintenanceCapabilities,
makeStaticProviderMaintenanceResolver,
type ProviderMaintenanceCapabilitiesResolver,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
import {
@@ -54,15 +54,16 @@ const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const DRIVER_KIND = ProviderDriverKind.make("cursor");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const UPDATE = makeStaticProviderMaintenanceResolver(
makeProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
packageName: null,
updateExecutable: "agent",
updateArgs: ["update"],
updateLockKey: "cursor-agent",
}),
);
const UPDATE: ProviderMaintenanceCapabilitiesResolver = {
resolve: (options) =>
makeProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
packageName: null,
updateExecutable: options?.binaryPath?.trim() || "cursor-agent",
updateArgs: ["update"],
updateLockKey: "cursor-agent",
}),
};
export type CursorDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
@@ -100,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;
@@ -132,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)));
@@ -294,7 +295,7 @@ const parameterizedClaudeModelOptionConfigOptions = [
const baseCursorSettings: CursorSettings = {
enabled: true,
binaryPath: "agent",
binaryPath: "cursor-agent",
apiEndpoint: "",
customModels: [],
};
@@ -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,
@@ -76,7 +76,7 @@ const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings =>
const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({
enabled: false,
binaryPath: "agent",
binaryPath: "cursor-agent",
apiEndpoint: "",
customModels: [],
...overrides,
@@ -1396,7 +1396,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(
mockCommandSpawnerLayer((command, args) => {
if (command === "agent") {
if (command === "cursor-agent") {
cursorSpawned = true;
}
const joined = args.join(" ");
@@ -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,5 +1,5 @@
/**
* Optional integration check against a real `agent acp` install.
* Optional integration check against a real `cursor-agent acp` install.
* Enable with: T3_CURSOR_ACP_PROBE=1 bun run test --filter CursorAcpCliProbe
*/
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -12,7 +12,7 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe", () => {
it.effect("initialize and authenticate against real agent acp", () =>
it.effect("initialize and authenticate against real cursor-agent acp", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const started = yield* runtime.start();
@@ -21,7 +21,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: "agent",
command: "cursor-agent",
args: ["acp"],
cwd: process.cwd(),
},
@@ -77,7 +77,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
command: "cursor-agent",
args: ["acp"],
cwd: process.cwd(),
},
@@ -133,7 +133,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
command: "cursor-agent",
args: ["acp"],
cwd: process.cwd(),
},
@@ -53,7 +53,7 @@ const parameterizedGpt54ConfigOptions: ReadonlyArray<EffectAcpSchema.SessionConf
describe("buildCursorAcpSpawnInput", () => {
it("builds the default Cursor ACP command", () => {
expect(buildCursorAcpSpawnInput(undefined, "/tmp/project")).toEqual({
command: "agent",
command: "cursor-agent",
args: ["acp"],
cwd: "/tmp/project",
});
@@ -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";
@@ -35,7 +36,7 @@ export function buildCursorAcpSpawnInput(
environment?: NodeJS.ProcessEnv,
): AcpSessionRuntime.AcpSpawnInput {
return {
command: cursorSettings?.binaryPath || "agent",
command: cursorSettings?.binaryPath || "cursor-agent",
args: [
...(cursorSettings?.apiEndpoint ? (["-e", cursorSettings.apiEndpoint] as const) : []),
"acp",
@@ -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(
@@ -48,7 +48,7 @@ function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabili
return makeProviderMaintenanceCapabilities({
provider,
packageName: null,
updateExecutable: "agent",
updateExecutable: "cursor-agent",
updateArgs: ["update"],
updateLockKey: "cursor-agent",
});
@@ -226,7 +226,7 @@ describe("providerMaintenanceRunner", () => {
const result = yield* updater.updateProvider(CURSOR_DRIVER);
assert.deepStrictEqual(calls, [
{
command: "agent",
command: "cursor-agent",
args: ["update"],
},
]);
+57
View File
@@ -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();
+48 -1
View File
@@ -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;
@@ -1,9 +1,11 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -64,7 +66,7 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
relativePath: "src/index.ts",
});
expect(result).toEqual({
assert.deepStrictEqual(result, {
relativePath: "src/index.ts",
contents: "export const answer = 42;\n",
byteLength: 26,
@@ -82,7 +84,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFile({ cwd, relativePath: "../escape.md" })
.pipe(Effect.flip);
expect(error.message).toContain(
assert.include(
error.message,
"Workspace file path must be relative to the project root: ../escape.md",
);
}),
@@ -107,14 +110,14 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
const resolvedWorkspaceRoot = yield* fileSystem.realPath(cwd);
const resolvedPath = yield* fileSystem.realPath(path.join(outsideDir, "secret.txt"));
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
expect(error).toMatchObject({
assert.strictEqual(error._tag, "WorkspaceFilePathEscapeError");
assert.deepInclude(error, {
workspaceRoot: cwd,
relativePath: "linked-secret.txt",
resolvedWorkspaceRoot,
resolvedPath,
});
expect("cause" in error).toBe(false);
assert.notProperty(error, "cause");
}),
);
@@ -131,13 +134,13 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.pipe(Effect.flip);
const resolvedPath = yield* fileSystem.realPath(path.join(cwd, "src"));
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
expect(error).toMatchObject({
assert.strictEqual(error._tag, "WorkspacePathNotFileError");
assert.deepInclude(error, {
workspaceRoot: cwd,
relativePath: "src",
resolvedPath,
});
expect("cause" in error).toBe(false);
assert.notProperty(error, "cause");
}),
);
@@ -155,14 +158,31 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.pipe(Effect.flip);
const resolvedPath = yield* fileSystem.realPath(absolutePath);
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
expect(error).toMatchObject({
assert.strictEqual(error._tag, "WorkspaceBinaryFileError");
assert.deepInclude(error, {
workspaceRoot: cwd,
relativePath: "asset.bin",
resolvedPath,
});
expect("cause" in error).toBe(false);
expect("contents" in error).toBe(false);
assert.notProperty(error, "cause");
assert.notProperty(error, "contents");
}),
);
it.effect("reads at most the preview limit", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "large.txt", "a".repeat(1024 * 1024 + 1));
const result = yield* workspaceFileSystem.readFile({
cwd,
relativePath: "large.txt",
});
assert.strictEqual(result.contents.length, 1024 * 1024);
assert.strictEqual(result.byteLength, 1024 * 1024 + 1);
assert.isTrue(result.truncated);
}),
);
@@ -177,16 +197,16 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFile({ cwd, relativePath: "missing.txt" })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFileSystemOperationError);
expect(error).toMatchObject({
assert.strictEqual(error._tag, "WorkspaceFileSystemOperationError");
assert.deepInclude(error, {
workspaceRoot: cwd,
relativePath: "missing.txt",
resolvedPath,
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.strictEqual((error.cause as PlatformError.PlatformError).reason._tag, "NotFound");
}),
);
});
@@ -207,8 +227,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFileString(path.join(cwd, "plans/effect-rpc.md"))
.pipe(Effect.orDie);
expect(result).toEqual({ relativePath: "plans/effect-rpc.md" });
expect(saved).toBe("# Plan\n");
assert.deepStrictEqual(result, { relativePath: "plans/effect-rpc.md" });
assert.strictEqual(saved, "# Plan\n");
}),
);
@@ -220,9 +240,7 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
const beforeWrite = yield* workspaceEntries.list({ cwd });
expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
false,
);
assert.isFalse(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md"));
yield* workspaceFileSystem.writeFile({
cwd,
@@ -231,10 +249,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
});
const afterWrite = yield* workspaceEntries.list({ cwd });
expect(afterWrite.entries).toEqual(
expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
);
expect(afterWrite.truncated).toBe(false);
assert.isTrue(afterWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md"));
assert.isFalse(afterWrite.truncated);
}),
);
@@ -253,15 +269,14 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
})
.pipe(Effect.flip);
expect(error.message).toContain(
assert.include(
error.message,
"Workspace file path must be relative to the project root: ../escape.md",
);
const escapedPath = path.resolve(cwd, "..", "escape.md");
const escapedStat = yield* fileSystem
.stat(escapedPath)
.pipe(Effect.orElseSucceed(() => null));
expect(escapedStat).toBeNull();
const escapedStat = yield* fileSystem.stat(escapedPath).pipe(Effect.option);
assert.isTrue(Option.isNone(escapedStat));
}),
);
});
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,8 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -19,6 +16,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -140,30 +138,32 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const realWorkspaceRoot = yield* fileSystem.realPath(input.cwd).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
),
);
const realTargetPath = yield* fileSystem.realPath(target.absolutePath).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
),
);
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -178,24 +178,24 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
return yield* Effect.scoped(
Effect.gen(function* () {
const handle = yield* fileSystem.open(realTargetPath, { flag: "r" }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
),
);
const stat = yield* handle.stat.pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -204,58 +204,56 @@ export const make = Effect.gen(function* () {
operation: "stat",
cause,
}),
),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
const truncated = stat.size > FileSystem.Size(PROJECT_READ_FILE_MAX_BYTES);
const byteLength = Number(stat.size);
const bytesToRead = truncated ? PROJECT_READ_FILE_MAX_BYTES : byteLength;
const fileBytes =
bytesToRead === 0
? new Uint8Array()
: yield* handle.readAlloc(bytesToRead).pipe(
Effect.map(
Option.match({
onNone: () => new Uint8Array(),
onSome: (bytes) => bytes,
}),
),
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
),
);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength,
truncated,
};
}),
);
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1003 B

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 204 KiB

After

Width:  |  Height:  |  Size: 277 KiB

+7 -3
View File
@@ -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}>
+56 -1
View File
@@ -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,
+13
View File
@@ -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;
}
+385 -140
View File
@@ -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>
+14 -4
View File
@@ -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);
@@ -19,6 +19,7 @@ import {
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortScopedProjectsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import {
@@ -1066,3 +1067,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",
]);
});
});
+72 -20
View File
@@ -24,6 +24,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 +544,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 +571,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 +578,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),
);
}
+68 -28
View File
@@ -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">
+42 -5
View File
@@ -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>
+96 -56
View File
@@ -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 &quot;ultrathink&quot; 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 &quot;ultrathink&quot; 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,
@@ -0,0 +1,13 @@
import { describe, expect, it } from "vite-plus/test";
import { getPreviewPanelMaxWidth } from "./PreviewPanelShell";
describe("getPreviewPanelMaxWidth", () => {
it("allows the panel to use 70% of an ultra-wide viewport without a pixel ceiling", () => {
expect(getPreviewPanelMaxWidth(6_000)).toBe(4_200);
});
it("rounds fractional CSS pixels down", () => {
expect(getPreviewPanelMaxWidth(2_001)).toBe(1_400);
});
});
@@ -10,12 +10,14 @@ export type PreviewPanelMode = "inline" | "sheet" | "sidebar" | "embedded";
const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width";
const PREVIEW_PANEL_MIN_WIDTH = 360;
/** Hard ceiling so a wide monitor can't yield a panel that swallows the chat. */
const PREVIEW_PANEL_MAX_WIDTH_PX = 1400;
/** Fraction of the viewport allowed; the panel is min(this · vw, MAX_PX). */
/** Fraction of the viewport allowed, preserving the remaining space for chat. */
const PREVIEW_PANEL_MAX_WIDTH_FRACTION = 0.7;
const PREVIEW_PANEL_DEFAULT_WIDTH = 540;
export function getPreviewPanelMaxWidth(viewportWidth: number): number {
return Math.floor(viewportWidth * PREVIEW_PANEL_MAX_WIDTH_FRACTION);
}
/**
* Shell for the preview panel. In inline mode the panel is user-resizable
* via a drag handle on the left edge; width persists per browser. In
@@ -82,5 +84,5 @@ function useViewportClampedMaxWidth(): number {
if (frame !== 0) window.cancelAnimationFrame(frame);
};
}, []);
return Math.min(PREVIEW_PANEL_MAX_WIDTH_PX, Math.floor(vw * PREVIEW_PANEL_MAX_WIDTH_FRACTION));
return getPreviewPanelMaxWidth(vw);
}
@@ -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,
+28 -18
View File
@@ -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>
);
}
+15
View File
@@ -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";
+7
View File
@@ -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 }
+17
View File
@@ -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([
{
+3 -1
View File
@@ -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);
});
}
}
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more