Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c283d2a85b | ||
|
|
67dddb31df | ||
|
|
a26f299b73 | ||
|
|
b1c85fa3cc |
No files matched your search
@@ -45,7 +45,3 @@ Docs:
|
||||
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
|
||||
|
||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||
|
||||
## Dummy Change
|
||||
|
||||
- This line is a no-op dummy edit.
|
||||
@@ -18,7 +18,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@types/node": "^24.10.13",
|
||||
"@types/node": "^22.10.2",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
|
||||
+16
-138
@@ -5,10 +5,9 @@ import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from "electron";
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, protocol, shell } from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { fixPath } from "./fixPath";
|
||||
|
||||
@@ -26,8 +25,6 @@ const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
|
||||
const COMMIT_HASH_DISPLAY_LENGTH = 12;
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
@@ -38,32 +35,6 @@ let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
let desktopProtocolRegistered = false;
|
||||
let aboutCommitHashCache: string | null | undefined;
|
||||
|
||||
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||
|
||||
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
||||
if (process.platform !== "darwin") return undefined;
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache ?? undefined;
|
||||
}
|
||||
try {
|
||||
const icon = nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 14,
|
||||
height: 14,
|
||||
});
|
||||
if (icon.isEmpty()) {
|
||||
destructiveMenuIconCache = null;
|
||||
return undefined;
|
||||
}
|
||||
icon.setTemplateImage(true);
|
||||
destructiveMenuIconCache = icon;
|
||||
return icon;
|
||||
} catch {
|
||||
destructiveMenuIconCache = null;
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
@@ -84,54 +55,6 @@ function resolveAppRoot(): string {
|
||||
return app.getAppPath();
|
||||
}
|
||||
|
||||
function normalizeCommitHash(value: unknown): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!COMMIT_HASH_PATTERN.test(trimmed)) {
|
||||
return null;
|
||||
}
|
||||
return trimmed.slice(0, COMMIT_HASH_DISPLAY_LENGTH).toLowerCase();
|
||||
}
|
||||
|
||||
function resolveEmbeddedCommitHash(): string | null {
|
||||
const packageJsonPath = path.join(resolveAppRoot(), "package.json");
|
||||
if (!fs.existsSync(packageJsonPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(packageJsonPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
|
||||
return normalizeCommitHash(parsed.t3codeCommitHash);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveAboutCommitHash(): string | null {
|
||||
if (aboutCommitHashCache !== undefined) {
|
||||
return aboutCommitHashCache;
|
||||
}
|
||||
|
||||
const envCommitHash = normalizeCommitHash(process.env.T3CODE_COMMIT_HASH);
|
||||
if (envCommitHash) {
|
||||
aboutCommitHashCache = envCommitHash;
|
||||
return aboutCommitHashCache;
|
||||
}
|
||||
|
||||
// Only packaged builds are required to expose commit metadata.
|
||||
if (!app.isPackaged) {
|
||||
aboutCommitHashCache = null;
|
||||
return aboutCommitHashCache;
|
||||
}
|
||||
|
||||
aboutCommitHashCache = resolveEmbeddedCommitHash();
|
||||
|
||||
return aboutCommitHashCache;
|
||||
}
|
||||
|
||||
function resolveBackendEntry(): string {
|
||||
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
}
|
||||
@@ -328,11 +251,8 @@ function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
|
||||
|
||||
function configureAppIdentity(): void {
|
||||
app.setName(APP_DISPLAY_NAME);
|
||||
const commitHash = resolveAboutCommitHash();
|
||||
app.setAboutPanelOptions({
|
||||
applicationName: APP_DISPLAY_NAME,
|
||||
applicationVersion: app.getVersion(),
|
||||
version: commitHash ?? "unknown",
|
||||
});
|
||||
|
||||
if (process.platform === "win32") {
|
||||
@@ -477,65 +397,23 @@ function registerIpcHandlers(): void {
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
|
||||
ipcMain.handle(
|
||||
CONTEXT_MENU_CHANNEL,
|
||||
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
|
||||
const normalizedItems = items
|
||||
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
|
||||
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
if (!window) return null;
|
||||
|
||||
return new Promise<string | null>((resolve) => {
|
||||
const menu = Menu.buildFromTemplate(
|
||||
items.map((item) => ({
|
||||
label: item.label,
|
||||
destructive: item.destructive === true,
|
||||
}));
|
||||
if (normalizedItems.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const popupPosition =
|
||||
position &&
|
||||
Number.isFinite(position.x) &&
|
||||
Number.isFinite(position.y) &&
|
||||
position.x >= 0 &&
|
||||
position.y >= 0
|
||||
? {
|
||||
x: Math.floor(position.x),
|
||||
y: Math.floor(position.y),
|
||||
}
|
||||
: null;
|
||||
|
||||
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
if (!window) return null;
|
||||
|
||||
return new Promise<string | null>((resolve) => {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
for (const item of normalizedItems) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
click: () => resolve(item.id),
|
||||
};
|
||||
if (item.destructive) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (destructiveIcon) {
|
||||
itemOption.icon = destructiveIcon;
|
||||
}
|
||||
}
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
const menu = Menu.buildFromTemplate(template);
|
||||
menu.popup({
|
||||
window,
|
||||
...popupPosition,
|
||||
callback: () => resolve(null),
|
||||
});
|
||||
click: () => resolve(item.id),
|
||||
})),
|
||||
);
|
||||
menu.popup({
|
||||
window,
|
||||
callback: () => resolve(null),
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
|
||||
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
|
||||
|
||||
@@ -12,7 +12,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
showContextMenu: (items) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
|
||||
@@ -126,7 +126,10 @@ function parseRemoteRefWithRemoteNames(
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
|
||||
function parseTrackingBranchByUpstreamRef(
|
||||
stdout: string,
|
||||
upstreamRef: string,
|
||||
): string | null {
|
||||
for (const line of stdout.split("\n")) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.length === 0) {
|
||||
@@ -386,12 +389,9 @@ const makeGitCore = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||
executeGit(
|
||||
"GitCore.resolveDefaultBranchName",
|
||||
cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{ allowNonZeroExit: true },
|
||||
).pipe(
|
||||
executeGit("GitCore.resolveDefaultBranchName", cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
@@ -888,34 +888,33 @@ const makeGitCore = Effect.gen(function* () {
|
||||
|
||||
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.listBranches.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitCore.listBranches.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.listBranches.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitCore.listBranches.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const remoteNames =
|
||||
remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
const remoteNames = remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
|
||||
@@ -1113,23 +1112,24 @@ const makeGitCore = Effect.gen(function* () {
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const localTrackingBranch = remoteExists
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackingBranch",
|
||||
input.cwd,
|
||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) =>
|
||||
result.code === 0
|
||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const localTrackingBranch =
|
||||
remoteExists
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackingBranch",
|
||||
input.cwd,
|
||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) =>
|
||||
result.code === 0
|
||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
|
||||
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
|
||||
const localTrackedBranchTargetExists =
|
||||
@@ -1145,15 +1145,16 @@ const makeGitCore = Effect.gen(function* () {
|
||||
).pipe(Effect.map((result) => result.code === 0))
|
||||
: false;
|
||||
|
||||
const checkoutArgs = localInputExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||
const checkoutArgs =
|
||||
localInputExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch
|
||||
? ["checkout", "--track", input.branch]
|
||||
: remoteExists && localTrackingBranch
|
||||
? ["checkout", localTrackingBranch]
|
||||
: ["checkout", input.branch];
|
||||
? ["checkout", "--track", input.branch]
|
||||
: remoteExists && localTrackingBranch
|
||||
? ["checkout", localTrackingBranch]
|
||||
: ["checkout", input.branch];
|
||||
|
||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
|
||||
timeoutMs: 10_000,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* @module GitCore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
@@ -149,9 +149,7 @@ export interface GitCoreShape {
|
||||
/**
|
||||
* Checkout an existing branch and refresh its upstream metadata in background.
|
||||
*/
|
||||
readonly checkoutBranch: (
|
||||
input: GitCheckoutInput,
|
||||
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
|
||||
readonly checkoutBranch: (input: GitCheckoutInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Initialize a repository in the provided directory.
|
||||
|
||||
@@ -1,51 +1,24 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
import { launchDetached, resolveEditorLaunch } from "./open";
|
||||
import { Effect } from "effect";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
|
||||
describe("resolveEditorLaunch", () => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
it.effect("returns cursor command for cursor editor", () =>
|
||||
Effect.gen(function* () {
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
assert.deepEqual(launch, {
|
||||
command: "cursor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses --goto when editor supports line/column suffixes", () =>
|
||||
it.effect("uses --goto when cursor target includes line/column suffixes", () =>
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
@@ -64,24 +37,6 @@ describe("resolveEditorLaunch", () => {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -138,85 +93,3 @@ describe("launchDetached", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("isCommandAvailable", () => {
|
||||
function withTempDir(run: (dir: string) => void): void {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-"));
|
||||
try {
|
||||
run(dir);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
it("resolves win32 commands with PATHEXT", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns false when a command is not on PATH", () => {
|
||||
const env = {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
|
||||
});
|
||||
|
||||
it("does not treat bare files without executable extension as available on win32", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "npm"), "echo nope\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
|
||||
});
|
||||
});
|
||||
|
||||
it("appends PATHEXT for commands with non-executable extensions on win32", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "my.tool.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
|
||||
it("uses platform-specific PATH delimiter for platform overrides", () => {
|
||||
withTempDir((firstDir) => {
|
||||
withTempDir((secondDir) => {
|
||||
fs.writeFileSync(path.join(secondDir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: `${firstDir};${secondDir}`,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAvailableEditors", () => {
|
||||
it("returns only editors whose launch commands are available", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
|
||||
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
+9
-141
@@ -7,8 +7,6 @@
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
@@ -32,147 +30,10 @@ interface EditorLaunch {
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface CommandAvailabilityOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
function stripWrappingQuotes(value: string): string {
|
||||
return value.replace(/^"+|"+$/g, "");
|
||||
}
|
||||
|
||||
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
|
||||
return env.PATH ?? env.Path ?? env.path ?? "";
|
||||
}
|
||||
|
||||
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
|
||||
const rawValue = env.PATHEXT;
|
||||
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
|
||||
if (!rawValue) return fallback;
|
||||
|
||||
const parsed = rawValue
|
||||
.split(";")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
|
||||
}
|
||||
|
||||
function resolveCommandCandidates(
|
||||
command: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> {
|
||||
if (platform !== "win32") return [command];
|
||||
const extension = extname(command);
|
||||
const normalizedExtension = extension.toUpperCase();
|
||||
|
||||
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
|
||||
const commandWithoutExtension = command.slice(0, -extension.length);
|
||||
return Array.from(
|
||||
new Set([
|
||||
command,
|
||||
`${commandWithoutExtension}${normalizedExtension}`,
|
||||
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const candidates: string[] = [];
|
||||
for (const extension of windowsPathExtensions) {
|
||||
candidates.push(`${command}${extension}`);
|
||||
candidates.push(`${command}${extension.toLowerCase()}`);
|
||||
}
|
||||
return Array.from(new Set(candidates));
|
||||
}
|
||||
|
||||
function isExecutableFile(
|
||||
filePath: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): boolean {
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
if (!stat.isFile()) return false;
|
||||
if (platform === "win32") {
|
||||
const extension = extname(filePath);
|
||||
if (extension.length === 0) return false;
|
||||
return windowsPathExtensions.includes(extension.toUpperCase());
|
||||
}
|
||||
accessSync(filePath, constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePathDelimiter(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? ";" : ":";
|
||||
}
|
||||
|
||||
export function isCommandAvailable(
|
||||
command: string,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): boolean {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
|
||||
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
return commandCandidates.some((candidate) =>
|
||||
isExecutableFile(candidate, platform, windowsPathExtensions),
|
||||
);
|
||||
}
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(env);
|
||||
if (pathValue.length === 0) return false;
|
||||
const pathEntries = pathValue
|
||||
.split(resolvePathDelimiter(platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of commandCandidates) {
|
||||
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
return editorId === "cursor" && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -220,7 +81,14 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return { command: "open", args: [input.cwd] };
|
||||
case "win32":
|
||||
return { command: "explorer", args: [input.cwd] };
|
||||
default:
|
||||
return { command: "xdg-open", args: [input.cwd] };
|
||||
}
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
|
||||
@@ -415,7 +415,8 @@ const make = Effect.gen(function* () {
|
||||
: event.threadId !== undefined
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
: null;
|
||||
const providerThreadId = providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
||||
const providerThreadId =
|
||||
providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
||||
const status =
|
||||
event.type === "turn.started"
|
||||
? "running"
|
||||
|
||||
@@ -489,10 +489,12 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* toRequestError(
|
||||
input.sessionId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
return yield* Effect.fail(
|
||||
toRequestError(
|
||||
input.sessionId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
),
|
||||
);
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
|
||||
@@ -13,7 +13,6 @@ import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serve
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
EDITORS,
|
||||
EventId,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
@@ -341,15 +340,6 @@ function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsCon
|
||||
}
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
|
||||
const VALID_EDITOR_IDS = new Set(EDITORS.map((editor) => editor.id));
|
||||
|
||||
function expectAvailableEditors(value: unknown): void {
|
||||
expect(Array.isArray(value)).toBe(true);
|
||||
for (const editorId of value as unknown[]) {
|
||||
expect(typeof editorId).toBe("string");
|
||||
expect(VALID_EDITOR_IDS.has(editorId as (typeof EDITORS)[number]["id"])).toBe(true);
|
||||
}
|
||||
}
|
||||
|
||||
describe("WebSocket Server", () => {
|
||||
let server: Http.Server | null = null;
|
||||
@@ -736,9 +726,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
issues: [],
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
|
||||
it("bootstraps default keybindings file when missing", async () => {
|
||||
@@ -761,9 +749,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
issues: [],
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
|
||||
const persistedConfig = JSON.parse(
|
||||
fs.readFileSync(keybindingsPath, "utf8"),
|
||||
@@ -796,9 +782,7 @@ describe("WebSocket Server", () => {
|
||||
message: expect.stringContaining("expected JSON array"),
|
||||
},
|
||||
],
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
|
||||
});
|
||||
|
||||
@@ -830,7 +814,6 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: string;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
issues: Array<{ kind: string; index?: number; message: string }>;
|
||||
availableEditors: unknown;
|
||||
};
|
||||
expect(result.cwd).toBe("/my/workspace");
|
||||
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
|
||||
@@ -849,7 +832,6 @@ describe("WebSocket Server", () => {
|
||||
expect(result.keybindings).toHaveLength(DEFAULT_RESOLVED_KEYBINDINGS.length);
|
||||
expect(result.keybindings.some((entry) => entry.command === "terminal.toggle")).toBe(true);
|
||||
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
|
||||
expectAvailableEditors(result.availableEditors);
|
||||
});
|
||||
|
||||
it("pushes server.configUpdated issues when keybindings file changes", async () => {
|
||||
@@ -947,9 +929,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
issues: [],
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
|
||||
it("upserts keybinding rules and updates cached server config", async () => {
|
||||
@@ -994,11 +974,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
issues: [],
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors(
|
||||
(configResponse.result as { availableEditors: unknown }).availableEditors,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns error for unknown methods", async () => {
|
||||
|
||||
@@ -54,7 +54,7 @@ import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReac
|
||||
import { ProviderService } from "./provider/Services/ProviderService";
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
||||
import { clamp } from "effect/Number";
|
||||
import { Open, resolveAvailableEditors } from "./open";
|
||||
import { Open } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
@@ -63,11 +63,7 @@ import {
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths";
|
||||
import {
|
||||
createAttachmentId,
|
||||
resolveAttachmentPath,
|
||||
resolveAttachmentPathById,
|
||||
} from "./attachmentStore.ts";
|
||||
import { createAttachmentId, resolveAttachmentPath, resolveAttachmentPathById } from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
|
||||
/**
|
||||
@@ -193,7 +189,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
logWebSocketEvents,
|
||||
autoBootstrapProjectFromCwd,
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
@@ -690,7 +685,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case WS_METHODS.gitCheckout: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* Effect.scoped(git.checkoutBranch(body));
|
||||
return yield* git.checkoutBranch(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitInit: {
|
||||
@@ -735,7 +730,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
keybindingsConfigPath,
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
availableEditors,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
@@ -23,7 +22,6 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
|
||||
@@ -1,10 +1,67 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { ThreadId, type GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
deriveSyncedLocalBranch,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: threadId,
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: threadId,
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: threadId,
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
it("strips the remote prefix from a remote ref", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import type { GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: ThreadId | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
queryBranches: ReadonlyArray<GitBranch> | undefined;
|
||||
}
|
||||
|
||||
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
|
||||
const firstSeparatorIndex = branchName.indexOf("/");
|
||||
@@ -47,3 +55,22 @@ export function dedupeRemoteBranchesWithLocalMatches(
|
||||
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -1,15 +1,20 @@
|
||||
import type { GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useOptimistic, useState, useTransition } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { newCommandId } from "../lib/utils";
|
||||
import { gitBranchesQueryOptions, invalidateGitQueries } from "../lib/gitReactQuery";
|
||||
import {
|
||||
gitBranchesQueryOptions,
|
||||
gitCheckoutMutationOptions,
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useStore } from "../store";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
deriveSyncedLocalBranch,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
@@ -22,7 +27,6 @@ import {
|
||||
ComboboxTrigger,
|
||||
} from "./ui/combobox";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { toastManager } from "./ui/toast";
|
||||
|
||||
interface BranchToolbarProps {
|
||||
threadId: ThreadId;
|
||||
@@ -39,10 +43,7 @@ export default function BranchToolbar({
|
||||
envLocked,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarProps) {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
|
||||
const setThreadErrorAction = useStore((store) => store.setError);
|
||||
const { state, dispatch } = useStore();
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const queryClient = useQueryClient();
|
||||
@@ -50,9 +51,9 @@ export default function BranchToolbar({
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
|
||||
const serverThread = threads.find((thread) => thread.id === threadId);
|
||||
const serverThread = state.threads.find((thread) => thread.id === threadId);
|
||||
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
|
||||
const activeProject = projects.find((project) => project.id === activeProjectId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeProjectId);
|
||||
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
|
||||
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
@@ -68,11 +69,6 @@ export default function BranchToolbar({
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||
|
||||
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
|
||||
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
|
||||
const canonicalActiveBranch =
|
||||
effectiveEnvMode === "worktree" && !activeWorktreePath
|
||||
? activeThreadBranch
|
||||
: (currentGitBranch ?? activeThreadBranch);
|
||||
const branchNames = branches.map((branch) => branch.name);
|
||||
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
|
||||
const trimmedBranchQuery = branchQuery.trim();
|
||||
@@ -85,24 +81,68 @@ export default function BranchToolbar({
|
||||
createBranchItemValue && !hasExactBranchMatch
|
||||
? [...branchNames, createBranchItemValue]
|
||||
: branchNames;
|
||||
// ── Mutations ─────────────────────────────────────────────────────────
|
||||
|
||||
const checkoutMutation = useMutation(gitCheckoutMutationOptions({ cwd: branchCwd, queryClient }));
|
||||
|
||||
const createBranchMutation = useMutation(
|
||||
gitCreateBranchAndCheckoutMutationOptions({ cwd: branchCwd, queryClient }),
|
||||
);
|
||||
|
||||
// ── Effects ───────────────────────────────────────────────────────────
|
||||
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode: effectiveEnvMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
const api = readNativeApi();
|
||||
|
||||
if (api && hasServerThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
dispatch.setThreadBranch(activeThreadId, syncedBranch, null);
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(threadId, {
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
effectiveEnvMode,
|
||||
dispatch,
|
||||
hasServerThread,
|
||||
setDraftThreadContext,
|
||||
threadId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
setBranchQuery("");
|
||||
}, [isBranchMenuOpen]);
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
|
||||
canonicalActiveBranch,
|
||||
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
||||
);
|
||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||
const runBranchAction = (action: () => Promise<void>) => {
|
||||
startBranchActionTransition(async () => {
|
||||
await action().catch(() => undefined);
|
||||
await invalidateGitQueries(queryClient).catch(() => undefined);
|
||||
});
|
||||
};
|
||||
|
||||
const setThreadError = (error: string | null) => {
|
||||
if (!activeThreadId) return;
|
||||
setThreadErrorAction(activeThreadId, error);
|
||||
dispatch.setError(activeThreadId, error);
|
||||
};
|
||||
|
||||
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
|
||||
@@ -131,7 +171,7 @@ export default function BranchToolbar({
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
setThreadBranchAction(activeThreadId, branch, worktreePath);
|
||||
dispatch.setThreadBranch(activeThreadId, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(threadId, {
|
||||
@@ -143,10 +183,11 @@ export default function BranchToolbar({
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !branchCwd || isBranchActionPending) return;
|
||||
if (!api || !activeThreadId || !branchCwd) return;
|
||||
|
||||
// For new worktree mode, selecting a branch picks the base branch.
|
||||
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||
setThreadError(null);
|
||||
setThreadBranch(branch.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
@@ -157,6 +198,7 @@ export default function BranchToolbar({
|
||||
// trying to checkout (which git would reject with "already used by worktree").
|
||||
if (branch.worktreePath) {
|
||||
const isMainWorktree = branch.worktreePath === activeProject?.cwd;
|
||||
setThreadError(null);
|
||||
// Main worktree → switch back to local (project cwd, worktreePath=null).
|
||||
// Secondary worktree → point the thread at that worktree path.
|
||||
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
|
||||
@@ -169,71 +211,42 @@ export default function BranchToolbar({
|
||||
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||
: branch.name;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
|
||||
runBranchAction(async () => {
|
||||
setOptimisticBranch(selectedBranchName);
|
||||
try {
|
||||
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
|
||||
await invalidateGitQueries(queryClient);
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let nextBranchName = selectedBranchName;
|
||||
if (branch.isRemote) {
|
||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||
if (status?.branch) {
|
||||
nextBranchName = status.branch;
|
||||
checkoutMutation.mutate(branch.name, {
|
||||
onSuccess: async () => {
|
||||
setThreadError(null);
|
||||
let nextBranchName = selectedBranchName;
|
||||
if (branch.isRemote) {
|
||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||
if (status?.branch) {
|
||||
nextBranchName = status.branch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setOptimisticBranch(nextBranchName);
|
||||
setThreadBranch(nextBranchName, activeWorktreePath);
|
||||
setThreadBranch(nextBranchName, activeWorktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const createBranch = (rawName: string) => {
|
||||
const name = rawName.trim();
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !branchCwd || !name || isBranchActionPending) return;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
|
||||
runBranchAction(async () => {
|
||||
setOptimisticBranch(name);
|
||||
|
||||
try {
|
||||
await api.git.createBranch({ cwd: branchCwd, branch: name });
|
||||
try {
|
||||
await api.git.checkout({ cwd: branchCwd, branch: name });
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to create branch.",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setOptimisticBranch(name);
|
||||
setThreadBranch(name, activeWorktreePath);
|
||||
setBranchQuery("");
|
||||
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
|
||||
createBranchMutation.mutate(name, {
|
||||
onSuccess: () => {
|
||||
setThreadError(null);
|
||||
setThreadBranch(name, activeWorktreePath);
|
||||
setBranchQuery("");
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -252,7 +265,9 @@ export default function BranchToolbar({
|
||||
variant="ghost"
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
size="xs"
|
||||
onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")}
|
||||
onClick={() =>
|
||||
onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")
|
||||
}
|
||||
>
|
||||
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
|
||||
</Button>
|
||||
@@ -262,24 +277,20 @@ export default function BranchToolbar({
|
||||
<Combobox
|
||||
items={branchPickerItems}
|
||||
autoHighlight
|
||||
onOpenChange={(open) => {
|
||||
setIsBranchMenuOpen(open);
|
||||
if (!open) setBranchQuery("");
|
||||
else void invalidateGitQueries(queryClient);
|
||||
}}
|
||||
onOpenChange={(open) => setIsBranchMenuOpen(open)}
|
||||
open={isBranchMenuOpen}
|
||||
value={resolvedActiveBranch}
|
||||
value={activeThreadBranch}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={branchesQuery.isLoading || isBranchActionPending}
|
||||
disabled={branchesQuery.isLoading}
|
||||
>
|
||||
<span className="max-w-[240px] truncate">
|
||||
{resolvedActiveBranch
|
||||
{activeThreadBranch
|
||||
? effectiveEnvMode === "worktree" && !activeWorktreePath
|
||||
? `From ${resolvedActiveBranch}`
|
||||
: resolvedActiveBranch
|
||||
? `From ${activeThreadBranch}`
|
||||
: activeThreadBranch
|
||||
: "Select branch"}
|
||||
</span>
|
||||
<ChevronDownIcon />
|
||||
@@ -333,15 +344,13 @@ export default function BranchToolbar({
|
||||
key={itemValue}
|
||||
value={itemValue}
|
||||
className={
|
||||
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
|
||||
itemValue === activeThreadBranch ? "bg-accent text-foreground" : undefined
|
||||
}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="truncate">{itemValue}</span>
|
||||
{badge && (
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
|
||||
)}
|
||||
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,813 +0,0 @@
|
||||
import {
|
||||
LexicalComposer,
|
||||
type InitialConfigType,
|
||||
} from "@lexical/react/LexicalComposer";
|
||||
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
|
||||
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
|
||||
import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
|
||||
import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
|
||||
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
|
||||
import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
|
||||
import {
|
||||
$applyNodeReplacement,
|
||||
$createRangeSelection,
|
||||
$getSelection,
|
||||
$setSelection,
|
||||
$isElementNode,
|
||||
$isLineBreakNode,
|
||||
$isRangeSelection,
|
||||
$isTextNode,
|
||||
$createLineBreakNode,
|
||||
$createParagraphNode,
|
||||
$createTextNode,
|
||||
KEY_ARROW_DOWN_COMMAND,
|
||||
KEY_ARROW_LEFT_COMMAND,
|
||||
KEY_ARROW_RIGHT_COMMAND,
|
||||
KEY_ARROW_UP_COMMAND,
|
||||
KEY_ENTER_COMMAND,
|
||||
KEY_TAB_COMMAND,
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
KEY_BACKSPACE_COMMAND,
|
||||
$getRoot,
|
||||
type ElementNode,
|
||||
type LexicalNode,
|
||||
TextNode,
|
||||
type EditorConfig,
|
||||
type EditorState,
|
||||
type NodeKey,
|
||||
type SerializedTextNode,
|
||||
type Spread,
|
||||
} from "lexical";
|
||||
import {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ClipboardEventHandler,
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
|
||||
|
||||
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
type SerializedComposerMentionNode = Spread<
|
||||
{
|
||||
path: string;
|
||||
type: "composer-mention";
|
||||
version: 1;
|
||||
},
|
||||
SerializedTextNode
|
||||
>;
|
||||
|
||||
class ComposerMentionNode extends TextNode {
|
||||
__path: string;
|
||||
|
||||
static override getType(): string {
|
||||
return "composer-mention";
|
||||
}
|
||||
|
||||
static override clone(node: ComposerMentionNode): ComposerMentionNode {
|
||||
return new ComposerMentionNode(node.__path, node.__key);
|
||||
}
|
||||
|
||||
static override importJSON(serializedNode: SerializedComposerMentionNode): ComposerMentionNode {
|
||||
return $createComposerMentionNode(serializedNode.path);
|
||||
}
|
||||
|
||||
constructor(path: string, key?: NodeKey) {
|
||||
const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
|
||||
super(`@${normalizedPath}`, key);
|
||||
this.__path = normalizedPath;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerMentionNode {
|
||||
return {
|
||||
...super.exportJSON(),
|
||||
path: this.__path,
|
||||
type: "composer-mention",
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(_config: EditorConfig): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className =
|
||||
"inline-flex select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
dom.contentEditable = "false";
|
||||
dom.setAttribute("spellcheck", "false");
|
||||
renderMentionChipDom(dom, this.__path);
|
||||
return dom;
|
||||
}
|
||||
|
||||
override updateDOM(
|
||||
prevNode: ComposerMentionNode,
|
||||
dom: HTMLElement,
|
||||
_config: EditorConfig,
|
||||
): boolean {
|
||||
dom.contentEditable = "false";
|
||||
if (prevNode.__text !== this.__text || prevNode.__path !== this.__path) {
|
||||
renderMentionChipDom(dom, this.__path);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
override canInsertTextBefore(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override canInsertTextAfter(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override isTextEntity(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
override isToken(): true {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function $createComposerMentionNode(path: string): ComposerMentionNode {
|
||||
return $applyNodeReplacement(new ComposerMentionNode(path));
|
||||
}
|
||||
|
||||
function inferMentionPathKind(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||
return "directory";
|
||||
}
|
||||
if (base.includes(".")) {
|
||||
return "file";
|
||||
}
|
||||
return "directory";
|
||||
}
|
||||
|
||||
function resolvedThemeFromDocument(): "light" | "dark" {
|
||||
return document.documentElement.classList.contains("dark") ? "dark" : "light";
|
||||
}
|
||||
|
||||
function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
|
||||
container.textContent = "";
|
||||
container.style.setProperty("user-select", "none");
|
||||
container.style.setProperty("-webkit-user-select", "none");
|
||||
|
||||
const theme = resolvedThemeFromDocument();
|
||||
const icon = document.createElement("img");
|
||||
icon.alt = "";
|
||||
icon.ariaHidden = "true";
|
||||
icon.className = "size-3.5 shrink-0 opacity-85";
|
||||
icon.loading = "lazy";
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = "truncate select-none leading-tight";
|
||||
label.textContent = basenameOfPath(pathValue);
|
||||
|
||||
container.append(icon, label);
|
||||
}
|
||||
|
||||
function clampCursor(value: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return value.length;
|
||||
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
|
||||
}
|
||||
|
||||
function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return 1;
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
}
|
||||
if ($isLineBreakNode(node)) {
|
||||
return 1;
|
||||
}
|
||||
if ($isElementNode(node)) {
|
||||
return node.getChildren().reduce((total, child) => total + getComposerNodeTextLength(child), 0);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
|
||||
let offset = 0;
|
||||
let current: LexicalNode | null = node;
|
||||
|
||||
while (current) {
|
||||
const nextParent = current.getParent() as LexicalNode | null;
|
||||
if (!nextParent || !$isElementNode(nextParent)) {
|
||||
break;
|
||||
}
|
||||
const siblings = nextParent.getChildren();
|
||||
const index = current.getIndexWithinParent();
|
||||
for (let i = 0; i < index; i += 1) {
|
||||
const sibling = siblings[i];
|
||||
if (!sibling) continue;
|
||||
offset += getComposerNodeTextLength(sibling);
|
||||
}
|
||||
current = nextParent;
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return offset + (pointOffset > 0 ? 1 : 0);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
return offset + Math.min(pointOffset, 1);
|
||||
}
|
||||
|
||||
if ($isElementNode(node)) {
|
||||
const children = node.getChildren();
|
||||
const clampedOffset = Math.max(0, Math.min(pointOffset, children.length));
|
||||
for (let i = 0; i < clampedOffset; i += 1) {
|
||||
const child = children[i];
|
||||
if (!child) continue;
|
||||
offset += getComposerNodeTextLength(child);
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
function findSelectionPointAtOffset(
|
||||
node: LexicalNode,
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
const parent = node.getParent();
|
||||
if (!parent || !$isElementNode(parent)) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === 1) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
const size = node.getTextContentSize();
|
||||
if (remainingRef.value <= size) {
|
||||
return {
|
||||
key: node.getKey(),
|
||||
offset: remainingRef.value,
|
||||
type: "text",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= size;
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
const parent = node.getParent();
|
||||
if (!parent) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === 1) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($isElementNode(node)) {
|
||||
const children = node.getChildren();
|
||||
for (const child of children) {
|
||||
const point = findSelectionPointAtOffset(child, remainingRef);
|
||||
if (point) {
|
||||
return point;
|
||||
}
|
||||
}
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: node.getKey(),
|
||||
offset: children.length,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function $getComposerRootLength(): number {
|
||||
const root = $getRoot();
|
||||
const children = root.getChildren();
|
||||
return children.reduce((sum, child) => sum + getComposerNodeTextLength(child), 0);
|
||||
}
|
||||
|
||||
function $setSelectionAtComposerOffset(nextOffset: number): void {
|
||||
const root = $getRoot();
|
||||
const composerLength = $getComposerRootLength();
|
||||
const boundedOffset = Math.max(0, Math.min(nextOffset, composerLength));
|
||||
const remainingRef = { value: boundedOffset };
|
||||
const point =
|
||||
findSelectionPointAtOffset(root, remainingRef) ?? {
|
||||
key: root.getKey(),
|
||||
offset: root.getChildren().length,
|
||||
type: "element" as const,
|
||||
};
|
||||
const selection = $createRangeSelection();
|
||||
selection.anchor.set(point.key, point.offset, point.type);
|
||||
selection.focus.set(point.key, point.offset, point.type);
|
||||
$setSelection(selection);
|
||||
}
|
||||
|
||||
function $readSelectionOffsetFromEditorState(fallback: number): number {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
|
||||
return fallback;
|
||||
}
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
const offset = getAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
|
||||
const composerLength = $getComposerRootLength();
|
||||
return Math.max(0, Math.min(offset, composerLength));
|
||||
}
|
||||
|
||||
function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||
const lines = text.split("\n");
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
const line = lines[index] ?? "";
|
||||
if (line.length > 0) {
|
||||
parent.append($createTextNode(line));
|
||||
}
|
||||
if (index < lines.length - 1) {
|
||||
parent.append($createLineBreakNode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function $setComposerEditorPrompt(prompt: string): void {
|
||||
const root = $getRoot();
|
||||
root.clear();
|
||||
const paragraph = $createParagraphNode();
|
||||
root.append(paragraph);
|
||||
|
||||
const segments = splitPromptIntoComposerSegments(prompt);
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
paragraph.append($createComposerMentionNode(segment.path));
|
||||
continue;
|
||||
}
|
||||
$appendTextWithLineBreaks(paragraph, segment.text);
|
||||
}
|
||||
}
|
||||
|
||||
export interface ComposerPromptEditorHandle {
|
||||
focus: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
focusAtEnd: () => void;
|
||||
readSnapshot: () => { value: string; cursor: number };
|
||||
}
|
||||
|
||||
interface ComposerPromptEditorProps {
|
||||
value: string;
|
||||
cursor: number;
|
||||
disabled: boolean;
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
onChange: (nextValue: string, nextCursor: number, cursorAdjacentToMention: boolean) => void;
|
||||
onCommandKeyDown?: (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
) => boolean;
|
||||
onPaste: ClipboardEventHandler<HTMLElement>;
|
||||
}
|
||||
|
||||
interface ComposerPromptEditorInnerProps extends ComposerPromptEditorProps {
|
||||
editorRef: Ref<ComposerPromptEditorHandle>;
|
||||
}
|
||||
|
||||
function ComposerCommandKeyPlugin(props: {
|
||||
onCommandKeyDown?: (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
) => boolean;
|
||||
}) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
const handleCommand = (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent | null,
|
||||
): boolean => {
|
||||
if (!props.onCommandKeyDown || !event) {
|
||||
return false;
|
||||
}
|
||||
const handled = props.onCommandKeyDown(key, event);
|
||||
if (handled) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
return handled;
|
||||
};
|
||||
|
||||
const unregisterArrowDown = editor.registerCommand(
|
||||
KEY_ARROW_DOWN_COMMAND,
|
||||
(event) => handleCommand("ArrowDown", event),
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
const unregisterArrowUp = editor.registerCommand(
|
||||
KEY_ARROW_UP_COMMAND,
|
||||
(event) => handleCommand("ArrowUp", event),
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
const unregisterEnter = editor.registerCommand(
|
||||
KEY_ENTER_COMMAND,
|
||||
(event) => handleCommand("Enter", event),
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
const unregisterTab = editor.registerCommand(
|
||||
KEY_TAB_COMMAND,
|
||||
(event) => handleCommand("Tab", event),
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
|
||||
return () => {
|
||||
unregisterArrowDown();
|
||||
unregisterArrowUp();
|
||||
unregisterEnter();
|
||||
unregisterTab();
|
||||
};
|
||||
}, [editor, props]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionArrowPlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
const unregisterLeft = editor.registerCommand(
|
||||
KEY_ARROW_LEFT_COMMAND,
|
||||
() => {
|
||||
let currentOffset = -1;
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
});
|
||||
if (currentOffset <= 0) return false;
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(currentOffset - 1);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
const unregisterRight = editor.registerCommand(
|
||||
KEY_ARROW_RIGHT_COMMAND,
|
||||
() => {
|
||||
let currentOffset = -1;
|
||||
let composerLength = 0;
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
composerLength = $getComposerRootLength();
|
||||
currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
});
|
||||
if (currentOffset < 0 || currentOffset >= composerLength) return false;
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(currentOffset + 1);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
return () => {
|
||||
unregisterLeft();
|
||||
unregisterRight();
|
||||
};
|
||||
}, [editor]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionSelectionNormalizePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerUpdateListener(({ editorState }) => {
|
||||
let afterOffset: number | null = null;
|
||||
editorState.read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
if (!(anchorNode instanceof ComposerMentionNode)) return;
|
||||
if (selection.anchor.offset === 0) return;
|
||||
const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
|
||||
afterOffset = beforeOffset + 1;
|
||||
});
|
||||
if (afterOffset !== null) {
|
||||
queueMicrotask(() => {
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(afterOffset!);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}, [editor]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function $isCursorAdjacentToMention(): boolean {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
|
||||
if (anchorNode instanceof ComposerMentionNode) return true;
|
||||
|
||||
if ($isElementNode(anchorNode)) {
|
||||
const childIndex = selection.anchor.offset - 1;
|
||||
if (childIndex >= 0) {
|
||||
const child = anchorNode.getChildAtIndex(childIndex);
|
||||
if (child instanceof ComposerMentionNode) return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($isTextNode(anchorNode) && selection.anchor.offset === 0) {
|
||||
const prev = anchorNode.getPreviousSibling();
|
||||
if (prev instanceof ComposerMentionNode) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function ComposerMentionBackspacePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerCommand(
|
||||
KEY_BACKSPACE_COMMAND,
|
||||
(event) => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
const removeMentionNode = (candidate: unknown): boolean => {
|
||||
if (!(candidate instanceof ComposerMentionNode)) {
|
||||
return false;
|
||||
}
|
||||
const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
candidate.remove();
|
||||
$setSelectionAtComposerOffset(mentionStart);
|
||||
event?.preventDefault();
|
||||
return true;
|
||||
};
|
||||
|
||||
if (removeMentionNode(anchorNode)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($isTextNode(anchorNode)) {
|
||||
if (selection.anchor.offset > 0) {
|
||||
return false;
|
||||
}
|
||||
if (removeMentionNode(anchorNode.getPreviousSibling())) {
|
||||
return true;
|
||||
}
|
||||
const parent = anchorNode.getParent();
|
||||
if ($isElementNode(parent)) {
|
||||
const index = anchorNode.getIndexWithinParent();
|
||||
if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($isElementNode(anchorNode)) {
|
||||
const childIndex = selection.anchor.offset - 1;
|
||||
if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
}, [editor]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
editorRef,
|
||||
}: ComposerPromptEditorInnerProps) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const onChangeRef = useRef(onChange);
|
||||
const snapshotRef = useRef({ value, cursor: clampCursor(value, cursor) });
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
useEffect(() => {
|
||||
editor.setEditable(!disabled);
|
||||
}, [disabled, editor]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const normalizedCursor = clampCursor(value, cursor);
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (previousSnapshot.value !== value) {
|
||||
editor.update(() => {
|
||||
$setComposerEditorPrompt(value);
|
||||
});
|
||||
}
|
||||
|
||||
snapshotRef.current = { value, cursor: normalizedCursor };
|
||||
|
||||
const rootElement = editor.getRootElement();
|
||||
if (!rootElement || document.activeElement !== rootElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
});
|
||||
}, [cursor, editor, value]);
|
||||
|
||||
const focusAt = useCallback(
|
||||
(nextCursor: number) => {
|
||||
const rootElement = editor.getRootElement();
|
||||
if (!rootElement) return;
|
||||
const boundedCursor = clampCursor(snapshotRef.current.value, nextCursor);
|
||||
rootElement.focus();
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(boundedCursor);
|
||||
});
|
||||
snapshotRef.current = {
|
||||
value: snapshotRef.current.value,
|
||||
cursor: boundedCursor,
|
||||
};
|
||||
onChangeRef.current(snapshotRef.current.value, boundedCursor, false);
|
||||
},
|
||||
[editor],
|
||||
);
|
||||
|
||||
const readSnapshot = useCallback((): { value: string; cursor: number } => {
|
||||
let snapshot = snapshotRef.current;
|
||||
editor.getEditorState().read(() => {
|
||||
const nextValue = $getRoot().getTextContent();
|
||||
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
|
||||
const nextCursor = clampCursor(
|
||||
nextValue,
|
||||
$readSelectionOffsetFromEditorState(fallbackCursor),
|
||||
);
|
||||
snapshot = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
};
|
||||
});
|
||||
snapshotRef.current = snapshot;
|
||||
return snapshot;
|
||||
}, [editor]);
|
||||
|
||||
useImperativeHandle(
|
||||
editorRef,
|
||||
() => ({
|
||||
focus: () => {
|
||||
focusAt(snapshotRef.current.cursor);
|
||||
},
|
||||
focusAt: (nextCursor: number) => {
|
||||
focusAt(nextCursor);
|
||||
},
|
||||
focusAtEnd: () => {
|
||||
focusAt(snapshotRef.current.value.length);
|
||||
},
|
||||
readSnapshot,
|
||||
}),
|
||||
[focusAt, readSnapshot],
|
||||
);
|
||||
|
||||
const handleEditorChange = useCallback((editorState: EditorState) => {
|
||||
editorState.read(() => {
|
||||
const nextValue = $getRoot().getTextContent();
|
||||
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
|
||||
const nextCursor = clampCursor(nextValue, $readSelectionOffsetFromEditorState(fallbackCursor));
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
|
||||
return;
|
||||
}
|
||||
snapshotRef.current = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
};
|
||||
onChangeRef.current(nextValue, nextCursor, $isCursorAdjacentToMention());
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
|
||||
className,
|
||||
)}
|
||||
aria-placeholder={placeholder}
|
||||
placeholder={<span />}
|
||||
onPaste={onPaste}
|
||||
/>
|
||||
}
|
||||
placeholder={
|
||||
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
|
||||
{placeholder}
|
||||
</div>
|
||||
}
|
||||
ErrorBoundary={LexicalErrorBoundary}
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerMentionArrowPlugin />
|
||||
<ComposerMentionSelectionNormalizePlugin />
|
||||
<ComposerMentionBackspacePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const ComposerPromptEditor = forwardRef<ComposerPromptEditorHandle, ComposerPromptEditorProps>(
|
||||
function ComposerPromptEditor(
|
||||
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
|
||||
ref,
|
||||
) {
|
||||
const initialValueRef = useRef(value);
|
||||
const initialConfig = useMemo<InitialConfigType>(
|
||||
() => ({
|
||||
namespace: "t3tools-composer-editor",
|
||||
editable: true,
|
||||
nodes: [ComposerMentionNode],
|
||||
editorState: () => {
|
||||
$setComposerEditorPrompt(initialValueRef.current);
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>
|
||||
<ComposerPromptEditorInner
|
||||
value={value}
|
||||
cursor={cursor}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onChange={onChange}
|
||||
onPaste={onPaste}
|
||||
editorRef={ref}
|
||||
{...(onCommandKeyDown ? { onCommandKeyDown } : {})}
|
||||
{...(className ? { className } : {})}
|
||||
/>
|
||||
</LexicalComposer>
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -4,7 +4,7 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
@@ -156,6 +156,7 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { state } = useStore();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
@@ -167,13 +168,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
});
|
||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = useStore((store) =>
|
||||
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
|
||||
);
|
||||
const activeProjectId = activeThread?.projectId ?? null;
|
||||
const activeProject = useStore((store) =>
|
||||
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
||||
);
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
@@ -346,7 +342,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
if (!element) return;
|
||||
element.scrollBy({ left: offset, behavior: "smooth" });
|
||||
}, []);
|
||||
const onTurnStripWheel = useCallback((event: ReactWheelEvent<HTMLDivElement>) => {
|
||||
const onTurnStripWheel = useCallback((event: WheelEvent) => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
if (element.scrollWidth <= element.clientWidth + 1) return;
|
||||
@@ -360,26 +356,24 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
|
||||
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
|
||||
updateTurnStripScrollState();
|
||||
const onScroll = () => updateTurnStripScrollState();
|
||||
|
||||
element.addEventListener("scroll", onScroll, { passive: true });
|
||||
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
|
||||
resizeObserver.observe(element);
|
||||
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
element.removeEventListener("scroll", onScroll);
|
||||
element.removeEventListener("wheel", onTurnStripWheel);
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [updateTurnStripScrollState]);
|
||||
}, [updateTurnStripScrollState, onTurnStripWheel]);
|
||||
|
||||
useEffect(() => {
|
||||
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
};
|
||||
updateTurnStripScrollState();
|
||||
}, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -428,11 +422,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
>
|
||||
<ChevronRightIcon className="size-3.5" />
|
||||
</button>
|
||||
<div
|
||||
ref={turnStripRef}
|
||||
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
|
||||
onWheel={onTurnStripWheel}
|
||||
>
|
||||
<div ref={turnStripRef} className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5">
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type SVGProps, useId } from "react";
|
||||
import type { SVGProps } from "react";
|
||||
|
||||
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
|
||||
|
||||
@@ -19,126 +19,3 @@ export const CursorIcon: Icon = (props) => (
|
||||
<path 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" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const VisualStudioCode: Icon = (props) => {
|
||||
const id = useId();
|
||||
const maskId = `${id}-vscode-a`;
|
||||
const topShadowFilterId = `${id}-vscode-b`;
|
||||
const sideShadowFilterId = `${id}-vscode-c`;
|
||||
const overlayGradientId = `${id}-vscode-d`;
|
||||
|
||||
return (
|
||||
<svg {...props} fill="none" viewBox="0 0 100 100">
|
||||
<mask id={maskId} width="100" height="100" x="0" y="0" maskUnits="userSpaceOnUse">
|
||||
<path
|
||||
fill="#fff"
|
||||
fillRule="evenodd"
|
||||
d="M70.912 99.317a6.223 6.223 0 0 0 4.96-.19l20.589-9.907A6.25 6.25 0 0 0 100 83.587V16.413a6.25 6.25 0 0 0-3.54-5.632L75.874.874a6.226 6.226 0 0 0-7.104 1.21L29.355 38.04 12.187 25.01a4.162 4.162 0 0 0-5.318.236l-5.506 5.009a4.168 4.168 0 0 0-.004 6.162L16.247 50 1.36 63.583a4.168 4.168 0 0 0 .004 6.162l5.506 5.01a4.162 4.162 0 0 0 5.318.236l17.168-13.032L68.77 97.917a6.217 6.217 0 0 0 2.143 1.4ZM75.015 27.3 45.11 50l29.906 22.701V27.3Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</mask>
|
||||
<g mask={`url(#${maskId})`}>
|
||||
<path
|
||||
fill="#0065A9"
|
||||
d="M96.461 10.796 75.857.876a6.23 6.23 0 0 0-7.107 1.207l-67.451 61.5a4.167 4.167 0 0 0 .004 6.162l5.51 5.009a4.167 4.167 0 0 0 5.32.236l81.228-61.62c2.725-2.067 6.639-.124 6.639 3.297v-.24a6.25 6.25 0 0 0-3.539-5.63Z"
|
||||
/>
|
||||
<g filter={`url(#${topShadowFilterId})`}>
|
||||
<path
|
||||
fill="#007ACC"
|
||||
d="m96.461 89.204-20.604 9.92a6.229 6.229 0 0 1-7.107-1.207l-67.451-61.5a4.167 4.167 0 0 1 .004-6.162l5.51-5.009a4.167 4.167 0 0 1 5.32-.236l81.228 61.62c2.725 2.067 6.639.124 6.639-3.297v.24a6.25 6.25 0 0 1-3.539 5.63Z"
|
||||
/>
|
||||
</g>
|
||||
<g filter={`url(#${sideShadowFilterId})`}>
|
||||
<path
|
||||
fill="#1F9CF0"
|
||||
d="M75.858 99.126a6.232 6.232 0 0 1-7.108-1.21c2.306 2.307 6.25.674 6.25-2.588V4.672c0-3.262-3.944-4.895-6.25-2.589a6.232 6.232 0 0 1 7.108-1.21l20.6 9.908A6.25 6.25 0 0 1 100 16.413v67.174a6.25 6.25 0 0 1-3.541 5.633l-20.601 9.906Z"
|
||||
/>
|
||||
</g>
|
||||
<path
|
||||
fill={`url(#${overlayGradientId})`}
|
||||
fillRule="evenodd"
|
||||
d="M70.851 99.317a6.224 6.224 0 0 0 4.96-.19L96.4 89.22a6.25 6.25 0 0 0 3.54-5.633V16.413a6.25 6.25 0 0 0-3.54-5.632L75.812.874a6.226 6.226 0 0 0-7.104 1.21L29.294 38.04 12.126 25.01a4.162 4.162 0 0 0-5.317.236l-5.507 5.009a4.168 4.168 0 0 0-.004 6.162L16.186 50 1.298 63.583a4.168 4.168 0 0 0 .004 6.162l5.507 5.009a4.162 4.162 0 0 0 5.317.236L29.294 61.96l39.414 35.958a6.218 6.218 0 0 0 2.143 1.4ZM74.954 27.3 45.048 50l29.906 22.701V27.3Z"
|
||||
clipRule="evenodd"
|
||||
opacity=".25"
|
||||
style={{ mixBlendMode: "overlay" }}
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<filter
|
||||
id={topShadowFilterId}
|
||||
width="116.727"
|
||||
height="92.246"
|
||||
x="-8.394"
|
||||
y="15.829"
|
||||
colorInterpolationFilters="sRGB"
|
||||
filterUnits="userSpaceOnUse"
|
||||
>
|
||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
/>
|
||||
<feOffset />
|
||||
<feGaussianBlur stdDeviation="4.167" />
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
|
||||
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
|
||||
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
|
||||
</filter>
|
||||
<filter
|
||||
id={sideShadowFilterId}
|
||||
width="47.917"
|
||||
height="116.151"
|
||||
x="60.417"
|
||||
y="-8.076"
|
||||
colorInterpolationFilters="sRGB"
|
||||
filterUnits="userSpaceOnUse"
|
||||
>
|
||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
/>
|
||||
<feOffset />
|
||||
<feGaussianBlur stdDeviation="4.167" />
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
|
||||
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
|
||||
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
|
||||
</filter>
|
||||
<linearGradient
|
||||
id={overlayGradientId}
|
||||
x1="49.939"
|
||||
x2="49.939"
|
||||
y1=".258"
|
||||
y2="99.742"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#fff" />
|
||||
<stop offset="1" stopColor="#fff" stopOpacity="0" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const Zed: Icon = (props) => {
|
||||
const id = useId();
|
||||
const clipPathId = `${id}-zed-logo-a`;
|
||||
|
||||
return (
|
||||
<svg {...props} fill="none" viewBox="0 0 96 96">
|
||||
<g clipPath={`url(#${clipPathId})`}>
|
||||
<path
|
||||
fill="currentColor"
|
||||
fillRule="evenodd"
|
||||
d="M9 6a3 3 0 0 0-3 3v66H0V9a9 9 0 0 1 9-9h80.379c4.009 0 6.016 4.847 3.182 7.682L43.055 57.187H57V51h6v7.688a4.5 4.5 0 0 1-4.5 4.5H37.055L26.743 73.5H73.5V36h6v37.5a6 6 0 0 1-6 6H20.743L10.243 90H87a3 3 0 0 0 3-3V21h6v66a9 9 0 0 1-9 9H6.621c-4.009 0-6.016-4.847-3.182-7.682L52.757 39H39v6h-6v-7.5a4.5 4.5 0 0 1 4.5-4.5h21.257l10.5-10.5H22.5V60h-6V22.5a6 6 0 0 1 6-6h52.757L85.757 6H9Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id={clipPathId}>
|
||||
<path fill="#fff" d="M0 0h96v96H0z" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
ProjectId,
|
||||
@@ -21,7 +21,7 @@ import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
@@ -231,17 +231,13 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const markThreadUnread = useStore((store) => store.markThreadUnread);
|
||||
const toggleProject = useStore((store) => store.toggleProject);
|
||||
const { state, dispatch } = useStore();
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
|
||||
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||
(store) => store.getDraftThreadByProjectId,
|
||||
);
|
||||
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
|
||||
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
|
||||
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
|
||||
const getTerminalState = useTerminalStateStore((s) => s.getTerminalState);
|
||||
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const clearProjectDraftThreadId = useComposerDraftStore(
|
||||
@@ -266,29 +262,25 @@ export default function Sidebar() {
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
const [isAddingProject, setIsAddingProject] = useState(false);
|
||||
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
|
||||
const [renamingTitle, setRenamingTitle] = useState("");
|
||||
const renamingCommittedRef = useRef(false);
|
||||
const renamingInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const pendingApprovalByThreadId = useMemo(() => {
|
||||
const map = new Map<ThreadId, boolean>();
|
||||
for (const thread of threads) {
|
||||
for (const thread of state.threads) {
|
||||
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
|
||||
}
|
||||
return map;
|
||||
}, [threads]);
|
||||
}, [state.threads]);
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[projects],
|
||||
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[state.projects],
|
||||
);
|
||||
const threadGitTargets = useMemo(
|
||||
() =>
|
||||
threads.map((thread) => ({
|
||||
state.threads.map((thread) => ({
|
||||
threadId: thread.id,
|
||||
branch: thread.branch,
|
||||
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
||||
})),
|
||||
[projectCwdById, threads],
|
||||
[projectCwdById, state.threads],
|
||||
);
|
||||
const threadGitStatusCwds = useMemo(
|
||||
() => [
|
||||
@@ -426,7 +418,7 @@ export default function Sidebar() {
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
(projectId: ProjectId) => {
|
||||
const latestThread = threads
|
||||
const latestThread = state.threads
|
||||
.filter((thread) => thread.projectId === projectId)
|
||||
.toSorted((a, b) => {
|
||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
@@ -440,7 +432,7 @@ export default function Sidebar() {
|
||||
params: { threadId: latestThread.id },
|
||||
});
|
||||
},
|
||||
[navigate, threads],
|
||||
[navigate, state.threads],
|
||||
);
|
||||
|
||||
const addProjectFromPath = useCallback(
|
||||
@@ -448,27 +440,20 @@ export default function Sidebar() {
|
||||
const cwd = rawCwd.trim();
|
||||
if (!cwd || isAddingProject) return;
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
|
||||
setIsAddingProject(true);
|
||||
const finishAddingProject = () => {
|
||||
setIsAddingProject(false);
|
||||
setNewCwd("");
|
||||
setAddingProject(false);
|
||||
};
|
||||
try {
|
||||
if (!api) return;
|
||||
const existing = state.projects.find((project) => project.cwd === cwd);
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = projects.find((project) => project.cwd === cwd);
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
finishAddingProject();
|
||||
return;
|
||||
}
|
||||
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
const projectCreated = await api.orchestration
|
||||
.dispatchCommand({
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "project.create",
|
||||
commandId: newCommandId(),
|
||||
projectId,
|
||||
@@ -476,15 +461,15 @@ export default function Sidebar() {
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: DEFAULT_MODEL,
|
||||
createdAt,
|
||||
})
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
if (projectCreated) {
|
||||
await handleNewThread(projectId).catch(() => undefined);
|
||||
});
|
||||
await handleNewThread(projectId);
|
||||
} finally {
|
||||
setIsAddingProject(false);
|
||||
setNewCwd("");
|
||||
setAddingProject(false);
|
||||
}
|
||||
finishAddingProject();
|
||||
},
|
||||
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
|
||||
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, state.projects],
|
||||
);
|
||||
|
||||
const handleAddProject = () => {
|
||||
@@ -495,94 +480,34 @@ export default function Sidebar() {
|
||||
const api = readNativeApi();
|
||||
if (!api || isPickingFolder) return;
|
||||
setIsPickingFolder(true);
|
||||
let pickedPath: string | null = null;
|
||||
try {
|
||||
pickedPath = await api.dialogs.pickFolder();
|
||||
} catch {
|
||||
// Ignore picker failures and leave the current thread selection unchanged.
|
||||
}
|
||||
if (pickedPath) {
|
||||
const pickedPath = await api.dialogs.pickFolder();
|
||||
if (!pickedPath) return;
|
||||
await addProjectFromPath(pickedPath);
|
||||
} finally {
|
||||
setIsPickingFolder(false);
|
||||
}
|
||||
setIsPickingFolder(false);
|
||||
};
|
||||
|
||||
const cancelRename = useCallback(() => {
|
||||
setRenamingThreadId(null);
|
||||
renamingInputRef.current = null;
|
||||
}, []);
|
||||
|
||||
const commitRename = useCallback(
|
||||
async (threadId: ThreadId, newTitle: string, originalTitle: string) => {
|
||||
const finishRename = () => {
|
||||
setRenamingThreadId((current) => {
|
||||
if (current !== threadId) return current;
|
||||
renamingInputRef.current = null;
|
||||
return null;
|
||||
});
|
||||
};
|
||||
|
||||
const trimmed = newTitle.trim();
|
||||
if (trimmed.length === 0) {
|
||||
toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
|
||||
finishRename();
|
||||
return;
|
||||
}
|
||||
if (trimmed === originalTitle) {
|
||||
finishRename();
|
||||
return;
|
||||
}
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
finishRename();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId,
|
||||
title: trimmed,
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to rename thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
finishRename();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleThreadContextMenu = useCallback(
|
||||
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
{ id: "delete", label: "Delete" },
|
||||
],
|
||||
position,
|
||||
);
|
||||
const thread = threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
|
||||
if (clicked === "rename") {
|
||||
setRenamingThreadId(threadId);
|
||||
setRenamingTitle(thread.title);
|
||||
renamingCommittedRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
markThreadUnread(threadId);
|
||||
dispatch.markThreadUnread(threadId);
|
||||
return;
|
||||
}
|
||||
if (clicked !== "delete") return;
|
||||
|
||||
const thread = state.threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
if (appSettings.confirmThreadDelete) {
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
[
|
||||
@@ -594,8 +519,8 @@ export default function Sidebar() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const threadProject = projects.find((project) => project.id === thread.projectId);
|
||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
|
||||
const threadProject = state.projects.find((project) => project.id === thread.projectId);
|
||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
|
||||
const displayWorktreePath = orphanedWorktreePath
|
||||
? formatWorktreePathForDisplay(orphanedWorktreePath)
|
||||
: null;
|
||||
@@ -632,7 +557,7 @@ export default function Sidebar() {
|
||||
}
|
||||
|
||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||
const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.delete",
|
||||
commandId: newCommandId(),
|
||||
@@ -640,7 +565,6 @@ export default function Sidebar() {
|
||||
});
|
||||
clearComposerDraftForThread(threadId);
|
||||
clearProjectDraftThreadById(thread.projectId, thread.id);
|
||||
clearTerminalState(threadId);
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
void navigate({
|
||||
@@ -682,13 +606,12 @@ export default function Sidebar() {
|
||||
appSettings.confirmThreadDelete,
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadById,
|
||||
clearTerminalState,
|
||||
markThreadUnread,
|
||||
dispatch,
|
||||
navigate,
|
||||
projects,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
threads,
|
||||
state.projects,
|
||||
state.threads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -696,16 +619,13 @@ export default function Sidebar() {
|
||||
async (projectId: ProjectId, position: { x: number; y: number }) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[{ id: "delete", label: "Delete", destructive: true }],
|
||||
position,
|
||||
);
|
||||
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
|
||||
if (clicked !== "delete") return;
|
||||
|
||||
const project = projects.find((entry) => entry.id === projectId);
|
||||
const project = state.projects.find((entry) => entry.id === projectId);
|
||||
if (!project) return;
|
||||
|
||||
const projectThreads = threads.filter((thread) => thread.projectId === projectId);
|
||||
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
|
||||
if (projectThreads.length > 0) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
@@ -745,20 +665,20 @@ export default function Sidebar() {
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThreadByProjectId,
|
||||
projects,
|
||||
threads,
|
||||
state.projects,
|
||||
state.threads,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
const activeThread = routeThreadId
|
||||
? threads.find((thread) => thread.id === routeThreadId)
|
||||
? state.threads.find((thread) => thread.id === routeThreadId)
|
||||
: undefined;
|
||||
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
|
||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
||||
const projectId =
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
void handleNewThread(projectId);
|
||||
@@ -767,7 +687,7 @@ export default function Sidebar() {
|
||||
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
const projectId =
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
void handleNewThread(projectId, {
|
||||
@@ -781,14 +701,14 @@ export default function Sidebar() {
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
};
|
||||
}, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
|
||||
}, [getDraftThread, handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
||||
|
||||
const onCreateThreadClick = () => {
|
||||
if (projects.length === 0) {
|
||||
if (state.projects.length === 0) {
|
||||
setAddingProject(true);
|
||||
return;
|
||||
}
|
||||
const firstProject = projects[0];
|
||||
const firstProject = state.projects[0];
|
||||
if (firstProject) void handleNewThread(firstProject.id);
|
||||
};
|
||||
|
||||
@@ -837,8 +757,8 @@ export default function Sidebar() {
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 py-2">
|
||||
<SidebarMenu>
|
||||
{projects.map((project) => {
|
||||
const visibleThreads = threads
|
||||
{state.projects.map((project) => {
|
||||
const visibleThreads = state.threads
|
||||
.filter((thread) => thread.projectId === project.id)
|
||||
.toSorted((a, b) => {
|
||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
@@ -853,7 +773,7 @@ export default function Sidebar() {
|
||||
open={project.expanded}
|
||||
onOpenChange={(open) => {
|
||||
if (open === project.expanded) return;
|
||||
toggleProject(project.id);
|
||||
dispatch.toggleProject(project.id);
|
||||
}}
|
||||
>
|
||||
<SidebarMenuItem>
|
||||
@@ -896,8 +816,7 @@ export default function Sidebar() {
|
||||
);
|
||||
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
|
||||
const terminalStatus = terminalStatusFromRunningIds(
|
||||
selectThreadTerminalState(terminalStateByThreadId, thread.id)
|
||||
.runningTerminalIds,
|
||||
getTerminalState(thread.id).runningTerminalIds,
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -965,42 +884,9 @@ export default function Sidebar() {
|
||||
<span className="hidden md:inline">{threadStatus.label}</span>
|
||||
</span>
|
||||
)}
|
||||
{renamingThreadId === thread.id ? (
|
||||
<input
|
||||
ref={(el) => {
|
||||
if (el && renamingInputRef.current !== el) {
|
||||
renamingInputRef.current = el;
|
||||
el.focus();
|
||||
el.select();
|
||||
}
|
||||
}}
|
||||
className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
|
||||
value={renamingTitle}
|
||||
onChange={(e) => setRenamingTitle(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
renamingCommittedRef.current = true;
|
||||
void commitRename(thread.id, renamingTitle, thread.title);
|
||||
} else if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
renamingCommittedRef.current = true;
|
||||
cancelRename();
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (!renamingCommittedRef.current) {
|
||||
void commitRename(thread.id, renamingTitle, thread.title);
|
||||
}
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
) : (
|
||||
<span className="min-w-0 flex-1 truncate text-xs">
|
||||
{thread.title}
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-xs">
|
||||
{thread.title}
|
||||
</span>
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{terminalStatus && (
|
||||
@@ -1049,7 +935,7 @@ export default function Sidebar() {
|
||||
})}
|
||||
</SidebarMenu>
|
||||
|
||||
{projects.length === 0 && !addingProject && (
|
||||
{state.projects.length === 0 && !addingProject && (
|
||||
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
|
||||
No projects yet.
|
||||
<br />
|
||||
|
||||
@@ -389,9 +389,6 @@ function TerminalViewport({
|
||||
fitAddonRef.current = null;
|
||||
terminal.dispose();
|
||||
};
|
||||
// autoFocus is intentionally omitted;
|
||||
// it is only read at mount time and must not trigger terminal teardown/recreation.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [cwd, runtimeEnv, terminalId, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -20,9 +20,10 @@ function Combobox<Value, Multiple extends boolean | undefined = false>(
|
||||
props: ComboboxPrimitive.Root.Props<Value, Multiple>,
|
||||
) {
|
||||
const chipsRef = React.useRef<Element | null>(null);
|
||||
const value = React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple]);
|
||||
return (
|
||||
<ComboboxContext.Provider value={value}>
|
||||
<ComboboxContext.Provider
|
||||
value={React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple])}
|
||||
>
|
||||
<ComboboxPrimitive.Root {...props} />
|
||||
</ComboboxContext.Provider>
|
||||
);
|
||||
|
||||
@@ -22,7 +22,6 @@ function ToggleGroup({
|
||||
children,
|
||||
...props
|
||||
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const value = React.useMemo(() => ({ size, variant }), [size, variant]);
|
||||
return (
|
||||
<ToggleGroupPrimitive
|
||||
className={cn(
|
||||
@@ -43,7 +42,11 @@ function ToggleGroup({
|
||||
orientation={orientation}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider value={value}>{children}</ToggleGroupContext.Provider>
|
||||
<ToggleGroupContext.Provider
|
||||
value={React.useMemo(() => ({ size, variant }), [size, variant])}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
|
||||
describe("splitPromptIntoComposerSegments", () => {
|
||||
it("splits mention tokens followed by whitespace into mention segments", () => {
|
||||
expect(splitPromptIntoComposerSegments("Inspect @AGENTS.md please")).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{ type: "mention", path: "AGENTS.md" },
|
||||
{ type: "text", text: " please" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not convert an incomplete trailing mention token", () => {
|
||||
expect(splitPromptIntoComposerSegments("Inspect @AGENTS.md")).toEqual([
|
||||
{ type: "text", text: "Inspect @AGENTS.md" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps newlines around mention tokens", () => {
|
||||
expect(splitPromptIntoComposerSegments("one\n@src/index.ts \ntwo")).toEqual([
|
||||
{ type: "text", text: "one\n" },
|
||||
{ type: "mention", path: "src/index.ts" },
|
||||
{ type: "text", text: " \ntwo" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
export type ComposerPromptSegment =
|
||||
| {
|
||||
type: "text";
|
||||
text: string;
|
||||
}
|
||||
| {
|
||||
type: "mention";
|
||||
path: string;
|
||||
};
|
||||
|
||||
const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
|
||||
|
||||
function pushTextSegment(segments: ComposerPromptSegment[], text: string): void {
|
||||
if (!text) return;
|
||||
const last = segments[segments.length - 1];
|
||||
if (last && last.type === "text") {
|
||||
last.text += text;
|
||||
return;
|
||||
}
|
||||
segments.push({ type: "text", text });
|
||||
}
|
||||
|
||||
export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptSegment[] {
|
||||
const segments: ComposerPromptSegment[] = [];
|
||||
if (!prompt) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
for (const match of prompt.matchAll(MENTION_TOKEN_REGEX)) {
|
||||
const fullMatch = match[0];
|
||||
const prefix = match[1] ?? "";
|
||||
const path = match[2] ?? "";
|
||||
const matchIndex = match.index ?? 0;
|
||||
const mentionStart = matchIndex + prefix.length;
|
||||
const mentionEnd = mentionStart + fullMatch.length - prefix.length;
|
||||
|
||||
if (mentionStart > cursor) {
|
||||
pushTextSegment(segments, prompt.slice(cursor, mentionStart));
|
||||
}
|
||||
|
||||
if (path.length > 0) {
|
||||
segments.push({ type: "mention", path });
|
||||
} else {
|
||||
pushTextSegment(segments, prompt.slice(mentionStart, mentionEnd));
|
||||
}
|
||||
|
||||
cursor = mentionEnd;
|
||||
}
|
||||
|
||||
if (cursor < prompt.length) {
|
||||
pushTextSegment(segments, prompt.slice(cursor));
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
detectComposerTrigger,
|
||||
expandCollapsedComposerCursor,
|
||||
replaceTextRange,
|
||||
} from "./composer-logic";
|
||||
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
@@ -53,27 +49,3 @@ describe("replaceTextRange", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("expandCollapsedComposerCursor", () => {
|
||||
it("keeps cursor unchanged when no mention segment is present", () => {
|
||||
expect(expandCollapsedComposerCursor("plain text", 5)).toBe(5);
|
||||
});
|
||||
|
||||
it("maps collapsed mention cursor to expanded text cursor", () => {
|
||||
const text = "what's in my @AGENTS.md fsfdas";
|
||||
const collapsedCursorAfterMention = "what's in my ".length + 2;
|
||||
const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
|
||||
|
||||
expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
|
||||
expandedCursorAfterMention,
|
||||
);
|
||||
});
|
||||
|
||||
it("allows path trigger detection to close after selecting a mention", () => {
|
||||
const text = "what's in my @AGENTS.md ";
|
||||
const collapsedCursorAfterMention = "what's in my ".length + 2;
|
||||
const expandedCursor = expandCollapsedComposerCursor(text, collapsedCursorAfterMention);
|
||||
|
||||
expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,3 @@
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
|
||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
||||
|
||||
export interface ComposerTrigger {
|
||||
@@ -26,38 +24,6 @@ function tokenStartForCursor(text: string, cursor: number): number {
|
||||
return index + 1;
|
||||
}
|
||||
|
||||
export function expandCollapsedComposerCursor(text: string, cursorInput: number): number {
|
||||
const collapsedCursor = clampCursor(text, cursorInput);
|
||||
const segments = splitPromptIntoComposerSegments(text);
|
||||
if (segments.length === 0) {
|
||||
return collapsedCursor;
|
||||
}
|
||||
|
||||
let remaining = collapsedCursor;
|
||||
let expandedCursor = 0;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
const expandedLength = segment.path.length + 1;
|
||||
if (remaining <= 1) {
|
||||
return expandedCursor + (remaining === 0 ? 0 : expandedLength);
|
||||
}
|
||||
remaining -= 1;
|
||||
expandedCursor += expandedLength;
|
||||
continue;
|
||||
}
|
||||
|
||||
const segmentLength = segment.text.length;
|
||||
if (remaining <= segmentLength) {
|
||||
return expandedCursor + remaining;
|
||||
}
|
||||
remaining -= segmentLength;
|
||||
expandedCursor += segmentLength;
|
||||
}
|
||||
|
||||
return expandedCursor;
|
||||
}
|
||||
|
||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||
const cursor = clampCursor(text, cursorInput);
|
||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||
|
||||
@@ -28,6 +28,7 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
|
||||
|
||||
interface PersistedComposerThreadDraftState {
|
||||
prompt: string;
|
||||
cursor: number;
|
||||
attachments: PersistedComposerImageAttachment[];
|
||||
model?: string | null;
|
||||
effort?: ReasoningEffort | null;
|
||||
@@ -49,6 +50,7 @@ interface PersistedComposerDraftStoreState {
|
||||
|
||||
interface ComposerThreadDraftState {
|
||||
prompt: string;
|
||||
cursor: number;
|
||||
images: ComposerImageAttachment[];
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
@@ -98,6 +100,7 @@ interface ComposerDraftStoreState {
|
||||
clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
|
||||
clearDraftThread: (threadId: ThreadId) => void;
|
||||
setPrompt: (threadId: ThreadId, prompt: string) => void;
|
||||
setCursor: (threadId: ThreadId, cursor: number) => void;
|
||||
setModel: (threadId: ThreadId, model: string | null | undefined) => void;
|
||||
setEffort: (threadId: ThreadId, effort: ReasoningEffort | null | undefined) => void;
|
||||
addImage: (threadId: ThreadId, image: ComposerImageAttachment) => void;
|
||||
@@ -126,6 +129,7 @@ Object.freeze(EMPTY_IDS);
|
||||
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
|
||||
const EMPTY_THREAD_DRAFT = Object.freeze({
|
||||
prompt: "",
|
||||
cursor: 0,
|
||||
images: EMPTY_IMAGES,
|
||||
nonPersistedImageIds: EMPTY_IDS,
|
||||
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
||||
@@ -138,6 +142,7 @@ const REASONING_EFFORT_VALUES = new Set<ReasoningEffort>(REASONING_OPTIONS);
|
||||
function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
return {
|
||||
prompt: "",
|
||||
cursor: 0,
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
@@ -299,6 +304,10 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
}
|
||||
const draftCandidate = draftValue as Record<string, unknown>;
|
||||
const prompt = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
|
||||
const cursor =
|
||||
typeof draftCandidate.cursor === "number" && Number.isFinite(draftCandidate.cursor)
|
||||
? Math.max(0, Math.floor(draftCandidate.cursor))
|
||||
: 0;
|
||||
const attachments = Array.isArray(draftCandidate.attachments)
|
||||
? draftCandidate.attachments.flatMap((entry) => {
|
||||
const normalized = normalizePersistedAttachment(entry);
|
||||
@@ -318,6 +327,7 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
}
|
||||
nextDraftsByThreadId[threadId as ThreadId] = {
|
||||
prompt,
|
||||
cursor,
|
||||
attachments,
|
||||
...(model ? { model } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
@@ -419,6 +429,7 @@ function toHydratedThreadDraft(
|
||||
): ComposerThreadDraftState {
|
||||
return {
|
||||
prompt: persistedDraft.prompt,
|
||||
cursor: persistedDraft.cursor,
|
||||
images: hydrateImagesFromPersisted(persistedDraft.attachments),
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: persistedDraft.attachments,
|
||||
@@ -661,9 +672,36 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const cursor = Math.min(existing.cursor, prompt.length);
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...existing,
|
||||
prompt,
|
||||
cursor,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setCursor: (threadId, cursor) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const nextCursor = Number.isFinite(cursor) ? Math.max(0, Math.floor(cursor)) : 0;
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && nextCursor === 0) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const boundedCursor = Math.min(nextCursor, base.prompt.length);
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
cursor: boundedCursor,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
@@ -901,6 +939,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
prompt: "",
|
||||
cursor: 0,
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
@@ -970,6 +1009,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
}
|
||||
const persistedDraft: PersistedComposerThreadDraftState = {
|
||||
prompt: draft.prompt,
|
||||
cursor: Math.min(Math.max(0, draft.cursor), draft.prompt.length),
|
||||
attachments: draft.persistedAttachments,
|
||||
};
|
||||
if (draft.model) {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Imperative DOM-based context menu for non-Electron environments.
|
||||
* Shows a positioned dropdown and returns a promise that resolves
|
||||
* with the clicked item id, or null if dismissed.
|
||||
*/
|
||||
export function showContextMenuFallback<T extends string>(
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
items: readonly { id: T; label: string }[],
|
||||
position?: { x: number; y: number },
|
||||
): Promise<T | null> {
|
||||
return new Promise<T | null>((resolve) => {
|
||||
@@ -43,8 +41,8 @@ export function showContextMenuFallback<T extends string>(
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.textContent = item.label;
|
||||
const isDestructiveAction = item.destructive === true || item.id === "delete";
|
||||
btn.className = isDestructiveAction
|
||||
const isDeleteAction = item.id === "delete";
|
||||
btn.className = isDeleteAction
|
||||
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
|
||||
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
|
||||
btn.addEventListener("click", () => cleanup(item.id));
|
||||
|
||||
@@ -124,18 +124,13 @@ function errorDetails(error: unknown): string {
|
||||
}
|
||||
|
||||
function EventRouter() {
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
|
||||
const removeOrphanedTerminalStates = useTerminalStateStore(
|
||||
(store) => store.removeOrphanedTerminalStates,
|
||||
);
|
||||
const { dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname });
|
||||
const pathnameRef = useRef(pathname);
|
||||
const lastConfigIssuesSignatureRef = useRef<string | null>(null);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
|
||||
pathnameRef.current = pathname;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -150,13 +145,7 @@ function EventRouter() {
|
||||
const snapshot = await api.orchestration.getSnapshot();
|
||||
if (disposed) return;
|
||||
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
|
||||
syncServerReadModel(snapshot);
|
||||
const activeThreadIds = new Set(
|
||||
snapshot.threads
|
||||
.filter((t) => t.deletedAt === null)
|
||||
.map((t) => t.id),
|
||||
);
|
||||
removeOrphanedTerminalStates(activeThreadIds);
|
||||
dispatch.syncServerReadModel(snapshot);
|
||||
if (pending) {
|
||||
pending = false;
|
||||
await flushSnapshotSync();
|
||||
@@ -169,13 +158,14 @@ function EventRouter() {
|
||||
return;
|
||||
}
|
||||
syncing = true;
|
||||
pending = false;
|
||||
try {
|
||||
pending = false;
|
||||
await flushSnapshotSync();
|
||||
} catch {
|
||||
// Keep prior state and wait for next domain event to trigger a resync.
|
||||
} finally {
|
||||
syncing = false;
|
||||
}
|
||||
syncing = false;
|
||||
};
|
||||
|
||||
void syncSnapshot().catch(() => undefined);
|
||||
@@ -211,7 +201,7 @@ function EventRouter() {
|
||||
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
setProjectExpanded(payload.bootstrapProjectId, true);
|
||||
dispatch.setProjectExpanded(payload.bootstrapProjectId, true);
|
||||
|
||||
if (pathnameRef.current !== "/") {
|
||||
return;
|
||||
@@ -276,7 +266,7 @@ function EventRouter() {
|
||||
unsubWelcome();
|
||||
unsubServerConfigUpdated();
|
||||
};
|
||||
}, [navigate, queryClient, removeOrphanedTerminalStates, setProjectExpanded, syncServerReadModel]);
|
||||
}, [dispatch, navigate, queryClient]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -133,13 +133,13 @@ const DiffPanelInlineSidebar = (props: {
|
||||
};
|
||||
|
||||
function ChatThreadRouteView() {
|
||||
const threadsHydrated = useStore((store) => store.threadsHydrated);
|
||||
const { state } = useStore();
|
||||
const navigate = useNavigate();
|
||||
const threadId = Route.useParams({
|
||||
select: (params) => ThreadId.makeUnsafe(params.threadId),
|
||||
});
|
||||
const search = Route.useSearch();
|
||||
const threadExists = useStore((store) => store.threads.some((thread) => thread.id === threadId));
|
||||
const threadExists = state.threads.some((thread) => thread.id === threadId);
|
||||
const draftThreadExists = useComposerDraftStore(
|
||||
(store) => Object.hasOwn(store.draftThreadsByThreadId, threadId),
|
||||
);
|
||||
@@ -167,7 +167,7 @@ function ChatThreadRouteView() {
|
||||
}, [navigate, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!threadsHydrated) {
|
||||
if (!state.threadsHydrated) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -175,9 +175,9 @@ function ChatThreadRouteView() {
|
||||
void navigate({ to: "/", replace: true });
|
||||
return;
|
||||
}
|
||||
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
|
||||
}, [navigate, routeThreadExists, state.threadsHydrated, threadId]);
|
||||
|
||||
if (!threadsHydrated || !routeThreadExists) {
|
||||
if (!state.threadsHydrated || !routeThreadExists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ function ChatThreadRouteView() {
|
||||
return (
|
||||
<>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<ChatView key={threadId} threadId={threadId} />
|
||||
<ChatView threadId={threadId} />
|
||||
</SidebarInset>
|
||||
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
|
||||
</>
|
||||
@@ -195,7 +195,7 @@ function ChatThreadRouteView() {
|
||||
return (
|
||||
<>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<ChatView key={threadId} threadId={threadId} />
|
||||
<ChatView threadId={threadId} />
|
||||
</SidebarInset>
|
||||
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
<Suspense fallback={<DiffLoadingFallback inline={false} />}>
|
||||
|
||||
@@ -48,8 +48,7 @@ const RUNTIME_MODE_OPTIONS = [
|
||||
|
||||
function SettingsRouteView() {
|
||||
const { theme, setTheme, resolvedTheme } = useTheme();
|
||||
const runtimeMode = useStore((store) => store.runtimeMode);
|
||||
const setRuntimeMode = useStore((store) => store.setRuntimeMode);
|
||||
const { state, dispatch } = useStore();
|
||||
const { settings, defaults, updateSettings } = useAppSettings();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
@@ -187,10 +186,9 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<label htmlFor="codex-binary-path" className="block space-y-1">
|
||||
<label className="block space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">Codex binary path</span>
|
||||
<Input
|
||||
id="codex-binary-path"
|
||||
value={codexBinaryPath}
|
||||
onChange={(event) => updateSettings({ codexBinaryPath: event.target.value })}
|
||||
placeholder="codex"
|
||||
@@ -201,10 +199,9 @@ function SettingsRouteView() {
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label htmlFor="codex-home-path" className="block space-y-1">
|
||||
<label className="block space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">CODEX_HOME path</span>
|
||||
<Input
|
||||
id="codex-home-path"
|
||||
value={codexHomePath}
|
||||
onChange={(event) => updateSettings({ codexHomePath: event.target.value })}
|
||||
placeholder="/Users/you/.codex"
|
||||
@@ -245,11 +242,16 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start">
|
||||
<label htmlFor="custom-model-slug" className="block flex-1 space-y-1">
|
||||
<form
|
||||
className="flex flex-col gap-3 sm:flex-row sm:items-start"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
addCustomModel();
|
||||
}}
|
||||
>
|
||||
<label className="block flex-1 space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">Custom model slug</span>
|
||||
<Input
|
||||
id="custom-model-slug"
|
||||
value={customModelInput}
|
||||
onChange={(event) => {
|
||||
setCustomModelInput(event.target.value);
|
||||
@@ -257,11 +259,6 @@ function SettingsRouteView() {
|
||||
setCustomModelError(null);
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
addCustomModel();
|
||||
}}
|
||||
placeholder="your-model-slug"
|
||||
spellCheck={false}
|
||||
/>
|
||||
@@ -270,10 +267,10 @@ function SettingsRouteView() {
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<Button className="sm:mt-6" type="button" onClick={addCustomModel}>
|
||||
<Button className="sm:mt-6" type="submit">
|
||||
Add model
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{customModelError ? (
|
||||
<p className="text-xs text-destructive">{customModelError}</p>
|
||||
@@ -336,7 +333,7 @@ function SettingsRouteView() {
|
||||
|
||||
<div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
|
||||
{RUNTIME_MODE_OPTIONS.map((option) => {
|
||||
const selected = runtimeMode === option.value;
|
||||
const selected = state.runtimeMode === option.value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
@@ -349,7 +346,7 @@ function SettingsRouteView() {
|
||||
: "border-border bg-background text-muted-foreground hover:bg-accent"
|
||||
}`}
|
||||
onClick={() => {
|
||||
setRuntimeMode(option.value);
|
||||
dispatch.setRuntimeMode(option.value);
|
||||
}}
|
||||
>
|
||||
<span className="flex flex-col">
|
||||
|
||||
+66
-56
@@ -101,14 +101,7 @@ function updateThread(
|
||||
threadId: ThreadId,
|
||||
updater: (t: Thread) => Thread,
|
||||
): Thread[] {
|
||||
let changed = false;
|
||||
const next = threads.map((t) => {
|
||||
if (t.id !== threadId) return t;
|
||||
const updated = updater(t);
|
||||
if (updated !== t) changed = true;
|
||||
return updated;
|
||||
});
|
||||
return changed ? next : threads;
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
function mapProjectsFromReadModel(
|
||||
@@ -284,30 +277,34 @@ export function markThreadVisited(
|
||||
): AppState {
|
||||
const at = visitedAt ?? new Date().toISOString();
|
||||
const visitedAtMs = Date.parse(at);
|
||||
const threads = updateThread(state.threads, threadId, (thread) => {
|
||||
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
|
||||
if (
|
||||
Number.isFinite(previousVisitedAtMs) &&
|
||||
Number.isFinite(visitedAtMs) &&
|
||||
previousVisitedAtMs >= visitedAtMs
|
||||
) {
|
||||
return thread;
|
||||
}
|
||||
return { ...thread, lastVisitedAt: at };
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => {
|
||||
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
|
||||
if (
|
||||
Number.isFinite(previousVisitedAtMs) &&
|
||||
Number.isFinite(visitedAtMs) &&
|
||||
previousVisitedAtMs >= visitedAtMs
|
||||
) {
|
||||
return thread;
|
||||
}
|
||||
return { ...thread, lastVisitedAt: at };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export function markThreadUnread(state: AppState, threadId: ThreadId): AppState {
|
||||
const threads = updateThread(state.threads, threadId, (thread) => {
|
||||
if (!thread.latestTurn?.completedAt) return thread;
|
||||
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
|
||||
if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
|
||||
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
|
||||
if (thread.lastVisitedAt === unreadVisitedAt) return thread;
|
||||
return { ...thread, lastVisitedAt: unreadVisitedAt };
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => {
|
||||
if (!thread.latestTurn?.completedAt) return thread;
|
||||
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
|
||||
if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
|
||||
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
|
||||
if (thread.lastVisitedAt === unreadVisitedAt) return thread;
|
||||
return { ...thread, lastVisitedAt: unreadVisitedAt };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
|
||||
@@ -324,21 +321,19 @@ export function setProjectExpanded(
|
||||
projectId: Project["id"],
|
||||
expanded: boolean,
|
||||
): AppState {
|
||||
let changed = false;
|
||||
const projects = state.projects.map((p) => {
|
||||
if (p.id !== projectId || p.expanded === expanded) return p;
|
||||
changed = true;
|
||||
return { ...p, expanded };
|
||||
});
|
||||
return changed ? { ...state, projects } : state;
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === projectId ? { ...p, expanded } : p,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
|
||||
const threads = updateThread(state.threads, threadId, (t) => {
|
||||
if (t.error === error) return t;
|
||||
return { ...t, error };
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (t) => ({ ...t, error })),
|
||||
};
|
||||
}
|
||||
|
||||
export function setThreadBranch(
|
||||
@@ -347,21 +342,21 @@ export function setThreadBranch(
|
||||
branch: string | null,
|
||||
worktreePath: string | null,
|
||||
): AppState {
|
||||
const threads = updateThread(state.threads, threadId, (t) => {
|
||||
if (t.branch === branch && t.worktreePath === worktreePath) return t;
|
||||
const cwdChanged = t.worktreePath !== worktreePath;
|
||||
return {
|
||||
...t,
|
||||
branch,
|
||||
worktreePath,
|
||||
...(cwdChanged ? { session: null } : {}),
|
||||
};
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (t) => {
|
||||
const cwdChanged = t.worktreePath !== worktreePath;
|
||||
return {
|
||||
...t,
|
||||
branch,
|
||||
worktreePath,
|
||||
...(cwdChanged ? { session: null } : {}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export function setRuntimeMode(state: AppState, mode: RuntimeMode): AppState {
|
||||
if (state.runtimeMode === mode) return state;
|
||||
return { ...state, runtimeMode: mode };
|
||||
}
|
||||
|
||||
@@ -382,7 +377,7 @@ interface AppStore extends AppState {
|
||||
setRuntimeMode: (mode: RuntimeMode) => void;
|
||||
}
|
||||
|
||||
export const useStore = create<AppStore>((set) => ({
|
||||
export const useAppStore = create<AppStore>((set, _get) => ({
|
||||
...readPersistedState(),
|
||||
syncServerReadModel: (readModel) =>
|
||||
set((state) => syncServerReadModel(state, readModel)),
|
||||
@@ -403,11 +398,26 @@ export const useStore = create<AppStore>((set) => ({
|
||||
}));
|
||||
|
||||
// Persist on every state change (only runtimeMode + expandedProjectCwds)
|
||||
useStore.subscribe((state) => persistState(state));
|
||||
useAppStore.subscribe((state) => persistState(state));
|
||||
|
||||
// ── useStore (state + store API for call sites that want both) ────────────────
|
||||
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
useEffect(() => {
|
||||
persistState(useStore.getState());
|
||||
persistState(useAppStore.getState());
|
||||
}, []);
|
||||
return createElement(Fragment, null, children);
|
||||
}
|
||||
|
||||
export function useStore() {
|
||||
const state = useAppStore((s) => ({
|
||||
projects: s.projects,
|
||||
threads: s.threads,
|
||||
threadsHydrated: s.threadsHydrated,
|
||||
runtimeMode: s.runtimeMode,
|
||||
}));
|
||||
return {
|
||||
state,
|
||||
dispatch: useAppStore.getState(),
|
||||
};
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "./terminalStateStore";
|
||||
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
|
||||
describe("terminalStateStore actions", () => {
|
||||
beforeEach(() => {
|
||||
if (typeof localStorage !== "undefined") {
|
||||
localStorage.clear();
|
||||
}
|
||||
useTerminalStateStore.setState({ terminalStateByThreadId: {} });
|
||||
});
|
||||
|
||||
it("returns a closed default terminal state for unknown threads", () => {
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState).toEqual({
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
});
|
||||
});
|
||||
|
||||
it("opens and splits terminals into the active group", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.setTerminalOpen(THREAD_ID, true);
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState.terminalOpen).toBe(true);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates new terminals in a separate group", () => {
|
||||
useTerminalStateStore.getState().newTerminal(THREAD_ID, "terminal-2");
|
||||
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.activeTerminalGroupId).toBe("group-terminal-2");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("tracks and clears terminal subprocess activity", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
store.setTerminalActivity(THREAD_ID, "terminal-2", true);
|
||||
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([
|
||||
"terminal-2",
|
||||
]);
|
||||
|
||||
store.setTerminalActivity(THREAD_ID, "terminal-2", false);
|
||||
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("resets to default and clears persisted entry when closing the last terminal", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.closeTerminal(THREAD_ID, "default");
|
||||
|
||||
expect(useTerminalStateStore.getState().terminalStateByThreadId[THREAD_ID]).toBeUndefined();
|
||||
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).terminalIds).toEqual(["default"]);
|
||||
});
|
||||
|
||||
it("keeps a valid active terminal after closing an active split terminal", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
store.splitTerminal(THREAD_ID, "terminal-3");
|
||||
store.closeTerminal(THREAD_ID, "terminal-3");
|
||||
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,454 +1,40 @@
|
||||
/**
|
||||
* Single Zustand store for terminal UI state keyed by threadId.
|
||||
*
|
||||
* Terminal transition helpers are intentionally private to keep the public
|
||||
* API constrained to store actions/selectors.
|
||||
* Single Zustand store for terminal UI state keyed by threadId. Used by both
|
||||
* persisted (server) threads and draft threads; threadId is stable for both.
|
||||
*/
|
||||
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
createDefaultThreadTerminalState,
|
||||
getDefaultThreadTerminalState,
|
||||
reduceThreadTerminalState,
|
||||
type ThreadTerminalAction,
|
||||
type ThreadTerminalState,
|
||||
} from "./threadTerminalState";
|
||||
|
||||
interface ThreadTerminalState {
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
}
|
||||
export const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
|
||||
|
||||
const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))].slice(
|
||||
0,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
);
|
||||
return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
|
||||
function normalizeRunningTerminalIds(runningTerminalIds: string[], terminalIds: string[]): string[] {
|
||||
if (runningTerminalIds.length === 0) return [];
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): string {
|
||||
let candidate = baseId;
|
||||
let index = 2;
|
||||
while (usedGroupIds.has(candidate)) {
|
||||
candidate = `${baseId}-${index}`;
|
||||
index += 1;
|
||||
}
|
||||
usedGroupIds.add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function findGroupIndexByTerminalId(terminalGroups: ThreadTerminalGroup[], terminalId: string): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalIds: string[],
|
||||
): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const nextGroups: ThreadTerminalGroup[] = [];
|
||||
const usedGroupIds = new Set<string>();
|
||||
|
||||
for (const group of terminalGroups) {
|
||||
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (nextGroups.length === 0) {
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return nextGroups;
|
||||
}
|
||||
|
||||
function arraysEqual(a: string[], b: string[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let index = 0; index < a.length; index += 1) {
|
||||
if (a[index] !== b[index]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalGroup[]): boolean {
|
||||
if (left.length !== right.length) return false;
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
const leftGroup = left[index];
|
||||
const rightGroup = right[index];
|
||||
if (!leftGroup || !rightGroup) return false;
|
||||
if (leftGroup.id !== rightGroup.id) return false;
|
||||
if (!arraysEqual(leftGroup.terminalIds, rightGroup.terminalIds)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTerminalState): boolean {
|
||||
return (
|
||||
left.terminalOpen === right.terminalOpen &&
|
||||
left.terminalHeight === right.terminalHeight &&
|
||||
left.activeTerminalId === right.activeTerminalId &&
|
||||
left.activeTerminalGroupId === right.activeTerminalGroupId &&
|
||||
arraysEqual(left.terminalIds, right.terminalIds) &&
|
||||
arraysEqual(left.runningTerminalIds, right.runningTerminalIds) &&
|
||||
terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
|
||||
);
|
||||
}
|
||||
|
||||
const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
});
|
||||
|
||||
function createDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return {
|
||||
...DEFAULT_THREAD_TERMINAL_STATE,
|
||||
terminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.terminalIds],
|
||||
runningTerminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalIds],
|
||||
terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_STATE.terminalGroups),
|
||||
};
|
||||
}
|
||||
|
||||
function getDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return DEFAULT_THREAD_TERMINAL_STATE;
|
||||
}
|
||||
|
||||
function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTerminalState {
|
||||
const terminalIds = normalizeTerminalIds(state.terminalIds);
|
||||
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const runningTerminalIds = normalizeRunningTerminalIds(state.runningTerminalIds, nextTerminalIds);
|
||||
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
|
||||
? state.activeTerminalId
|
||||
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
|
||||
const activeGroupIdFromState = terminalGroups.some((group) => group.id === state.activeTerminalGroupId)
|
||||
? state.activeTerminalGroupId
|
||||
: null;
|
||||
const activeGroupIdFromTerminal =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? null;
|
||||
|
||||
const normalized: ThreadTerminalState = {
|
||||
terminalOpen: state.terminalOpen,
|
||||
terminalHeight:
|
||||
Number.isFinite(state.terminalHeight) && state.terminalHeight > 0
|
||||
? state.terminalHeight
|
||||
: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: nextTerminalIds,
|
||||
runningTerminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId:
|
||||
activeGroupIdFromState ??
|
||||
activeGroupIdFromTerminal ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
};
|
||||
return threadTerminalStateEqual(state, normalized) ? state : normalized;
|
||||
}
|
||||
|
||||
function isDefaultThreadTerminalState(state: ThreadTerminalState): boolean {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
return threadTerminalStateEqual(normalized, DEFAULT_THREAD_TERMINAL_STATE);
|
||||
}
|
||||
|
||||
function isValidTerminalId(terminalId: string): boolean {
|
||||
return terminalId.trim().length > 0;
|
||||
}
|
||||
|
||||
function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[] {
|
||||
return groups.map((group) => ({
|
||||
id: group.id,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
}
|
||||
|
||||
function upsertTerminalIntoGroups(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
mode: "split" | "new",
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!isValidTerminalId(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const isNewTerminal = !normalized.terminalIds.includes(terminalId);
|
||||
if (isNewTerminal && normalized.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const terminalIds = isNewTerminal ? [...normalized.terminalIds, terminalId] : normalized.terminalIds;
|
||||
const terminalGroups = copyTerminalGroups(normalized.terminalGroups);
|
||||
|
||||
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, terminalId);
|
||||
if (existingGroupIndex >= 0) {
|
||||
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[existingGroupIndex]!.terminalIds.filter(
|
||||
(id) => id !== terminalId,
|
||||
);
|
||||
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
|
||||
terminalGroups.splice(existingGroupIndex, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === "new") {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [terminalId] });
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
let activeGroupIndex = terminalGroups.findIndex((group) => group.id === normalized.activeTerminalGroupId);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(normalized.activeTerminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (!destinationGroup.terminalIds.includes(terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(terminalId);
|
||||
}
|
||||
}
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalOpen(state: ThreadTerminalState, open: boolean): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (normalized.terminalOpen === open) return normalized;
|
||||
return { ...normalized, terminalOpen: open };
|
||||
}
|
||||
|
||||
function setThreadTerminalHeight(state: ThreadTerminalState, height: number): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!Number.isFinite(height) || height <= 0 || normalized.terminalHeight === height) {
|
||||
return normalized;
|
||||
}
|
||||
return { ...normalized, terminalHeight: height };
|
||||
}
|
||||
|
||||
function splitThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "split");
|
||||
}
|
||||
|
||||
function newThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "new");
|
||||
}
|
||||
|
||||
function setThreadActiveTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const activeTerminalGroupId =
|
||||
normalized.terminalGroups.find((group) => group.terminalIds.includes(terminalId))?.id ??
|
||||
normalized.activeTerminalGroupId;
|
||||
if (
|
||||
normalized.activeTerminalId === terminalId &&
|
||||
normalized.activeTerminalGroupId === activeTerminalGroupId
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
return {
|
||||
...normalized,
|
||||
activeTerminalId: terminalId,
|
||||
activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
|
||||
function closeThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = normalized.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
return createDefaultThreadTerminalState();
|
||||
}
|
||||
|
||||
const closedTerminalIndex = normalized.terminalIds.indexOf(terminalId);
|
||||
const nextActiveTerminalId =
|
||||
normalized.activeTerminalId === terminalId
|
||||
? (remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: normalized.activeTerminalId;
|
||||
|
||||
const terminalGroups = normalized.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
const nextActiveTerminalGroupId =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(nextActiveTerminalId);
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
terminalOpen: normalized.terminalOpen,
|
||||
terminalHeight: normalized.terminalHeight,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: normalized.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextActiveTerminalGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalActivity(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const alreadyRunning = normalized.runningTerminalIds.includes(terminalId);
|
||||
if (hasRunningSubprocess === alreadyRunning) {
|
||||
return normalized;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalized.runningTerminalIds);
|
||||
if (hasRunningSubprocess) {
|
||||
runningTerminalIds.add(terminalId);
|
||||
} else {
|
||||
runningTerminalIds.delete(terminalId);
|
||||
}
|
||||
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
|
||||
}
|
||||
|
||||
export function selectThreadTerminalState(
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>,
|
||||
function applyTerminalAction(
|
||||
state: Record<ThreadId, ThreadTerminalState>,
|
||||
threadId: ThreadId,
|
||||
): ThreadTerminalState {
|
||||
if (threadId.length === 0) {
|
||||
return getDefaultThreadTerminalState();
|
||||
}
|
||||
return terminalStateByThreadId[threadId] ?? getDefaultThreadTerminalState();
|
||||
}
|
||||
|
||||
function updateTerminalStateByThreadId(
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>,
|
||||
threadId: ThreadId,
|
||||
updater: (state: ThreadTerminalState) => ThreadTerminalState,
|
||||
action: ThreadTerminalAction,
|
||||
): Record<ThreadId, ThreadTerminalState> {
|
||||
if (threadId.length === 0) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
|
||||
const current = selectThreadTerminalState(terminalStateByThreadId, threadId);
|
||||
const next = updater(current);
|
||||
const current = state[threadId] ?? createDefaultThreadTerminalState();
|
||||
const next = reduceThreadTerminalState(current, action);
|
||||
if (next === current) {
|
||||
return terminalStateByThreadId;
|
||||
return state;
|
||||
}
|
||||
|
||||
if (isDefaultThreadTerminalState(next)) {
|
||||
if (terminalStateByThreadId[threadId] === undefined) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
const { [threadId]: _removed, ...rest } = terminalStateByThreadId;
|
||||
return rest as Record<ThreadId, ThreadTerminalState>;
|
||||
}
|
||||
|
||||
return {
|
||||
...terminalStateByThreadId,
|
||||
...state,
|
||||
[threadId]: next,
|
||||
};
|
||||
}
|
||||
|
||||
interface TerminalStateStoreState {
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>;
|
||||
getTerminalState: (threadId: ThreadId) => ThreadTerminalState;
|
||||
setTerminalOpen: (threadId: ThreadId, open: boolean) => void;
|
||||
setTerminalHeight: (threadId: ThreadId, height: number) => void;
|
||||
splitTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
@@ -461,63 +47,55 @@ interface TerminalStateStoreState {
|
||||
hasRunningSubprocess: boolean,
|
||||
) => void;
|
||||
clearTerminalState: (threadId: ThreadId) => void;
|
||||
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
|
||||
}
|
||||
|
||||
export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
persist(
|
||||
(set) => {
|
||||
const updateTerminal = (
|
||||
threadId: ThreadId,
|
||||
updater: (state: ThreadTerminalState) => ThreadTerminalState,
|
||||
) => {
|
||||
set((state) => {
|
||||
const nextTerminalStateByThreadId = updateTerminalStateByThreadId(
|
||||
(set, get) => {
|
||||
const updateTerminal = (threadId: ThreadId, action: ThreadTerminalAction) => {
|
||||
if (threadId.length === 0) return;
|
||||
set((state) => ({
|
||||
terminalStateByThreadId: applyTerminalAction(
|
||||
state.terminalStateByThreadId,
|
||||
threadId,
|
||||
updater,
|
||||
);
|
||||
if (nextTerminalStateByThreadId === state.terminalStateByThreadId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
terminalStateByThreadId: nextTerminalStateByThreadId,
|
||||
};
|
||||
});
|
||||
action,
|
||||
),
|
||||
}));
|
||||
};
|
||||
|
||||
return {
|
||||
terminalStateByThreadId: {},
|
||||
setTerminalOpen: (threadId, open) =>
|
||||
updateTerminal(threadId, (state) => setThreadTerminalOpen(state, open)),
|
||||
getTerminalState: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return getDefaultThreadTerminalState();
|
||||
}
|
||||
const state = get().terminalStateByThreadId[threadId];
|
||||
return state ?? getDefaultThreadTerminalState();
|
||||
},
|
||||
setTerminalOpen: (threadId, open) => updateTerminal(threadId, { type: "set-open", open }),
|
||||
setTerminalHeight: (threadId, height) =>
|
||||
updateTerminal(threadId, (state) => setThreadTerminalHeight(state, height)),
|
||||
updateTerminal(threadId, { type: "set-height", height }),
|
||||
splitTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => splitThreadTerminal(state, terminalId)),
|
||||
updateTerminal(threadId, { type: "split", terminalId }),
|
||||
newTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => newThreadTerminal(state, terminalId)),
|
||||
updateTerminal(threadId, { type: "new", terminalId }),
|
||||
setActiveTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => setThreadActiveTerminal(state, terminalId)),
|
||||
updateTerminal(threadId, { type: "set-active", terminalId }),
|
||||
closeTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => closeThreadTerminal(state, terminalId)),
|
||||
updateTerminal(threadId, { type: "close", terminalId }),
|
||||
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
|
||||
updateTerminal(threadId, (state) =>
|
||||
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
|
||||
),
|
||||
clearTerminalState: (threadId) =>
|
||||
updateTerminal(threadId, () => createDefaultThreadTerminalState()),
|
||||
removeOrphanedTerminalStates: (activeThreadIds) =>
|
||||
updateTerminal(threadId, { type: "set-activity", terminalId, hasRunningSubprocess }),
|
||||
clearTerminalState: (threadId) => {
|
||||
if (threadId.length === 0) return;
|
||||
set((state) => {
|
||||
const orphanedIds = Object.keys(state.terminalStateByThreadId).filter(
|
||||
(id) => !activeThreadIds.has(id as ThreadId),
|
||||
);
|
||||
if (orphanedIds.length === 0) return state;
|
||||
const next = { ...state.terminalStateByThreadId };
|
||||
for (const id of orphanedIds) {
|
||||
delete next[id as ThreadId];
|
||||
if (state.terminalStateByThreadId[threadId] === undefined) {
|
||||
return state;
|
||||
}
|
||||
return { terminalStateByThreadId: next };
|
||||
}),
|
||||
const { [threadId]: _removed, ...rest } = state.terminalStateByThreadId;
|
||||
return {
|
||||
terminalStateByThreadId: rest as Record<ThreadId, ThreadTerminalState>,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createDefaultThreadTerminalState,
|
||||
reduceThreadTerminalState,
|
||||
} from "./threadTerminalState";
|
||||
|
||||
describe("threadTerminalState", () => {
|
||||
it("creates a closed default terminal state", () => {
|
||||
expect(createDefaultThreadTerminalState()).toEqual({
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
});
|
||||
});
|
||||
|
||||
it("opens and splits terminal tabs into the active group", () => {
|
||||
const opened = reduceThreadTerminalState(createDefaultThreadTerminalState(), {
|
||||
type: "set-open",
|
||||
open: true,
|
||||
});
|
||||
const split = reduceThreadTerminalState(opened, {
|
||||
type: "split",
|
||||
terminalId: "terminal-2",
|
||||
});
|
||||
|
||||
expect(split.terminalOpen).toBe(true);
|
||||
expect(split.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(split.activeTerminalId).toBe("terminal-2");
|
||||
expect(split.terminalGroups).toEqual([
|
||||
{
|
||||
id: "group-default",
|
||||
terminalIds: ["default", "terminal-2"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates new terminals in a new group", () => {
|
||||
const next = reduceThreadTerminalState(createDefaultThreadTerminalState(), {
|
||||
type: "new",
|
||||
terminalId: "terminal-2",
|
||||
});
|
||||
|
||||
expect(next.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(next.activeTerminalId).toBe("terminal-2");
|
||||
expect(next.activeTerminalGroupId).toBe("group-terminal-2");
|
||||
expect(next.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("resets to default when closing the last terminal", () => {
|
||||
const closed = reduceThreadTerminalState(createDefaultThreadTerminalState(), {
|
||||
type: "close",
|
||||
terminalId: "default",
|
||||
});
|
||||
|
||||
expect(closed).toEqual(createDefaultThreadTerminalState());
|
||||
});
|
||||
|
||||
it("keeps a valid active terminal after closing an active split terminal", () => {
|
||||
const splitOnce = reduceThreadTerminalState(createDefaultThreadTerminalState(), {
|
||||
type: "split",
|
||||
terminalId: "terminal-2",
|
||||
});
|
||||
const splitTwice = reduceThreadTerminalState(splitOnce, {
|
||||
type: "split",
|
||||
terminalId: "terminal-3",
|
||||
});
|
||||
|
||||
const closed = reduceThreadTerminalState(splitTwice, {
|
||||
type: "close",
|
||||
terminalId: "terminal-3",
|
||||
});
|
||||
|
||||
expect(closed.activeTerminalId).toBe("terminal-2");
|
||||
expect(closed.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(closed.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,374 @@
|
||||
/**
|
||||
* Shared thread terminal state and reducer. Used by both the main app store
|
||||
* (persisted threads) and the composer draft store (draft threads), so we can
|
||||
* reuse the same shape and helpers and easily copy terminal state from draft
|
||||
* to thread when reconciling server state.
|
||||
*/
|
||||
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
/** Terminal slice shared by Thread and draft thread. Same shape in both stores. */
|
||||
export interface ThreadTerminalState {
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
}
|
||||
|
||||
export type ThreadTerminalAction =
|
||||
| { type: "set-open"; open: boolean }
|
||||
| { type: "set-height"; height: number }
|
||||
| { type: "split"; terminalId: string }
|
||||
| { type: "new"; terminalId: string }
|
||||
| { type: "set-active"; terminalId: string }
|
||||
| { type: "close"; terminalId: string }
|
||||
| { type: "set-activity"; terminalId: string; hasRunningSubprocess: boolean };
|
||||
|
||||
// ─── Helpers (exported for store reducers that need to work with Thread) ───
|
||||
|
||||
export function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))].slice(
|
||||
0,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
);
|
||||
return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
|
||||
export function normalizeRunningTerminalIds(
|
||||
runningTerminalIds: string[],
|
||||
terminalIds: string[],
|
||||
): string[] {
|
||||
if (runningTerminalIds.length === 0) return [];
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
export function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): string {
|
||||
let candidate = baseId;
|
||||
let index = 2;
|
||||
while (usedGroupIds.has(candidate)) {
|
||||
candidate = `${baseId}-${index}`;
|
||||
index += 1;
|
||||
}
|
||||
usedGroupIds.add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
export function findGroupIndexByTerminalId(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalId: string,
|
||||
): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
/** Normalize groups to match terminalIds; used by both thread and draft. */
|
||||
export function normalizeTerminalGroups(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalIds: string[],
|
||||
): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const nextGroups: ThreadTerminalGroup[] = [];
|
||||
const usedGroupIds = new Set<string>();
|
||||
|
||||
for (const group of terminalGroups) {
|
||||
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (nextGroups.length === 0) {
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return nextGroups;
|
||||
}
|
||||
|
||||
// ─── Default & normalize ─────────────────────────────────────────────────
|
||||
|
||||
const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
});
|
||||
|
||||
export function createDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return { ...DEFAULT_THREAD_TERMINAL_STATE };
|
||||
}
|
||||
|
||||
export function getDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return DEFAULT_THREAD_TERMINAL_STATE;
|
||||
}
|
||||
|
||||
export function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTerminalState {
|
||||
const terminalIds = normalizeTerminalIds(state.terminalIds);
|
||||
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const runningTerminalIds = normalizeRunningTerminalIds(
|
||||
state.runningTerminalIds,
|
||||
nextTerminalIds,
|
||||
);
|
||||
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
|
||||
? state.activeTerminalId
|
||||
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
|
||||
const activeGroupIdFromState = terminalGroups.some((group) => group.id === state.activeTerminalGroupId)
|
||||
? state.activeTerminalGroupId
|
||||
: null;
|
||||
const activeGroupIdFromTerminal =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? null;
|
||||
|
||||
return {
|
||||
terminalOpen: state.terminalOpen,
|
||||
terminalHeight:
|
||||
Number.isFinite(state.terminalHeight) && state.terminalHeight > 0
|
||||
? state.terminalHeight
|
||||
: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: nextTerminalIds,
|
||||
runningTerminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId:
|
||||
activeGroupIdFromState ??
|
||||
activeGroupIdFromTerminal ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Close terminal (shared) ─────────────────────────────────────────────
|
||||
|
||||
function closeTerminal(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
): ThreadTerminalState {
|
||||
if (!state.terminalIds.includes(terminalId)) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = state.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
return createDefaultThreadTerminalState();
|
||||
}
|
||||
|
||||
const closedTerminalIndex = state.terminalIds.indexOf(terminalId);
|
||||
const nextActiveTerminalId =
|
||||
state.activeTerminalId === terminalId
|
||||
? (remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: state.activeTerminalId;
|
||||
|
||||
const terminalGroups = state.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
const nextActiveTerminalGroupId =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(nextActiveTerminalId);
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
terminalOpen: state.terminalOpen,
|
||||
terminalHeight: state.terminalHeight,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: state.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextActiveTerminalGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[] {
|
||||
return groups.map((group) => ({
|
||||
id: group.id,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── Single reducer for both draft and persisted thread ────────────────────
|
||||
|
||||
export function reduceThreadTerminalState(
|
||||
state: ThreadTerminalState,
|
||||
action: ThreadTerminalAction,
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
|
||||
if (action.type === "set-open") {
|
||||
if (normalized.terminalOpen === action.open) return normalized;
|
||||
return { ...normalized, terminalOpen: action.open };
|
||||
}
|
||||
|
||||
if (action.type === "set-height") {
|
||||
if (
|
||||
!Number.isFinite(action.height) ||
|
||||
action.height <= 0 ||
|
||||
normalized.terminalHeight === action.height
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
return { ...normalized, terminalHeight: action.height };
|
||||
}
|
||||
|
||||
if (action.type === "set-active") {
|
||||
if (!normalized.terminalIds.includes(action.terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const activeTerminalGroupId =
|
||||
normalized.terminalGroups.find((group) => group.terminalIds.includes(action.terminalId))?.id ??
|
||||
normalized.activeTerminalGroupId;
|
||||
return {
|
||||
...normalized,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
|
||||
if (action.type === "close") {
|
||||
return closeTerminal(normalized, action.terminalId);
|
||||
}
|
||||
|
||||
if (action.type === "set-activity") {
|
||||
if (!normalized.terminalIds.includes(action.terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalized.runningTerminalIds);
|
||||
if (action.hasRunningSubprocess) {
|
||||
runningTerminalIds.add(action.terminalId);
|
||||
} else {
|
||||
runningTerminalIds.delete(action.terminalId);
|
||||
}
|
||||
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
|
||||
}
|
||||
|
||||
if (!action.terminalId || action.terminalId.trim().length === 0) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const isNewTerminal = !normalized.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalized.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const terminalIds = isNewTerminal
|
||||
? [...normalized.terminalIds, action.terminalId]
|
||||
: normalized.terminalIds;
|
||||
const terminalGroups = copyTerminalGroups(normalized.terminalGroups);
|
||||
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
|
||||
if (existingGroupIndex >= 0) {
|
||||
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
|
||||
existingGroupIndex
|
||||
]!.terminalIds.filter((id) => id !== action.terminalId);
|
||||
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
|
||||
terminalGroups.splice(existingGroupIndex, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (action.type === "new") {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(action.terminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
// split
|
||||
let activeGroupIndex = terminalGroups.findIndex((group) => group.id === normalized.activeTerminalGroupId);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(
|
||||
fallbackGroupId(normalized.activeTerminalId),
|
||||
usedGroupIds,
|
||||
);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(action.terminalId);
|
||||
}
|
||||
}
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
CommandId,
|
||||
type ContextMenuItem,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProjectId,
|
||||
@@ -10,12 +9,6 @@ import {
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const requestMock = vi.fn<(...args: Array<unknown>) => Promise<unknown>>();
|
||||
const showContextMenuFallbackMock = vi.fn<
|
||||
<T extends string>(
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
position?: { x: number; y: number },
|
||||
) => Promise<T | null>
|
||||
>();
|
||||
const channelListeners = new Map<string, Set<(data: unknown) => void>>();
|
||||
const subscribeMock = vi.fn<(channel: string, listener: (data: unknown) => void) => () => void>(
|
||||
(channel, listener) => {
|
||||
@@ -40,10 +33,6 @@ vi.mock("./wsTransport", () => {
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./contextMenuFallback", () => ({
|
||||
showContextMenuFallback: showContextMenuFallbackMock,
|
||||
}));
|
||||
|
||||
function emitPush(channel: string, data: unknown): void {
|
||||
const listeners = channelListeners.get(channel);
|
||||
if (!listeners) return;
|
||||
@@ -52,23 +41,11 @@ function emitPush(channel: string, data: unknown): void {
|
||||
}
|
||||
}
|
||||
|
||||
function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unknown } {
|
||||
const testGlobal = globalThis as typeof globalThis & {
|
||||
window?: Window & typeof globalThis & { desktopBridge?: unknown };
|
||||
};
|
||||
if (!testGlobal.window) {
|
||||
testGlobal.window = {} as Window & typeof globalThis & { desktopBridge?: unknown };
|
||||
}
|
||||
return testGlobal.window;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
requestMock.mockReset();
|
||||
showContextMenuFallbackMock.mockReset();
|
||||
subscribeMock.mockClear();
|
||||
channelListeners.clear();
|
||||
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -330,51 +307,4 @@ describe("wsNativeApi", () => {
|
||||
toTurnCount: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards context menu metadata to desktop bridge", async () => {
|
||||
const showContextMenu = vi.fn().mockResolvedValue("delete");
|
||||
Object.defineProperty(getWindowForTest(), "desktopBridge", {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: {
|
||||
showContextMenu,
|
||||
},
|
||||
});
|
||||
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
const api = createWsNativeApi();
|
||||
await api.contextMenu.show(
|
||||
[
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
],
|
||||
{ x: 200, y: 300 },
|
||||
);
|
||||
|
||||
expect(showContextMenu).toHaveBeenCalledWith(
|
||||
[
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
],
|
||||
{ x: 200, y: 300 },
|
||||
);
|
||||
});
|
||||
|
||||
it("uses fallback context menu when desktop bridge is unavailable", async () => {
|
||||
showContextMenuFallbackMock.mockResolvedValue("delete");
|
||||
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
|
||||
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
const api = createWsNativeApi();
|
||||
await api.contextMenu.show(
|
||||
[{ id: "delete", label: "Delete", destructive: true }],
|
||||
{ x: 20, y: 30 },
|
||||
);
|
||||
|
||||
expect(showContextMenuFallbackMock).toHaveBeenCalledWith(
|
||||
[{ id: "delete", label: "Delete", destructive: true }],
|
||||
{ x: 20, y: 30 },
|
||||
);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -2,7 +2,6 @@ import {
|
||||
OrchestrationEvent,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ContextMenuItem,
|
||||
type NativeApi,
|
||||
ServerConfigUpdatedPayload,
|
||||
TerminalEvent,
|
||||
@@ -172,11 +171,11 @@ export function createWsNativeApi(): NativeApi {
|
||||
},
|
||||
contextMenu: {
|
||||
show: async <T extends string>(
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
items: readonly { id: T; label: string }[],
|
||||
position?: { x: number; y: number },
|
||||
): Promise<T | null> => {
|
||||
if (window.desktopBridge) {
|
||||
return window.desktopBridge.showContextMenu(items, position) as Promise<T | null>;
|
||||
return window.desktopBridge.showContextMenu(items) as Promise<T | null>;
|
||||
}
|
||||
return showContextMenuFallback(items, position);
|
||||
},
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
"name": "@t3tools/monorepo",
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@types/node": "^24.10.13",
|
||||
"effect": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
@@ -23,7 +22,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@types/node": "^24.10.13",
|
||||
"@types/node": "^22.10.2",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
@@ -52,7 +51,7 @@
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
@@ -64,7 +63,6 @@
|
||||
"version": "0.0.0-alpha.4",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
@@ -75,7 +73,6 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
@@ -113,10 +110,10 @@
|
||||
},
|
||||
"catalog": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
|
||||
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@f591738",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@f591738",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@f591738",
|
||||
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@f591738",
|
||||
},
|
||||
"packages": {
|
||||
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
|
||||
@@ -169,13 +166,13 @@
|
||||
|
||||
"@effect/language-service": ["@effect/[email protected]", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-g9xD2tAQgRFpYC2YgpZq02VeSL5fBbFJ0B/g1o+14NuNmwtaYJc7SjiLWAA9eyhJHosNrn6h1Ye+Kx6j5mN0AA=="],
|
||||
|
||||
"@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25", "ioredis": "^5.7.0" } }],
|
||||
"@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@f591738", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@f59173885df0eb490dc2e6619ae89467feac0413", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.19", "ioredis": "^5.7.0" } }],
|
||||
|
||||
"@effect/platform-node-shared": ["@effect/platform-node-shared@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25" } }],
|
||||
"@effect/platform-node-shared": ["@effect/platform-node-shared@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@f59173885df0eb490dc2e6619ae89467feac0413", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.19" } }],
|
||||
|
||||
"@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", { "peerDependencies": { "effect": "^4.0.0-beta.25" } }],
|
||||
"@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@f591738", { "peerDependencies": { "effect": "^4.0.0-beta.19" } }],
|
||||
|
||||
"@effect/vitest": ["@effect/vitest@https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", { "peerDependencies": { "effect": "^4.0.0-beta.25", "vitest": "^3.0.0 || ^4.0.0" } }],
|
||||
"@effect/vitest": ["@effect/vitest@https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@f591738", { "peerDependencies": { "effect": "^4.0.0-beta.19", "vitest": "^3.0.0" } }],
|
||||
|
||||
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
|
||||
|
||||
@@ -241,8 +238,6 @@
|
||||
|
||||
"@floating-ui/dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/core": "^1.7.4", "@floating-ui/utils": "^0.2.10" } }, "sha512-N0bD2kIPInNHUHehXhMke1rBGs1dwqvC9O9KYMyyjK7iXt7GAhnro7UlcuYcGdS/yYOlq0MAVgrow8IbWJwyqg=="],
|
||||
|
||||
"@floating-ui/react": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/react-dom": "^2.1.7", "@floating-ui/utils": "^0.2.10", "tabbable": "^6.0.0" }, "peerDependencies": { "react": ">=17.0.0", "react-dom": ">=17.0.0" } }, "sha512-xJWJxvmy3a05j643gQt+pRbht5XnTlGpsEsAPnMi5F5YTOEEJymA90uZKBD8OvIv5XvZ1qi4GcccSlqT3Bq44Q=="],
|
||||
|
||||
"@floating-ui/react-dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/dom": "^1.7.5" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-0tLRojf/1Go2JgEVm+3Frg9A3IW8bJgKgdO0BN5RkF//ufuz2joZM63Npau2ff3J6lUVYgDSNzNkR+aH3IVfjg=="],
|
||||
|
||||
"@floating-ui/utils": ["@floating-ui/[email protected]", "", {}, "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ=="],
|
||||
@@ -281,50 +276,6 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@lexical/clipboard": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/html": "0.41.0", "@lexical/list": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-Ex5lPkb4NBBX1DCPzOAIeHBJFH1bJcmATjREaqpnTfxCbuOeQkt44wchezUA0oDl+iAxNZ3+pLLWiUju9icoSA=="],
|
||||
|
||||
"@lexical/code": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/utils": "0.41.0", "lexical": "0.41.0", "prismjs": "^1.30.0" } }, "sha512-0hoNi1KC9/N3SBOGcOcFqnT0OpwmcRRAhfxTKMGqfCtCvAMzULVwZ8RWc9/NV9bKYESgBTW5D9xkDANP2mspHg=="],
|
||||
|
||||
"@lexical/devtools-core": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/html": "0.41.0", "@lexical/link": "0.41.0", "@lexical/mark": "0.41.0", "@lexical/table": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" }, "peerDependencies": { "react": ">=17.x", "react-dom": ">=17.x" } }, "sha512-FzJtluBhBc8bKS11TUZe72KoZN/hnzIyiiM0SPJAsPwGpoXuM01jqpXQGybWf/1bWB+bmmhOae7O4Nywi/Csuw=="],
|
||||
|
||||
"@lexical/dragon": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/extension": "0.41.0", "lexical": "0.41.0" } }, "sha512-gBEqkk8Q6ZPruvDaRcOdF1EK9suCVBODzOCcR+EnoJTaTjfDkCM7pkPAm4w90Wa1wCZEtFHvCfas+jU9MDSumg=="],
|
||||
|
||||
"@lexical/extension": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/utils": "0.41.0", "@preact/signals-core": "^1.11.0", "lexical": "0.41.0" } }, "sha512-sF4SPiP72yXvIGchmmIZ7Yg2XZTxNLOpFEIIzdqG7X/1fa1Ham9P/T7VbrblWpF6Ei5LJtK9JgNVB0hb4l3o1g=="],
|
||||
|
||||
"@lexical/hashtag": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/text": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-tFWM74RW4KU0E/sj2aowfWl26vmLUTp331CgVESnhQKcZBfT40KJYd57HEqBDTfQKn4MUhylQCCA0hbpw6EeFQ=="],
|
||||
|
||||
"@lexical/history": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/extension": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-kGoVWsiOn62+RMjRolRa+NXZl8jFwxav6GNDiHH8yzivtoaH8n1SwUfLJELXCzeqzs81HySqD4q30VLJVTGoDg=="],
|
||||
|
||||
"@lexical/html": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-3RyZy+H/IDKz2D66rNN/NqYx87xVFrngfEbyu1OWtbY963RUFnopiVHCQvsge/8kT04QSZ7U/DzjVFqeNS6clg=="],
|
||||
|
||||
"@lexical/link": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/extension": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-Rjtx5cGWAkKcnacncbVsZ1TqRnUB2Wm4eEVKpaAEG41+kHgqghzM2P+UGT15yROroxJu8KvAC9ISiYFiU4XE1w=="],
|
||||
|
||||
"@lexical/list": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/extension": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-RXvB+xcbzVoQLGRDOBRCacztG7V+bI95tdoTwl8pz5xvgPtAaRnkZWMDP+yMNzMJZsqEChdtpxbf0NgtMkun6g=="],
|
||||
|
||||
"@lexical/mark": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-UO5WVs9uJAYIKHSlYh4Z1gHrBBchTOi21UCYBIZ7eAs4suK84hPzD+3/LAX5CB7ZltL6ke5Sly3FOwNXv/wfpA=="],
|
||||
|
||||
"@lexical/markdown": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/code": "0.41.0", "@lexical/link": "0.41.0", "@lexical/list": "0.41.0", "@lexical/rich-text": "0.41.0", "@lexical/text": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-bzI73JMXpjGFhqUWNV6KqfjWcgAWzwFT+J3RHtbCF5rysC8HLldBYojOgAAtPfXqfxyv2mDzsY7SoJ75s9uHZA=="],
|
||||
|
||||
"@lexical/offset": ["@lexical/[email protected]", "", { "dependencies": { "lexical": "0.41.0" } }, "sha512-2RHBXZqC8gm3X9C0AyRb0M8w7zJu5dKiasrif+jSKzsxPjAUeF1m95OtIOsWs1XLNUgASOSUqGovDZxKJslZfA=="],
|
||||
|
||||
"@lexical/overflow": ["@lexical/[email protected]", "", { "dependencies": { "lexical": "0.41.0" } }, "sha512-Iy6ZiJip8X14EBYt1zKPOrXyQ4eG9JLBEoPoSVBTiSbVd+lYicdUvaOThT0k0/qeVTN9nqTaEltBjm56IrVKCQ=="],
|
||||
|
||||
"@lexical/plain-text": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/clipboard": "0.41.0", "@lexical/dragon": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-HIsGgmFUYRUNNyvckun33UQfU7LRzDlxymHUq67+Bxd5bXqdZOrStEKJXuDX+LuLh/GXZbaWNbDLqwLBObfbQg=="],
|
||||
|
||||
"@lexical/react": ["@lexical/[email protected]", "", { "dependencies": { "@floating-ui/react": "^0.27.16", "@lexical/devtools-core": "0.41.0", "@lexical/dragon": "0.41.0", "@lexical/extension": "0.41.0", "@lexical/hashtag": "0.41.0", "@lexical/history": "0.41.0", "@lexical/link": "0.41.0", "@lexical/list": "0.41.0", "@lexical/mark": "0.41.0", "@lexical/markdown": "0.41.0", "@lexical/overflow": "0.41.0", "@lexical/plain-text": "0.41.0", "@lexical/rich-text": "0.41.0", "@lexical/table": "0.41.0", "@lexical/text": "0.41.0", "@lexical/utils": "0.41.0", "@lexical/yjs": "0.41.0", "lexical": "0.41.0", "react-error-boundary": "^6.0.0" }, "peerDependencies": { "react": ">=17.x", "react-dom": ">=17.x" } }, "sha512-7+GUdZUm6sofWm+zdsWAs6cFBwKNsvsHezZTrf6k8jrZxL461ZQmbz/16b4DvjCGL9r5P1fR7md9/LCmk8TiCg=="],
|
||||
|
||||
"@lexical/rich-text": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/clipboard": "0.41.0", "@lexical/dragon": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-yUcr7ZaaVTZNi8bow4CK1M8jy2qyyls1Vr+5dVjwBclVShOL/F/nFyzBOSb6RtXXRbd3Ahuk9fEleppX/RNIdw=="],
|
||||
|
||||
"@lexical/selection": ["@lexical/[email protected]", "", { "dependencies": { "lexical": "0.41.0" } }, "sha512-1s7/kNyRzcv5uaTwsUL28NpiisqTf5xZ1zNukLsCN1xY+TWbv9RE9OxIv+748wMm4pxNczQe/UbIBODkbeknLw=="],
|
||||
|
||||
"@lexical/table": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/clipboard": "0.41.0", "@lexical/extension": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-d3SPThBAr+oZ8O74TXU0iXM3rLbrAVC7/HcOnSAq7/AhWQW8yMutT51JQGN+0fMLP9kqoWSAojNtkdvzXfU/+A=="],
|
||||
|
||||
"@lexical/text": ["@lexical/[email protected]", "", { "dependencies": { "lexical": "0.41.0" } }, "sha512-gGA+Anc7ck110EXo4KVKtq6Ui3M7Vz3OpGJ4QE6zJHWW8nV5h273koUGSutAMeoZgRVb6t01Izh3ORoFt/j1CA=="],
|
||||
|
||||
"@lexical/utils": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/selection": "0.41.0", "lexical": "0.41.0" } }, "sha512-Wlsokr5NQCq83D+7kxZ9qs5yQ3dU3Qaf2M+uXxLRoPoDaXqW8xTWZq1+ZFoEzsHzx06QoPa4Vu/40BZR91uQPg=="],
|
||||
|
||||
"@lexical/yjs": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/offset": "0.41.0", "@lexical/selection": "0.41.0", "lexical": "0.41.0" }, "peerDependencies": { "yjs": ">=13.5.22" } }, "sha512-PaKTxSbVC4fpqUjQ7vUL9RkNF1PjL8TFl5jRe03PqoPYpE33buf3VXX6+cOUEfv9+uknSqLCPHoBS/4jN3a97w=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
|
||||
@@ -429,8 +380,6 @@
|
||||
|
||||
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-McjTuEPuacSIcXdoI2O9W6VSHIOs9ApEHnEUwONKZnKqIo2GGv1vNg9Pr8tgBOL7lgBWNEHX5ROJ5z1X74sENQ=="],
|
||||
|
||||
"@preact/signals-core": ["@preact/[email protected]", "", {}, "sha512-slT6XeTCAbdql61GVLlGU4x7XHI7kCZV5Um5uhE4zLX4ApgiiXc0UYFvVOKq06xcovzp7p+61l68oPi563ARKg=="],
|
||||
|
||||
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
|
||||
|
||||
"@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-0T1k9FinuBZ/t7rZ8jN6OpUKPnUjNdYHoj/cESWrQ3ZraAJ4OMm6z7QjSfCxqj8mOp9kTKc1zHK3kGz5vMu+nQ=="],
|
||||
@@ -637,7 +586,7 @@
|
||||
|
||||
"@types/ms": ["@types/[email protected]", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
|
||||
|
||||
"@types/node": ["@types/node@24.10.13", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
|
||||
"@types/node": ["@types/node@22.19.11", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
|
||||
|
||||
@@ -811,7 +760,7 @@
|
||||
|
||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
"effect": ["effect@https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }],
|
||||
"effect": ["effect@https://pkg.pr.new/Effect-TS/effect-smol/effect@f591738", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }],
|
||||
|
||||
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
|
||||
|
||||
@@ -973,8 +922,6 @@
|
||||
|
||||
"isbot": ["[email protected]", "", {}, "sha512-waFfC72ZNfwLLuJ2iLaoVaqcNo+CAaLR7xCpAn0Y5WfGzkNHv7ZN39Vbi1y+kb+Zs46XHOX3tZNExroFUPX+Kg=="],
|
||||
|
||||
"isomorphic.js": ["[email protected]", "", {}, "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw=="],
|
||||
|
||||
"jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
|
||||
|
||||
"joi": ["[email protected]", "", { "dependencies": { "@hapi/address": "^5.1.1", "@hapi/formula": "^3.0.2", "@hapi/hoek": "^11.0.7", "@hapi/pinpoint": "^2.0.1", "@hapi/tlds": "^1.1.1", "@hapi/topo": "^6.0.2", "@standard-schema/spec": "^1.0.0" } }, "sha512-RuCOQMIt78LWnktPoeBL0GErkNaJPTBGcYuyaBvUOQSpcpcLfWrHPPihYdOGbV5pam9VTWbeoF7TsGiHugcjGA=="],
|
||||
@@ -995,10 +942,6 @@
|
||||
|
||||
"kubernetes-types": ["[email protected]", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="],
|
||||
|
||||
"lexical": ["[email protected]", "", {}, "sha512-pNIm5+n+hVnJHB9gYPDYsIO5Y59dNaDU9rJmPPsfqQhP2ojKFnUoPbcRnrI9FJLXB14sSumcY8LUw7Sq70TZqA=="],
|
||||
|
||||
"lib0": ["[email protected]", "", { "dependencies": { "isomorphic.js": "^0.2.4" }, "bin": { "0serve": "bin/0serve.js", "0gentesthtml": "bin/gentesthtml.js", "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js" } }, "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw=="],
|
||||
|
||||
"lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.31.1", "lightningcss-darwin-arm64": "1.31.1", "lightningcss-darwin-x64": "1.31.1", "lightningcss-freebsd-x64": "1.31.1", "lightningcss-linux-arm-gnueabihf": "1.31.1", "lightningcss-linux-arm64-gnu": "1.31.1", "lightningcss-linux-arm64-musl": "1.31.1", "lightningcss-linux-x64-gnu": "1.31.1", "lightningcss-linux-x64-musl": "1.31.1", "lightningcss-win32-arm64-msvc": "1.31.1", "lightningcss-win32-x64-msvc": "1.31.1" } }, "sha512-l51N2r93WmGUye3WuFoN5k10zyvrVs0qfKBhyC5ogUQ6Ew6JUSswh78mbSO+IU3nTWsyOArqPCcShdQSadghBQ=="],
|
||||
|
||||
"lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-HXJF3x8w9nQ4jbXRiNppBCqeZPIAfUo8zE/kOEGbW5NZvGc/K7nMxbhIr+YlFlHW5mpbg/YFPdbnCh1wAXCKFg=="],
|
||||
@@ -1211,8 +1154,6 @@
|
||||
|
||||
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
|
||||
|
||||
"prismjs": ["[email protected]", "", {}, "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw=="],
|
||||
|
||||
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
|
||||
|
||||
"property-information": ["[email protected]", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="],
|
||||
@@ -1231,8 +1172,6 @@
|
||||
|
||||
"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
|
||||
|
||||
"react-error-boundary": ["[email protected]", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0" } }, "sha512-BrYwPOdXi5mqkk5lw+Uvt0ThHx32rCt3BkukS4X23A2AIWDPSGX6iaWTc0y9TU/mHDA/6qOSGel+B2ERkOvD1w=="],
|
||||
|
||||
"react-markdown": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "html-url-attributes": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "unified": "^11.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" }, "peerDependencies": { "@types/react": ">=18", "react": ">=18" } }, "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ=="],
|
||||
|
||||
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
||||
@@ -1409,7 +1348,7 @@
|
||||
|
||||
"undici": ["[email protected]", "", {}, "sha512-RqslV2Us5BrllB+JeiZnK4peryVTndy9Dnqq62S3yYRRTj0tFQCwEniUy2167skdGOy3vqRzEvl1Dm4sV2ReDg=="],
|
||||
|
||||
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
|
||||
|
||||
@@ -1475,8 +1414,6 @@
|
||||
|
||||
"yauzl": ["[email protected]", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
|
||||
|
||||
"yjs": ["[email protected]", "", { "dependencies": { "lib0": "^0.2.99" } }, "sha512-kHqDPdltoXH+X4w1lVmMtddE3Oeqq48nM40FD5ojTd8xYhQpzIDcfE2keMSU5bAgRPJBe225WTUdyUgj1DtbiQ=="],
|
||||
|
||||
"yoctocolors-cjs": ["[email protected]", "", {}, "sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw=="],
|
||||
|
||||
"zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||
@@ -1535,26 +1472,20 @@
|
||||
|
||||
"@types/babel__template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
|
||||
|
||||
"@types/cacheable-request/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/keyv/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/responselike/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/ws/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/yauzl/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@vitejs/plugin-react/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
|
||||
|
||||
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"babel-dead-code-elimination/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
|
||||
|
||||
"bun-types/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
|
||||
|
||||
"cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
|
||||
|
||||
"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
|
||||
|
||||
"electron/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
|
||||
|
||||
"mdast-util-find-and-replace/escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
|
||||
|
||||
"micromatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
@@ -1599,15 +1530,9 @@
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
|
||||
|
||||
"@types/cacheable-request/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
"bun-types/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
"@types/keyv/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/responselike/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/ws/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/yauzl/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
"electron/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
}
|
||||
|
||||
+4
-5
@@ -7,10 +7,10 @@
|
||||
"packages/*"
|
||||
],
|
||||
"catalog": {
|
||||
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
|
||||
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@f591738",
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@f591738",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@f591738",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@f591738",
|
||||
"@effect/language-service": "0.75.1"
|
||||
}
|
||||
},
|
||||
@@ -41,7 +41,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@types/node": "^24.10.13",
|
||||
"effect": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
|
||||
@@ -3,8 +3,6 @@ import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
export const EDITORS = [
|
||||
{ id: "cursor", label: "Cursor", command: "cursor" },
|
||||
{ id: "vscode", label: "VS Code", command: "code" },
|
||||
{ id: "zed", label: "Zed", command: "zed" },
|
||||
{ id: "file-manager", label: "File Manager", command: null },
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -37,18 +37,12 @@ import type {
|
||||
} from "./orchestration";
|
||||
import { EditorId } from "./editor";
|
||||
|
||||
export interface ContextMenuItem<T extends string = string> {
|
||||
id: T;
|
||||
label: string;
|
||||
destructive?: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopBridge {
|
||||
getWsUrl: () => string | null;
|
||||
pickFolder: () => Promise<string | null>;
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
showContextMenu: <T extends string>(
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
items: readonly { id: T; label: string }[],
|
||||
position?: { x: number; y: number },
|
||||
) => Promise<T | null>;
|
||||
openExternal: (url: string) => Promise<boolean>;
|
||||
@@ -91,7 +85,7 @@ export interface NativeApi {
|
||||
};
|
||||
contextMenu: {
|
||||
show: <T extends string>(
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
items: readonly { id: T; label: string }[],
|
||||
position?: { x: number; y: number },
|
||||
) => Promise<T | null>;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
|
||||
import { EditorId } from "./editor";
|
||||
|
||||
export const KeybindingsMalformedConfigIssue = Schema.Struct({
|
||||
kind: Schema.Literal("keybindings.malformed-config"),
|
||||
@@ -30,7 +29,6 @@ export const ServerConfig = Schema.Struct({
|
||||
keybindingsConfigPath: TrimmedNonEmptyString,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
issues: ServerConfigIssues,
|
||||
availableEditors: Schema.Array(EditorId),
|
||||
});
|
||||
export type ServerConfig = typeof ServerConfig.Type;
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import rootPackageJson from "../package.json" with { type: "json" };
|
||||
import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
|
||||
import serverPackageJson from "../apps/server/package.json" with { type: "json" };
|
||||
@@ -86,21 +84,6 @@ class BuildScriptError extends Data.TaggedError("BuildScriptError")<{
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
function resolveGitCommitHash(repoRoot: string): string {
|
||||
const result = spawnSync("git", ["rev-parse", "--short=12", "HEAD"], {
|
||||
cwd: repoRoot,
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
return "unknown";
|
||||
}
|
||||
const hash = result.stdout.trim();
|
||||
if (!/^[0-9a-f]{7,40}$/i.test(hash)) {
|
||||
return "unknown";
|
||||
}
|
||||
return hash.toLowerCase();
|
||||
}
|
||||
|
||||
interface ResolvedBuildOptions {
|
||||
readonly platform: typeof BuildPlatform.Type;
|
||||
readonly target: string;
|
||||
@@ -117,7 +100,6 @@ interface StagePackageJson {
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
readonly buildVersion: string;
|
||||
readonly t3codeCommitHash: string;
|
||||
readonly private: true;
|
||||
readonly description: string;
|
||||
readonly author: string;
|
||||
@@ -454,7 +436,6 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
|
||||
});
|
||||
|
||||
const appVersion = options.version ?? serverPackageJson.version;
|
||||
const commitHash = resolveGitCommitHash(repoRoot);
|
||||
const mkdir = options.keepStage ? fs.makeTempDirectory : fs.makeTempDirectoryScoped;
|
||||
const stageRoot = yield* mkdir({
|
||||
prefix: `t3code-desktop-${options.platform}-stage-`,
|
||||
@@ -509,7 +490,6 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
|
||||
name: "t3-code-desktop",
|
||||
version: appVersion,
|
||||
buildVersion: appVersion,
|
||||
t3codeCommitHash: commitHash,
|
||||
private: true,
|
||||
description: "T3 Code desktop build",
|
||||
author: "T3 Tools",
|
||||
|
||||
Reference in new issue
Block a user