agent-console 1.0.0: a page plugin that drives the local Agent CLIs (#535)
Adds Agent Console (@magpie-community/page-agent-console 1.0.0), a community page plugin that drives the Agent CLIs on this computer (Claude Code, Codex, ACP agents) through a local daemon on 127.0.0.1, with its source in packages/agent-console and a registry entry. Claude Code is the user's own `claude` CLI driven over stream-json (daemon/src/providers/claude/cli.ts); no Anthropic SDK is installed, bundled or in the branch's history. Cold install ~45 MB (node-pty ~26 MB), stated in the README and registry summary in en and zh. By qingnian108 (#535). What was run at 8e8f910 (mote, macOS, throwaway HOME, no real accounts): - packages/agent-console: `npm ci --ignore-scripts --workspaces=false`; `node scripts/verify-build.mjs`: all five bundles byte-identical (daemon/dist/main.js 08c95aa3…, app/app.js 9a6911f3…); `vitest run`: 45 files, 254 passed, 17 skipped; `npm run check` clean. - Real Claude Code 2.1.316 (npm @anthropic-ai/claude-code, sandbox HOME/CLAUDE_CONFIG_DIR, local fake Messages API): `AC_REAL_CLAUDE=… vitest run --config vitest.real.config.ts test/real/claude-cli.real.test.ts`: 4 of 4 (initialize lists 51 slash commands, streaming turn, Bash permission approved and denied, interrupt, --resume with set_model). - Probe: the driver's exact argv with `--permission-mode bypassPermissions --allow-dangerously-skip-permissions`: the tool runs with no can_use_tool request. - Repo root: `HOME=$(mktemp -d) bun test`: 4006 tests, 0 fail; `bun scripts/check.mjs` exit 0. - Install as magpie does: `npm pack --ignore-scripts` (552 KB) then `bun add --ignore-scripts`: 45 MB node_modules, no @anthropic-ai/*, index.mjs imports. - Read every changed line since 41c7a94: argv values limited to SAFE_ARG tokens (no cmd.exe metacharacters reach the shim path), no new network hosts, no install scripts, no eval; no commit in main..8e8f910 contains claude-agent-sdk. Not tried: magpie's desktop window loading the page; a Windows .cmd/.ps1 claude shim end to end.
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
// Conversation area (§8.6): virtual list, stick-to-bottom, empty state, queue list, Composer.
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { isImeComposing } from "../composer/ime";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { useData, pickDefaultProvider } from "../stores/data";
|
||||
import { useTimeline } from "../stores/timeline";
|
||||
import { TimelineRow } from "./Timeline";
|
||||
import { Composer } from "./Composer";
|
||||
import { Icon } from "./Icons";
|
||||
import { ws } from "../main";
|
||||
import { toast } from "./Toast";
|
||||
import { useLiveSettings } from "./Settings";
|
||||
import { errMsg, localizeDaemonMessage, t as tr, tf } from "../i18n/index.js";
|
||||
|
||||
export function Chat() {
|
||||
const ui = useUi();
|
||||
const { projects, threads } = useData();
|
||||
const tl = useTimeline();
|
||||
const prefs = useLiveSettings();
|
||||
const items = prefs.showThinking ? tl.items : tl.items.filter((it) => it.kind !== "reasoning");
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [stick, setStick] = useState(true);
|
||||
const [hasNew, setHasNew] = useState(false);
|
||||
|
||||
const project = projects.find((p) => p.id === ui.currentProjectId) ?? null;
|
||||
const threadId = ui.currentThreadId;
|
||||
const thread = threadId ? threads.find((th) => th.id === threadId) ?? null : null;
|
||||
const activeThreadId =
|
||||
project && thread && thread.projectId === project.id ? thread.id : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (activeThreadId) tl.open(activeThreadId);
|
||||
else tl.close();
|
||||
setStick(true);
|
||||
setHasNew(false);
|
||||
}, [activeThreadId]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const est = useCallback((i: number) => {
|
||||
const it = items[i];
|
||||
if (!it) return 80;
|
||||
switch (it.kind) {
|
||||
case "user": return 60;
|
||||
case "assistant": case "reasoning": return 120;
|
||||
case "toolgroup": return 30 + it.steps.length * 26;
|
||||
case "plan": return 200;
|
||||
case "permission": case "question": return 120;
|
||||
case "todo": return 30;
|
||||
case "turnend": case "notice": return 30;
|
||||
default: return 60;
|
||||
}
|
||||
}, [items]);
|
||||
|
||||
const virt = useVirtualizer({
|
||||
count: items.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: est,
|
||||
getItemKey: (i) => items[i]?.key ?? i,
|
||||
overscan: 8,
|
||||
measureElement: (el) => el.getBoundingClientRect().height,
|
||||
});
|
||||
|
||||
const count = items.length;
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
if (stick) el.scrollTop = el.scrollHeight;
|
||||
else setHasNew(true);
|
||||
}, [count, stick]);
|
||||
|
||||
const onScroll = () => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 60;
|
||||
setStick(nearBottom);
|
||||
if (nearBottom) setHasNew(false);
|
||||
};
|
||||
|
||||
const jump = () => {
|
||||
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
|
||||
setStick(true);
|
||||
setHasNew(false);
|
||||
};
|
||||
|
||||
const resend = (text: string) => {
|
||||
if (!activeThreadId) return;
|
||||
void ws.call("thread.send", { id: activeThreadId, text });
|
||||
};
|
||||
const retryLast = () => {
|
||||
if (tl.lastUserText) resend(tl.lastUserText);
|
||||
};
|
||||
|
||||
if (projects.length === 0) {
|
||||
return (
|
||||
<div className="scroll" ref={scrollRef}>
|
||||
<WorkspaceEmpty kind="no-projects" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!activeThreadId) {
|
||||
return (
|
||||
<div className="scroll" ref={scrollRef}>
|
||||
<div className="empty-wrap">
|
||||
{project ? (
|
||||
<>
|
||||
<div className="cp-hero-t">{tf("chat.newInProject", { name: project.name })}</div>
|
||||
<EmptyComposer projectId={project.id} />
|
||||
</>
|
||||
) : (
|
||||
<WorkspaceEmpty kind="no-projects" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="scroll" ref={scrollRef} onScroll={onScroll}>
|
||||
<div className="tl-wrap">
|
||||
<div style={{ height: virt.getTotalSize(), position: "relative" }}>
|
||||
{virt.getVirtualItems().map((v) => {
|
||||
const it = items[v.index];
|
||||
if (!it) return null;
|
||||
return (
|
||||
<div
|
||||
key={v.key}
|
||||
data-index={v.index}
|
||||
ref={virt.measureElement}
|
||||
style={{ position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${v.start}px)` }}
|
||||
>
|
||||
<TimelineRow it={it} threadId={activeThreadId} onEditResend={resend} onRetryLast={retryLast} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{tl.items.length === 0 && !tl.error && (
|
||||
<div className="sb-empty">{tr("chat.emptyHint")}</div>
|
||||
)}
|
||||
{tl.error && <div className="nt error">{localizeDaemonMessage(tl.error)}</div>}
|
||||
</div>
|
||||
</div>
|
||||
{!stick && (
|
||||
<button className="jump" onClick={jump} title={tr("chat.jumpBottom")}>
|
||||
<Icon name="caret" />
|
||||
{hasNew && <span className="jd" />}
|
||||
</button>
|
||||
)}
|
||||
<Composer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** No project / nothing selected: centered onboarding matching the sidebar's empty state, no Composer at the bottom */
|
||||
function WorkspaceEmpty({ kind }: { kind: "no-projects" }) {
|
||||
void kind;
|
||||
return (
|
||||
<div className="empty-wrap workspace-empty">
|
||||
<div className="cp-hero-t">{tr("sidebar.noProjectsTitle")}</div>
|
||||
<div className="cp-hero-s">{tr("sidebar.noProjectsSub")}</div>
|
||||
<div className="empty-actions">
|
||||
<button type="button" className="btn primary" onClick={() => window.dispatchEvent(new CustomEvent("open-new-project"))}>
|
||||
{tr("sidebar.newProject")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyComposer({ projectId }: { projectId: string }) {
|
||||
const ui = useUi();
|
||||
const prefs = useLiveSettings();
|
||||
const [text, setText] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const send = async () => {
|
||||
if (!text.trim() || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const provider = await pickDefaultProvider();
|
||||
const s = (await ws.call("settings.get")) as { defaultMode?: string; defaultEffort?: string | null };
|
||||
const created = (await ws.call("threads.create", {
|
||||
projectId, provider, model: null,
|
||||
mode: s.defaultMode ?? "default", effort: s.defaultEffort ?? null,
|
||||
})) as { id: string };
|
||||
ui.select(projectId, created.id);
|
||||
await ws.call("thread.send", { id: created.id, text: text.trim() });
|
||||
} catch (e) {
|
||||
toast(tr("chat.failSend") + errMsg(e), true);
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="cp-card" style={{ marginTop: 18 }}>
|
||||
<textarea
|
||||
className="cp-ta"
|
||||
rows={3}
|
||||
placeholder={tr("chat.emptyPlaceholder")}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (isImeComposing(e.nativeEvent)) return;
|
||||
const ctrl = e.ctrlKey || e.metaKey;
|
||||
const sendCombo = prefs.sendKey === "ctrlEnter"
|
||||
? e.key === "Enter" && ctrl
|
||||
: e.key === "Enter" && !e.shiftKey && !ctrl;
|
||||
if (sendCombo) {
|
||||
e.preventDefault();
|
||||
void send();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="cp-bar">
|
||||
<span className="dlg-hint">{tr("chat.autoNewThread")}</span>
|
||||
<div className="cp-right">
|
||||
<button className="cp-send" disabled={!text.trim() || busy} onClick={() => void send()} title={tr("common.send")}>
|
||||
<Icon name="send" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Command palette (§8.6 Ctrl+K): filter projects/conversations/actions, ↑↓ to select, Enter to run.
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { isImeComposing } from "../composer/ime";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useData, pickDefaultProvider } from "../stores/data";
|
||||
import { useUi, type PanelTab } from "../stores/ui";
|
||||
import { ws } from "../main";
|
||||
import type { Project } from "../types/models";
|
||||
import { toast } from "./Toast";
|
||||
import { errMsg, t } from "../i18n/index.js";
|
||||
|
||||
type Cmd = { id: string; label: string; hint?: string; run: () => void };
|
||||
|
||||
export function CommandPalette({ onClose }: { onClose: () => void }) {
|
||||
const { projects, threads, providers } = useData();
|
||||
const ui = useUi();
|
||||
const [q, setQ] = useState("");
|
||||
const [idx, setIdx] = useState(0);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => { inputRef.current?.focus(); }, []);
|
||||
|
||||
const items = useMemo<Cmd[]>(() => {
|
||||
const out: Cmd[] = [];
|
||||
const ql = q.trim().toLowerCase();
|
||||
const match = (s: string) => !ql || s.toLowerCase().includes(ql);
|
||||
|
||||
const acts: [string, () => void][] = [
|
||||
[t("palette.actNewThread"), () => { const p = ui.currentProjectId ?? projects[0]?.id; if (p) void newThread(p); }],
|
||||
[t("palette.actSettings"), () => window.dispatchEvent(new CustomEvent("open-settings"))],
|
||||
[t("palette.actTheme"), () => void cycleTheme()],
|
||||
[t("palette.actChanges"), () => ui.openPanel("changes" as PanelTab)],
|
||||
[t("palette.actFiles"), () => ui.openPanel("files" as PanelTab)],
|
||||
[t("palette.actTerminal"), () => ui.openPanel("terminal" as PanelTab)],
|
||||
[t("palette.actImport"), () => {
|
||||
const p = ui.currentProjectId ?? projects[0]?.id;
|
||||
if (p) window.dispatchEvent(new CustomEvent("open-import", { detail: { projectId: p } }));
|
||||
}],
|
||||
];
|
||||
for (const [label, run] of acts) if (match(label)) out.push({ id: `act:${label}`, label, hint: t("palette.hintAction"), run });
|
||||
|
||||
for (const p of projects) {
|
||||
if (match(p.name)) out.push({ id: `p:${p.id}`, label: p.name, hint: t("palette.hintProject"), run: () => ui.select(p.id, null) });
|
||||
}
|
||||
for (const t0 of threads) {
|
||||
const proj = projects.find((p) => p.id === t0.projectId);
|
||||
const hay = `${t0.title} ${proj?.name ?? ""}`;
|
||||
if (match(hay)) out.push({ id: `t:${t0.id}`, label: t0.title, hint: proj?.name ?? t("palette.hintThread"), run: () => ui.select(t0.projectId, t0.id) });
|
||||
}
|
||||
return out.slice(0, 30);
|
||||
}, [q, projects, threads]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => { setIdx(0); }, [q]);
|
||||
|
||||
const onKey = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "ArrowDown") { e.preventDefault(); setIdx((i) => Math.min(items.length - 1, i + 1)); }
|
||||
else if (e.key === "ArrowUp") { e.preventDefault(); setIdx((i) => Math.max(0, i - 1)); }
|
||||
else if (e.key === "Enter" && !isImeComposing(e.nativeEvent)) { e.preventDefault(); const it = items[idx]; if (it) { onClose(); it.run(); } }
|
||||
else if (e.key === "Escape") { e.preventDefault(); onClose(); }
|
||||
};
|
||||
|
||||
async function newThread(projectId: string) {
|
||||
try {
|
||||
const s = (await ws.call("settings.get")) as { defaultProvider?: string; defaultMode?: string; defaultEffort?: string | null };
|
||||
const provider = await pickDefaultProvider();
|
||||
const th = (await ws.call("threads.create", { projectId, provider, mode: s.defaultMode ?? "default", effort: s.defaultEffort ?? null })) as { id: string };
|
||||
useUi.getState().select(projectId, th.id);
|
||||
} catch (e) { toast(t("palette.failNew") + errMsg(e), true); }
|
||||
}
|
||||
|
||||
return createPortal(
|
||||
<div className="dlg-scrim" style={{ alignItems: "flex-start", paddingTop: "14vh" }}
|
||||
onPointerDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div className="dlg cpal" role="dialog" aria-label={t("palette.aria")}>
|
||||
<input ref={inputRef} className="cpal-in" placeholder={t("palette.placeholder")}
|
||||
value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={onKey} />
|
||||
<div className="cpal-list">
|
||||
{items.map((it, i) => (
|
||||
<button key={it.id} className={`cpal-item${i === idx ? " on" : ""}`}
|
||||
onMouseEnter={() => setIdx(i)}
|
||||
onClick={() => { onClose(); it.run(); }}>
|
||||
<span className="cpal-label">{it.label}</span>
|
||||
{it.hint && <span className="cpal-hint">{it.hint}</span>}
|
||||
</button>
|
||||
))}
|
||||
{items.length === 0 && <div className="sb-empty">{t("palette.noMatch")}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
async function cycleTheme() {
|
||||
const cur = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
|
||||
document.documentElement.dataset.theme = cur;
|
||||
try { await ws.call("settings.set", { patch: { theme: cur } }); } catch {}
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
// Input area (§8.6 Composer): auto-grow, IME, queue/steer, waiting for permission, attachments,
|
||||
// Agent·model popover, thinking level, permission mode, ↑ to recall.
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { isImeComposing } from "../composer/ime";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { useData } from "../stores/data";
|
||||
import { useTimeline } from "../stores/timeline";
|
||||
import { ws } from "../main";
|
||||
import { getToken } from "../api/token";
|
||||
import { Icon } from "./Icons";
|
||||
import { attachmentUrl } from "./Timeline";
|
||||
import type { Mode, ModelInfo } from "../types/models";
|
||||
import type { SlashCommand } from "../composer/slashMenu";
|
||||
import { toast } from "./Toast";
|
||||
import { useLiveSettings } from "./Settings";
|
||||
import { permissionModes, composerModeOptions } from "../i18n/modes.js";
|
||||
import { errMsg, t as tr, tf } from "../i18n/index.js";
|
||||
import {
|
||||
applySlashPick,
|
||||
slashEnterSends,
|
||||
clampSlashIndex,
|
||||
filterSlashCommands,
|
||||
selectableSlashRows,
|
||||
slashMenuRows,
|
||||
slashMenuState,
|
||||
} from "../composer/slashMenu";
|
||||
|
||||
type Attachment = { path: string; name: string; mime: string; uploading?: boolean };
|
||||
|
||||
/** Maximum rows drawn in the model list at once (hundreds of buttons make the popover noticeably sluggish) */
|
||||
const MODEL_LIST_CAP = 150;
|
||||
|
||||
export function Composer() {
|
||||
const ui = useUi();
|
||||
const { threads, providers } = useData();
|
||||
const tl = useTimeline();
|
||||
const [text, setText] = useState("");
|
||||
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||
const [agentPop, setAgentPop] = useState(false);
|
||||
const [pickerProviderId, setPickerProviderId] = useState<string | null>(null);
|
||||
const [modelQ, setModelQ] = useState("");
|
||||
const pickerRef = useRef<HTMLDivElement>(null);
|
||||
const taRef = useRef<HTMLTextAreaElement>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [lastSent, setLastSent] = useState<string[]>([]);
|
||||
const [elapsed, setElapsed] = useState(0);
|
||||
const [slashSel, setSlashSel] = useState(0);
|
||||
const slashSuppress = useRef(false);
|
||||
const slashLoadThreads = useRef(new Set<string>());
|
||||
const [slashLoading, setSlashLoading] = useState(false);
|
||||
const prefs = useLiveSettings();
|
||||
|
||||
const thread = threads.find((t) => t.id === ui.currentThreadId);
|
||||
const provider = providers.find((p) => p.id === thread?.provider);
|
||||
const running = tl.status === "running" || tl.status === "initializing";
|
||||
const waiting = tl.pending.length > 0;
|
||||
const steerOk = provider?.capabilities.steer ?? false;
|
||||
// Known not to take images (an ACP Agent whose initialize doesn't advertise them): images still go, as file paths
|
||||
const imagesByPath = !!provider && !provider.capabilities.images && provider.capabilities.imagesKnown !== false;
|
||||
const mode = thread?.mode ?? "default";
|
||||
const modes = composerModeOptions(thread?.provider, provider?.capabilities.modes ?? [], provider?.capabilities.modeLabels);
|
||||
const modeMeta = modes.find((m) => m.id === mode);
|
||||
const started = tl.items.some((it) => it.kind === "user");
|
||||
|
||||
const slashMenu = useMemo(() => slashMenuState(text, slashSuppress.current), [text]);
|
||||
const slashFiltered = useMemo(
|
||||
() => filterSlashCommands(tl.slashCommands, slashMenu.query),
|
||||
[tl.slashCommands, slashMenu.query],
|
||||
);
|
||||
const slashRows = useMemo(() => slashMenuRows(slashFiltered), [slashFiltered]);
|
||||
const slashPickable = useMemo(() => selectableSlashRows(slashRows), [slashRows]);
|
||||
const slashOpen = slashMenu.open && !waiting;
|
||||
|
||||
useEffect(() => {
|
||||
setSlashSel(0);
|
||||
}, [slashMenu.query, slashOpen]);
|
||||
|
||||
// Only the first "/" typed fetches commands with load:true (opening a conversation doesn't start the Agent)
|
||||
useEffect(() => {
|
||||
const id = thread?.id;
|
||||
if (!slashOpen || !id) return;
|
||||
if (slashLoadThreads.current.has(id)) return;
|
||||
slashLoadThreads.current.add(id);
|
||||
// The first time we start the Agent and wait for its commands (seconds): meanwhile the menu shows "loading commands…" rather than "no commands"
|
||||
setSlashLoading(true);
|
||||
void ws.call("thread.commands", { id, load: true }, 30000).then((r) => {
|
||||
const commands = (r as { commands?: SlashCommand[] }).commands ?? [];
|
||||
// A background push (commands event) may already have arrived: don't overwrite it with an empty result
|
||||
if (commands.length || !useTimeline.getState().slashCommands.length) {
|
||||
useTimeline.setState({ slashCommands: commands });
|
||||
}
|
||||
}).catch(() => {}).finally(() => setSlashLoading(false));
|
||||
}, [slashOpen, thread?.id]);
|
||||
|
||||
const visibleProviders = useMemo(
|
||||
() => providers.filter((p) => p.enabled !== false || p.id === thread?.provider),
|
||||
[providers, thread?.provider],
|
||||
);
|
||||
|
||||
const pickerProvider = visibleProviders.find((p) => p.id === (pickerProviderId ?? thread?.provider));
|
||||
|
||||
const providerOk = (p: (typeof visibleProviders)[0]) =>
|
||||
p.enabled !== false && p.available && p.status !== "planned";
|
||||
|
||||
const openPicker = (open: boolean) => {
|
||||
setAgentPop(open);
|
||||
if (open) {
|
||||
setPickerProviderId(null);
|
||||
setModelQ("");
|
||||
}
|
||||
};
|
||||
|
||||
// Close on outside click / Esc (it used to close as soon as the pointer left, so a height change would "throw" the user out)
|
||||
useEffect(() => {
|
||||
if (!agentPop) return;
|
||||
const onDown = (e: PointerEvent) => {
|
||||
if (pickerRef.current && !pickerRef.current.contains(e.target as Node)) openPicker(false);
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") { e.stopPropagation(); openPicker(false); }
|
||||
};
|
||||
document.addEventListener("pointerdown", onDown, true);
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onDown, true);
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
};
|
||||
}, [agentPop]);
|
||||
|
||||
const pickModelForProvider = async (providerId: string, model: string | null) => {
|
||||
if (!thread) return;
|
||||
// Close the popover first; the switch happens in the background (no longer waits for detection/model fetching to respond)
|
||||
openPicker(false);
|
||||
try {
|
||||
if (!started && providerId !== thread.provider) {
|
||||
await ws.call("thread.setProvider", { id: thread.id, provider: providerId });
|
||||
}
|
||||
await ws.call("thread.setModel", { id: thread.id, model });
|
||||
} catch (e) {
|
||||
toast(tr("composer.failSwitchAgent") + errMsg(e), true);
|
||||
}
|
||||
};
|
||||
|
||||
const modelSearchHits = useMemo(() => {
|
||||
const q = modelQ.trim().toLowerCase();
|
||||
if (!q) return [] as { providerId: string; providerName: string; model: ModelInfo }[];
|
||||
const hits: { providerId: string; providerName: string; model: ModelInfo }[] = [];
|
||||
for (const p of visibleProviders) {
|
||||
if (!providerOk(p)) continue;
|
||||
for (const m of p.models ?? []) {
|
||||
if (m.name.toLowerCase().includes(q) || m.id.toLowerCase().includes(q)) {
|
||||
hits.push({ providerId: p.id, providerName: p.name, model: m });
|
||||
}
|
||||
}
|
||||
}
|
||||
return hits.slice(0, 100);
|
||||
}, [modelQ, visibleProviders]);
|
||||
|
||||
const inModelList = Boolean(pickerProviderId && !modelQ.trim());
|
||||
|
||||
// Timer
|
||||
useEffect(() => {
|
||||
if (!running) return;
|
||||
const t0 = Date.now();
|
||||
const t = setInterval(() => setElapsed(Math.floor((Date.now() - t0) / 1000)), 1000);
|
||||
return () => clearInterval(t);
|
||||
}, [running]);
|
||||
|
||||
// Auto-grow 1–12 lines
|
||||
useEffect(() => {
|
||||
const ta = taRef.current;
|
||||
if (!ta) return;
|
||||
ta.style.height = "auto";
|
||||
ta.style.height = Math.min(ta.scrollHeight, 12 * 22) + "px";
|
||||
}, [text]);
|
||||
|
||||
const send = useCallback(async (behavior: "queue" | "steer" = "queue") => {
|
||||
const id = ui.currentThreadId;
|
||||
const msg = text.trim();
|
||||
if (!id || (!msg && attachments.length === 0)) return;
|
||||
if (running && behavior === "queue") setLastSent((s) => [...s, msg]);
|
||||
setText("");
|
||||
try {
|
||||
await ws.call("thread.send", {
|
||||
id, text: msg,
|
||||
attachments: attachments.map((a) => ({ path: a.path, mime: a.mime, name: a.name })),
|
||||
behavior: running && behavior === "steer" && steerOk ? "steer" : "queue",
|
||||
});
|
||||
setAttachments([]);
|
||||
if (!running) setLastSent((s) => [...s.slice(-9), msg]);
|
||||
} catch (e) {
|
||||
setText(msg);
|
||||
toast(tr("composer.failSend") + errMsg(e), true);
|
||||
}
|
||||
}, [text, attachments, ui.currentThreadId, running, steerOk]);
|
||||
|
||||
const onKey = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (isImeComposing(e.nativeEvent)) return;
|
||||
|
||||
if (slashOpen && slashPickable.length > 0) {
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setSlashSel((i) => clampSlashIndex(i + 1, slashPickable.length));
|
||||
return;
|
||||
}
|
||||
if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setSlashSel((i) => clampSlashIndex(i - 1, slashPickable.length));
|
||||
return;
|
||||
}
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
slashSuppress.current = true;
|
||||
setSlashSel(0);
|
||||
return;
|
||||
}
|
||||
const pick = slashPickable[slashSel] ?? slashPickable[0];
|
||||
const enterSends = e.key === "Enter" && slashEnterSends(text, pick?.name);
|
||||
if (((e.key === "Enter" && !e.shiftKey) || e.key === "Tab") && !enterSends) {
|
||||
e.preventDefault();
|
||||
if (pick) {
|
||||
slashSuppress.current = false;
|
||||
setText(applySlashPick(pick.name));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const ctrl = e.ctrlKey || e.metaKey;
|
||||
const sendCombo = prefs.sendKey === "ctrlEnter"
|
||||
? e.key === "Enter" && ctrl
|
||||
: e.key === "Enter" && !e.shiftKey && !ctrl;
|
||||
if (sendCombo) {
|
||||
e.preventDefault();
|
||||
if (running && prefs.runningSend === "steer" && steerOk) void send("steer");
|
||||
else void send("queue");
|
||||
return;
|
||||
}
|
||||
// With Enter to send: Ctrl+Enter while running still steers (with the "steer" setting the branch above already steers)
|
||||
if (prefs.sendKey === "enter" && e.key === "Enter" && ctrl && running) {
|
||||
e.preventDefault();
|
||||
if (steerOk) void send("steer");
|
||||
else void send("queue");
|
||||
return;
|
||||
}
|
||||
if (e.key === "ArrowUp" && text === "" && lastSent.length > 0) {
|
||||
e.preventDefault();
|
||||
setText(lastSent[lastSent.length - 1]);
|
||||
}
|
||||
};
|
||||
|
||||
// Paste: image → upload; text >32KB → .txt attachment (§8.6)
|
||||
const onPaste = async (e: React.ClipboardEvent) => {
|
||||
const items = e.clipboardData?.items;
|
||||
if (!items) return;
|
||||
for (const it of items) {
|
||||
if (it.type.startsWith("image/")) {
|
||||
e.preventDefault();
|
||||
const f = it.getAsFile();
|
||||
if (f) await upload(f);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const t = e.clipboardData.getData("text/plain");
|
||||
if (t && t.length > 32 * 1024) {
|
||||
e.preventDefault();
|
||||
const f = new File([t], "paste.txt", { type: "text/plain" });
|
||||
await upload(f);
|
||||
}
|
||||
};
|
||||
|
||||
const upload = async (f: File) => {
|
||||
const token = getToken();
|
||||
const tmp: Attachment = { path: "", name: f.name, mime: f.type || "application/octet-stream", uploading: true };
|
||||
setAttachments((a) => [...a, tmp]);
|
||||
try {
|
||||
const res = await fetch(`/api/upload?name=${encodeURIComponent(f.name)}`, {
|
||||
method: "POST", headers: { "x-agent-console": token }, body: f,
|
||||
});
|
||||
const r = await res.json();
|
||||
if (!r.ok) throw new Error(r.e?.message ?? tr("composer.uploadFailed"));
|
||||
setAttachments((a) => a.map((x) => (x === tmp ? { ...x, path: r.id, name: r.name ?? f.name, uploading: false } : x)));
|
||||
} catch (e) {
|
||||
setAttachments((a) => a.filter((x) => x !== tmp));
|
||||
toast(tr("composer.failUpload") + errMsg(e), true);
|
||||
}
|
||||
};
|
||||
|
||||
const onDrop = async (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
for (const f of e.dataTransfer.files) {
|
||||
if (f.type.startsWith("image/") || f.type.startsWith("text/")) await upload(f);
|
||||
}
|
||||
};
|
||||
|
||||
const setMode = (m: Mode) => {
|
||||
if (thread) void ws.call("thread.setMode", { id: thread.id, mode: m });
|
||||
};
|
||||
const setEffort = (effort: string | null) => {
|
||||
if (thread) void ws.call("thread.setEffort", { id: thread.id, effort });
|
||||
};
|
||||
const setCursorOpts = (patch: { cursorFast?: boolean; cursorAutoReview?: boolean }) => {
|
||||
if (thread) void ws.call("thread.setCursorOpts", { id: thread.id, ...patch }).catch((e) => toast(errMsg(e), true));
|
||||
};
|
||||
|
||||
// With the default model: some Providers don't mark isDefault → fall back to the first one so the level dropdown appears
|
||||
const modelRow = thread?.model
|
||||
? provider?.models?.find((m) => m.id === thread.model)
|
||||
: provider?.models?.find((m) => m.isDefault) ?? provider?.models?.[0];
|
||||
// Defensive: an old daemon may pass Codex's { reasoningEffort, description } objects straight through, and rendering an object would blank the whole page
|
||||
const thinkingOpts = (modelRow?.thinkingOptions ?? [])
|
||||
.map((o) => {
|
||||
const raw = o as unknown as { id?: unknown; label?: unknown; reasoningEffort?: unknown };
|
||||
const id = typeof raw.id === "string" ? raw.id : typeof raw.reasoningEffort === "string" ? raw.reasoningEffort : null;
|
||||
const idObj = raw.id as { reasoningEffort?: unknown } | null;
|
||||
const fixedId = id ?? (idObj && typeof idObj.reasoningEffort === "string" ? idObj.reasoningEffort : null);
|
||||
return fixedId ? { id: fixedId, label: typeof raw.label === "string" ? raw.label : fixedId } : null;
|
||||
})
|
||||
.filter((o): o is { id: string; label: string } => o !== null);
|
||||
const defaultThinking = typeof modelRow?.defaultThinking === "string" ? modelRow.defaultThinking : null;
|
||||
const showThinking = thinkingOpts.length > 0;
|
||||
|
||||
const modelLabel = (() => {
|
||||
if (!thread?.model) {
|
||||
const d = provider?.models?.find((x) => x.isDefault);
|
||||
return d ? `${tr("composer.defaultModel")} · ${d.name}` : tr("composer.defaultModel");
|
||||
}
|
||||
const m = provider?.models?.find((x) => x.id === thread.model);
|
||||
let name = m?.name ?? thread.model;
|
||||
if (thread.cursorFast) name += " · Fast";
|
||||
return name;
|
||||
})();
|
||||
|
||||
if (!ui.currentThreadId) return null;
|
||||
|
||||
return (
|
||||
<div className={`composer${waiting ? " waiting" : ""}`} onDrop={onDrop} onDragOver={(e) => e.preventDefault()}>
|
||||
{/* queue list */}
|
||||
{tl.queue.length > 0 && (
|
||||
<div className="q-list">
|
||||
{tl.queue.map((q) => (
|
||||
<div key={q.id} className="q-item">
|
||||
<span className="q-text">{q.text}</span>
|
||||
<button className="ibtn" title={tr("common.remove")} onClick={() => void ws.call("thread.queueRemove", { id: thread?.id, queueId: q.id }).catch(() => {})}>
|
||||
<Icon name="x" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{mode === "bypassPermissions" && (
|
||||
<div className="cp-danger">{tr("composer.bypassWarn")}</div>
|
||||
)}
|
||||
<div className={`cp-card${waiting ? " waiting" : ""}${mode === "bypassPermissions" ? " danger" : ""}`}>
|
||||
{imagesByPath && attachments.some((a) => a.mime.startsWith("image/")) && (
|
||||
<div className="att-note">{tf("composer.imagesByPath", { agent: provider?.name ?? "" })}</div>
|
||||
)}
|
||||
{attachments.length > 0 && (
|
||||
<div className="att-bar">
|
||||
{attachments.map((a, i) => (
|
||||
<span key={i} className={`att${a.uploading ? " up" : ""}`}>
|
||||
{a.mime.startsWith("image/") && a.path
|
||||
? <img src={attachmentUrl(a.path)} alt={a.name} />
|
||||
: <Icon name="attach" size={12} />}
|
||||
<span className="att-name">{a.name}</span>
|
||||
{a.uploading && <span className="att-prog">…</span>}
|
||||
<button className="att-x" onClick={() => setAttachments((s) => s.filter((_, j) => j !== i))}>×</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="cp-ta-wrap">
|
||||
{slashOpen && (
|
||||
<div className="pop agent-picker slash-pop" role="listbox">
|
||||
<div className="ap-scroll">
|
||||
{slashRows.length === 0 ? (
|
||||
<div className="ap-empty">{tr(slashLoading ? "composer.slashLoading" : "composer.slashNoCommands")}</div>
|
||||
) : (
|
||||
slashRows.map((row) => {
|
||||
if (row.type === "heading") {
|
||||
return (
|
||||
<div key={row.id} className="slash-h">
|
||||
{row.labelKey === "slashGroupCommand"
|
||||
? tr("composer.slashGroupCommand")
|
||||
: tr("composer.slashGroupSkill")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const idx = slashPickable.indexOf(row.command);
|
||||
const sel = idx === slashSel;
|
||||
return (
|
||||
<button
|
||||
key={row.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={sel}
|
||||
className={`mi slash-item${sel ? " sel" : ""}`}
|
||||
onMouseDown={(ev) => ev.preventDefault()}
|
||||
onClick={() => {
|
||||
slashSuppress.current = false;
|
||||
setText(applySlashPick(row.command.name));
|
||||
}}
|
||||
>
|
||||
<span className="slash-name">/{row.command.name}</span>
|
||||
<span className="slash-desc">{row.command.description}</span>
|
||||
{row.command.argumentHint ? (
|
||||
<span className="slash-hint">{row.command.argumentHint}</span>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<textarea
|
||||
ref={taRef}
|
||||
className="cp-ta"
|
||||
rows={1}
|
||||
placeholder={waiting ? tr("composer.waitPerm") : running ? tr("composer.queuePlaceholder") : tr("composer.inputPlaceholder")}
|
||||
value={text}
|
||||
disabled={waiting}
|
||||
onChange={(e) => {
|
||||
slashSuppress.current = false;
|
||||
setText(e.target.value);
|
||||
}}
|
||||
onKeyDown={onKey}
|
||||
onPaste={onPaste}
|
||||
/>
|
||||
</div>
|
||||
<div className="cp-bar">
|
||||
{/* Agent·model pill */}
|
||||
<div className="pill-wrap" ref={pickerRef}>
|
||||
<button className="pill" onClick={() => openPicker(!agentPop)} title={tr("composer.agentModel")}>
|
||||
<span className="p-a">{provider?.name ?? thread?.provider ?? tr("composer.agent")}</span>
|
||||
<span className="p-t">{modelLabel}</span>
|
||||
</button>
|
||||
{agentPop && (
|
||||
<div className="pop agent-pop agent-picker">
|
||||
<div className="ap-search">
|
||||
<Icon name="search" size={14} />
|
||||
<input
|
||||
className="ap-search-in"
|
||||
autoFocus
|
||||
placeholder={tr("composer.searchAllModels")}
|
||||
value={modelQ}
|
||||
onChange={(e) => setModelQ(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{modelQ.trim() ? (
|
||||
<div className="ap-scroll">
|
||||
{modelSearchHits.length === 0 && (
|
||||
<div className="ap-empty">{tr("composer.noModelMatch")}</div>
|
||||
)}
|
||||
{modelSearchHits.map(({ providerId, providerName, model }) => {
|
||||
const locked = started && providerId !== thread?.provider;
|
||||
return (
|
||||
<button
|
||||
key={`${providerId}:${model.id}`}
|
||||
className="mi mi-row"
|
||||
disabled={locked}
|
||||
onClick={() => void pickModelForProvider(providerId, model.id)}
|
||||
>
|
||||
<span className="mi-sub">{providerName}</span>
|
||||
<span className="mi-name">{model.name}</span>
|
||||
{thread?.provider === providerId && thread?.model === model.id && (
|
||||
<span className="mi-check">✓</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : inModelList && pickerProvider ? (
|
||||
<div className="ap-scroll">
|
||||
<button
|
||||
type="button"
|
||||
className="ap-back mi"
|
||||
onClick={() => setPickerProviderId(null)}
|
||||
>
|
||||
<span className="ap-back-icon"><Icon name="caret" size={14} /></span>
|
||||
{pickerProvider.name}
|
||||
</button>
|
||||
<button
|
||||
className="mi model-pick-row"
|
||||
title={pickerProvider.models?.find((m) => m.isDefault)?.name ?? tr("composer.defaultModel")}
|
||||
onClick={() => void pickModelForProvider(pickerProvider.id, null)}
|
||||
>
|
||||
<span className="model-pick-name">{tr("composer.defaultModel")}</span>
|
||||
{/* which model the default really is (behind magpie = the model magpie applies to this Agent) */}
|
||||
{(() => {
|
||||
const d = pickerProvider.models?.find((m) => m.isDefault);
|
||||
return d ? <span className="mi-sub model-pick-default"> ({d.name})</span> : null;
|
||||
})()}
|
||||
{thread?.provider === pickerProvider.id && !thread?.model ? <span className="mi-check">✓</span> : ""}
|
||||
</button>
|
||||
{/* Devin/Cursor have hundreds of models: draw only the first MODEL_LIST_CAP, search for the rest */}
|
||||
{/* the default model already appears in the "Default (…)" row above, so it isn't listed again (Copilot used to show "Default (Auto)" + "Auto") */}
|
||||
{(pickerProvider.models ?? []).filter((m) => !m.isDefault).slice(0, MODEL_LIST_CAP).map((m) => (
|
||||
<button
|
||||
key={m.id}
|
||||
className="mi model-pick-row"
|
||||
title={m.name}
|
||||
onClick={() => void pickModelForProvider(pickerProvider.id, m.id)}
|
||||
>
|
||||
<span className="model-pick-name">{m.name}</span>
|
||||
{thread?.provider === pickerProvider.id && thread?.model === m.id
|
||||
? <span className="mi-check">✓</span>
|
||||
: ""}
|
||||
</button>
|
||||
))}
|
||||
{(pickerProvider.models?.length ?? 0) > MODEL_LIST_CAP && (
|
||||
<div className="ap-empty">
|
||||
{tf("composer.moreModels", { n: String((pickerProvider.models?.length ?? 0) - MODEL_LIST_CAP) })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="ap-scroll">
|
||||
<div className="mlabel">
|
||||
{started ? tr("composer.agentLocked") : tr("composer.providers")}
|
||||
</div>
|
||||
{started && <div className="ap-empty">{tr("composer.agentLockedHint")}</div>}
|
||||
{visibleProviders.length === 0 && <div className="ap-empty">{tr("composer.providersLoading")}</div>}
|
||||
{visibleProviders.map((p) => {
|
||||
const ok = providerOk(p);
|
||||
const canOpen = ok && (!started || p.id === thread?.provider);
|
||||
const n = p.models?.length ?? 0;
|
||||
const label = p.name?.trim() || p.id;
|
||||
return (
|
||||
<button
|
||||
key={p.id}
|
||||
className="mi mi-row provider-pick-row"
|
||||
disabled={!canOpen}
|
||||
onClick={() => {
|
||||
if (!canOpen) return;
|
||||
setPickerProviderId(p.id);
|
||||
}}
|
||||
>
|
||||
<span className="provider-pick-name">{label}</span>
|
||||
<span className="provider-pick-meta">
|
||||
{p.id === thread?.provider && <span className="mi-tag">Current</span>}
|
||||
{/* option labels in the picker are English throughout */}
|
||||
<span className="mi-meta">{n === 1 ? "1 model" : `${n} models`}</span>
|
||||
{canOpen && <span className="mi-caret"><Icon name="caret" size={14} /></span>}
|
||||
{p.enabled === false && <span className="dlg-hint">Disabled</span>}
|
||||
{p.enabled !== false && p.status === "planned" && <span className="dlg-hint">Not available</span>}
|
||||
{p.enabled !== false && p.status !== "planned" && !p.available && (
|
||||
<span className="dlg-hint">Not detected</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* thinking level */}
|
||||
{showThinking && (
|
||||
<select className="pill sel" value={thread?.effort ?? ""} title={tr("composer.effortTitle")}
|
||||
onChange={(e) => setEffort(e.target.value || null)}>
|
||||
<option value="">
|
||||
{defaultThinking
|
||||
? tf("composer.defaultEffortNamed", { level: defaultThinking })
|
||||
: tr("composer.defaultEffort")}
|
||||
</option>
|
||||
{thinkingOpts.map((e) => <option key={e.id} value={e.id}>{e.label}</option>)}
|
||||
</select>
|
||||
)}
|
||||
{/* permission mode: list only the modes this Agent really has; hidden when there is only one (e.g. Pi has no modes) */}
|
||||
{modes.length > 1 && (
|
||||
<select
|
||||
className={`pill sel${mode === "bypassPermissions" ? " danger" : ""}`}
|
||||
// The mode stored on the conversation doesn't exist for this Agent (e.g. the default setting is Accept File Edits but OpenCode only has build/plan) → show the first one it will actually use
|
||||
value={modes.some((m) => m.id === mode) ? mode : modes[0].id}
|
||||
title={modeMeta?.desc}
|
||||
onChange={(e) => setMode(e.target.value as Mode)}
|
||||
>
|
||||
{modes.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
|
||||
</select>
|
||||
)}
|
||||
{/* Cursor speed (like Paseo's Fast toggle); the old shield (auto-accept permissions) was removed */}
|
||||
{thread?.provider === "cursor" && (
|
||||
<select
|
||||
className="pill sel cursor-fast"
|
||||
value={thread.cursorFast ? "fast" : "off"}
|
||||
title="Fast"
|
||||
onChange={(e) => setCursorOpts({ cursorFast: e.target.value === "fast" })}
|
||||
>
|
||||
<option value="off">Fast: Off</option>
|
||||
<option value="fast">Fast: On</option>
|
||||
</select>
|
||||
)}
|
||||
{/* attachments */}
|
||||
<button className="ibtn" title={tr("composer.attachTitle")} onClick={() => fileRef.current?.click()}>
|
||||
<Icon name="attach" />
|
||||
</button>
|
||||
<input ref={fileRef} type="file" hidden multiple accept="image/*,.txt,.md,.log,.json,.csv"
|
||||
onChange={(e) => { for (const f of e.target.files ?? []) void upload(f); e.target.value = ""; }} />
|
||||
<div className="cp-right">
|
||||
{running ? (
|
||||
<>
|
||||
<span className="cp-clock">{elapsed}s</span>
|
||||
<button className="cp-stop" title={tr("common.stop")} onClick={() => void ws.call("thread.interrupt", { id: thread?.id })}>
|
||||
<Icon name="stop" />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button className="cp-send" title={tr("common.send")} disabled={waiting || (!text.trim() && attachments.length === 0) || attachments.some((a) => a.uploading)}
|
||||
onClick={() => void send("queue")}>
|
||||
<Icon name="send" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// Generic dialog primitive: scrim + card + close on Esc/scrim.
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { t } from "../i18n/index.js";
|
||||
|
||||
export function Dialog({
|
||||
title, children, footer, onClose, wide,
|
||||
}: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
onClose: () => void;
|
||||
wide?: boolean;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") { e.stopPropagation(); onClose(); }
|
||||
};
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
return () => window.removeEventListener("keydown", onKey, true);
|
||||
}, [onClose]);
|
||||
|
||||
return createPortal(
|
||||
<div className="dlg-scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div className="dlg" style={wide ? { width: 560 } : undefined} role="dialog" aria-label={title}>
|
||||
<div className="dlg-title">{title}</div>
|
||||
<div className="dlg-body">{children}</div>
|
||||
{footer && <div className="dlg-foot">{footer}</div>}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
// Confirmation dialog (second confirmation for delete/discard etc.).
|
||||
export function ConfirmDialog({
|
||||
title, body, okLabel, danger, onOk, onClose,
|
||||
}: {
|
||||
title: string; body: ReactNode; okLabel?: string; danger?: boolean;
|
||||
onOk: () => void; onClose: () => void;
|
||||
}) {
|
||||
const ok = okLabel ?? t("common.ok");
|
||||
return (
|
||||
<Dialog
|
||||
title={title}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<button className="btn ghost" onClick={onClose}>{t("common.cancel")}</button>
|
||||
<button className={`btn${danger ? " danger" : " primary"}`} onClick={() => { onClose(); onOk(); }}>
|
||||
{ok}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="dlg-hint" style={{ fontSize: "var(--fs-m)", color: "var(--fg)" }}>{body}</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Small line icons (stroke=currentColor, 1.6px); no third-party icon pack, keeps the bundle small.
|
||||
const PATHS: Record<string, string> = {
|
||||
plus: "M12 5v14M5 12h14",
|
||||
search: "M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm10 17-4.5-4.5",
|
||||
caret: "M9 6l6 6-6 6",
|
||||
dots: "M5 12h.01M12 12h.01M19 12h.01",
|
||||
pin: "M9 4h6l1 7 3 3v2H5v-2l3-3 1-7Zm3 12v4",
|
||||
send: "M4 12 20 4l-4 8 4 8-16-8Zm0 0h8",
|
||||
stop: "M7 7h10v10H7z",
|
||||
attach: "M8 12l6-6a3.5 3.5 0 0 1 5 5l-7 7a5 5 0 0 1-7-7l6-6",
|
||||
menu: "M4 6h16M4 12h16M4 18h16",
|
||||
changes: "M7 4v13m0 0a3 3 0 1 0 .01 0M7 17a3 3 0 1 1-.01 0M17 7v13m0-13a3 3 0 1 0 .01 0M17 7a3 3 0 1 1-.01 0",
|
||||
files: "M4 4h6l2 3h8v13H4V4Z",
|
||||
term: "M4 5h16v14H4zM7 9l3 3-3 3m5 0h5",
|
||||
x: "M6 6l12 12M18 6 6 18",
|
||||
refresh: "M20 11a8 8 0 1 0-2.3 6.3M20 5v6h-6",
|
||||
copy: "M8 8h11v12H8zM5 16V4h11",
|
||||
check: "M5 13l4 4L19 7",
|
||||
shield: "M12 3l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V6l8-3z",
|
||||
zap: "M13 2L4 14h7l-1 8 9-12h-7l1-8z",
|
||||
settings: "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z",
|
||||
};
|
||||
|
||||
export function Icon({ name, size = 16 }: { name: keyof typeof PATHS | string; size?: number }) {
|
||||
const d = PATHS[name];
|
||||
if (!d) return null;
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d={d} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// Three-column layout shell: sidebar | drag handle | main | drag handle | right panel (§8.5).
|
||||
// Narrow-screen breakpoints live in layout.css (<900 panel drawer, <760 sidebar drawer); this only handles state and dragging.
|
||||
// Whether a drawer counts as an overlay is decided by matchMedia breakpoints (not clientWidth, to avoid transient jitter).
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { useUi, SB_MIN, PN_MIN } from "../stores/ui";
|
||||
import { maxPanelWidth, maxSidebarWidth, clampLayoutWidths } from "../layout/bounds";
|
||||
|
||||
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
|
||||
|
||||
function useMedia(query: string): boolean {
|
||||
const [on, setOn] = useState(() => window.matchMedia?.(query).matches ?? false);
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia?.(query);
|
||||
if (!mq) return;
|
||||
const fn = () => setOn(mq.matches);
|
||||
mq.addEventListener?.("change", fn);
|
||||
fn();
|
||||
return () => mq.removeEventListener?.("change", fn);
|
||||
}, [query]);
|
||||
return on;
|
||||
}
|
||||
|
||||
function useColumnDrag(
|
||||
getBase: () => number,
|
||||
apply: (base: number, dx: number) => void,
|
||||
commit: () => void,
|
||||
) {
|
||||
const startX = useRef(0);
|
||||
const base = useRef(0);
|
||||
const [drag, setDrag] = useState(false);
|
||||
const down = useCallback(
|
||||
(e: React.PointerEvent) => {
|
||||
e.preventDefault();
|
||||
startX.current = e.clientX;
|
||||
base.current = getBase();
|
||||
setDrag(true);
|
||||
document.body.classList.add("col-drag");
|
||||
const move = (ev: PointerEvent) => apply(base.current, ev.clientX - startX.current);
|
||||
const up = () => {
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", up);
|
||||
document.body.classList.remove("col-drag");
|
||||
setDrag(false);
|
||||
commit();
|
||||
};
|
||||
window.addEventListener("pointermove", move);
|
||||
window.addEventListener("pointerup", up);
|
||||
},
|
||||
[getBase, apply, commit],
|
||||
);
|
||||
return { drag, down };
|
||||
}
|
||||
|
||||
export function Layout({
|
||||
sidebar,
|
||||
topbar,
|
||||
children,
|
||||
panel,
|
||||
}: {
|
||||
sidebar: ReactNode;
|
||||
topbar: ReactNode;
|
||||
children: ReactNode;
|
||||
panel: ReactNode;
|
||||
}) {
|
||||
const ui = useUi();
|
||||
const sbDrawer = useMedia("(max-width: 759px)"); // Sidebar drawer breakpoint
|
||||
const pnDrawer = useMedia("(max-width: 899px)"); // Panel drawer breakpoint
|
||||
const sbDragged = useRef(false);
|
||||
const pnDragged = useRef(false);
|
||||
|
||||
const sbDrag = useColumnDrag(
|
||||
useCallback(() => useUi.getState().sidebarWidth, []),
|
||||
useCallback((base, dx) => {
|
||||
sbDragged.current = true;
|
||||
const s = useUi.getState();
|
||||
const hi = maxSidebarWidth(s);
|
||||
useUi.setState({ sidebarWidth: clamp(Math.round(base + dx), SB_MIN, hi) });
|
||||
}, []),
|
||||
useCallback(() => {
|
||||
if (!sbDragged.current) return;
|
||||
sbDragged.current = false;
|
||||
useUi.getState().setSidebarWidth(useUi.getState().sidebarWidth);
|
||||
}, []),
|
||||
);
|
||||
const pnDrag = useColumnDrag(
|
||||
useCallback(() => useUi.getState().panelWidth, []),
|
||||
useCallback((base, dx) => {
|
||||
pnDragged.current = true;
|
||||
const s = useUi.getState();
|
||||
const hi = maxPanelWidth(s);
|
||||
useUi.setState({ panelWidth: clamp(Math.round(base - dx), PN_MIN, hi) });
|
||||
}, []),
|
||||
useCallback(() => {
|
||||
if (!pnDragged.current) return;
|
||||
pnDragged.current = false;
|
||||
useUi.getState().setPanelWidth(useUi.getState().panelWidth);
|
||||
}, []),
|
||||
);
|
||||
|
||||
// Shortcuts: Ctrl+B sidebar, Ctrl+J panel (§8.7; inside inputs/dialogs/terminals only Ctrl+K/B/J are intercepted)
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (!(e.ctrlKey || e.metaKey)) return;
|
||||
const k = e.key.toLowerCase();
|
||||
if (k === "b") {
|
||||
e.preventDefault();
|
||||
const s = useUi.getState();
|
||||
if (window.matchMedia("(max-width: 759px)").matches) s.setSbOpen(!s.sbOpen);
|
||||
else s.toggleSidebarHidden();
|
||||
} else if (k === "j") {
|
||||
e.preventDefault();
|
||||
const s = useUi.getState();
|
||||
if (s.panelOpen) s.closePanel();
|
||||
else s.openPanel();
|
||||
}
|
||||
// The Ctrl+K command palette is handled by P2-6
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, []);
|
||||
|
||||
// Sync width changes to CSS variables
|
||||
useEffect(() => {
|
||||
document.documentElement.style.setProperty("--sb-w", `${ui.sidebarWidth}px`);
|
||||
}, [ui.sidebarWidth]);
|
||||
useEffect(() => {
|
||||
document.documentElement.style.setProperty("--pn-w", `${ui.panelWidth}px`);
|
||||
}, [ui.panelWidth]);
|
||||
|
||||
// Shrink the sidebar/panel when the window narrows so the conversation in the middle isn't squeezed into a vertical column of characters
|
||||
useEffect(() => {
|
||||
const sync = () => {
|
||||
const s = useUi.getState();
|
||||
const sized = clampLayoutWidths(s);
|
||||
if (sized.sidebarWidth !== s.sidebarWidth) {
|
||||
useUi.getState().setSidebarWidth(sized.sidebarWidth);
|
||||
}
|
||||
if (sized.panelWidth !== s.panelWidth) {
|
||||
useUi.getState().setPanelWidth(sized.panelWidth);
|
||||
}
|
||||
};
|
||||
window.addEventListener("resize", sync);
|
||||
sync();
|
||||
return () => window.removeEventListener("resize", sync);
|
||||
}, []);
|
||||
|
||||
const scrim = ui.sbOpen || (ui.panelOpen && pnDrawer);
|
||||
return (
|
||||
<div className="app">
|
||||
<aside
|
||||
className={`sidebar${ui.sbHidden && !sbDrawer ? " w-hide" : ""}${ui.sbOpen ? " open" : ""}`}
|
||||
>
|
||||
{sidebar}
|
||||
</aside>
|
||||
<div className={`rs rs-l${sbDrag.drag ? " drag" : ""}`} onPointerDown={sbDrag.down} />
|
||||
<main className="main">
|
||||
{topbar}
|
||||
{children}
|
||||
</main>
|
||||
<div className={`rs rs-r${pnDrag.drag ? " drag" : ""}`} onPointerDown={pnDrag.down} />
|
||||
<section className={`panel${ui.panelOpen ? " open" : " w-hide"}`} aria-hidden={!ui.panelOpen}>
|
||||
{panel}
|
||||
</section>
|
||||
<div
|
||||
className={`scrim${scrim ? " show" : ""}`}
|
||||
onClick={() => {
|
||||
useUi.getState().setSbOpen(false);
|
||||
if (useUi.getState().panelOpen && pnDrawer) useUi.getState().closePanel();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Markdown rendering: marked + DOMPurify + highlight.js (languages on demand, code blocks with a copy button).
|
||||
import { useMemo, useRef, useEffect } from "react";
|
||||
import { marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import hljs from "highlight.js/lib/common";
|
||||
|
||||
marked.setOptions({ gfm: true, breaks: true });
|
||||
|
||||
const purify = (html: string) =>
|
||||
DOMPurify.sanitize(html, { USE_PROFILES: { html: true }, ADD_ATTR: ["target", "rel"] });
|
||||
|
||||
export function renderMarkdown(text: string): string {
|
||||
return purify(marked.parse(text, { async: false }));
|
||||
}
|
||||
|
||||
export function Markdown({ text, streaming }: { text: string; streaming?: boolean }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const html = useMemo(() => renderMarkdown(text), [text]);
|
||||
|
||||
// After rendering: highlight code blocks + copy button; external links target=_blank
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
for (const a of el.querySelectorAll("a[href^='http']")) {
|
||||
(a as HTMLAnchorElement).target = "_blank";
|
||||
(a as HTMLAnchorElement).rel = "noopener";
|
||||
}
|
||||
for (const pre of el.querySelectorAll("pre")) {
|
||||
const code = pre.querySelector("code");
|
||||
if (code && !code.dataset.hl) {
|
||||
code.dataset.hl = "1";
|
||||
try { hljs.highlightElement(code as HTMLElement); } catch {}
|
||||
}
|
||||
if (!pre.querySelector(".cb-copy")) {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "cb-copy";
|
||||
btn.textContent = "复制";
|
||||
btn.onclick = () => {
|
||||
const t = code?.textContent ?? "";
|
||||
void copyText(t).then(() => { btn.textContent = "已复制"; setTimeout(() => (btn.textContent = "复制"), 1200); });
|
||||
};
|
||||
pre.appendChild(btn);
|
||||
}
|
||||
}
|
||||
}, [html]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`md${streaming ? " streaming" : ""}`}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Clipboard: writeText → on failure fall back to a hidden textarea + execCommand (§8.2)
|
||||
export async function copyText(t: string): Promise<void> {
|
||||
try {
|
||||
await navigator.clipboard.writeText(t);
|
||||
return;
|
||||
} catch {}
|
||||
try {
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = t;
|
||||
ta.style.position = "fixed";
|
||||
ta.style.opacity = "0";
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
document.execCommand("copy");
|
||||
ta.remove();
|
||||
} catch {}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Generic popup menu: anchored positioning, close on outside click/Esc.
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
export type MenuItem =
|
||||
| { kind: "item"; label: string; danger?: boolean; disabled?: boolean; checked?: boolean; onClick: () => void }
|
||||
| { kind: "sep" }
|
||||
| { kind: "label"; text: string };
|
||||
|
||||
export function Menu({
|
||||
x, y, items, onClose,
|
||||
}: {
|
||||
x: number; y: number; items: MenuItem[]; onClose: () => void;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [pos, setPos] = useState({ left: x, top: y });
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const r = el.getBoundingClientRect();
|
||||
let { left, top } = pos;
|
||||
if (left + r.width > window.innerWidth - 8) left = Math.max(8, window.innerWidth - r.width - 8);
|
||||
if (top + r.height > window.innerHeight - 8) top = Math.max(8, window.innerHeight - r.height - 8);
|
||||
if (left !== pos.left || top !== pos.top) setPos({ left, top });
|
||||
}, [x, y]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
const onDown = (e: PointerEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) onClose();
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") { e.stopPropagation(); onClose(); }
|
||||
};
|
||||
window.addEventListener("pointerdown", onDown, true);
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
return () => {
|
||||
window.removeEventListener("pointerdown", onDown, true);
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
return createPortal(
|
||||
<div ref={ref} className="menu" style={pos} role="menu">
|
||||
{items.map((it, i) =>
|
||||
it.kind === "sep" ? (
|
||||
<div key={i} className="msep" />
|
||||
) : it.kind === "label" ? (
|
||||
<div key={i} className="mlabel">{it.text}</div>
|
||||
) : (
|
||||
<button
|
||||
key={i}
|
||||
className={`mi${it.danger ? " danger" : ""}`}
|
||||
disabled={it.disabled}
|
||||
role="menuitem"
|
||||
onClick={() => { onClose(); it.onClick(); }}
|
||||
>
|
||||
<span>{it.label}</span>
|
||||
{it.checked && <span className="mi-check">✓</span>}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
// Trigger helper: turns onContextMenu/onClick into {x,y} state.
|
||||
export function useMenu(): [{ x: number; y: number } | null, (e: React.MouseEvent) => void, () => void] {
|
||||
const [pos, setPos] = useState<{ x: number; y: number } | null>(null);
|
||||
const open = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setPos({ x: e.clientX, y: e.clientY });
|
||||
};
|
||||
return [pos, open, () => setPos(null)];
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
// Right panel (§8.6): tab header (changes | files | terminal) + close; content comes from each panel component.
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useUi, type PanelTab } from "../stores/ui";
|
||||
import { useData } from "../stores/data";
|
||||
import { useTimeline } from "../stores/timeline";
|
||||
import { ws } from "../main";
|
||||
import { Icon } from "./Icons";
|
||||
import { DiffView, type DiffHunk } from "./Timeline";
|
||||
import { ConfirmDialog } from "./Dialog";
|
||||
import { toast } from "./Toast";
|
||||
import { errMsg, t, tf } from "../i18n/index.js";
|
||||
import { TerminalPanel } from "./TerminalPanel";
|
||||
import { copyText } from "./Markdown";
|
||||
import hljs from "highlight.js/lib/common";
|
||||
|
||||
export function Panel() {
|
||||
const ui = useUi();
|
||||
const tabs: { tab: PanelTab; label: string }[] = [
|
||||
{ tab: "changes", label: t("panel.changes") },
|
||||
{ tab: "files", label: t("panel.files") },
|
||||
{ tab: "terminal", label: t("panel.terminal") },
|
||||
];
|
||||
return (
|
||||
<>
|
||||
<div className="pn-head">
|
||||
<div className="pn-tabs">
|
||||
{tabs.map((t) => (
|
||||
<button
|
||||
key={t.tab}
|
||||
className={`pn-tab${ui.panelTab === t.tab ? " on" : ""}`}
|
||||
onClick={() => ui.setPanelTab(t.tab)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button className="ibtn pn-close" title={t("panel.closeTitle")} onClick={() => ui.closePanel()}>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="pn-body">
|
||||
{ui.panelTab === "changes" && <ChangesPanel />}
|
||||
{ui.panelTab === "files" && <FilesPanel />}
|
||||
{ui.panelTab === "terminal" && <TerminalPanel />}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- changes panel ----------
|
||||
type GitFile = { path: string; index: string; worktree: string; kind: "modified" | "added" | "deleted" | "untracked" | "renamed" };
|
||||
type GitStatus = { isRepo: boolean; branch?: string; files?: GitFile[]; error?: string };
|
||||
|
||||
const gitKindLabel = (k: GitFile["kind"]) => t(`panel.gitKind.${k}`);
|
||||
|
||||
// Unified diff text → DiffHunk[] (fed to DiffView)
|
||||
function parseUnified(diff: string): DiffHunk[] {
|
||||
const hunks: DiffHunk[] = [];
|
||||
let cur: DiffHunk | null = null;
|
||||
for (const line of diff.split("\n")) {
|
||||
if (line.startsWith("diff ") || line.startsWith("index ") || line.startsWith("--- ") || line.startsWith("+++ ")) continue;
|
||||
if (line.startsWith("@@")) {
|
||||
cur = { head: line, lines: [] };
|
||||
hunks.push(cur);
|
||||
continue;
|
||||
}
|
||||
if (!cur) continue;
|
||||
if (line.startsWith("+")) cur.lines.push({ t: "+", text: line.slice(1) });
|
||||
else if (line.startsWith("-")) cur.lines.push({ t: "-", text: line.slice(1) });
|
||||
else if (line.startsWith("\\")) cur.lines.push({ t: " ", text: line });
|
||||
else cur.lines.push({ t: " ", text: line.startsWith(" ") ? line.slice(1) : line });
|
||||
}
|
||||
return hunks;
|
||||
}
|
||||
|
||||
// +/- counts (rough line count of one file's diff text; untracked = all added)
|
||||
function diffStats(diff: string): { add: number; del: number } {
|
||||
let add = 0, del = 0;
|
||||
for (const l of diff.split("\n")) {
|
||||
if (l.startsWith("+") && !l.startsWith("+++")) add++;
|
||||
else if (l.startsWith("-") && !l.startsWith("---")) del++;
|
||||
}
|
||||
return { add, del };
|
||||
}
|
||||
|
||||
function ChangesPanel() {
|
||||
const { projects, threads } = useData();
|
||||
const ui = useUi();
|
||||
const tlStatus = useTimeline((s) => s.status);
|
||||
const [st, setSt] = useState<GitStatus | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [selPath, setSelPath] = useState<string | null>(null);
|
||||
const [diff, setDiff] = useState<{ hunks?: DiffHunk[]; tooLarge?: boolean; error?: string; loading?: boolean } | null>(null);
|
||||
const [confirmPath, setConfirmPath] = useState<GitFile | null>(null);
|
||||
const [stats, setStats] = useState<Record<string, { add: number; del: number }>>({});
|
||||
const prevStatus = useRef(tlStatus);
|
||||
const selPathRef = useRef<string | null>(null);
|
||||
selPathRef.current = selPath;
|
||||
|
||||
const thread = threads.find((t) => t.id === ui.currentThreadId) ?? null;
|
||||
const project = thread
|
||||
? projects.find((p) => p.id === thread.projectId)
|
||||
: projects.find((p) => p.id === ui.currentProjectId);
|
||||
const projectId = project?.id ?? null;
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!projectId) { setSt(null); return; }
|
||||
try {
|
||||
const r = (await ws.call("git.status", { projectId })) as GitStatus;
|
||||
setSt(r);
|
||||
// The selected file may have been discarded/restored → clear the selection (a ref keeps the interval closure from seeing a stale selPath)
|
||||
const cur = selPathRef.current;
|
||||
if (cur && !r.files?.some((f) => f.path === cur)) {
|
||||
setSelPath(null);
|
||||
setDiff(null);
|
||||
}
|
||||
} catch (e) {
|
||||
setSt({ isRepo: false, error: String((e as Error)?.message ?? e) });
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Initial load + refresh every 3 seconds (the component stays mounted while the panel is visible)
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
const t = setInterval(() => void refresh(), 3000);
|
||||
return () => clearInterval(t);
|
||||
}, [refresh]);
|
||||
|
||||
// Linked to turn_ended: refresh immediately when status goes from running/initializing back to idle
|
||||
useEffect(() => {
|
||||
const was = prevStatus.current;
|
||||
prevStatus.current = tlStatus;
|
||||
if ((was === "running" || was === "initializing") && tlStatus !== "running" && tlStatus !== "initializing") {
|
||||
void refresh();
|
||||
}
|
||||
}, [tlStatus, refresh]);
|
||||
|
||||
// Selected file → fetch its diff (and refresh the counts in the list)
|
||||
const openFile = useCallback(async (f: GitFile) => {
|
||||
if (!projectId) return;
|
||||
setSelPath(f.path);
|
||||
setDiff({ loading: true });
|
||||
try {
|
||||
const r = (await ws.call("git.diff", { projectId, path: f.path })) as { diff?: string; tooLarge?: boolean; error?: string };
|
||||
if (r.tooLarge) setDiff({ tooLarge: true });
|
||||
else if (r.error) setDiff({ error: r.error });
|
||||
else {
|
||||
const hunks = parseUnified(r.diff ?? "");
|
||||
setDiff({ hunks });
|
||||
setStats((s) => ({ ...s, [f.path]: diffStats(r.diff ?? "") }));
|
||||
}
|
||||
} catch (e) {
|
||||
setDiff({ error: String((e as Error)?.message ?? e) });
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
const discard = useCallback(async (f: GitFile) => {
|
||||
if (!projectId) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await ws.call("git.discard", { projectId, path: f.path });
|
||||
if (selPath === f.path) { setSelPath(null); setDiff(null); }
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
toast(t("panel.failDiscard") + errMsg(e), true);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [projectId, selPath, refresh]);
|
||||
|
||||
if (!project) return <div className="pn-empty">{t("panel.pickProject")}</div>;
|
||||
if (st && !st.isRepo) {
|
||||
return (
|
||||
<div className="pn-empty">
|
||||
{t("panel.notGit")}
|
||||
{st.error && <div className="pn-empty-sub">{st.error}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="chg-head">
|
||||
<span className="chg-branch" title={t("panel.branch")}><Icon name="changes" size={13} /> {st?.branch ?? "…"}</span>
|
||||
<button className="ibtn" title={t("common.refresh")} onClick={() => void refresh()}><Icon name="refresh" size={14} /></button>
|
||||
</div>
|
||||
<div className="chg-list">
|
||||
{(st?.files ?? []).length === 0 && <div className="pn-empty">{t("panel.clean")}</div>}
|
||||
{st?.files?.map((f) => {
|
||||
const s = stats[f.path];
|
||||
return (
|
||||
<div key={f.path} className={`chg-row${selPath === f.path ? " on" : ""}`} onClick={() => void openFile(f)}>
|
||||
<span className={`chg-kind k-${f.kind}`} title={f.kind}>{gitKindLabel(f.kind)}</span>
|
||||
<span className="chg-path" title={f.path}>{f.path}</span>
|
||||
{s && <span className="chg-stat"><em className="add">+{s.add}</em> <em className="del">−{s.del}</em></span>}
|
||||
<button
|
||||
className="ibtn chg-discard"
|
||||
title={t("panel.discardBtn")}
|
||||
disabled={busy}
|
||||
onClick={(e) => { e.stopPropagation(); setConfirmPath(f); }}
|
||||
>
|
||||
<Icon name="x" size={13} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="chg-diff">
|
||||
{diff?.loading && <div className="pn-empty">{t("panel.loadingDiff")}</div>}
|
||||
{diff?.tooLarge && <div className="pn-empty">{t("panel.diffTooLarge")}</div>}
|
||||
{diff?.error && <div className="pn-empty">{diff.error}</div>}
|
||||
{diff?.hunks && <DiffView hunks={diff.hunks} path={selPath ?? undefined} />}
|
||||
</div>
|
||||
{confirmPath && (
|
||||
<ConfirmDialog
|
||||
title={t("panel.discardTitle")}
|
||||
body={
|
||||
confirmPath.kind === "untracked"
|
||||
? tf("panel.discardUntracked", { path: confirmPath.path })
|
||||
: tf("panel.discardTracked", { path: confirmPath.path })
|
||||
}
|
||||
okLabel={t("common.discard")}
|
||||
danger
|
||||
onOk={() => void discard(confirmPath)}
|
||||
onClose={() => setConfirmPath(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- files panel ----------
|
||||
type TreeEntry = { name: string; path: string; isDir: boolean };
|
||||
|
||||
function FilesPanel() {
|
||||
const { projects, threads } = useData();
|
||||
const ui = useUi();
|
||||
const thread = threads.find((t) => t.id === ui.currentThreadId) ?? null;
|
||||
const project = thread
|
||||
? projects.find((p) => p.id === thread.projectId)
|
||||
: projects.find((p) => p.id === ui.currentProjectId);
|
||||
const projectId = project?.id ?? null;
|
||||
|
||||
// expanded: dir path → entries | "loading" | error string
|
||||
const [dirs, setDirs] = useState<Record<string, TreeEntry[] | "loading" | string>>({});
|
||||
const [sel, setSel] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<{ text?: string; language?: string; binary?: boolean; tooLarge?: boolean; error?: string; loading?: boolean } | null>(null);
|
||||
|
||||
const loadDir = useCallback(async (dir: string) => {
|
||||
if (!projectId) return;
|
||||
setDirs((d) => ({ ...d, [dir]: "loading" }));
|
||||
try {
|
||||
const r = (await ws.call("files.tree", { projectId, dir })) as { entries?: TreeEntry[]; error?: string };
|
||||
setDirs((d) => ({ ...d, [dir]: r.error ? `err:${r.error}` : (r.entries ?? []) }));
|
||||
} catch (e) {
|
||||
setDirs((d) => ({ ...d, [dir]: `err:${String((e as Error)?.message ?? e)}` }));
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Project changed → reload the root
|
||||
useEffect(() => {
|
||||
setDirs({});
|
||||
setSel(null);
|
||||
setFile(null);
|
||||
if (projectId) void loadDir(".");
|
||||
}, [projectId, loadDir]);
|
||||
|
||||
const toggle = (e: TreeEntry) => {
|
||||
if (!e.isDir) {
|
||||
void openFile(e.path);
|
||||
return;
|
||||
}
|
||||
const cur = dirs[e.path];
|
||||
if (cur && cur !== "loading") {
|
||||
// Expanded → collapse (remove the entries; keeping the subdirectory cache is harmless, expanding again refetches)
|
||||
setDirs((d) => { const n = { ...d }; delete n[e.path]; return n; });
|
||||
} else if (!cur) {
|
||||
void loadDir(e.path);
|
||||
}
|
||||
// Ignore clicks while "loading"
|
||||
};
|
||||
|
||||
const openFile = async (path: string) => {
|
||||
if (!projectId) return;
|
||||
setSel(path);
|
||||
setFile({ loading: true });
|
||||
try {
|
||||
const r = (await ws.call("files.read", { projectId, path })) as { text?: string; language?: string; binary?: boolean; tooLarge?: boolean; error?: string };
|
||||
setFile(r);
|
||||
} catch (e) {
|
||||
setFile({ error: String((e as Error)?.message ?? e) });
|
||||
}
|
||||
};
|
||||
|
||||
// Highlighting: run hljs once on the code after the preview text renders
|
||||
const preRef = useRef<HTMLElement | null>(null);
|
||||
useEffect(() => {
|
||||
const el = preRef.current;
|
||||
if (!el || !file?.text) return;
|
||||
try { hljs.highlightElement(el); } catch {}
|
||||
}, [file?.text, file?.language]);
|
||||
|
||||
if (!project) return <div className="pn-empty">{t("panel.pickProject")}</div>;
|
||||
|
||||
const crumbs = sel ? sel.split("/") : [];
|
||||
const renderDir = (dir: string, depth: number) => {
|
||||
const d = dirs[dir];
|
||||
if (!d || d === "loading") return null;
|
||||
if (typeof d === "string") return <div className="ft-err" style={{ paddingLeft: 8 + depth * 14 }}>{d.slice(4)}</div>;
|
||||
return d.map((e) => (
|
||||
<div key={e.path}>
|
||||
<div
|
||||
className={`ft-row${sel === e.path ? " on" : ""}`}
|
||||
style={{ paddingLeft: 8 + depth * 14 }}
|
||||
onClick={() => toggle(e)}
|
||||
title={e.path}
|
||||
>
|
||||
{e.isDir ? (
|
||||
<>
|
||||
<span className={`caret${dirs[e.path] && dirs[e.path] !== "loading" ? " open" : ""}`}>›</span>
|
||||
<Icon name="files" size={13} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="caret" style={{ visibility: "hidden" }}>›</span>
|
||||
<span className="ft-dot" />
|
||||
</>
|
||||
)}
|
||||
<span className="ft-name">{e.name}</span>
|
||||
</div>
|
||||
{e.isDir && renderDir(e.path, depth + 1)}
|
||||
</div>
|
||||
));
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="ft-crumbs">
|
||||
{sel ? (
|
||||
<>
|
||||
<button className="ft-crumb" onClick={() => setSel(null)} title={t("panel.closePreview")}>×</button>
|
||||
{crumbs.map((c, i) => <span key={i} className="ft-crumb-t">{i > 0 ? "/" : ""}{c}</span>)}
|
||||
<button className="ibtn" title={t("common.copyPath")} onClick={() => { void copyText(sel); toast(t("common.copiedPath")); }}>
|
||||
<Icon name="copy" size={13} />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<span className="ft-crumb-t muted">{project.name}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="ft-tree">{renderDir(".", 0)}</div>
|
||||
{sel && (
|
||||
<div className="ft-view">
|
||||
{file?.loading && <div className="pn-empty">{t("panel.reading")}</div>}
|
||||
{file?.binary && <div className="pn-empty">{t("panel.binary")}</div>}
|
||||
{file?.tooLarge && <div className="pn-empty">{t("panel.tooLarge")}</div>}
|
||||
{file?.error && <div className="pn-empty">{file.error}</div>}
|
||||
{file?.text != null && (
|
||||
<pre className="ft-pre"><code ref={preRef} className={`language-${file.language ?? "plaintext"}`}>{file.text}</code></pre>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// Settings dialog (§8.6): fields = §5.6; saved on change; version/data directory/PID at the bottom.
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dialog } from "./Dialog";
|
||||
import { ws } from "../main";
|
||||
import { toast } from "./Toast";
|
||||
import { permissionModes } from "../i18n/modes.js";
|
||||
import { errMsg, t, tf } from "../i18n/index.js";
|
||||
import type { ProviderInfo } from "../types/models.js";
|
||||
import { useData } from "../stores/data.js";
|
||||
|
||||
type Settings = {
|
||||
defaultProvider?: string; defaultMode?: string; defaultEffort?: string | null;
|
||||
sendKey?: string; runningSend?: string; showThinking?: boolean; density?: string;
|
||||
theme?: string; idleCloseMinutes?: number; idleExitMinutes?: number;
|
||||
providerEnabled?: Record<string, boolean>;
|
||||
providerCommand?: Record<string, { executable?: string; args?: string[] }>;
|
||||
[k: string]: unknown;
|
||||
};
|
||||
|
||||
function providerUsable(p: ProviderInfo): boolean {
|
||||
if (p.enabled === false || !p.available) return false;
|
||||
if (p.status === "planned") return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function statusLabel(p: ProviderInfo): string {
|
||||
if (p.status === "verified") return t("settings.providerVerified");
|
||||
if (p.status === "experimental") return t("settings.providerExperimental");
|
||||
if (p.status === "planned") return t("settings.providerPlanned");
|
||||
return t("settings.providerPending");
|
||||
}
|
||||
|
||||
export function SettingsDialog({ onClose, providers }: { onClose: () => void; providers: ProviderInfo[] }) {
|
||||
const wsClient = useData((s) => s.ws);
|
||||
const [s, setS] = useState<Settings | null>(null);
|
||||
const [info, setInfo] = useState<{ version?: string; dataDir?: string; pid?: number }>({});
|
||||
const [expanded, setExpanded] = useState<string | null>(null);
|
||||
const modes = permissionModes();
|
||||
|
||||
useEffect(() => {
|
||||
void ws.call("settings.get").then((v) => setS(v as Settings));
|
||||
void ws.call("app.info").then((v) => setInfo(v as typeof info)).catch(() => {});
|
||||
}, []);
|
||||
|
||||
const set = async (patch: Partial<Settings>) => {
|
||||
const next = { ...s, ...patch } as Settings;
|
||||
setS(next);
|
||||
try {
|
||||
await ws.call("settings.set", { patch });
|
||||
window.dispatchEvent(new CustomEvent("settings-changed", { detail: next }));
|
||||
if (patch.theme) applyTheme(patch.theme as string);
|
||||
if (patch.providerEnabled && wsClient) {
|
||||
void ws.call("providers.list", { refresh: true }).then((list) => {
|
||||
useData.setState({ providers: list as ProviderInfo[] });
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
toast(t("settings.failSave") + errMsg(e), true);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleProvider = (id: string, on: boolean) => {
|
||||
const cur = s?.providerEnabled ?? {};
|
||||
void set({ providerEnabled: { ...cur, [id]: on } });
|
||||
};
|
||||
|
||||
const redetect = () => {
|
||||
void ws.call("providers.list", { refresh: true }).then((list) => {
|
||||
useData.setState({ providers: list as ProviderInfo[] });
|
||||
toast(t("settings.providerRedetect") + " ✓");
|
||||
}).catch((e) => toast(errMsg(e), true));
|
||||
};
|
||||
|
||||
const setLaunch = (id: string, patch: { executable?: string; args?: string[] }) => {
|
||||
const cur = { ...(s?.providerCommand ?? {}) };
|
||||
cur[id] = { ...cur[id], ...patch };
|
||||
void set({ providerCommand: cur });
|
||||
};
|
||||
|
||||
const providerStatus = (p: ProviderInfo) => {
|
||||
if (p.enabled === false) return { dot: "off", text: t("settings.providerOff") };
|
||||
if (!p.available) return { dot: "off", text: p.reason ?? t("common.notDetected") };
|
||||
const n = p.models?.length ?? 0;
|
||||
const base = statusLabel(p);
|
||||
const extra = n > 0 ? ` · ${tf("settings.providerModels", { n: String(n) })}` : "";
|
||||
return { dot: p.status === "verified" ? "on" : "pending", text: base + extra };
|
||||
};
|
||||
|
||||
if (!s) return <Dialog title={t("settings.title")} onClose={onClose}><div className="dlg-hint">{t("common.loading")}</div></Dialog>;
|
||||
|
||||
const row = (label: string, el: React.ReactNode) => (
|
||||
<div className="dlg-row"><label>{label}</label>{el}</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog title={t("settings.title")} onClose={onClose} wide
|
||||
footer={<button className="btn primary" onClick={onClose}>{t("common.done")}</button>}>
|
||||
{row(t("settings.defaultAgent"), (
|
||||
<select className="tinput" value={s.defaultProvider ?? "claude"} onChange={(e) => void set({ defaultProvider: e.target.value })}>
|
||||
{providers.map((p) => <option key={p.id} value={p.id} disabled={!providerUsable(p)}>{p.name}{!providerUsable(p) ? t("common.notInstalled") : ""}</option>)}
|
||||
</select>
|
||||
))}
|
||||
<div className="dlg-row dlg-row-top">
|
||||
<label>{t("settings.providers")}</label>
|
||||
<div className="provider-list">
|
||||
<button type="button" className="btn sm provider-redetect" onClick={redetect}>{t("settings.providerRedetect")}</button>
|
||||
{providers.map((p) => {
|
||||
const st = providerStatus(p);
|
||||
const on = p.enabled !== false;
|
||||
const open = expanded === p.id;
|
||||
const cmd = s.providerCommand?.[p.id];
|
||||
return (
|
||||
<div key={p.id} className={`provider-row${open ? " open" : ""}`}>
|
||||
<button type="button" className="provider-head" onClick={() => setExpanded(open ? null : p.id)}>
|
||||
<span className={`provider-dot provider-dot-${st.dot}`} aria-hidden />
|
||||
<div className="provider-meta">
|
||||
<span className="provider-name">{p.name}</span>
|
||||
<span className="dlg-hint">{st.text}</span>
|
||||
</div>
|
||||
<span className="mi-caret">{open ? "▾" : "▸"}</span>
|
||||
</button>
|
||||
<label className="provider-switch" title={p.name}>
|
||||
<input type="checkbox" checked={on} onChange={(e) => toggleProvider(p.id, e.target.checked)} />
|
||||
</label>
|
||||
{open && (
|
||||
<div className="provider-detail">
|
||||
{p.bin && <div className="dlg-hint">{p.bin}{p.version ? ` · ${p.version}` : ""}</div>}
|
||||
{p.installHint && (
|
||||
<div className="provider-hint-row">
|
||||
<span className="dlg-hint">{p.installHint}</span>
|
||||
<button type="button" className="te-files" onClick={() => void navigator.clipboard?.writeText(p.installHint ?? "").then(() => toast(t("common.copied")))}>{t("settings.providerCopyHint")}</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="dlg-hint">{t("settings.providerLaunchCmd")}</div>
|
||||
<input className="tinput" placeholder={t("settings.providerLaunchExe")} value={cmd?.executable ?? ""}
|
||||
onChange={(e) => setLaunch(p.id, { executable: e.target.value || undefined })} />
|
||||
<input className="tinput" placeholder='["--acp"]' value={cmd?.args ? JSON.stringify(cmd.args) : ""}
|
||||
onChange={(e) => {
|
||||
try {
|
||||
const v = e.target.value.trim();
|
||||
setLaunch(p.id, { args: v ? (JSON.parse(v) as string[]) : undefined });
|
||||
} catch { /* typing */ }
|
||||
}} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{row(t("settings.defaultMode"), (
|
||||
<select className="tinput" value={s.defaultMode ?? "default"} onChange={(e) => void set({ defaultMode: e.target.value })}>
|
||||
{modes.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
|
||||
</select>
|
||||
))}
|
||||
{row(t("settings.theme"), (
|
||||
<select className="tinput" value={s.theme ?? "auto"} onChange={(e) => void set({ theme: e.target.value })}>
|
||||
<option value="auto">{t("settings.themeAuto")}</option>
|
||||
<option value="light">{t("settings.themeLight")}</option>
|
||||
<option value="dark">{t("settings.themeDark")}</option>
|
||||
</select>
|
||||
))}
|
||||
{row(t("settings.sendKey"), (
|
||||
<select className="tinput" value={s.sendKey ?? "enter"} onChange={(e) => void set({ sendKey: e.target.value })}>
|
||||
<option value="enter">{t("settings.sendEnter")}</option>
|
||||
<option value="ctrlEnter">{t("settings.sendCtrl")}</option>
|
||||
</select>
|
||||
))}
|
||||
{row(t("settings.runningSend"), (
|
||||
<select className="tinput" value={s.runningSend ?? "queue"} onChange={(e) => void set({ runningSend: e.target.value })}>
|
||||
<option value="queue">{t("settings.queue")}</option>
|
||||
<option value="steer">{t("settings.steer")}</option>
|
||||
</select>
|
||||
))}
|
||||
{row(t("settings.thinking"), (
|
||||
<label style={{ display: "flex", gap: 8, alignItems: "center", fontSize: "var(--fs-m)", color: "var(--fg)" }}>
|
||||
<input type="checkbox" checked={s.showThinking !== false} onChange={(e) => void set({ showThinking: e.target.checked })} />
|
||||
{t("settings.showThinking")}
|
||||
</label>
|
||||
))}
|
||||
{row(t("settings.idleClose"), (
|
||||
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
|
||||
<input className="tinput" type="number" min={5} max={240} style={{ width: 90 }}
|
||||
value={s.idleCloseMinutes ?? 30}
|
||||
onChange={(e) => void set({ idleCloseMinutes: Math.max(5, Number(e.target.value) || 30) })} />
|
||||
<span className="dlg-hint">{t("settings.idleMinutes")}</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="msep" />
|
||||
<div className="dlg-hint">
|
||||
{tf("settings.versionLine", { ver: info.version ?? "?", pid: info.pid ?? "?" })}<br />
|
||||
{t("settings.dataDir")}{info.dataDir ?? "?"} <button className="te-files" onClick={() => void navigator.clipboard?.writeText(info.dataDir ?? "").catch(() => {})}>{t("common.copy")}</button>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function applyTheme(theme: string) {
|
||||
const preferDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches;
|
||||
document.documentElement.dataset.theme =
|
||||
theme === "light" || theme === "dark" ? theme : preferDark ? "dark" : "light";
|
||||
}
|
||||
|
||||
export type LiveSettings = {
|
||||
sendKey: "enter" | "ctrlEnter";
|
||||
runningSend: "queue" | "steer";
|
||||
showThinking: boolean;
|
||||
};
|
||||
|
||||
const LIVE_DEFAULTS: LiveSettings = { sendKey: "enter", runningSend: "queue", showThinking: true };
|
||||
|
||||
function liveFrom(v: Record<string, unknown> | undefined): LiveSettings {
|
||||
return {
|
||||
sendKey: v?.sendKey === "ctrlEnter" ? "ctrlEnter" : "enter",
|
||||
runningSend: v?.runningSend === "steer" ? "steer" : "queue",
|
||||
showThinking: v?.showThinking !== false,
|
||||
};
|
||||
}
|
||||
|
||||
/** The settings the composer/timeline read: fetched once at startup, updated as soon as the settings page changes them. */
|
||||
export function useLiveSettings(): LiveSettings {
|
||||
const [s, setS] = useState<LiveSettings>(LIVE_DEFAULTS);
|
||||
useEffect(() => {
|
||||
void ws.call("settings.get").then((v) => setS(liveFrom(v as Record<string, unknown>))).catch(() => {});
|
||||
const on = (e: Event) => setS(liveFrom((e as CustomEvent).detail as Record<string, unknown> | undefined));
|
||||
window.addEventListener("settings-changed", on);
|
||||
return () => window.removeEventListener("settings-changed", on);
|
||||
}, []);
|
||||
return s;
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
// Sidebar (§8.6): new project / search box / project groups / conversation rows / menus.
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { isImeComposing } from "../composer/ime";
|
||||
import { useData, pickDefaultProvider } from "../stores/data";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { ws } from "../main";
|
||||
import type { Project, ThreadMeta } from "../types/models";
|
||||
import { relTime } from "../util/format";
|
||||
import { Menu, useMenu, type MenuItem } from "./Menu";
|
||||
import { Dialog, ConfirmDialog } from "./Dialog";
|
||||
import { Icon } from "./Icons";
|
||||
import { toast } from "./Toast";
|
||||
import { displayThreadTitle, errMsg, t as tr, tf } from "../i18n/index.js";
|
||||
|
||||
const THREAD_PAGE = 10;
|
||||
|
||||
function dotClass(t: ThreadMeta, pendingIds: Set<string>): string {
|
||||
if (pendingIds.has(t.id)) return "dot wait";
|
||||
if (t.status === "running" || t.status === "initializing") return "dot run";
|
||||
if (t.status === "error" || t.lastTurnStatus === "failed") return "dot err";
|
||||
return "dot";
|
||||
}
|
||||
|
||||
export function Sidebar({ pendingByThread }: { pendingByThread: Set<string> }) {
|
||||
const { projects, threads } = useData();
|
||||
const ui = useUi();
|
||||
const [filter, setFilter] = useState("");
|
||||
const [showArchived, setShowArchived] = useState<Record<string, boolean>>({});
|
||||
const [showAll, setShowAll] = useState<Record<string, boolean>>({});
|
||||
const [renaming, setRenaming] = useState<string | null>(null);
|
||||
const [renameVal, setRenameVal] = useState("");
|
||||
const [newProjOpen, setNewProjOpen] = useState(false);
|
||||
const [importFor, setImportFor] = useState<Project | null>(null);
|
||||
const [confirm, setConfirm] = useState<null | { title: string; body: string; onOk: () => void }>(null);
|
||||
const [renameProj, setRenameProj] = useState<Project | null>(null);
|
||||
const [pmPos, openPm, closePm] = useMenu();
|
||||
const [tmPos, openTm, closeTm] = useMenu();
|
||||
const menuRef = useRef<{ project?: Project; thread?: ThreadMeta }>({});
|
||||
const filterRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// The command palette's "Import existing conversations…" action opens the import dialog through an event
|
||||
useEffect(() => {
|
||||
const onOpen = (e: Event) => {
|
||||
const pid = (e as CustomEvent).detail?.projectId as string | undefined;
|
||||
const p = projects.find((x) => x.id === pid) ?? projects[0];
|
||||
if (p) setImportFor(p);
|
||||
};
|
||||
const onNewProject = () => setNewProjOpen(true);
|
||||
window.addEventListener("open-import", onOpen);
|
||||
window.addEventListener("open-new-project", onNewProject);
|
||||
return () => {
|
||||
window.removeEventListener("open-import", onOpen);
|
||||
window.removeEventListener("open-new-project", onNewProject);
|
||||
};
|
||||
}, [projects]);
|
||||
|
||||
// Ctrl+K command palette (handled by P2-6); the sidebar search only filters titles
|
||||
const filtered = useMemo(() => {
|
||||
const q = filter.trim().toLowerCase();
|
||||
if (!q) return threads;
|
||||
return threads.filter((t) => t.title.toLowerCase().includes(q));
|
||||
}, [threads, filter]);
|
||||
|
||||
const byProject = useMemo(() => {
|
||||
const m = new Map<string, ThreadMeta[]>();
|
||||
for (const t of filtered) {
|
||||
if (!t.archived || showArchived[t.projectId]) {
|
||||
(m.get(t.projectId) ?? m.set(t.projectId, []).get(t.projectId)!).push(t);
|
||||
}
|
||||
}
|
||||
for (const list of m.values()) {
|
||||
list.sort((a, b) => Number(a.archived) - Number(b.archived) || Number(b.pinned) - Number(a.pinned) || b.updatedAt - a.updatedAt);
|
||||
}
|
||||
return m;
|
||||
}, [filtered, showArchived]);
|
||||
|
||||
const archivedCount = useMemo(() => {
|
||||
const m = new Map<string, number>();
|
||||
for (const t of filtered) {
|
||||
if (t.archived) m.set(t.projectId, (m.get(t.projectId) ?? 0) + 1);
|
||||
}
|
||||
return m;
|
||||
}, [filtered]);
|
||||
|
||||
async function createThread(projectId: string) {
|
||||
try {
|
||||
const s = await getSettings();
|
||||
const provider = await pickDefaultProvider();
|
||||
const t = (await ws.call("threads.create", {
|
||||
projectId,
|
||||
provider,
|
||||
model: null,
|
||||
mode: (s.defaultMode as string) ?? "default",
|
||||
effort: (s.defaultEffort as string | null) ?? null,
|
||||
})) as ThreadMeta;
|
||||
ui.select(projectId, t.id);
|
||||
} catch (e) {
|
||||
toast(tr("sidebar.failNewThread") + errMsg(e), true);
|
||||
}
|
||||
}
|
||||
|
||||
function threadMenuItems(t: ThreadMeta): MenuItem[] {
|
||||
return [
|
||||
{ kind: "item", label: tr("common.rename"), onClick: () => { setRenaming(t.id); setRenameVal(t.title); } },
|
||||
{ kind: "item", label: t.pinned ? tr("sidebar.unpin") : tr("sidebar.pin"), onClick: () => void ws.call("threads.update", { id: t.id, pinned: !t.pinned }) },
|
||||
{ kind: "item", label: t.archived ? tr("sidebar.unarchive") : tr("sidebar.archive"), onClick: () => void toggleArchive(t) },
|
||||
{ kind: "item", label: tr("sidebar.exportMd"), onClick: () => void exportThread(t) },
|
||||
{ kind: "sep" },
|
||||
{
|
||||
kind: "item", label: tr("common.delete"), danger: true,
|
||||
onClick: () => setConfirm({
|
||||
title: tr("sidebar.deleteThread"),
|
||||
body: tf("sidebar.deleteThreadBody", { title: t.title }),
|
||||
onOk: () => void ws.call("threads.delete", { id: t.id }),
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async function toggleArchive(t: ThreadMeta) {
|
||||
try {
|
||||
await ws.call("threads.update", { id: t.id, archived: !t.archived });
|
||||
if (!t.archived) {
|
||||
setShowArchived((s) => ({ ...s, [t.projectId]: true }));
|
||||
toast(tr("sidebar.archivedHint"));
|
||||
} else {
|
||||
toast(tr("sidebar.unarchived"));
|
||||
}
|
||||
} catch (e) {
|
||||
toast(errMsg(e), true);
|
||||
}
|
||||
}
|
||||
|
||||
function projectMenuItems(p: Project): MenuItem[] {
|
||||
return [
|
||||
{ kind: "item", label: tr("sidebar.newThread"), onClick: () => void createThread(p.id) },
|
||||
{ kind: "item", label: tr("sidebar.importHist"), onClick: () => setImportFor(p) },
|
||||
{ kind: "item", label: tr("common.rename"), onClick: () => setRenameProj(p) },
|
||||
{ kind: "item", label: tr("sidebar.openExplorer"), onClick: () => void ws.call("projects.open", { id: p.id }) },
|
||||
{ kind: "sep" },
|
||||
{ kind: "item", label: showArchived[p.id] ? tr("sidebar.hideArchived") : tr("sidebar.showArchived"), onClick: () => setShowArchived((s) => ({ ...s, [p.id]: !s[p.id] })) },
|
||||
{ kind: "sep" },
|
||||
{
|
||||
kind: "item", label: tr("sidebar.removeProject"), danger: true,
|
||||
onClick: () => setConfirm({
|
||||
title: tr("sidebar.removeProject"),
|
||||
body: tf("sidebar.removeProjectBody", { name: p.name }),
|
||||
onOk: () => void ws.call("projects.remove", { id: p.id }),
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="sb-row">
|
||||
<button className="sb-new" onClick={() => setNewProjOpen(true)}>
|
||||
<Icon name="plus" /> {tr("sidebar.newProject")}
|
||||
</button>
|
||||
<button className="ibtn" title={tr("common.settings")} onClick={() => window.dispatchEvent(new CustomEvent("open-settings"))}>
|
||||
<Icon name="settings" />
|
||||
</button>
|
||||
<button className="ibtn" title={tr("sidebar.searchTitle")} onClick={() => filterRef.current?.focus()}>
|
||||
<Icon name="search" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="sb-row" style={{ height: 32, paddingTop: 0 }}>
|
||||
<div className="sb-search">
|
||||
<input
|
||||
ref={filterRef}
|
||||
placeholder={tr("sidebar.filterPlaceholder")}
|
||||
value={filter}
|
||||
onChange={(e) => setFilter(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === "Escape") setFilter(""); }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="sb-list">
|
||||
{projects.length === 0 && (
|
||||
<div className="sb-start">
|
||||
<div className="sb-start-t">{tr("sidebar.noProjectsTitle")}</div>
|
||||
<div className="sb-start-s">{tr("sidebar.noProjectsSub")}</div>
|
||||
<button className="btn primary" onClick={() => setNewProjOpen(true)}>{tr("sidebar.newProject")}</button>
|
||||
</div>
|
||||
)}
|
||||
{projects.map((p) => {
|
||||
const list = byProject.get(p.id) ?? [];
|
||||
const collapsed = ui.collapsed[p.id];
|
||||
const nArchived = archivedCount.get(p.id) ?? 0;
|
||||
const shown = showAll[p.id] ? list : list.slice(0, THREAD_PAGE);
|
||||
return (
|
||||
<div className="pj-group" key={p.id}>
|
||||
<div
|
||||
className="pj"
|
||||
onContextMenu={(e) => { menuRef.current.project = p; openPm(e); }}
|
||||
>
|
||||
<button className="pj-toggle" onClick={() => ui.toggleCollapsed(p.id)}>
|
||||
<span className={`pj-caret${collapsed ? "" : " open"}`}><Icon name="caret" /></span>
|
||||
<span className="pj-badge">{p.name.slice(0, 1)}</span>
|
||||
<span className="pj-name">{p.name}</span>
|
||||
</button>
|
||||
<span className="pj-count">{list.length || ""}</span>
|
||||
<button className="pj-act" title={tr("sidebar.newThread")} onClick={() => void createThread(p.id)}>
|
||||
<Icon name="plus" />
|
||||
</button>
|
||||
<button className="pj-act" title={tr("sidebar.projectMenu")} onClick={(e) => { menuRef.current.project = p; openPm(e); }}>
|
||||
<Icon name="dots" />
|
||||
</button>
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<div className="pj-sessions">
|
||||
{shown.map((t) =>
|
||||
renaming === t.id ? (
|
||||
<div className="t-item" key={t.id}>
|
||||
<input
|
||||
className="t-rename"
|
||||
autoFocus
|
||||
value={renameVal}
|
||||
onChange={(e) => setRenameVal(e.target.value)}
|
||||
onBlur={() => setRenaming(null)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !isImeComposing(e.nativeEvent) && renameVal.trim()) {
|
||||
void ws.call("threads.update", { id: t.id, title: renameVal.trim() });
|
||||
setRenaming(null);
|
||||
} else if (e.key === "Escape") setRenaming(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
key={t.id}
|
||||
className={`t-item${ui.currentThreadId === t.id ? " on" : ""}${t.archived ? " archived" : ""}`}
|
||||
onClick={() => ui.select(p.id, t.id)}
|
||||
onContextMenu={(e) => { menuRef.current.thread = t; openTm(e); }}
|
||||
>
|
||||
<span className={dotClass(t, pendingByThread)} />
|
||||
{t.pinned && <span className="t-pin"><Icon name="pin" /></span>}
|
||||
<span className="t-title">{displayThreadTitle(t.title, t.titleAuto)}</span>
|
||||
<span className="t-time">{relTime(t.updatedAt)}</span>
|
||||
<span
|
||||
className="t-more"
|
||||
role="button"
|
||||
onClick={(e) => { e.stopPropagation(); menuRef.current.thread = t; openTm(e); }}
|
||||
>
|
||||
<Icon name="dots" />
|
||||
</span>
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
{list.length > THREAD_PAGE && !showAll[p.id] && (
|
||||
<button className="pj-more" onClick={() => setShowAll((s) => ({ ...s, [p.id]: true }))}>
|
||||
{tf("sidebar.showAll", { n: list.length })}
|
||||
</button>
|
||||
)}
|
||||
{nArchived > 0 && (
|
||||
<button className="pj-more" onClick={() => setShowArchived((s) => ({ ...s, [p.id]: !s[p.id] }))}>
|
||||
{showArchived[p.id] ? tr("sidebar.hideArchived") : tf("sidebar.archivedN", { n: nArchived })}
|
||||
</button>
|
||||
)}
|
||||
{list.length === 0 && nArchived === 0 && <div className="pj-empty">{tr("sidebar.noThreads")}</div>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{pmPos && menuRef.current.project && (
|
||||
<Menu x={pmPos.x} y={pmPos.y} items={projectMenuItems(menuRef.current.project)} onClose={closePm} />
|
||||
)}
|
||||
{tmPos && menuRef.current.thread && (
|
||||
<Menu x={tmPos.x} y={tmPos.y} items={threadMenuItems(menuRef.current.thread)} onClose={closeTm} />
|
||||
)}
|
||||
{newProjOpen && <NewProjectDialog onClose={() => setNewProjOpen(false)} />}
|
||||
{importFor && <ImportDialog project={importFor} onClose={() => setImportFor(null)} />}
|
||||
{confirm && (
|
||||
<ConfirmDialog title={confirm.title} body={confirm.body} danger onOk={confirm.onOk} onClose={() => setConfirm(null)} />
|
||||
)}
|
||||
{renameProj && <RenameProjectDialog project={renameProj} onClose={() => setRenameProj(null)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function RenameProjectDialog({ project, onClose }: { project: Project; onClose: () => void }) {
|
||||
const [name, setName] = useState(project.name);
|
||||
const ok = name.trim().length > 0 && name.trim() !== project.name;
|
||||
const save = () => {
|
||||
if (!ok) return;
|
||||
ws.call("projects.rename", { id: project.id, name: name.trim() })
|
||||
.then(onClose)
|
||||
.catch((e) => toast(tr("sidebar.failRename") + errMsg(e), true));
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
title={tr("sidebar.renameProject")}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<button className="btn ghost" onClick={onClose}>{tr("common.cancel")}</button>
|
||||
<button className="btn primary" disabled={!ok} onClick={save}>{tr("common.save")}</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="dlg-row">
|
||||
<label>{tr("sidebar.projectName")}</label>
|
||||
<input
|
||||
className="tinput"
|
||||
autoFocus
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === "Enter" && !isImeComposing(e.nativeEvent)) save(); }}
|
||||
/>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Sidebar-related fields from settings.get: fetched once and cached (module level, avoids setState during render)
|
||||
function getSettings(): Promise<Record<string, unknown>> {
|
||||
// No cache: the Settings dialog / e2e may have just changed it, always get the latest
|
||||
return ws.call("settings.get").then((v) => v as Record<string, unknown>).catch(() => ({}));
|
||||
}
|
||||
|
||||
// ---- new project dialog: path + fs.check + recent directories ----
|
||||
function NewProjectDialog({ onClose }: { onClose: () => void }) {
|
||||
const [path, setPath] = useState("");
|
||||
const [state, setState] = useState<null | { exists: boolean; isDir: boolean }>(null);
|
||||
const [recent, setRecent] = useState<string[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const ui = useUi();
|
||||
|
||||
useEffect(() => {
|
||||
void ws.call("fs.recentDirs").then((d) => setRecent(d as string[])).catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const p = path.trim();
|
||||
if (!p) { setState(null); return; }
|
||||
const t = setTimeout(() => {
|
||||
void ws.call("fs.check", { path: p }).then((r) => setState(r as { exists: boolean; isDir: boolean })).catch(() => setState(null));
|
||||
}, 200);
|
||||
return () => clearTimeout(t);
|
||||
}, [path]);
|
||||
|
||||
const ok = state?.exists && state.isDir;
|
||||
async function add() {
|
||||
if (!ok || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const p = (await ws.call("projects.create", { path: path.trim() })) as Project;
|
||||
ui.select(p.id, null);
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast(tr("sidebar.failAddProject") + errMsg(e), true);
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
title={tr("sidebar.newProjectDlg")}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<button className="btn ghost" onClick={onClose}>{tr("common.cancel")}</button>
|
||||
<button className="btn primary" disabled={!ok || busy} onClick={() => void add()}>{tr("common.add")}</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="dlg-row">
|
||||
<label>{tr("sidebar.dirLabel")}</label>
|
||||
<div style={{ display: "flex", gap: 6 }}>
|
||||
<input
|
||||
className={`tinput${state && !ok ? " err" : ""}`}
|
||||
style={{ flex: 1 }}
|
||||
autoFocus
|
||||
placeholder="D:\\path\\to\\project"
|
||||
value={path}
|
||||
onChange={(e) => setPath(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === "Enter" && !isImeComposing(e.nativeEvent)) void add(); }}
|
||||
/>
|
||||
<button
|
||||
className="btn"
|
||||
style={{ flex: "none", whiteSpace: "nowrap" }}
|
||||
onClick={() => {
|
||||
void ws.call("fs.pickFolder", { initial: path.trim() || undefined }).then((r) => {
|
||||
const res = r as { available: boolean; path: string | null };
|
||||
if (res?.path) setPath(res.path);
|
||||
else if (res && !res.available) toast(tr("sidebar.pickFolderUnsupported"));
|
||||
}).catch(() => toast(tr("sidebar.pickFolderFailed")));
|
||||
}}
|
||||
>{tr("common.browse")}</button>
|
||||
</div>
|
||||
{state && !state.exists && <div className="dlg-hint err">{tr("sidebar.dirMissing")}</div>}
|
||||
{state && state.exists && !state.isDir && <div className="dlg-hint err">{tr("sidebar.notDir")}</div>}
|
||||
{ok && <div className="dlg-hint">{tr("sidebar.dirOk")}</div>}
|
||||
</div>
|
||||
{recent.length > 0 && (
|
||||
<div className="dlg-row">
|
||||
<label>{tr("sidebar.recent")}</label>
|
||||
{recent.map((r) => (
|
||||
<button key={r} className="mi" style={{ height: 26 }} onClick={() => setPath(r)}>{r}</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- import existing conversations dialog (P4-1): list sessions in ~/.claude/projects matching the project directory, tick to import ----
|
||||
type HistItem = { provider: string; sessionId: string; title: string; updatedAt: number; messageCount: number; imported: boolean };
|
||||
|
||||
function ImportDialog({ project, onClose }: { project: Project; onClose: () => void }) {
|
||||
const [items, setItems] = useState<HistItem[] | null>(null);
|
||||
const [checked, setChecked] = useState<Set<string>>(new Set());
|
||||
const [busy, setBusy] = useState(false);
|
||||
const ui = useUi();
|
||||
|
||||
useEffect(() => {
|
||||
void ws.call("history.list", { projectId: project.id })
|
||||
.then((r) => setItems(r as HistItem[]))
|
||||
.catch((e) => { toast(tr("sidebar.failImportList") + errMsg(e), true); setItems([]); });
|
||||
}, [project.id]);
|
||||
|
||||
const toggle = (sid: string) => {
|
||||
setChecked((s) => {
|
||||
const n = new Set(s);
|
||||
if (n.has(sid)) n.delete(sid); else n.add(sid);
|
||||
return n;
|
||||
});
|
||||
};
|
||||
|
||||
async function doImport() {
|
||||
if (busy || checked.size === 0 || !items) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const list = items.filter((i) => checked.has(i.sessionId) && !i.imported);
|
||||
const created = (await ws.call("history.import", {
|
||||
projectId: project.id,
|
||||
items: list.map((i) => ({ provider: i.provider, sessionId: i.sessionId, title: i.title })),
|
||||
})) as ThreadMeta[];
|
||||
toast(tf("sidebar.importedN", { n: created.length }));
|
||||
if (created.length > 0) ui.select(project.id, (created[created.length - 1] as ThreadMeta).id);
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast(tr("sidebar.failImport") + errMsg(e), true);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
title={tf("sidebar.importTitle", { name: project.name })}
|
||||
onClose={onClose}
|
||||
wide
|
||||
footer={
|
||||
<>
|
||||
<button className="btn ghost" onClick={onClose}>{tr("common.cancel")}</button>
|
||||
<button className="btn primary" disabled={busy || checked.size === 0} onClick={() => void doImport()}>
|
||||
{busy ? tr("sidebar.importing") : tf("sidebar.importN", { n: checked.size || 0 })}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{items === null && <div className="dlg-hint">{tr("sidebar.scanning")}</div>}
|
||||
{items !== null && items.length === 0 && (
|
||||
<div className="dlg-hint">{tr("sidebar.importEmpty")}</div>
|
||||
)}
|
||||
{items !== null && items.length > 0 && (
|
||||
<div className="imp-list">
|
||||
{items.map((i) => (
|
||||
<label key={i.sessionId} className={`imp-row${i.imported ? " done" : ""}`}>
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={i.imported}
|
||||
checked={checked.has(i.sessionId)}
|
||||
onChange={() => toggle(i.sessionId)}
|
||||
/>
|
||||
<span className="imp-title">{i.title}</span>
|
||||
<span className="imp-meta">
|
||||
{i.provider} · {i.messageCount}{tr("common.messages")} · {relTime(i.updatedAt)}{i.imported ? tr("common.imported") : ""}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Export: the daemon writes to the local Downloads folder and selects it in the file manager (a.download is blocked inside Magpie).
|
||||
async function exportThread(t: ThreadMeta) {
|
||||
try {
|
||||
const r = (await ws.call("thread.exportMarkdown", { id: t.id })) as { markdown: string; filename: string; path?: string };
|
||||
if (r.path) {
|
||||
toast(tf("sidebar.exportSaved", { path: r.path }));
|
||||
return;
|
||||
}
|
||||
const blob = new Blob([r.markdown], { type: "text/markdown;charset=utf-8" });
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = r.filename || `${t.title}.md`;
|
||||
a.style.display = "none";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
setTimeout(() => {
|
||||
URL.revokeObjectURL(a.href);
|
||||
a.remove();
|
||||
}, 5000);
|
||||
} catch (e) {
|
||||
toast(tr("sidebar.failExport") + errMsg(e), true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
// Terminal panel (§8.6 + §7.5): multiple tabs, xterm.js + fit, attach snapshot, resize, kill confirmation.
|
||||
// Binary frames: op 1=output (daemon→here), 2=input, 3=resize.
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { useData } from "../stores/data";
|
||||
import { ws } from "../main";
|
||||
import { Icon } from "./Icons";
|
||||
import { ConfirmDialog } from "./Dialog";
|
||||
import { toast } from "./Toast";
|
||||
import { errMsg, t as tr, tf } from "../i18n/index.js";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import { xtermTheme } from "../terminal/theme";
|
||||
|
||||
type TermInfo = { id: string; index: number; projectId: string; title: string; alive: boolean; simple?: boolean };
|
||||
|
||||
export function TerminalPanel() {
|
||||
const { projects, threads } = useData();
|
||||
const ui = useUi();
|
||||
const thread = threads.find((t) => t.id === ui.currentThreadId) ?? null;
|
||||
const project = thread
|
||||
? projects.find((p) => p.id === thread.projectId)
|
||||
: projects.find((p) => p.id === ui.currentProjectId);
|
||||
const projectId = project?.id ?? null;
|
||||
|
||||
const [terms, setTerms] = useState<TermInfo[]>([]);
|
||||
const [active, setActive] = useState<string | null>(null);
|
||||
const [confirm, setConfirm] = useState<TermInfo | null>(null);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!projectId) { setTerms([]); return; }
|
||||
try {
|
||||
const list = (await ws.call("terminal.list", { projectId })) as TermInfo[];
|
||||
setTerms(list);
|
||||
setActive((a) => (a && list.some((t) => t.id === a) ? a : (list[0]?.id ?? null)));
|
||||
} catch {}
|
||||
}, [projectId]);
|
||||
|
||||
useEffect(() => { void refresh(); }, [refresh]);
|
||||
|
||||
// Terminal exit push
|
||||
useEffect(() => {
|
||||
const unsub = ws.subscribe("terminals", (_ch, d) => {
|
||||
const ev = d as { type?: string; id?: string };
|
||||
if (ev?.type === "terminal.exit") {
|
||||
setTerms((l) => l.filter((t) => t.id !== ev.id));
|
||||
setActive((a) => (a === ev.id ? null : a));
|
||||
}
|
||||
});
|
||||
return unsub;
|
||||
}, []);
|
||||
|
||||
const create = async () => {
|
||||
if (!projectId) return;
|
||||
try {
|
||||
const r = (await ws.call("terminal.create", { projectId, cols: 100, rows: 28 })) as { id: string };
|
||||
await refresh();
|
||||
setActive(r.id);
|
||||
} catch (e) {
|
||||
toast(tr("terminal.failNew") + errMsg(e), true);
|
||||
}
|
||||
};
|
||||
|
||||
const kill = async (term: TermInfo) => {
|
||||
try {
|
||||
await ws.call("terminal.kill", { id: term.id });
|
||||
setTerms((l) => l.filter((x) => x.id !== term.id));
|
||||
setActive((a) => (a === term.id ? null : a));
|
||||
} catch (e) {
|
||||
toast(tr("terminal.failKill") + errMsg(e), true);
|
||||
}
|
||||
};
|
||||
|
||||
if (!project) return <div className="pn-empty">{tr("panel.pickProject")}</div>;
|
||||
|
||||
const activeTerm = terms.find((t) => t.id === active) ?? null;
|
||||
return (
|
||||
<>
|
||||
<div className="tm-tabs">
|
||||
{terms.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
className={`tm-tab${t.id === active ? " on" : ""}`}
|
||||
onClick={() => setActive(t.id)}
|
||||
title={t.title}
|
||||
>
|
||||
{t.title}
|
||||
<span className="tm-x" onClick={(e) => { e.stopPropagation(); setConfirm(t); }}>×</span>
|
||||
</button>
|
||||
))}
|
||||
<button className="ibtn" title={tr("terminal.new")} onClick={() => void create()}><Icon name="plus" size={14} /></button>
|
||||
</div>
|
||||
{activeTerm?.simple && <div className="tm-note">{tr("terminal.simpleNote")}</div>}
|
||||
<div className="tm-body">
|
||||
{terms.length === 0 && (
|
||||
<div className="pn-empty">
|
||||
{tr("terminal.noTerm")}
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<button className="btn primary" onClick={() => void create()}>{tr("terminal.new")}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{terms.map((t) => (
|
||||
<TermView key={t.id} term={t} visible={t.id === active} />
|
||||
))}
|
||||
</div>
|
||||
{confirm && (
|
||||
<ConfirmDialog
|
||||
title={tr("terminal.closeTitle")}
|
||||
body={tf("terminal.closeBody", { title: confirm.title })}
|
||||
okLabel={tr("terminal.closeOk")}
|
||||
danger
|
||||
onOk={() => void kill(confirm)}
|
||||
onClose={() => setConfirm(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function TermView({ term, visible }: { term: TermInfo; visible: boolean }) {
|
||||
const hostRef = useRef<HTMLDivElement | null>(null);
|
||||
const termRef = useRef<Terminal | null>(null);
|
||||
const fitRef = useRef<FitAddon | null>(null);
|
||||
const [attached, setAttached] = useState(false);
|
||||
|
||||
// Mount once: xterm + fit + attach snapshot + output frames + input
|
||||
useEffect(() => {
|
||||
const host = hostRef.current;
|
||||
if (!host) return;
|
||||
const xterm = new Terminal({
|
||||
// Monospace fonts for Windows / macOS / Linux, followed by each platform's Chinese font
|
||||
fontFamily:
|
||||
'"Cascadia Mono", "Cascadia Code", Consolas, "SF Mono", Menlo, Monaco, "DejaVu Sans Mono", "Ubuntu Mono", ' +
|
||||
'"Microsoft YaHei UI", "PingFang SC", "Noto Sans Mono CJK SC", monospace',
|
||||
fontSize: 13,
|
||||
lineHeight: 1.25,
|
||||
cursorBlink: true,
|
||||
scrollback: 5000,
|
||||
allowTransparency: false,
|
||||
theme: xtermTheme(),
|
||||
});
|
||||
const fit = new FitAddon();
|
||||
xterm.loadAddon(fit);
|
||||
xterm.open(host);
|
||||
termRef.current = xterm;
|
||||
fitRef.current = fit;
|
||||
try { fit.fit(); } catch {}
|
||||
|
||||
const dec = new TextDecoder();
|
||||
const enc = new TextEncoder();
|
||||
const offBin = ws.onBinaryFrame((op, index, payload) => {
|
||||
if (index !== term.index || op !== 1) return;
|
||||
xterm.write(dec.decode(payload));
|
||||
});
|
||||
xterm.onData((d) => ws.sendBinary(2, term.index, enc.encode(d)));
|
||||
|
||||
// attach returns the snapshot (and completes the subscription)
|
||||
void (async () => {
|
||||
try {
|
||||
const r = (await ws.call("terminal.attach", { id: term.id })) as {
|
||||
snapshot?: string;
|
||||
windowsPty?: { backend: "conpty"; buildNumber: number };
|
||||
};
|
||||
if (r.windowsPty) xterm.options.windowsPty = r.windowsPty;
|
||||
if (r.snapshot) xterm.write(r.snapshot);
|
||||
setAttached(true);
|
||||
} catch {
|
||||
xterm.writeln(tr("terminal.ended"));
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
offBin();
|
||||
xterm.dispose();
|
||||
termRef.current = null;
|
||||
fitRef.current = null;
|
||||
};
|
||||
}, [term.id, term.index]);
|
||||
|
||||
// Sync xterm colors when switching light/dark theme
|
||||
useEffect(() => {
|
||||
const el = document.documentElement;
|
||||
const sync = () => {
|
||||
const xt = termRef.current;
|
||||
if (xt) xt.options.theme = xtermTheme();
|
||||
};
|
||||
const obs = new MutationObserver(sync);
|
||||
obs.observe(el, { attributes: true, attributeFilter: ["data-theme"] });
|
||||
const mq = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
mq.addEventListener("change", sync);
|
||||
return () => {
|
||||
obs.disconnect();
|
||||
mq.removeEventListener("change", sync);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Visibility/size change → fit + resize frame
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
const fit = fitRef.current;
|
||||
const xterm = termRef.current;
|
||||
if (!fit || !xterm || !attached) return;
|
||||
const t = setTimeout(() => {
|
||||
try {
|
||||
fit.fit();
|
||||
const enc = new TextEncoder();
|
||||
ws.sendBinary(3, term.index, enc.encode(JSON.stringify({ cols: xterm.cols, rows: xterm.rows })));
|
||||
} catch {}
|
||||
}, 50);
|
||||
return () => clearTimeout(t);
|
||||
}, [visible, attached, term.index]);
|
||||
|
||||
// ResizeObserver: fit + resize automatically when the container size changes
|
||||
useEffect(() => {
|
||||
const host = hostRef.current;
|
||||
if (!host) return;
|
||||
const ro = new ResizeObserver(() => {
|
||||
const fit = fitRef.current;
|
||||
const xterm = termRef.current;
|
||||
if (!fit || !xterm || !visible) return;
|
||||
try {
|
||||
fit.fit();
|
||||
const enc = new TextEncoder();
|
||||
ws.sendBinary(3, term.index, enc.encode(JSON.stringify({ cols: xterm.cols, rows: xterm.rows })));
|
||||
} catch {}
|
||||
});
|
||||
ro.observe(host);
|
||||
return () => ro.disconnect();
|
||||
}, [visible, term.index]);
|
||||
|
||||
return <div className="tm-view" ref={hostRef} style={{ display: visible ? "block" : "none" }} />;
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
// Timeline item components (§8.6): user bubble, body, thinking, tool group, plan, todo, permission, question, error, turn end.
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { DisplayItem, ToolStep } from "../timeline/reducer";
|
||||
import { Markdown, copyText } from "./Markdown";
|
||||
import { Reveal } from "../timeline/reveal";
|
||||
import { Icon } from "./Icons";
|
||||
import { ws } from "../main";
|
||||
import { getToken } from "../api/token";
|
||||
import { normalizeHunks } from "../timeline/diffHunks";
|
||||
import { fmtDur, fmtTokens, fmtCost } from "../util/format";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { localizeDaemonMessage, t, tf } from "../i18n/index.js";
|
||||
|
||||
const token = () => getToken();
|
||||
|
||||
export function attachmentUrl(id: string): string {
|
||||
return `/attachments/${id}?t=${token()}`;
|
||||
}
|
||||
|
||||
// ---------- user message ----------
|
||||
export function UserItem({ it, onRetry }: { it: Extract<DisplayItem, { kind: "user" }>; onRetry?: (text: string) => void }) {
|
||||
return (
|
||||
<div className="um-row">
|
||||
<div className="um">
|
||||
{it.attachments?.map((a) => (
|
||||
<img key={a.id} className="um-img" src={`/attachments/${a.id}?t=${token()}`} alt={a.name} />
|
||||
))}
|
||||
<span className="um-text">{it.text}</span>
|
||||
<div className="um-act">
|
||||
<button className="ibtn" title={t("common.copy")} onClick={() => void copyText(it.text)}><Icon name="copy" size={13} /></button>
|
||||
{onRetry && <button className="ibtn" title={t("timeline.editResend")} onClick={() => onRetry(it.text)}><Icon name="send" size={13} /></button>}
|
||||
</div>
|
||||
</div>
|
||||
{it.steered && <div className="um-tag">{t("timeline.steer")}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- body (streaming reveal) ----------
|
||||
export function AssistantItem({ it }: { it: Extract<DisplayItem, { kind: "assistant" }> }) {
|
||||
const [shown, setShown] = useState(it.streaming ? "" : it.text);
|
||||
const reveal = useRef<Reveal | null>(null);
|
||||
useEffect(() => {
|
||||
if (!reveal.current) reveal.current = new Reveal(setShown);
|
||||
reveal.current.push(it.text);
|
||||
if (!it.streaming) reveal.current.flush();
|
||||
}, [it.text, it.streaming]);
|
||||
useEffect(() => () => reveal.current?.stop(), []);
|
||||
return <Markdown text={shown} streaming={it.streaming} />;
|
||||
}
|
||||
|
||||
// ---------- thinking ----------
|
||||
export function ReasoningItem({ it }: { it: Extract<DisplayItem, { kind: "reasoning" }> }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const secs = Math.max(1, Math.round(it.text.length / 40));
|
||||
return (
|
||||
<div className="rs-item">
|
||||
<button className="rs-head" onClick={() => setOpen(!open)}>
|
||||
<span className={`caret${open ? " open" : ""}`}>›</span> {tf("timeline.thinking", { s: secs })}
|
||||
</button>
|
||||
{open && <div className="rs-body">{it.text}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- tool group ----------
|
||||
function toolKind(k: string): string {
|
||||
const key = `timeline.tool.${k}` as const;
|
||||
const v = t(key);
|
||||
return v.startsWith("timeline.tool.") ? t("timeline.tool.other") : v;
|
||||
}
|
||||
|
||||
export function ToolGroupItem({ it }: { it: Extract<DisplayItem, { kind: "toolgroup" }> }) {
|
||||
// Failed steps or steps with a diff are worth seeing directly → auto-expand (never reopened after the user collapses them)
|
||||
const hasFail = it.steps.some((s) => s.status === "failed");
|
||||
const hasDiff = it.steps.some((s) => {
|
||||
const d = s.detail as { hunks?: unknown[]; diff?: { hunks?: unknown[] } } | undefined;
|
||||
const h = d?.hunks ?? d?.diff?.hunks;
|
||||
return Array.isArray(h) && h.length > 0;
|
||||
});
|
||||
const [open, setOpen] = useState(hasFail || hasDiff);
|
||||
const userToggled = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!userToggled.current && (hasFail || hasDiff)) setOpen(true);
|
||||
}, [hasFail, hasDiff]);
|
||||
const summary = useMemo(() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const s of it.steps) counts.set(s.kind, (counts.get(s.kind) ?? 0) + 1);
|
||||
const parts = [...counts.entries()].map(([k, n]) => `${toolKind(k)} ${n}`);
|
||||
return tf("timeline.toolSummary", { n: it.steps.length, parts: parts.join(" · ") });
|
||||
}, [it.steps]);
|
||||
const runningStep = it.steps.find((s) => s.status === "running");
|
||||
return (
|
||||
<div className="tg">
|
||||
<button className="tg-head" onClick={() => { userToggled.current = true; setOpen(!open); }}>
|
||||
<span className={`caret${open ? " open" : ""}`}>›</span>
|
||||
<span>{summary}</span>
|
||||
{runningStep && <span className="tg-live">{tf("timeline.toolRunning", { kind: toolKind(runningStep.kind), title: runningStep.title })}</span>}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="tg-list">
|
||||
{it.steps.map((s) => <ToolStepRow key={s.itemId} s={s} />)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolStepRow({ s }: { s: ToolStep }) {
|
||||
// Failed steps and steps with a diff expand their details by default (the diff is what the user wants to see)
|
||||
const detail = s.detail as { hunks?: unknown[] } | undefined;
|
||||
const [open, setOpen] = useState(s.status === "failed" || (Array.isArray(detail?.hunks) && detail.hunks.length > 0));
|
||||
const icon = s.status === "running" ? "…" : s.status === "ok" ? "✓" : "✗";
|
||||
const cls = s.status === "running" ? "run" : s.status === "ok" ? "ok" : "fail";
|
||||
const hasDetail = s.output || s.detail;
|
||||
return (
|
||||
<div className="ts">
|
||||
<button className="ts-head" onClick={() => hasDetail && setOpen(!open)}>
|
||||
<span className={`ts-ic ${cls}`}>{icon}</span>
|
||||
<span className="ts-title">{s.title}</span>
|
||||
{s.durationMs != null && <span className="ts-meta">{fmtDur(s.durationMs)}</span>}
|
||||
{s.exitCode != null && s.exitCode !== 0 && <span className="ts-meta err">exit {s.exitCode}</span>}
|
||||
</button>
|
||||
{open && <ToolDetail s={s} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolDetail({ s }: { s: ToolStep }) {
|
||||
const [full, setFull] = useState(false);
|
||||
// editDetail outputs {path, hunks, added, removed}; the {diff:{hunks}} shape is also accepted
|
||||
const detail = s.detail as { hunks?: unknown; diff?: { path?: string; hunks?: unknown }; path?: string } | undefined;
|
||||
const rawHunks = detail?.hunks ?? detail?.diff?.hunks;
|
||||
if (rawHunks) {
|
||||
return <DiffView hunks={normalizeHunks(rawHunks)} path={detail?.diff?.path ?? detail?.path} />;
|
||||
}
|
||||
if (s.output != null) {
|
||||
const lines = s.output.split("\n");
|
||||
const tail = lines.length > 50 && !full;
|
||||
const text = tail ? lines.slice(-50).join("\n") : s.output;
|
||||
return (
|
||||
<div className="ts-out">
|
||||
{tail && <button className="ts-more" onClick={() => setFull(true)}>{tf("timeline.showAllLines", { n: lines.length })}</button>}
|
||||
<pre>{text}</pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (s.input != null) {
|
||||
return <pre className="ts-out">{JSON.stringify(s.input, null, 2).slice(0, 4000)}</pre>;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------- line-level diff (unified view) ----------
|
||||
export type DiffHunk = { head?: string; lines: { t: "+" | "-" | " "; text: string }[] };
|
||||
|
||||
export function DiffView({ hunks, path, max = 3000 }: { hunks: DiffHunk[]; path?: string; max?: number }) {
|
||||
let shown = 0;
|
||||
let clipped = false;
|
||||
return (
|
||||
<div className="diff">
|
||||
{path && <div className="diff-path">{path}</div>}
|
||||
<pre className="diff-pre">
|
||||
{hunks.map((h, hi) => (
|
||||
<span key={hi} className="dh">
|
||||
<span className="dh-head">{h.head ?? "@@"}</span>
|
||||
{h.lines.map((l, li) => {
|
||||
shown++;
|
||||
if (shown > max) { clipped = true; return null; }
|
||||
return <span key={li} className={`dl ${l.t === "+" ? "add" : l.t === "-" ? "del" : ""}`}>{l.t} {l.text}{"\n"}</span>;
|
||||
})}
|
||||
</span>
|
||||
))}
|
||||
</pre>
|
||||
{clipped && <div className="dlg-hint">{tf("timeline.diffClip", { n: max })}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- plan ----------
|
||||
export function PlanItem({ it }: { it: Extract<DisplayItem, { kind: "plan" }> }) {
|
||||
return (
|
||||
<div className="card plan">
|
||||
<Markdown text={it.markdown} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- todo ----------
|
||||
export function TodoItem({ it }: { it: Extract<DisplayItem, { kind: "todo" }> }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const done = it.items.filter((i) => i.status === "done" || i.status === "completed").length;
|
||||
return (
|
||||
<div className="rs-item">
|
||||
<button className="rs-head" onClick={() => setOpen(!open)}>
|
||||
<span className={`caret${open ? " open" : ""}`}>›</span> {tf("timeline.todo", { done, total: it.items.length })}
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="todo-list">
|
||||
{it.items.map((i, n) => (
|
||||
<li key={n} className={`todo ${i.status}`}>
|
||||
{i.status === "done" || i.status === "completed" ? "☑" : i.status === "in_progress" ? "◐" : "☐"} {i.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- permission ----------
|
||||
export function PermissionItem({ it, threadId }: { it: Extract<DisplayItem, { kind: "permission" }>; threadId: string }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const respond = (optionId: string) => {
|
||||
setBusy(true);
|
||||
void ws.call("thread.respond", { id: threadId, requestId: it.requestId, optionId }).catch(() => setBusy(false));
|
||||
};
|
||||
const detail = it.detail as { command?: string; path?: string; plan?: string; hunks?: DiffHunk[]; diff?: { path?: string; hunks?: DiffHunk[] } } | undefined;
|
||||
const hunks = detail?.hunks ?? detail?.diff?.hunks;
|
||||
const label = it.status === "resolved"
|
||||
? it.choice === "allow_always" || it.choice === "acceptForSession" ? t("timeline.permAllowSession")
|
||||
: it.choice === "deny" || it.choice === "reject" || it.choice === "decline" ? t("timeline.permDenied")
|
||||
: it.choice === "implement" ? t("timeline.permAllowed") : t("timeline.permAllowed")
|
||||
: t("timeline.permCancelled");
|
||||
return (
|
||||
<div className={`card perm${it.status !== "pending" ? " done" : ""}`}>
|
||||
<div className="perm-title">{it.title}</div>
|
||||
{detail?.command && <pre className="perm-cmd">{detail.command}</pre>}
|
||||
{detail?.path && <div className="perm-path">{detail.path}</div>}
|
||||
{hunks && <DiffView hunks={hunks} path={detail?.diff?.path ?? detail?.path} max={200} />}
|
||||
{it.status === "pending" ? (
|
||||
<div className="perm-btns">
|
||||
{it.options.map((o) => (
|
||||
<button key={o.id} className={`btn ${o.kind === "allow_once" ? "primary" : o.kind === "reject_once" ? "danger" : ""}`}
|
||||
disabled={busy} onClick={() => respond(o.id)}>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="perm-done">{label}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- question ----------
|
||||
export function QuestionItem({ it, threadId }: { it: Extract<DisplayItem, { kind: "question" }>; threadId: string }) {
|
||||
const [free, setFree] = useState<Record<number, string>>({});
|
||||
const [sel, setSel] = useState<Record<number, string>>({});
|
||||
const qs = it.questions as { id?: string; question?: string; header?: string; options?: { label: string; description?: string }[] }[];
|
||||
// answers keys: the question id first (codex/mock schema), then the question text
|
||||
const qkey = (q: (typeof qs)[number], i: number) => q.id ?? q.question ?? q.header ?? `q${i}`;
|
||||
|
||||
const submit = () => {
|
||||
const answers: Record<string, string> = {};
|
||||
qs.forEach((q, i) => {
|
||||
answers[qkey(q, i)] = free[i]?.trim() || sel[i] || "";
|
||||
});
|
||||
void ws.call("thread.respond", { id: threadId, requestId: it.requestId, answers });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`card ask${it.status !== "pending" ? " done" : ""}`}>
|
||||
{qs.map((q, i) => (
|
||||
<div key={i} className="ask-q">
|
||||
<div className="ask-t">{q.header ?? q.question}</div>
|
||||
{it.status === "pending" ? (
|
||||
<>
|
||||
<div className="ask-opts">
|
||||
{q.options?.map((o) => (
|
||||
<button key={o.label} className={`btn${sel[i] === o.label ? " primary" : ""}`}
|
||||
onClick={() => setSel((s) => ({ ...s, [i]: o.label }))}>{o.label}</button>
|
||||
))}
|
||||
</div>
|
||||
<input className="tinput ask-free" placeholder={t("common.other")}
|
||||
value={free[i] ?? ""} onChange={(e) => setFree((f) => ({ ...f, [i]: e.target.value }))} />
|
||||
</>
|
||||
) : (
|
||||
<div className="perm-done">
|
||||
{it.answers ? tf("timeline.submitted", { ans: Object.values(it.answers).join("、") }) : t("timeline.permCancelled")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{it.status === "pending" && <button className="btn primary" onClick={submit}>{t("common.submit")}</button>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- error / turn end ----------
|
||||
export function TurnEndItem({ it, onRetry }: { it: Extract<DisplayItem, { kind: "turnend" }>; onRetry?: () => void }) {
|
||||
const ui = useUi();
|
||||
const [showErr, setShowErr] = useState(false);
|
||||
if (it.status === "failed") {
|
||||
return (
|
||||
<div className="card err-card">
|
||||
<div className="err-line">{tf("timeline.turnError", { err: localizeDaemonMessage(it.error ?? t("timeline.unknownError")) })}</div>
|
||||
<div className="perm-btns">
|
||||
{onRetry && <button className="btn" onClick={onRetry}>{t("common.retry")}</button>}
|
||||
{it.error && it.error.length > 60 && (
|
||||
<button className="btn ghost" onClick={() => setShowErr(!showErr)}>{t("common.details")}</button>
|
||||
)}
|
||||
</div>
|
||||
{showErr && <pre className="perm-cmd">{localizeDaemonMessage(it.error ?? "")}</pre>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const parts: string[] = [];
|
||||
if (it.durationMs != null) parts.push(fmtDur(it.durationMs));
|
||||
if (it.usage) {
|
||||
const tk = it.usage.inputTokens + it.usage.outputTokens;
|
||||
if (tk) parts.push(`${fmtTokens(tk)} tokens`);
|
||||
if (it.usage.costUsd) parts.push(fmtCost(it.usage.costUsd));
|
||||
}
|
||||
if (it.status === "interrupted") parts.push(t("timeline.interrupted"));
|
||||
return (
|
||||
<div className="te">
|
||||
<span>{parts.join(" · ") || it.status}</span>
|
||||
{it.filesChanged != null && it.filesChanged > 0 && (
|
||||
<button className="te-files" onClick={() => ui.openPanel("changes")}>
|
||||
{tf("timeline.filesChanged", { n: it.filesChanged })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- dispatch ----------
|
||||
export function TimelineRow({ it, threadId, onEditResend, onRetryLast }: {
|
||||
it: DisplayItem; threadId: string;
|
||||
onEditResend?: (text: string) => void;
|
||||
onRetryLast?: () => void;
|
||||
}) {
|
||||
switch (it.kind) {
|
||||
case "user": return <UserItem it={it} onRetry={onEditResend} />;
|
||||
case "assistant": return <div className="as"><AssistantItem it={it} /></div>;
|
||||
case "reasoning": return <ReasoningItem it={it} />;
|
||||
case "toolgroup": return <ToolGroupItem it={it} />;
|
||||
case "plan": return <PlanItem it={it} />;
|
||||
case "todo": return <TodoItem it={it} />;
|
||||
case "permission": return <PermissionItem it={it} threadId={threadId} />;
|
||||
case "question": return <QuestionItem it={it} threadId={threadId} />;
|
||||
case "notice": return <div className={`nt ${it.level}`}>{localizeDaemonMessage(it.message)}</div>;
|
||||
case "turnend": return <TurnEndItem it={it} onRetry={onRetryLast} />;
|
||||
case "gone": return null;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Toast notifications (global store + component).
|
||||
import { create } from "zustand";
|
||||
|
||||
type ToastStore = {
|
||||
list: { id: number; text: string; err?: boolean }[];
|
||||
push(text: string, err?: boolean): void;
|
||||
};
|
||||
let nid = 0;
|
||||
export const useToasts = create<ToastStore>((set) => ({
|
||||
list: [],
|
||||
push: (text, err) => {
|
||||
const id = ++nid;
|
||||
set((s) => ({ list: [...s.list, { id, text, err }] }));
|
||||
setTimeout(() => set((s) => ({ list: s.list.filter((t) => t.id !== id) })), 3500);
|
||||
},
|
||||
}));
|
||||
export const toast = (text: string, err = false) => useToasts.getState().push(text, err);
|
||||
|
||||
export function Toasts() {
|
||||
const list = useToasts((s) => s.list);
|
||||
if (list.length === 0) return null;
|
||||
return (
|
||||
<div className="toasts">
|
||||
{list.map((t) => <div key={t.id} className={`toast${t.err ? " err" : ""}`}>{t.text}</div>)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// Top bar (§8.6): breadcrumb, status pill, model name on the right + panel toggle + ⋯.
|
||||
import { useEffect, useState } from "react";
|
||||
import { isImeComposing } from "../composer/ime";
|
||||
import { useData } from "../stores/data";
|
||||
import { useUi, type PanelTab } from "../stores/ui";
|
||||
import { useConnection } from "../stores/connection";
|
||||
import { ws } from "../main";
|
||||
import { Icon } from "./Icons";
|
||||
import { Menu, useMenu, type MenuItem } from "./Menu";
|
||||
import { Dialog } from "./Dialog";
|
||||
import { copyText } from "./Markdown";
|
||||
import { toast } from "./Toast";
|
||||
import { fmtTokens, fmtCost } from "../util/format";
|
||||
import type { Project, ThreadMeta } from "../types/models";
|
||||
import { displayThreadTitle, getIntlLocale, t, tf } from "../i18n/index.js";
|
||||
|
||||
function useNow(running: boolean): number {
|
||||
const [now, setNow] = useState(Date.now());
|
||||
useEffect(() => {
|
||||
if (!running) return;
|
||||
const t0 = setInterval(() => setNow(Date.now()), 1000);
|
||||
return () => clearInterval(t0);
|
||||
}, [running]);
|
||||
return now;
|
||||
}
|
||||
|
||||
export function Topbar({ pendingCount }: { pendingCount: number }) {
|
||||
const { projects, threads } = useData();
|
||||
const ui = useUi();
|
||||
const { version } = useConnection();
|
||||
const [renaming, setRenaming] = useState(false);
|
||||
const [infoOpen, setInfoOpen] = useState(false);
|
||||
const [val, setVal] = useState("");
|
||||
const [menuPos, openMenu, closeMenu] = useMenu();
|
||||
|
||||
const thread = threads.find((t) => t.id === ui.currentThreadId) ?? null;
|
||||
const project = thread ? projects.find((p) => p.id === thread.projectId) : projects.find((p) => p.id === ui.currentProjectId);
|
||||
const running = thread?.status === "running" || thread?.status === "initializing";
|
||||
const now = useNow(running);
|
||||
const elapsed = running && thread ? Math.max(0, now - thread.updatedAt) : 0;
|
||||
|
||||
const pill = thread
|
||||
? pendingCount > 0
|
||||
? { cls: "wait", text: t("topbar.waitAuth") }
|
||||
: running
|
||||
? { cls: "run", text: tf("topbar.running", { s: Math.floor(elapsed / 1000) }) }
|
||||
: thread.status === "error"
|
||||
? { cls: "err", text: t("topbar.error") }
|
||||
: thread.status === "closed"
|
||||
? { cls: "", text: t("topbar.closedResume") }
|
||||
: null
|
||||
: null;
|
||||
|
||||
const panelBtns: { tab: PanelTab; icon: string; title: string }[] = [
|
||||
{ tab: "changes", icon: "changes", title: t("topbar.panelChanges") },
|
||||
{ tab: "files", icon: "files", title: t("topbar.panelFiles") },
|
||||
{ tab: "terminal", icon: "term", title: t("topbar.panelTerminal") },
|
||||
];
|
||||
|
||||
const moreItems: MenuItem[] = thread
|
||||
? [
|
||||
{ kind: "item", label: t("common.rename"), onClick: () => { setVal(thread.title); setRenaming(true); } },
|
||||
{ kind: "item", label: t("topbar.threadInfo"), onClick: () => setInfoOpen(true) },
|
||||
{ kind: "sep" },
|
||||
{ kind: "item", label: t("common.settings"), onClick: () => window.dispatchEvent(new CustomEvent("open-settings")) },
|
||||
{ kind: "label", text: version ? `v${version}` : "" },
|
||||
]
|
||||
: [
|
||||
{ kind: "item", label: t("common.settings"), onClick: () => window.dispatchEvent(new CustomEvent("open-settings")) },
|
||||
{ kind: "label", text: version ? `v${version}` : "" },
|
||||
];
|
||||
|
||||
return (
|
||||
<header className="topbar">
|
||||
<button
|
||||
className="ibtn tb-menu-btn"
|
||||
title={t("topbar.sidebar")}
|
||||
onClick={() => ui.setSbOpen(!ui.sbOpen)}
|
||||
>
|
||||
<Icon name="menu" />
|
||||
</button>
|
||||
{project && <span className="tb-crumb">{project.name}</span>}
|
||||
{project && thread && <span className="tb-sep">/</span>}
|
||||
{thread ? (
|
||||
renaming ? (
|
||||
<input
|
||||
className="tb-rename"
|
||||
autoFocus
|
||||
value={val}
|
||||
onChange={(e) => setVal(e.target.value)}
|
||||
onBlur={() => setRenaming(false)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !isImeComposing(e.nativeEvent) && val.trim()) {
|
||||
void ws.call("threads.update", { id: thread.id, title: val.trim() });
|
||||
setRenaming(false);
|
||||
} else if (e.key === "Escape") setRenaming(false);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span className="tb-title" title={t("topbar.clickRename")} onClick={() => { setVal(thread.title); setRenaming(true); }}>
|
||||
{displayThreadTitle(thread.title, thread.titleAuto)}
|
||||
</span>
|
||||
)
|
||||
) : (
|
||||
<span className="tb-title ghost">{project ? t("topbar.pickThread") : t("app.title")}</span>
|
||||
)}
|
||||
{pill && <span className={`tb-pill ${pill.cls}`}>{pill.text}</span>}
|
||||
<div className="tb-right">
|
||||
{thread?.model && <span className="tb-model">{thread.model}</span>}
|
||||
{panelBtns.map((b) => (
|
||||
<button
|
||||
key={b.tab}
|
||||
className={`ibtn${ui.panelOpen && ui.panelTab === b.tab ? " on" : ""}`}
|
||||
title={b.title}
|
||||
onClick={() => (ui.panelOpen && ui.panelTab === b.tab ? ui.closePanel() : ui.openPanel(b.tab))}
|
||||
>
|
||||
<Icon name={b.icon} />
|
||||
</button>
|
||||
))}
|
||||
<button className="ibtn" title={t("common.more")} onClick={(e) => openMenu(e)}>
|
||||
<Icon name="dots" />
|
||||
</button>
|
||||
</div>
|
||||
{menuPos && <Menu x={menuPos.x} y={menuPos.y} items={moreItems} onClose={closeMenu} />}
|
||||
{infoOpen && thread && <ThreadInfoDialog thread={thread} project={project} onClose={() => setInfoOpen(false)} />}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadInfoDialog({ thread, project, onClose }: { thread: ThreadMeta; project: Project | null | undefined; onClose: () => void }) {
|
||||
const u = thread.usage;
|
||||
const loc = getIntlLocale();
|
||||
const rows: [string, string][] = [
|
||||
[t("thread.agent"), thread.provider],
|
||||
[t("thread.model"), thread.model ?? t("common.default")],
|
||||
[t("thread.mode"), thread.mode],
|
||||
[t("thread.effort"), thread.effort ?? t("common.default")],
|
||||
[t("thread.sessionId"), thread.providerSessionId ?? t("thread.sessionNone")],
|
||||
[t("thread.tokens"), tf("thread.tokensFmt", { in: fmtTokens(u.inputTokens), out: fmtTokens(u.outputTokens), cache: fmtTokens(u.cacheReadTokens) })],
|
||||
[t("thread.cost"), u.costUsd > 0 ? fmtCost(u.costUsd) : "—"],
|
||||
[t("thread.created"), new Date(thread.createdAt).toLocaleString(loc)],
|
||||
[t("thread.workdir"), project?.path ?? "—"],
|
||||
];
|
||||
if (thread.importedFrom) rows.push([t("thread.importedFrom"), `${thread.importedFrom.provider} / ${thread.importedFrom.sessionId.slice(0, 8)}…`]);
|
||||
const copyKeys = new Set([t("thread.sessionId"), t("thread.workdir")]);
|
||||
return (
|
||||
<Dialog title={t("thread.info")} onClose={onClose}>
|
||||
<div className="info-grid">
|
||||
{rows.map(([k, v]) => (
|
||||
<div className="info-row" key={k}>
|
||||
<span className="info-k">{k}</span>
|
||||
<span className="info-v" title={v}>{v}</span>
|
||||
{copyKeys.has(k) && v !== "—" && v !== t("thread.sessionNone") && (
|
||||
<button className="ibtn" title={t("common.copy")} onClick={() => { void copyText(v); toast(t("common.copied")); }}>
|
||||
<Icon name="copy" size={12} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user