Compare commits
55
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dbd6316db | ||
|
|
e484bb188c | ||
|
|
fb5a1ac205 | ||
|
|
a3aa4bd189 | ||
|
|
5a0006f7ef | ||
|
|
9e2e73c070 | ||
|
|
c530e5d50f | ||
|
|
674720c6cd | ||
|
|
58c9e4b96d | ||
|
|
feb286379c | ||
|
|
cefe641586 | ||
|
|
664451c296 | ||
|
|
fd4ff8ca46 | ||
|
|
1bcfbdf287 | ||
|
|
4e45c1a6ab | ||
|
|
32fe80d164 | ||
|
|
6e93d42023 | ||
|
|
6f50867aa1 | ||
|
|
4fca60469d | ||
|
|
afcd824ae9 | ||
|
|
f84f279738 | ||
|
|
246624ad3c | ||
|
|
410444aead | ||
|
|
7522d3bde3 | ||
|
|
ed26b84177 | ||
|
|
ad4d12cf94 | ||
|
|
f6fd760e4e | ||
|
|
506a5260dc | ||
|
|
d4c90d696d | ||
|
|
be4d26a1b3 | ||
|
|
5c09614319 | ||
|
|
4c846332c5 | ||
|
|
a3a0cbf0f8 | ||
|
|
2c7101092a | ||
|
|
9f068356a4 | ||
|
|
f239c90628 | ||
|
|
991dd05e72 | ||
|
|
96bf54e293 | ||
|
|
5ca9b54d66 | ||
|
|
4ab5fca4ca | ||
|
|
69a4fa8215 | ||
|
|
9e04bad0a5 | ||
|
|
a574d9c936 | ||
|
|
005e13089a | ||
|
|
d9cce6402a | ||
|
|
508872e04b | ||
|
|
aced302b63 | ||
|
|
0b8dfee17b | ||
|
|
6ab246676e | ||
|
|
122c94a24a | ||
|
|
b59c6d6ab1 | ||
|
|
c9995995a4 | ||
|
|
545a9193e2 | ||
|
|
fa0205cba3 | ||
|
|
8a20bd7f54 |
No files matched your search
@@ -84,6 +84,18 @@ jobs:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
run: bun install
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Commit and push release version + tag
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
shell: bash
|
||||
@@ -117,18 +129,6 @@ jobs:
|
||||
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
+88
-16
@@ -5,9 +5,10 @@ import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, protocol, shell } from "electron";
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { fixPath } from "./fixPath";
|
||||
|
||||
@@ -36,6 +37,31 @@ let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
let desktopProtocolRegistered = false;
|
||||
|
||||
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([
|
||||
{
|
||||
scheme: DESKTOP_SCHEME,
|
||||
@@ -397,23 +423,69 @@ function registerIpcHandlers(): void {
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
|
||||
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) => ({
|
||||
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,
|
||||
label: item.label,
|
||||
click: () => resolve(item.id),
|
||||
})),
|
||||
);
|
||||
menu.popup({
|
||||
window,
|
||||
callback: () => resolve(null),
|
||||
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),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
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) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.1.0",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
},
|
||||
|
||||
@@ -19,6 +19,17 @@ const CODEX_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
|
||||
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
|
||||
const document = Schema.toJsonSchemaDocument(schema);
|
||||
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||
return {
|
||||
...document.schema,
|
||||
$defs: document.definitions,
|
||||
};
|
||||
}
|
||||
return document.schema;
|
||||
}
|
||||
|
||||
function normalizeCodexError(
|
||||
operation: string,
|
||||
error: unknown,
|
||||
@@ -204,7 +215,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(Schema.toJsonSchemaDocument(outputSchemaJson).schema),
|
||||
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
|
||||
@@ -1162,7 +1162,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
// Refresh upstream refs in the background so checkout remains responsive.
|
||||
yield* Effect.forkDetach(
|
||||
yield* Effect.forkScoped(
|
||||
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -152,4 +152,16 @@ describe("tryHandleProjectFaviconRequest", () => {
|
||||
expect(response.body).toBe("<svg>brand-obj-order</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("serves a fallback favicon when no icon exists", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-fallback-");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toContain('data-fallback="project-favicon"');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,8 @@ const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
".ico": "image/x-icon",
|
||||
};
|
||||
|
||||
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg",
|
||||
@@ -85,6 +87,14 @@ function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
|
||||
});
|
||||
}
|
||||
|
||||
function serveFallbackFavicon(res: http.ServerResponse): void {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "image/svg+xml",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
});
|
||||
res.end(FALLBACK_FAVICON_SVG);
|
||||
}
|
||||
|
||||
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
|
||||
if (url.pathname !== "/api/project-favicon") {
|
||||
return false;
|
||||
@@ -118,8 +128,7 @@ export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerRespons
|
||||
|
||||
const trySourceFiles = (index: number): void => {
|
||||
if (index >= ICON_SOURCE_FILES.length) {
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("No favicon found");
|
||||
serveFallbackFavicon(res);
|
||||
return;
|
||||
}
|
||||
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -12,6 +12,7 @@
|
||||
},
|
||||
"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",
|
||||
@@ -22,6 +23,7 @@
|
||||
"@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",
|
||||
|
||||
@@ -43,7 +43,10 @@ export default function BranchToolbar({
|
||||
envLocked,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarProps) {
|
||||
const { state, dispatch } = useStore();
|
||||
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 draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const queryClient = useQueryClient();
|
||||
@@ -51,9 +54,9 @@ export default function BranchToolbar({
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
|
||||
const serverThread = state.threads.find((thread) => thread.id === threadId);
|
||||
const serverThread = threads.find((thread) => thread.id === threadId);
|
||||
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
|
||||
const activeProject = state.projects.find((project) => project.id === activeProjectId);
|
||||
const activeProject = 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;
|
||||
@@ -114,12 +117,7 @@ export default function BranchToolbar({
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
setThreadBranchAction(activeThreadId, syncedBranch, null);
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(threadId, {
|
||||
@@ -132,22 +130,17 @@ export default function BranchToolbar({
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
effectiveEnvMode,
|
||||
dispatch,
|
||||
setThreadBranchAction,
|
||||
hasServerThread,
|
||||
setDraftThreadContext,
|
||||
threadId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
setBranchQuery("");
|
||||
}, [isBranchMenuOpen]);
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
const setThreadError = (error: string | null) => {
|
||||
if (!activeThreadId) return;
|
||||
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
|
||||
setThreadErrorAction(activeThreadId, error);
|
||||
};
|
||||
|
||||
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
|
||||
@@ -176,7 +169,7 @@ export default function BranchToolbar({
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
|
||||
setThreadBranchAction(activeThreadId, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(threadId, {
|
||||
@@ -282,7 +275,12 @@ export default function BranchToolbar({
|
||||
<Combobox
|
||||
items={branchPickerItems}
|
||||
autoHighlight
|
||||
onOpenChange={(open) => setIsBranchMenuOpen(open)}
|
||||
onOpenChange={(open) => {
|
||||
setIsBranchMenuOpen(open);
|
||||
if (!open) {
|
||||
setBranchQuery("");
|
||||
}
|
||||
}}
|
||||
open={isBranchMenuOpen}
|
||||
value={activeThreadBranch}
|
||||
>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,813 @@
|
||||
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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
@@ -156,7 +156,6 @@ 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);
|
||||
@@ -168,8 +167,13 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
});
|
||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||
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 activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
@@ -342,7 +346,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
if (!element) return;
|
||||
element.scrollBy({ left: offset, behavior: "smooth" });
|
||||
}, []);
|
||||
const onTurnStripWheel = useCallback((event: WheelEvent) => {
|
||||
const onTurnStripWheel = useCallback((event: ReactWheelEvent<HTMLDivElement>) => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
if (element.scrollWidth <= element.clientWidth + 1) return;
|
||||
@@ -356,24 +360,26 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
|
||||
updateTurnStripScrollState();
|
||||
const frameId = window.requestAnimationFrame(() => 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, onTurnStripWheel]);
|
||||
}, [updateTurnStripScrollState]);
|
||||
|
||||
useEffect(() => {
|
||||
updateTurnStripScrollState();
|
||||
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
};
|
||||
}, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -422,7 +428,11 @@ 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">
|
||||
<div
|
||||
ref={turnStripRef}
|
||||
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
|
||||
onWheel={onTurnStripWheel}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
ProjectId,
|
||||
@@ -21,6 +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 { toastManager } from "./ui/toast";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
@@ -126,8 +127,10 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
|
||||
return null;
|
||||
}
|
||||
|
||||
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
|
||||
if (thread.runningTerminalIds.length === 0) {
|
||||
function terminalStatusFromRunningIds(
|
||||
runningTerminalIds: string[],
|
||||
): TerminalStatusIndicator | null {
|
||||
if (runningTerminalIds.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
@@ -171,7 +174,7 @@ function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
aria-label="T3"
|
||||
className="h-3 w-auto shrink-0 text-foreground"
|
||||
className="h-2.5 w-auto shrink-0 text-foreground"
|
||||
viewBox="15.5309 37 94.3941 56.96"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
@@ -228,12 +231,17 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
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 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 setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const clearProjectDraftThreadId = useComposerDraftStore(
|
||||
@@ -258,25 +266,29 @@ 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 state.threads) {
|
||||
for (const thread of threads) {
|
||||
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
|
||||
}
|
||||
return map;
|
||||
}, [state.threads]);
|
||||
}, [threads]);
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[state.projects],
|
||||
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[projects],
|
||||
);
|
||||
const threadGitTargets = useMemo(
|
||||
() =>
|
||||
state.threads.map((thread) => ({
|
||||
threads.map((thread) => ({
|
||||
threadId: thread.id,
|
||||
branch: thread.branch,
|
||||
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
||||
})),
|
||||
[projectCwdById, state.threads],
|
||||
[projectCwdById, threads],
|
||||
);
|
||||
const threadGitStatusCwds = useMemo(
|
||||
() => [
|
||||
@@ -312,7 +324,7 @@ export default function Sidebar() {
|
||||
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
||||
const branchMatches =
|
||||
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
||||
map.set(target.threadId, branchMatches ? status?.pr ?? null : null);
|
||||
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
|
||||
}
|
||||
return map;
|
||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||
@@ -414,7 +426,7 @@ export default function Sidebar() {
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
(projectId: ProjectId) => {
|
||||
const latestThread = state.threads
|
||||
const latestThread = threads
|
||||
.filter((thread) => thread.projectId === projectId)
|
||||
.toSorted((a, b) => {
|
||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
@@ -428,7 +440,7 @@ export default function Sidebar() {
|
||||
params: { threadId: latestThread.id },
|
||||
});
|
||||
},
|
||||
[navigate, state.threads],
|
||||
[navigate, threads],
|
||||
);
|
||||
|
||||
const addProjectFromPath = useCallback(
|
||||
@@ -436,20 +448,27 @@ export default function Sidebar() {
|
||||
const cwd = rawCwd.trim();
|
||||
if (!cwd || isAddingProject) return;
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
|
||||
setIsAddingProject(true);
|
||||
try {
|
||||
if (!api) return;
|
||||
const existing = state.projects.find((project) => project.cwd === cwd);
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
return;
|
||||
}
|
||||
const finishAddingProject = () => {
|
||||
setIsAddingProject(false);
|
||||
setNewCwd("");
|
||||
setAddingProject(false);
|
||||
};
|
||||
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
await api.orchestration.dispatchCommand({
|
||||
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({
|
||||
type: "project.create",
|
||||
commandId: newCommandId(),
|
||||
projectId,
|
||||
@@ -457,15 +476,15 @@ export default function Sidebar() {
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: DEFAULT_MODEL,
|
||||
createdAt,
|
||||
});
|
||||
await handleNewThread(projectId);
|
||||
} finally {
|
||||
setIsAddingProject(false);
|
||||
setNewCwd("");
|
||||
setAddingProject(false);
|
||||
})
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
if (projectCreated) {
|
||||
await handleNewThread(projectId).catch(() => undefined);
|
||||
}
|
||||
finishAddingProject();
|
||||
},
|
||||
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, state.projects],
|
||||
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
|
||||
);
|
||||
|
||||
const handleAddProject = () => {
|
||||
@@ -476,34 +495,94 @@ export default function Sidebar() {
|
||||
const api = readNativeApi();
|
||||
if (!api || isPickingFolder) return;
|
||||
setIsPickingFolder(true);
|
||||
let pickedPath: string | null = null;
|
||||
try {
|
||||
const pickedPath = await api.dialogs.pickFolder();
|
||||
if (!pickedPath) return;
|
||||
await addProjectFromPath(pickedPath);
|
||||
} finally {
|
||||
setIsPickingFolder(false);
|
||||
pickedPath = await api.dialogs.pickFolder();
|
||||
} catch {
|
||||
// Ignore picker failures and leave the current thread selection unchanged.
|
||||
}
|
||||
if (pickedPath) {
|
||||
await addProjectFromPath(pickedPath);
|
||||
}
|
||||
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" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
],
|
||||
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") {
|
||||
dispatch({ type: "MARK_THREAD_UNREAD", threadId });
|
||||
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(
|
||||
[
|
||||
@@ -515,8 +594,8 @@ export default function Sidebar() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const threadProject = state.projects.find((project) => project.id === thread.projectId);
|
||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
|
||||
const threadProject = projects.find((project) => project.id === thread.projectId);
|
||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
|
||||
const displayWorktreePath = orphanedWorktreePath
|
||||
? formatWorktreePathForDisplay(orphanedWorktreePath)
|
||||
: null;
|
||||
@@ -553,7 +632,7 @@ export default function Sidebar() {
|
||||
}
|
||||
|
||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||
const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.delete",
|
||||
commandId: newCommandId(),
|
||||
@@ -561,6 +640,7 @@ export default function Sidebar() {
|
||||
});
|
||||
clearComposerDraftForThread(threadId);
|
||||
clearProjectDraftThreadById(thread.projectId, thread.id);
|
||||
clearTerminalState(threadId);
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
void navigate({
|
||||
@@ -602,12 +682,13 @@ export default function Sidebar() {
|
||||
appSettings.confirmThreadDelete,
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadById,
|
||||
dispatch,
|
||||
clearTerminalState,
|
||||
markThreadUnread,
|
||||
navigate,
|
||||
projects,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
state.projects,
|
||||
state.threads,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -615,13 +696,16 @@ 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" }], position);
|
||||
const clicked = await api.contextMenu.show(
|
||||
[{ id: "delete", label: "Delete", destructive: true }],
|
||||
position,
|
||||
);
|
||||
if (clicked !== "delete") return;
|
||||
|
||||
const project = state.projects.find((entry) => entry.id === projectId);
|
||||
const project = projects.find((entry) => entry.id === projectId);
|
||||
if (!project) return;
|
||||
|
||||
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
|
||||
const projectThreads = threads.filter((thread) => thread.projectId === projectId);
|
||||
if (projectThreads.length > 0) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
@@ -661,20 +745,20 @@ export default function Sidebar() {
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThreadByProjectId,
|
||||
state.projects,
|
||||
state.threads,
|
||||
projects,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
const activeThread = routeThreadId
|
||||
? state.threads.find((thread) => thread.id === routeThreadId)
|
||||
? threads.find((thread) => thread.id === routeThreadId)
|
||||
: undefined;
|
||||
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
|
||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
||||
const projectId =
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
void handleNewThread(projectId);
|
||||
@@ -683,15 +767,13 @@ export default function Sidebar() {
|
||||
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
const projectId =
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
void handleNewThread(projectId, {
|
||||
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
|
||||
envMode:
|
||||
activeDraftThread?.envMode ??
|
||||
(activeThread?.worktreePath ? "worktree" : "local"),
|
||||
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -699,26 +781,26 @@ export default function Sidebar() {
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
};
|
||||
}, [getDraftThread, handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
||||
}, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
|
||||
|
||||
const onCreateThreadClick = () => {
|
||||
if (state.projects.length === 0) {
|
||||
if (projects.length === 0) {
|
||||
setAddingProject(true);
|
||||
return;
|
||||
}
|
||||
const firstProject = state.projects[0];
|
||||
const firstProject = projects[0];
|
||||
if (firstProject) void handleNewThread(firstProject.id);
|
||||
};
|
||||
|
||||
const wordmark = (
|
||||
<div className={`flex items-center gap-2 ${isElectron ? "-translate-y-px" : ""}`}>
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="shrink-0 md:hidden" />
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
|
||||
<T3Wordmark />
|
||||
<span className="truncate text-base font-medium tracking-tight text-muted-foreground">
|
||||
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
|
||||
Code
|
||||
</span>
|
||||
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
|
||||
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
|
||||
{APP_STAGE_LABEL}
|
||||
</span>
|
||||
</div>
|
||||
@@ -740,10 +822,10 @@ export default function Sidebar() {
|
||||
<>
|
||||
{isElectron ? (
|
||||
<>
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[88px]">
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
|
||||
{wordmark}
|
||||
</SidebarHeader>
|
||||
<div className="px-4 pb-2">{newThreadButton}</div>
|
||||
<div className="px-4 py-2">{newThreadButton}</div>
|
||||
</>
|
||||
) : (
|
||||
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
|
||||
@@ -755,8 +837,8 @@ export default function Sidebar() {
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 py-2">
|
||||
<SidebarMenu>
|
||||
{state.projects.map((project) => {
|
||||
const visibleThreads = state.threads
|
||||
{projects.map((project) => {
|
||||
const visibleThreads = threads
|
||||
.filter((thread) => thread.projectId === project.id)
|
||||
.toSorted((a, b) => {
|
||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
@@ -771,7 +853,7 @@ export default function Sidebar() {
|
||||
open={project.expanded}
|
||||
onOpenChange={(open) => {
|
||||
if (open === project.expanded) return;
|
||||
dispatch({ type: "TOGGLE_PROJECT", projectId: project.id });
|
||||
toggleProject(project.id);
|
||||
}}
|
||||
>
|
||||
<SidebarMenuItem>
|
||||
@@ -813,7 +895,10 @@ export default function Sidebar() {
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
|
||||
const terminalStatus = terminalStatusIndicator(thread);
|
||||
const terminalStatus = terminalStatusFromRunningIds(
|
||||
selectThreadTerminalState(terminalStateByThreadId, thread.id)
|
||||
.runningTerminalIds,
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarMenuSubItem key={thread.id} className="w-full">
|
||||
@@ -821,7 +906,7 @@ export default function Sidebar() {
|
||||
render={<div role="button" tabIndex={0} />}
|
||||
size="sm"
|
||||
isActive={isActive}
|
||||
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
|
||||
className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
|
||||
isActive
|
||||
? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
|
||||
: "text-muted-foreground"
|
||||
@@ -880,9 +965,42 @@ export default function Sidebar() {
|
||||
<span className="hidden md:inline">{threadStatus.label}</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-xs">
|
||||
{thread.title}
|
||||
</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>
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{terminalStatus && (
|
||||
@@ -931,7 +1049,7 @@ export default function Sidebar() {
|
||||
})}
|
||||
</SidebarMenu>
|
||||
|
||||
{state.projects.length === 0 && !addingProject && (
|
||||
{projects.length === 0 && !addingProject && (
|
||||
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
|
||||
No projects yet.
|
||||
<br />
|
||||
|
||||
@@ -389,6 +389,9 @@ 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,10 +20,9 @@ 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={React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple])}
|
||||
>
|
||||
<ComboboxContext.Provider value={value}>
|
||||
<ComboboxPrimitive.Root {...props} />
|
||||
</ComboboxContext.Provider>
|
||||
);
|
||||
|
||||
@@ -22,6 +22,7 @@ function ToggleGroup({
|
||||
children,
|
||||
...props
|
||||
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const value = React.useMemo(() => ({ size, variant }), [size, variant]);
|
||||
return (
|
||||
<ToggleGroupPrimitive
|
||||
className={cn(
|
||||
@@ -42,11 +43,7 @@ function ToggleGroup({
|
||||
orientation={orientation}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider
|
||||
value={React.useMemo(() => ({ size, variant }), [size, variant])}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
<ToggleGroupContext.Provider value={value}>{children}</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
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" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
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,6 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
|
||||
import {
|
||||
detectComposerTrigger,
|
||||
expandCollapsedComposerCursor,
|
||||
replaceTextRange,
|
||||
} from "./composer-logic";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
@@ -49,3 +53,27 @@ 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,3 +1,5 @@
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
|
||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
||||
|
||||
export interface ComposerTrigger {
|
||||
@@ -24,6 +26,38 @@ 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,7 +28,6 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
|
||||
|
||||
interface PersistedComposerThreadDraftState {
|
||||
prompt: string;
|
||||
cursor: number;
|
||||
attachments: PersistedComposerImageAttachment[];
|
||||
model?: string | null;
|
||||
effort?: ReasoningEffort | null;
|
||||
@@ -50,7 +49,6 @@ interface PersistedComposerDraftStoreState {
|
||||
|
||||
interface ComposerThreadDraftState {
|
||||
prompt: string;
|
||||
cursor: number;
|
||||
images: ComposerImageAttachment[];
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
@@ -100,7 +98,6 @@ 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;
|
||||
@@ -129,7 +126,6 @@ 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,
|
||||
@@ -142,7 +138,6 @@ const REASONING_EFFORT_VALUES = new Set<ReasoningEffort>(REASONING_OPTIONS);
|
||||
function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
return {
|
||||
prompt: "",
|
||||
cursor: 0,
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
@@ -304,10 +299,6 @@ 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);
|
||||
@@ -327,7 +318,6 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
}
|
||||
nextDraftsByThreadId[threadId as ThreadId] = {
|
||||
prompt,
|
||||
cursor,
|
||||
attachments,
|
||||
...(model ? { model } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
@@ -429,7 +419,6 @@ function toHydratedThreadDraft(
|
||||
): ComposerThreadDraftState {
|
||||
return {
|
||||
prompt: persistedDraft.prompt,
|
||||
cursor: persistedDraft.cursor,
|
||||
images: hydrateImagesFromPersisted(persistedDraft.attachments),
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: persistedDraft.attachments,
|
||||
@@ -672,36 +661,9 @@ 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)) {
|
||||
@@ -939,7 +901,6 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
prompt: "",
|
||||
cursor: 0,
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
@@ -1009,7 +970,6 @@ 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,10 +1,12 @@
|
||||
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 { id: T; label: string }[],
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
position?: { x: number; y: number },
|
||||
): Promise<T | null> {
|
||||
return new Promise<T | null>((resolve) => {
|
||||
@@ -41,8 +43,8 @@ export function showContextMenuFallback<T extends string>(
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.textContent = item.label;
|
||||
const isDeleteAction = item.id === "delete";
|
||||
btn.className = isDeleteAction
|
||||
const isDestructiveAction = item.destructive === true || item.id === "delete";
|
||||
btn.className = isDestructiveAction
|
||||
? "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));
|
||||
|
||||
@@ -15,6 +15,7 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
@@ -123,13 +124,18 @@ function errorDetails(error: unknown): string {
|
||||
}
|
||||
|
||||
function EventRouter() {
|
||||
const { dispatch } = useStore();
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
|
||||
const removeOrphanedTerminalStates = useTerminalStateStore(
|
||||
(store) => store.removeOrphanedTerminalStates,
|
||||
);
|
||||
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(() => {
|
||||
@@ -144,7 +150,13 @@ function EventRouter() {
|
||||
const snapshot = await api.orchestration.getSnapshot();
|
||||
if (disposed) return;
|
||||
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
|
||||
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
|
||||
syncServerReadModel(snapshot);
|
||||
const activeThreadIds = new Set(
|
||||
snapshot.threads
|
||||
.filter((t) => t.deletedAt === null)
|
||||
.map((t) => t.id),
|
||||
);
|
||||
removeOrphanedTerminalStates(activeThreadIds);
|
||||
if (pending) {
|
||||
pending = false;
|
||||
await flushSnapshotSync();
|
||||
@@ -157,14 +169,13 @@ 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);
|
||||
@@ -184,12 +195,11 @@ function EventRouter() {
|
||||
if (hasRunningSubprocess === null) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe(event.threadId),
|
||||
terminalId: event.terminalId,
|
||||
useTerminalStateStore.getState().setTerminalActivity(
|
||||
ThreadId.makeUnsafe(event.threadId),
|
||||
event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
});
|
||||
);
|
||||
});
|
||||
const unsubWelcome = onServerWelcome((payload) => {
|
||||
void (async () => {
|
||||
@@ -201,11 +211,7 @@ function EventRouter() {
|
||||
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_PROJECT_EXPANDED",
|
||||
projectId: payload.bootstrapProjectId,
|
||||
expanded: true,
|
||||
});
|
||||
setProjectExpanded(payload.bootstrapProjectId, true);
|
||||
|
||||
if (pathnameRef.current !== "/") {
|
||||
return;
|
||||
@@ -270,7 +276,7 @@ function EventRouter() {
|
||||
unsubWelcome();
|
||||
unsubServerConfigUpdated();
|
||||
};
|
||||
}, [dispatch, navigate, queryClient]);
|
||||
}, [navigate, queryClient, removeOrphanedTerminalStates, setProjectExpanded, syncServerReadModel]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -133,13 +133,13 @@ const DiffPanelInlineSidebar = (props: {
|
||||
};
|
||||
|
||||
function ChatThreadRouteView() {
|
||||
const { state } = useStore();
|
||||
const threadsHydrated = useStore((store) => store.threadsHydrated);
|
||||
const navigate = useNavigate();
|
||||
const threadId = Route.useParams({
|
||||
select: (params) => ThreadId.makeUnsafe(params.threadId),
|
||||
});
|
||||
const search = Route.useSearch();
|
||||
const threadExists = state.threads.some((thread) => thread.id === threadId);
|
||||
const threadExists = useStore((store) => store.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 (!state.threadsHydrated) {
|
||||
if (!threadsHydrated) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -175,9 +175,9 @@ function ChatThreadRouteView() {
|
||||
void navigate({ to: "/", replace: true });
|
||||
return;
|
||||
}
|
||||
}, [navigate, routeThreadExists, state.threadsHydrated, threadId]);
|
||||
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
|
||||
|
||||
if (!state.threadsHydrated || !routeThreadExists) {
|
||||
if (!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 threadId={threadId} />
|
||||
<ChatView key={threadId} 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 threadId={threadId} />
|
||||
<ChatView key={threadId} threadId={threadId} />
|
||||
</SidebarInset>
|
||||
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
<Suspense fallback={<DiffLoadingFallback inline={false} />}>
|
||||
|
||||
@@ -48,7 +48,8 @@ const RUNTIME_MODE_OPTIONS = [
|
||||
|
||||
function SettingsRouteView() {
|
||||
const { theme, setTheme, resolvedTheme } = useTheme();
|
||||
const { state, dispatch } = useStore();
|
||||
const runtimeMode = useStore((store) => store.runtimeMode);
|
||||
const setRuntimeMode = useStore((store) => store.setRuntimeMode);
|
||||
const { settings, defaults, updateSettings } = useAppSettings();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
@@ -186,9 +187,10 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<label className="block space-y-1">
|
||||
<label htmlFor="codex-binary-path" 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"
|
||||
@@ -199,9 +201,10 @@ function SettingsRouteView() {
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label className="block space-y-1">
|
||||
<label htmlFor="codex-home-path" 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"
|
||||
@@ -242,16 +245,11 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<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">
|
||||
<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">
|
||||
<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);
|
||||
@@ -259,6 +257,11 @@ function SettingsRouteView() {
|
||||
setCustomModelError(null);
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
addCustomModel();
|
||||
}}
|
||||
placeholder="your-model-slug"
|
||||
spellCheck={false}
|
||||
/>
|
||||
@@ -267,10 +270,10 @@ function SettingsRouteView() {
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<Button className="sm:mt-6" type="submit">
|
||||
<Button className="sm:mt-6" type="button" onClick={addCustomModel}>
|
||||
Add model
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{customModelError ? (
|
||||
<p className="text-xs text-destructive">{customModelError}</p>
|
||||
@@ -333,7 +336,7 @@ function SettingsRouteView() {
|
||||
|
||||
<div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
|
||||
{RUNTIME_MODE_OPTIONS.map((option) => {
|
||||
const selected = state.runtimeMode === option.value;
|
||||
const selected = runtimeMode === option.value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
@@ -346,10 +349,7 @@ function SettingsRouteView() {
|
||||
: "border-border bg-background text-muted-foreground hover:bg-accent"
|
||||
}`}
|
||||
onClick={() => {
|
||||
dispatch({
|
||||
type: "SET_RUNTIME_MODE",
|
||||
mode: option.value,
|
||||
});
|
||||
setRuntimeMode(option.value);
|
||||
}}
|
||||
>
|
||||
<span className="flex flex-col">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { reducer, type AppState } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
|
||||
import { markThreadUnread, type AppState } from "./store";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
@@ -11,18 +11,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
turnDiffSummaries: [],
|
||||
@@ -54,8 +42,8 @@ function makeState(thread: Thread): AppState {
|
||||
};
|
||||
}
|
||||
|
||||
describe("store reducer", () => {
|
||||
it("marks a completed thread as unread by moving lastVisitedAt before completion", () => {
|
||||
describe("store pure functions", () => {
|
||||
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
|
||||
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
@@ -71,10 +59,7 @@ describe("store reducer", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(initialState, {
|
||||
type: "MARK_THREAD_UNREAD",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
|
||||
|
||||
const updatedThread = next.threads[0];
|
||||
expect(updatedThread).toBeDefined();
|
||||
@@ -84,7 +69,7 @@ describe("store reducer", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("does not change a thread without a completed turn", () => {
|
||||
it("markThreadUnread does not change a thread without a completed turn", () => {
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
latestTurn: null,
|
||||
@@ -92,70 +77,8 @@ describe("store reducer", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(initialState, {
|
||||
type: "MARK_THREAD_UNREAD",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
|
||||
|
||||
expect(next).toEqual(initialState);
|
||||
});
|
||||
});
|
||||
|
||||
describe("store terminal activity reducer", () => {
|
||||
it("adds a terminal to runningTerminalIds when subprocess activity starts", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "alt",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["alt"]);
|
||||
});
|
||||
|
||||
it("removes a terminal from runningTerminalIds when subprocess activity stops", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
},
|
||||
],
|
||||
runningTerminalIds: ["alt"],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "alt",
|
||||
hasRunningSubprocess: false,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores activity events for unknown terminal ids", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "missing",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
+214
-627
@@ -1,13 +1,4 @@
|
||||
import {
|
||||
type Dispatch,
|
||||
type ReactNode,
|
||||
createContext,
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import { Fragment, type ReactNode, createElement, useEffect } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
ProviderSessionId,
|
||||
@@ -16,48 +7,15 @@ import {
|
||||
type OrchestrationSessionStatus,
|
||||
resolveModelSlug,
|
||||
} from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ChatMessage,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
|
||||
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
|
||||
| { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
|
||||
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
|
||||
| {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY";
|
||||
threadId: ThreadId;
|
||||
terminalId: string;
|
||||
hasRunningSubprocess: boolean;
|
||||
}
|
||||
| { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
|
||||
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
|
||||
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
|
||||
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
|
||||
| { type: "SPLIT_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "NEW_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "CLOSE_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "SET_ERROR"; threadId: ThreadId; error: string | null }
|
||||
| {
|
||||
type: "SET_THREAD_BRANCH";
|
||||
threadId: ThreadId;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}
|
||||
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AppState {
|
||||
@@ -87,11 +45,10 @@ const initialState: AppState = {
|
||||
};
|
||||
const persistedExpandedProjectCwds = new Set<string>();
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
// ── Persist helpers ──────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
if (!raw) return initialState;
|
||||
@@ -119,7 +76,6 @@ function readPersistedState(): AppState {
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
PERSISTED_STATE_KEY,
|
||||
@@ -138,12 +94,21 @@ function persistState(state: AppState): void {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Pure helpers ──────────────────────────────────────────────────────
|
||||
|
||||
function updateThread(
|
||||
threads: Thread[],
|
||||
threadId: ThreadId,
|
||||
updater: (t: Thread) => Thread,
|
||||
): Thread[] {
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
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;
|
||||
}
|
||||
|
||||
function mapProjectsFromReadModel(
|
||||
@@ -193,9 +158,7 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
if (typeof window === "undefined") {
|
||||
return "";
|
||||
}
|
||||
if (typeof window === "undefined") return "";
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
@@ -204,10 +167,7 @@ function resolveWsHttpOrigin(): string {
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
if (!wsCandidate) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
if (!wsCandidate) return window.location.origin;
|
||||
try {
|
||||
const wsUrl = new URL(wsCandidate);
|
||||
const protocol =
|
||||
@@ -233,594 +193,221 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
|
||||
return `/attachments/${encodeURIComponent(attachmentId)}`;
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
if (unique.length > 0) {
|
||||
return unique;
|
||||
}
|
||||
return [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
// ── Pure state transition functions ────────────────────────────────────
|
||||
|
||||
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 normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
|
||||
if (!usedGroupIds.has(groupId)) {
|
||||
usedGroupIds.add(groupId);
|
||||
return groupId;
|
||||
}
|
||||
let suffix = 2;
|
||||
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
const uniqueGroupId = `${groupId}-${suffix}`;
|
||||
usedGroupIds.add(uniqueGroupId);
|
||||
return uniqueGroupId;
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
const groups: ThreadTerminalGroup[] = [];
|
||||
|
||||
for (const group of thread.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);
|
||||
groups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
groups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (groups.length > 0) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function findGroupIndexByTerminalId(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalId: string,
|
||||
): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
function normalizeThreadTerminals(thread: Thread): Thread {
|
||||
const terminalIds = normalizeTerminalIds(thread.terminalIds);
|
||||
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
|
||||
? thread.activeTerminalId
|
||||
: (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
|
||||
const activeGroupIndexFromId = terminalGroups.findIndex(
|
||||
(group) => group.id === thread.activeTerminalGroupId,
|
||||
export function syncServerReadModel(
|
||||
state: AppState,
|
||||
readModel: OrchestrationReadModel,
|
||||
): AppState {
|
||||
const projects = mapProjectsFromReadModel(
|
||||
readModel.projects.filter((project) => project.deletedAt === null),
|
||||
state.projects,
|
||||
);
|
||||
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
|
||||
const activeGroupIndex =
|
||||
activeGroupIndexFromId >= 0
|
||||
? activeGroupIndexFromId
|
||||
: activeGroupIndexFromTerminal >= 0
|
||||
? activeGroupIndexFromTerminal
|
||||
: 0;
|
||||
const activeTerminalGroupId =
|
||||
terminalGroups[activeGroupIndex]?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(activeTerminalId);
|
||||
|
||||
const existingThreadById = new Map(
|
||||
state.threads.map((thread) => [thread.id, thread] as const),
|
||||
);
|
||||
const threads = readModel.threads
|
||||
.filter((thread) => thread.deletedAt === null)
|
||||
.map((thread) => {
|
||||
const existing = existingThreadById.get(thread.id);
|
||||
return {
|
||||
id: thread.id,
|
||||
codexThreadId: thread.session?.providerThreadId ?? null,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(thread.model),
|
||||
session: thread.session
|
||||
? {
|
||||
sessionId:
|
||||
thread.session.providerSessionId ??
|
||||
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
|
||||
provider: toLegacyProvider(thread.session.providerName),
|
||||
status: toLegacySessionStatus(thread.session.status),
|
||||
orchestrationStatus: thread.session.status,
|
||||
threadId: thread.session.providerThreadId,
|
||||
activeTurnId: thread.session.activeTurnId ?? undefined,
|
||||
createdAt: thread.session.updatedAt,
|
||||
updatedAt: thread.session.updatedAt,
|
||||
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
|
||||
}
|
||||
: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const attachments = message.attachments?.map((attachment) => ({
|
||||
type: "image" as const,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
|
||||
}));
|
||||
const normalizedMessage: ChatMessage = {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
...(message.streaming ? {} : { completedAt: message.updatedAt }),
|
||||
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
||||
};
|
||||
return normalizedMessage;
|
||||
}),
|
||||
error: thread.session?.lastError ?? null,
|
||||
createdAt: thread.createdAt,
|
||||
latestTurn: thread.latestTurn,
|
||||
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
|
||||
turnId: checkpoint.turnId,
|
||||
completedAt: checkpoint.completedAt,
|
||||
status: checkpoint.status,
|
||||
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
|
||||
checkpointTurnCount: checkpoint.checkpointTurnCount,
|
||||
checkpointRef: checkpoint.checkpointRef,
|
||||
files: checkpoint.files.map((file) => ({ ...file })),
|
||||
})),
|
||||
activities: thread.activities.map((activity) => ({ ...activity })),
|
||||
};
|
||||
});
|
||||
return {
|
||||
...thread,
|
||||
terminalIds,
|
||||
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId,
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
threadsHydrated: true,
|
||||
};
|
||||
}
|
||||
|
||||
function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
if (!thread.terminalIds.includes(terminalId)) {
|
||||
return thread;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalOpen: false,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: nextTerminalGroupId,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: nextTerminalGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
|
||||
const closedTerminalGroup = thread.terminalGroups.find((group) =>
|
||||
group.terminalIds.includes(terminalId),
|
||||
);
|
||||
const closedTerminalGroupIndex = closedTerminalGroup
|
||||
? closedTerminalGroup.terminalIds.indexOf(terminalId)
|
||||
: -1;
|
||||
const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
|
||||
(id) => id !== terminalId,
|
||||
);
|
||||
const nextActiveTerminalId =
|
||||
thread.activeTerminalId === terminalId
|
||||
? (remainingTerminalsInClosedGroup[
|
||||
Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
|
||||
] ??
|
||||
remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: thread.activeTerminalId;
|
||||
const nextTerminalGroups = thread.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups: nextTerminalGroups,
|
||||
export function markThreadVisited(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
visitedAt?: string,
|
||||
): 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 };
|
||||
}
|
||||
|
||||
function setThreadTerminalActivity(
|
||||
thread: Thread,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
): Thread {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
if (!normalizedThread.terminalIds.includes(terminalId)) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
|
||||
if (hasRunningSubprocess) {
|
||||
runningTerminalIds.add(terminalId);
|
||||
} else {
|
||||
runningTerminalIds.delete(terminalId);
|
||||
}
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
runningTerminalIds: [...runningTerminalIds],
|
||||
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 };
|
||||
}
|
||||
|
||||
// ── Reducer ──────────────────────────────────────────────────────────
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "SYNC_SERVER_READ_MODEL": {
|
||||
const projects = mapProjectsFromReadModel(
|
||||
action.readModel.projects.filter((project) => project.deletedAt === null),
|
||||
state.projects,
|
||||
);
|
||||
const existingThreadById = new Map(
|
||||
state.threads.map((thread) => [thread.id, thread] as const),
|
||||
);
|
||||
const threads = action.readModel.threads
|
||||
.filter((thread) => thread.deletedAt === null)
|
||||
.map((thread) => {
|
||||
const existing = existingThreadById.get(thread.id);
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
id: thread.id,
|
||||
codexThreadId: thread.session?.providerThreadId ?? null,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(thread.model),
|
||||
terminalOpen: existing?.terminalOpen ?? false,
|
||||
terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: existing?.runningTerminalIds ?? [],
|
||||
activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: existing?.terminalGroups ?? [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId:
|
||||
existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: thread.session
|
||||
? {
|
||||
sessionId:
|
||||
thread.session.providerSessionId ??
|
||||
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
|
||||
provider: toLegacyProvider(thread.session.providerName),
|
||||
status: toLegacySessionStatus(thread.session.status),
|
||||
orchestrationStatus: thread.session.status,
|
||||
threadId: thread.session.providerThreadId,
|
||||
activeTurnId: thread.session.activeTurnId ?? undefined,
|
||||
createdAt: thread.session.updatedAt,
|
||||
updatedAt: thread.session.updatedAt,
|
||||
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
|
||||
}
|
||||
: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const attachments = message.attachments?.map((attachment) => ({
|
||||
type: "image" as const,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
|
||||
}));
|
||||
const normalizedMessage: ChatMessage = {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
...(message.streaming ? {} : { completedAt: message.updatedAt }),
|
||||
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
||||
};
|
||||
return normalizedMessage;
|
||||
}),
|
||||
error: thread.session?.lastError ?? null,
|
||||
createdAt: thread.createdAt,
|
||||
latestTurn: thread.latestTurn,
|
||||
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
|
||||
turnId: checkpoint.turnId,
|
||||
completedAt: checkpoint.completedAt,
|
||||
status: checkpoint.status,
|
||||
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
|
||||
checkpointTurnCount: checkpoint.checkpointTurnCount,
|
||||
checkpointRef: checkpoint.checkpointRef,
|
||||
files: checkpoint.files.map((file) => ({ ...file })),
|
||||
})),
|
||||
activities: thread.activities.map((activity) => ({ ...activity })),
|
||||
});
|
||||
});
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
threadsHydrated: true,
|
||||
};
|
||||
}
|
||||
|
||||
case "MARK_THREAD_VISITED": {
|
||||
const visitedAt = action.visitedAt ?? new Date().toISOString();
|
||||
const visitedAtMs = Date.parse(visitedAt);
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.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: visitedAt,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "MARK_THREAD_UNREAD": {
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.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,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "TOGGLE_PROJECT":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_ACTIVITY":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) =>
|
||||
setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_PROJECT_EXPANDED":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
|
||||
),
|
||||
};
|
||||
|
||||
case "TOGGLE_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
terminalOpen: !t.terminalOpen,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_OPEN":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
terminalOpen: action.open,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_HEIGHT":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
terminalHeight: action.height,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SPLIT_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
|
||||
...group,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
let activeGroupIndex = terminalGroups.findIndex(
|
||||
(group) => group.id === normalizedThread.activeTerminalGroupId,
|
||||
);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(
|
||||
terminalGroups,
|
||||
normalizedThread.activeTerminalId,
|
||||
);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
terminalGroups.push({
|
||||
id: fallbackGroupId(normalizedThread.activeTerminalId),
|
||||
terminalIds: [normalizedThread.activeTerminalId],
|
||||
});
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
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 (existingGroupIndex < activeGroupIndex) {
|
||||
activeGroupIndex -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalizedThread;
|
||||
}
|
||||
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(
|
||||
normalizedThread.activeTerminalId,
|
||||
);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(action.terminalId);
|
||||
}
|
||||
}
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
terminalGroups,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "NEW_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
const terminalGroups = normalizedThread.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
const nextGroupId = fallbackGroupId(action.terminalId);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
terminalGroups,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_ACTIVE_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
if (!normalizedThread.terminalIds.includes(action.terminalId)) {
|
||||
return thread;
|
||||
}
|
||||
const nextActiveGroupIndex = findGroupIndexByTerminalId(
|
||||
normalizedThread.terminalGroups,
|
||||
action.terminalId,
|
||||
);
|
||||
const activeTerminalGroupId =
|
||||
nextActiveGroupIndex >= 0
|
||||
? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
|
||||
normalizedThread.activeTerminalGroupId)
|
||||
: normalizedThread.activeTerminalGroupId;
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "CLOSE_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) =>
|
||||
closeThreadTerminal(thread, action.terminalId),
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_ERROR":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
error: action.error,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_BRANCH": {
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
||||
// When the effective cwd changes (worktreePath differs), the old
|
||||
// session is no longer valid — clear it so ensureSession creates a
|
||||
// new one with the correct cwd on the next message.
|
||||
const cwdChanged = t.worktreePath !== action.worktreePath;
|
||||
return {
|
||||
...t,
|
||||
branch: action.branch,
|
||||
worktreePath: action.worktreePath,
|
||||
...(cwdChanged ? { session: null } : {}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "SET_RUNTIME_MODE":
|
||||
return {
|
||||
...state,
|
||||
runtimeMode: action.mode,
|
||||
};
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === projectId ? { ...p, expanded: !p.expanded } : p,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Context ──────────────────────────────────────────────────────────
|
||||
export function setProjectExpanded(
|
||||
state: AppState,
|
||||
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;
|
||||
}
|
||||
|
||||
const StoreContext = createContext<{
|
||||
state: AppState;
|
||||
dispatch: Dispatch<Action>;
|
||||
}>({ state: initialState, dispatch: () => {} });
|
||||
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 };
|
||||
}
|
||||
|
||||
export function setThreadBranch(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
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 };
|
||||
}
|
||||
|
||||
export function setRuntimeMode(state: AppState, mode: RuntimeMode): AppState {
|
||||
if (state.runtimeMode === mode) return state;
|
||||
return { ...state, runtimeMode: mode };
|
||||
}
|
||||
|
||||
// ── Zustand store ────────────────────────────────────────────────────
|
||||
|
||||
interface AppStore extends AppState {
|
||||
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
|
||||
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
|
||||
markThreadUnread: (threadId: ThreadId) => void;
|
||||
toggleProject: (projectId: Project["id"]) => void;
|
||||
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
|
||||
setError: (threadId: ThreadId, error: string | null) => void;
|
||||
setThreadBranch: (
|
||||
threadId: ThreadId,
|
||||
branch: string | null,
|
||||
worktreePath: string | null,
|
||||
) => void;
|
||||
setRuntimeMode: (mode: RuntimeMode) => void;
|
||||
}
|
||||
|
||||
export const useStore = create<AppStore>((set) => ({
|
||||
...readPersistedState(),
|
||||
syncServerReadModel: (readModel) =>
|
||||
set((state) => syncServerReadModel(state, readModel)),
|
||||
markThreadVisited: (threadId, visitedAt) =>
|
||||
set((state) => markThreadVisited(state, threadId, visitedAt)),
|
||||
markThreadUnread: (threadId) =>
|
||||
set((state) => markThreadUnread(state, threadId)),
|
||||
toggleProject: (projectId) =>
|
||||
set((state) => toggleProject(state, projectId)),
|
||||
setProjectExpanded: (projectId, expanded) =>
|
||||
set((state) => setProjectExpanded(state, projectId, expanded)),
|
||||
setError: (threadId, error) =>
|
||||
set((state) => setError(state, threadId, error)),
|
||||
setThreadBranch: (threadId, branch, worktreePath) =>
|
||||
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
|
||||
setRuntimeMode: (mode) =>
|
||||
set((state) => setRuntimeMode(state, mode)),
|
||||
}));
|
||||
|
||||
// Persist on every state change (only runtimeMode + expandedProjectCwds)
|
||||
useStore.subscribe((state) => persistState(state));
|
||||
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
|
||||
|
||||
useEffect(() => {
|
||||
persistState(state);
|
||||
}, [state]);
|
||||
|
||||
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
|
||||
}
|
||||
|
||||
export function useStore() {
|
||||
return useContext(StoreContext);
|
||||
persistState(useStore.getState());
|
||||
}, []);
|
||||
return createElement(Fragment, null, children);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
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"] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,532 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
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";
|
||||
|
||||
interface ThreadTerminalState {
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
}
|
||||
|
||||
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>,
|
||||
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,
|
||||
): Record<ThreadId, ThreadTerminalState> {
|
||||
if (threadId.length === 0) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
|
||||
const current = selectThreadTerminalState(terminalStateByThreadId, threadId);
|
||||
const next = updater(current);
|
||||
if (next === current) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
|
||||
if (isDefaultThreadTerminalState(next)) {
|
||||
if (terminalStateByThreadId[threadId] === undefined) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
const { [threadId]: _removed, ...rest } = terminalStateByThreadId;
|
||||
return rest as Record<ThreadId, ThreadTerminalState>;
|
||||
}
|
||||
|
||||
return {
|
||||
...terminalStateByThreadId,
|
||||
[threadId]: next,
|
||||
};
|
||||
}
|
||||
|
||||
interface TerminalStateStoreState {
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>;
|
||||
setTerminalOpen: (threadId: ThreadId, open: boolean) => void;
|
||||
setTerminalHeight: (threadId: ThreadId, height: number) => void;
|
||||
splitTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
newTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
setActiveTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
closeTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
setTerminalActivity: (
|
||||
threadId: ThreadId,
|
||||
terminalId: string,
|
||||
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(
|
||||
state.terminalStateByThreadId,
|
||||
threadId,
|
||||
updater,
|
||||
);
|
||||
if (nextTerminalStateByThreadId === state.terminalStateByThreadId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
terminalStateByThreadId: nextTerminalStateByThreadId,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
terminalStateByThreadId: {},
|
||||
setTerminalOpen: (threadId, open) =>
|
||||
updateTerminal(threadId, (state) => setThreadTerminalOpen(state, open)),
|
||||
setTerminalHeight: (threadId, height) =>
|
||||
updateTerminal(threadId, (state) => setThreadTerminalHeight(state, height)),
|
||||
splitTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => splitThreadTerminal(state, terminalId)),
|
||||
newTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => newThreadTerminal(state, terminalId)),
|
||||
setActiveTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => setThreadActiveTerminal(state, terminalId)),
|
||||
closeTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => closeThreadTerminal(state, terminalId)),
|
||||
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
|
||||
updateTerminal(threadId, (state) =>
|
||||
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
|
||||
),
|
||||
clearTerminalState: (threadId) =>
|
||||
updateTerminal(threadId, () => createDefaultThreadTerminalState()),
|
||||
removeOrphanedTerminalStates: (activeThreadIds) =>
|
||||
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];
|
||||
}
|
||||
return { terminalStateByThreadId: next };
|
||||
}),
|
||||
};
|
||||
},
|
||||
{
|
||||
name: TERMINAL_STATE_STORAGE_KEY,
|
||||
version: 1,
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
partialize: (state) => ({
|
||||
terminalStateByThreadId: state.terminalStateByThreadId,
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -79,13 +79,6 @@ export interface Thread {
|
||||
projectId: ProjectId;
|
||||
title: string;
|
||||
model: string;
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
session: ThreadSession | null;
|
||||
messages: ChatMessage[];
|
||||
error: string | null;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
|
||||
import type { Thread } from "./types";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
@@ -11,18 +11,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
turnDiffSummaries: [],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
CommandId,
|
||||
type ContextMenuItem,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProjectId,
|
||||
@@ -9,6 +10,12 @@ 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) => {
|
||||
@@ -33,6 +40,10 @@ vi.mock("./wsTransport", () => {
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./contextMenuFallback", () => ({
|
||||
showContextMenuFallback: showContextMenuFallbackMock,
|
||||
}));
|
||||
|
||||
function emitPush(channel: string, data: unknown): void {
|
||||
const listeners = channelListeners.get(channel);
|
||||
if (!listeners) return;
|
||||
@@ -41,11 +52,23 @@ 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(() => {
|
||||
@@ -307,4 +330,51 @@ 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,6 +2,7 @@ import {
|
||||
OrchestrationEvent,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ContextMenuItem,
|
||||
type NativeApi,
|
||||
ServerConfigUpdatedPayload,
|
||||
TerminalEvent,
|
||||
@@ -171,11 +172,11 @@ export function createWsNativeApi(): NativeApi {
|
||||
},
|
||||
contextMenu: {
|
||||
show: async <T extends string>(
|
||||
items: readonly { id: T; label: string }[],
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
position?: { x: number; y: number },
|
||||
): Promise<T | null> => {
|
||||
if (window.desktopBridge) {
|
||||
return window.desktopBridge.showContextMenu(items) as Promise<T | null>;
|
||||
return window.desktopBridge.showContextMenu(items, position) as Promise<T | null>;
|
||||
}
|
||||
return showContextMenuFallback(items, position);
|
||||
},
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"dependencies": {
|
||||
"electron": "40.6.0",
|
||||
},
|
||||
@@ -32,7 +32,7 @@
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.1.0",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
@@ -60,9 +60,10 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0",
|
||||
"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",
|
||||
@@ -73,6 +74,7 @@
|
||||
"@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",
|
||||
@@ -96,7 +98,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
@@ -238,6 +240,8 @@
|
||||
|
||||
"@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=="],
|
||||
@@ -276,6 +280,50 @@
|
||||
|
||||
"@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=="],
|
||||
@@ -380,6 +428,8 @@
|
||||
|
||||
"@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=="],
|
||||
@@ -922,6 +972,8 @@
|
||||
|
||||
"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=="],
|
||||
@@ -942,6 +994,10 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1154,6 +1210,8 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1172,6 +1230,8 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1414,6 +1474,8 @@
|
||||
|
||||
"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=="],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
|
||||
@@ -37,12 +37,18 @@ 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 { id: T; label: string }[],
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
position?: { x: number; y: number },
|
||||
) => Promise<T | null>;
|
||||
openExternal: (url: string) => Promise<boolean>;
|
||||
@@ -85,7 +91,7 @@ export interface NativeApi {
|
||||
};
|
||||
contextMenu: {
|
||||
show: <T extends string>(
|
||||
items: readonly { id: T; label: string }[],
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
position?: { x: number; y: number },
|
||||
) => Promise<T | null>;
|
||||
};
|
||||
|
||||
@@ -99,6 +99,7 @@ interface ResolvedBuildOptions {
|
||||
interface StagePackageJson {
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
readonly buildVersion: string;
|
||||
readonly private: true;
|
||||
readonly description: string;
|
||||
readonly author: string;
|
||||
@@ -488,6 +489,7 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
|
||||
const stagePackageJson: StagePackageJson = {
|
||||
name: "t3-code-desktop",
|
||||
version: appVersion,
|
||||
buildVersion: appVersion,
|
||||
private: true,
|
||||
description: "T3 Code desktop build",
|
||||
author: "T3 Tools",
|
||||
|
||||
+165
-14
@@ -1,4 +1,5 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import net from "node:net";
|
||||
import { homedir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
@@ -6,6 +7,7 @@ import { pathToFileURL } from "node:url";
|
||||
const BASE_SERVER_PORT = 3773;
|
||||
const BASE_WEB_PORT = 5733;
|
||||
const MAX_HASH_OFFSET = 3000;
|
||||
const MAX_PORT = 65535;
|
||||
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
|
||||
const MODE_ARGS = {
|
||||
dev: [
|
||||
@@ -209,7 +211,133 @@ export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
|
||||
return output;
|
||||
}
|
||||
|
||||
export function runDevRunner(argv = process.argv) {
|
||||
function portPairForOffset(offset) {
|
||||
return {
|
||||
serverPort: BASE_SERVER_PORT + offset,
|
||||
webPort: BASE_WEB_PORT + offset,
|
||||
};
|
||||
}
|
||||
|
||||
async function canListenOnHost(port, host) {
|
||||
return await new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
server.unref();
|
||||
server.once("error", (error) => {
|
||||
const code = error?.code;
|
||||
if (code === "EADDRNOTAVAIL") {
|
||||
// Host family unavailable on this machine (for example, no IPv6 loopback).
|
||||
resolve(true);
|
||||
return;
|
||||
}
|
||||
resolve(false);
|
||||
});
|
||||
server.once("listening", () => {
|
||||
server.close(() => {
|
||||
resolve(true);
|
||||
});
|
||||
});
|
||||
server.listen({ host, port });
|
||||
});
|
||||
}
|
||||
|
||||
async function isPortAvailable(port) {
|
||||
// Vite/dev traffic uses localhost loopback. Verify both IPv4 and IPv6 loopback
|
||||
// so we don't pick a port that fails later on one address family.
|
||||
const [ipv4, ipv6] = await Promise.all([
|
||||
canListenOnHost(port, "127.0.0.1"),
|
||||
canListenOnHost(port, "::1"),
|
||||
]);
|
||||
return ipv4 && ipv6;
|
||||
}
|
||||
|
||||
const defaultCheckPortAvailability = isPortAvailable;
|
||||
|
||||
export async function findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort,
|
||||
requireWebPort,
|
||||
checkPortAvailability = defaultCheckPortAvailability,
|
||||
}) {
|
||||
for (let candidate = startOffset; ; candidate += 1) {
|
||||
const { serverPort, webPort } = portPairForOffset(candidate);
|
||||
const serverPortOutOfRange = serverPort > MAX_PORT;
|
||||
const webPortOutOfRange = webPort > MAX_PORT;
|
||||
if (
|
||||
(requireServerPort && serverPortOutOfRange) ||
|
||||
(requireWebPort && webPortOutOfRange) ||
|
||||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
|
||||
const checks = [];
|
||||
if (requireServerPort) {
|
||||
checks.push(checkPortAvailability(serverPort));
|
||||
}
|
||||
if (requireWebPort) {
|
||||
checks.push(checkPortAvailability(webPort));
|
||||
}
|
||||
|
||||
if (checks.length === 0) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
const availability = await Promise.all(checks);
|
||||
if (availability.every(Boolean)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function resolveModePortOffsets({
|
||||
mode,
|
||||
startOffset,
|
||||
envOverrides,
|
||||
checkPortAvailability,
|
||||
}) {
|
||||
const hasExplicitServerPort = typeof envOverrides.T3CODE_PORT === "string";
|
||||
const hasExplicitDevUrl = typeof envOverrides.VITE_DEV_SERVER_URL === "string";
|
||||
|
||||
if (mode === "dev:web") {
|
||||
if (hasExplicitDevUrl) {
|
||||
return { serverOffset: startOffset, webOffset: startOffset };
|
||||
}
|
||||
const webOffset = await findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort: false,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability,
|
||||
});
|
||||
return { serverOffset: startOffset, webOffset };
|
||||
}
|
||||
|
||||
if (mode === "dev:server") {
|
||||
if (hasExplicitServerPort) {
|
||||
return { serverOffset: startOffset, webOffset: startOffset };
|
||||
}
|
||||
const serverOffset = await findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort: true,
|
||||
requireWebPort: false,
|
||||
checkPortAvailability,
|
||||
});
|
||||
return { serverOffset, webOffset: serverOffset };
|
||||
}
|
||||
|
||||
const sharedOffset = await findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort: !hasExplicitServerPort,
|
||||
requireWebPort: !hasExplicitDevUrl,
|
||||
checkPortAvailability,
|
||||
});
|
||||
return { serverOffset: sharedOffset, webOffset: sharedOffset };
|
||||
}
|
||||
|
||||
export async function runDevRunner(argv = process.argv) {
|
||||
const mode = argv[2];
|
||||
const parsedArgs = parseDevRunnerArgs(argv.slice(3));
|
||||
if (!mode || !(mode in MODE_ARGS)) {
|
||||
@@ -218,24 +346,49 @@ export function runDevRunner(argv = process.argv) {
|
||||
}
|
||||
|
||||
const { offset, source } = resolveOffset();
|
||||
const serverPort = BASE_SERVER_PORT + offset;
|
||||
const webPort = BASE_WEB_PORT + offset;
|
||||
const { serverOffset, webOffset } = await resolveModePortOffsets({
|
||||
mode,
|
||||
startOffset: offset,
|
||||
envOverrides: parsedArgs.envOverrides,
|
||||
});
|
||||
|
||||
if (serverPort > 65535 || webPort > 65535) {
|
||||
throw new Error(
|
||||
`Port offset too large (${offset}). Computed ports: server=${serverPort}, web=${webPort}`,
|
||||
);
|
||||
const mergedEnvOverrides = { ...parsedArgs.envOverrides };
|
||||
if (!("VITE_DEV_SERVER_URL" in mergedEnvOverrides)) {
|
||||
const { webPort } = portPairForOffset(webOffset);
|
||||
mergedEnvOverrides.PORT = String(webPort);
|
||||
mergedEnvOverrides.ELECTRON_RENDERER_PORT = String(webPort);
|
||||
mergedEnvOverrides.VITE_DEV_SERVER_URL = `http://localhost:${webPort}`;
|
||||
}
|
||||
|
||||
const env = createDevRunnerEnv({
|
||||
mode,
|
||||
env: process.env,
|
||||
offset,
|
||||
envOverrides: parsedArgs.envOverrides,
|
||||
offset: serverOffset,
|
||||
envOverrides: mergedEnvOverrides,
|
||||
});
|
||||
|
||||
const parsedServerPort = Number(env.T3CODE_PORT);
|
||||
const parsedWebPort = Number(env.PORT);
|
||||
if (
|
||||
!Number.isInteger(parsedServerPort) ||
|
||||
parsedServerPort < 1 ||
|
||||
parsedServerPort > MAX_PORT ||
|
||||
!Number.isInteger(parsedWebPort) ||
|
||||
parsedWebPort < 1 ||
|
||||
parsedWebPort > MAX_PORT
|
||||
) {
|
||||
throw new Error(
|
||||
`Invalid computed dev ports: server='${String(env.T3CODE_PORT)}' web='${String(env.PORT)}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
const selectionSuffix =
|
||||
serverOffset !== offset || webOffset !== offset
|
||||
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
|
||||
: "";
|
||||
|
||||
console.info(
|
||||
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort} stateDir=${env.T3CODE_STATE_DIR}`,
|
||||
`[dev-runner] mode=${mode} source=${source}${selectionSuffix} serverPort=${parsedServerPort} webPort=${parsedWebPort} stateDir=${env.T3CODE_STATE_DIR}`,
|
||||
);
|
||||
|
||||
if (parsedArgs.isDryRun) {
|
||||
@@ -265,10 +418,8 @@ export function runDevRunner(argv = process.argv) {
|
||||
const entrypointPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
|
||||
|
||||
if (import.meta.url === entrypointPath) {
|
||||
try {
|
||||
runDevRunner();
|
||||
} catch (error) {
|
||||
runDevRunner().catch((error) => {
|
||||
console.error("[dev-runner]", error);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_DEV_STATE_DIR,
|
||||
createDevRunnerEnv,
|
||||
findFirstAvailableOffset,
|
||||
parseDevRunnerArgs,
|
||||
resolveModePortOffsets,
|
||||
} from "./dev-runner.mjs";
|
||||
|
||||
describe("parseDevRunnerArgs", () => {
|
||||
@@ -123,3 +125,99 @@ describe("createDevRunnerEnv", () => {
|
||||
).toThrow("Invalid T3CODE_PORT override");
|
||||
});
|
||||
});
|
||||
|
||||
describe("findFirstAvailableOffset", () => {
|
||||
it("returns the starting offset when required ports are available", async () => {
|
||||
const offset = await findFirstAvailableOffset({
|
||||
startOffset: 0,
|
||||
requireServerPort: true,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability: async () => true,
|
||||
});
|
||||
|
||||
expect(offset).toBe(0);
|
||||
});
|
||||
|
||||
it("advances until all required ports are available", async () => {
|
||||
const taken = new Set([3773, 5733, 3774, 5734]);
|
||||
const offset = await findFirstAvailableOffset({
|
||||
startOffset: 0,
|
||||
requireServerPort: true,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability: async (port) => !taken.has(port),
|
||||
});
|
||||
|
||||
expect(offset).toBe(2);
|
||||
});
|
||||
|
||||
it("allows offsets where only non-required ports exceed max", async () => {
|
||||
const offset = await findFirstAvailableOffset({
|
||||
startOffset: 59_803,
|
||||
requireServerPort: true,
|
||||
requireWebPort: false,
|
||||
checkPortAvailability: async () => true,
|
||||
});
|
||||
|
||||
expect(offset).toBe(59_803);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveModePortOffsets", () => {
|
||||
it("uses a shared fallback offset for dev mode", async () => {
|
||||
const taken = new Set([3773, 5733]);
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev",
|
||||
startOffset: 0,
|
||||
envOverrides: {},
|
||||
checkPortAvailability: async (port) => !taken.has(port),
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
|
||||
});
|
||||
|
||||
it("keeps server offset stable for dev:web and only shifts web offset", async () => {
|
||||
const taken = new Set([5733]);
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev:web",
|
||||
startOffset: 0,
|
||||
envOverrides: {},
|
||||
checkPortAvailability: async (port) => !taken.has(port),
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 0, webOffset: 1 });
|
||||
});
|
||||
|
||||
it("shifts only server offset for dev:server", async () => {
|
||||
const taken = new Set([3773]);
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev:server",
|
||||
startOffset: 0,
|
||||
envOverrides: {},
|
||||
checkPortAvailability: async (port) => !taken.has(port),
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
|
||||
});
|
||||
|
||||
it("respects explicit dev-url override for dev:web", async () => {
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev:web",
|
||||
startOffset: 0,
|
||||
envOverrides: { VITE_DEV_SERVER_URL: "http://localhost:9999" },
|
||||
checkPortAvailability: async () => false,
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
|
||||
});
|
||||
|
||||
it("respects explicit server port override for dev:server", async () => {
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev:server",
|
||||
startOffset: 0,
|
||||
envOverrides: { T3CODE_PORT: "4888" },
|
||||
checkPortAvailability: async () => false,
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user