agent-console 1.3.8: scrolling up near the bottom leaves it at once, open the project in an IDE, reveal in the file manager (#1108)
Scrolling up near the bottom of the timeline now leaves stick-to-bottom at once. The project can be opened in the first IDE found (Cursor, VS Code, Windsurf, Zed, IntelliJ IDEA, WebStorm, Sublime Text) through argv arrays with shell:false, and a file or folder can be revealed in Explorer, Finder or the file manager. Reveal refuses absolute paths and "..", and checks the target's realpath against the project's real root. By qingnian108. Run at the reviewed head ad88364f4 on Linux (WSL magpie-desktop, Node 22), in a standalone copy of the package: - npm ci; npm run check (daemon + web tsconfig): clean - vitest run: 75 files, 585 passed, 21 skipped - npm run verify:build: app/* and daemon/dist/main.js(.map) match a rebuild from source byte for byte - bun scripts/check.mjs agent-console: ok Broken by hand: with files.reveal's realpath containment check removed, "files.reveal refuses a symlink that resolves outside the project" is red (1 failed, 14 passed); restored, 15/15. Not tried: a real IDE launch or reveal on Windows or macOS (the Windows branches ran only through injected-deps tests), and the scroll change in a real window.
This commit is contained in:
@@ -59,7 +59,9 @@ UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar
|
||||
- **Instant send (1.3)**: your message shows in the timeline the moment you click 发送 and the composer switches to working at once. The daemon saves and pushes the message before it starts the Agent (spawn + ACP `initialize` / `session/new`, seconds on Windows) instead of after; the page draws it right away and swaps in the daemon's copy by a client message id, so it neither doubles nor jumps. A send that fails stays in place marked 发送失败 with 重试 / 移除. A message sent while a turn runs still goes to the queue list
|
||||
- **Steer and queue**: steer while running, queue the next message, interrupt
|
||||
- **Changes panel**: git status refresh every 3s, unified per-file diffs; discarded untracked files go to trash instead of a hard delete
|
||||
- **Files panel**: lazy directory tree (respects `.gitignore`), syntax-highlighted preview
|
||||
- **Files panel**: lazy directory tree (respects `.gitignore`), syntax-highlighted preview. Right-click a file or folder for 在资源管理器中显示 / 在 Finder 中显示 / 在文件管理器中显示 (1.3.8): a file is selected in its folder (`explorer.exe /select,…`, `open -R`; Linux opens its folder with `xdg-open`), a folder is opened. The daemon only does it for a path that still resolves (symlinks followed) inside the project folder, and a failure shows a toast
|
||||
- **Open in IDE (1.3.8)**: the `</>` button at the top right, next to the panel toggles, opens the project folder in the first IDE found: Cursor, VS Code, Windsurf, Zed, IntelliJ IDEA, WebStorm, Sublime Text. Its CLI on PATH comes first; on Windows a `.cmd` launcher starts the `.exe` beside it, and the usual install folders (`%LOCALAPPDATA%\Programs\…`, `%ProgramFiles%\JetBrains\…`) are tried next; on macOS `/Applications/<App>.app` (or `~/Applications`) through `open -a`. Always an argv array, never a shell command line. No IDE, or one that fails to start, shows a toast
|
||||
- **Following the reply (1.3.8)**: the conversation sticks to the bottom while a reply streams. Any real upward scroll (wheel, trackpad, keys, scrollbar) leaves at once, even a few pixels from the bottom; a growing reply, rows being measured or the layout changing never pull it back down. It sticks again when you scroll back down to within 60px of the bottom, reach the very bottom, click 回到底部 or send. 1.3.7 stuck again anywhere within 60px, so a slow trackpad scroll near the bottom was snapped back
|
||||
- **Terminal panel**: real PTY via node-pty (pwsh / powershell); reconnects after reopening the page; degrades if PTY is unavailable
|
||||
- **Images**: attach or paste images (and text files). Only PNG, JPEG, GIF and WebP are sent as images. Claude Code and Codex take them natively; Claude Code gets a text file (up to 1 MB) as a plain-text document, Codex gets its path; any other file (SVG, binaries, images over Claude's 5 MB limit) goes by path, with a notice. An ACP Agent (Cursor, Copilot, OpenCode, Pi, Devin CLI, dsh) gets image blocks when its ACP `initialize` advertises `promptCapabilities.image`; otherwise it gets each image's file path (as text and a `resource_link`), so it can open it with its file tools, and the timeline says it can't see the image itself. The composer says so before you send once the Agent has been asked. dsh answers `initialize` for the route its ACP starts on (its `acp` config row, which ships as a model dsh's catalog doesn't have) and refuses image blocks otherwise, so Agent Console starts dsh with a `--patch` overlay that puts that row on the conversation's model: on a model that sees images (Magpie writes those as `input: [text, image]`) dsh then takes image blocks; after a switch to another model in the same chat, images go by path and dsh opens them with its `read_image` tool. Checked on 2026-10-31 with the real CLIs, a throwaway HOME, no sign-in and a local stand-in for the model API (`npm run test:real`, see `test/real/`): the image reaches the model request from Claude Code 2.1.316 (stream-json), Codex 0.165.0, Copilot 1.0.105 (BYOK), OpenCode 1.19.5, Pi (pi-acp 0.0.34 + pi 1.4.0) and dsh 0.2.1-rc.5; Devin CLI 3000.11.234 and Cursor 2026.10.22 advertise images and Devin gets the image block, but both need a sign-in to run a model. Inline media is capped at 10 MB per file and 16 MB per message (an ACP SDK peer refuses messages over 32 MB); larger images go by path
|
||||
- **Import history**: import matching sessions from `~/.claude/projects` and `~/.codex/sessions` as new threads (resumable)
|
||||
|
||||
File diff suppressed because one or more lines are too long
+332
-78
@@ -181,6 +181,11 @@ var init_i18n = __esm({
|
||||
"err.projectMissing": "\u9879\u76EE\u4E0D\u5B58\u5728",
|
||||
"err.threadMissing": "\u5BF9\u8BDD\u4E0D\u5B58\u5728",
|
||||
"err.dirMissing": "\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u6587\u4EF6\u5939",
|
||||
"err.noIde": "\u6CA1\u6709\u627E\u5230\u53EF\u7528\u7684 IDE\uFF08\u5DF2\u5C1D\u8BD5 Cursor\u3001VS Code\u3001Windsurf\u3001Zed\u3001IntelliJ IDEA\u3001WebStorm\u3001Sublime Text\uFF09",
|
||||
"err.ideFailed": "{ide} \u542F\u52A8\u5931\u8D25\uFF1A{detail}",
|
||||
"err.pathOutside": "\u8DEF\u5F84\u4E0D\u5728\u9879\u76EE\u76EE\u5F55\u5185",
|
||||
"err.targetMissing": "\u6587\u4EF6\u6216\u6587\u4EF6\u5939\u4E0D\u5B58\u5728",
|
||||
"err.revealFailed": "\u65E0\u6CD5\u6253\u5F00\u6587\u4EF6\u7BA1\u7406\u5668\uFF1A{detail}",
|
||||
"err.projectDirGone": "\u9879\u76EE\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",
|
||||
"err.terminalMissing": "\u7EC8\u7AEF\u4E0D\u5B58\u5728",
|
||||
"err.noManager": "\u4F1A\u8BDD\u7BA1\u7406\u5668\u672A\u542F\u52A8",
|
||||
@@ -294,6 +299,11 @@ var init_i18n = __esm({
|
||||
"err.projectMissing": "Project not found",
|
||||
"err.threadMissing": "Conversation not found",
|
||||
"err.dirMissing": "The folder does not exist or is not a folder",
|
||||
"err.noIde": "No IDE found (tried Cursor, VS Code, Windsurf, Zed, IntelliJ IDEA, WebStorm, Sublime Text)",
|
||||
"err.ideFailed": "{ide} failed to start: {detail}",
|
||||
"err.pathOutside": "The path is outside the project folder",
|
||||
"err.targetMissing": "The file or folder does not exist",
|
||||
"err.revealFailed": "Couldn't open the file manager: {detail}",
|
||||
"err.projectDirGone": "The project folder no longer exists",
|
||||
"err.terminalMissing": "Terminal not found",
|
||||
"err.noManager": "The session manager is not running",
|
||||
@@ -1321,8 +1331,8 @@ function extraBinDirs({ platform = process.platform, env = process.env, home = h
|
||||
return dirs;
|
||||
}
|
||||
function searchDirs({ platform = process.platform, env = process.env, home = homedir2(), extra = true } = {}) {
|
||||
const sep5 = platform === "win32" ? ";" : ":";
|
||||
const raw = String(envGet(env, "PATH") ?? "").split(sep5).map((d) => d.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
|
||||
const sep6 = platform === "win32" ? ";" : ":";
|
||||
const raw = String(envGet(env, "PATH") ?? "").split(sep6).map((d) => d.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
|
||||
const all = extra ? [...raw, ...extraBinDirs({ platform, env, home })] : raw;
|
||||
const seen = /* @__PURE__ */ new Set();
|
||||
const out = [];
|
||||
@@ -3011,8 +3021,8 @@ function parseLine(line) {
|
||||
}
|
||||
return { cwd, userText };
|
||||
}
|
||||
async function* linesOf(path4) {
|
||||
const text = await readFile5(path4, "utf8").catch(() => "");
|
||||
async function* linesOf(path5) {
|
||||
const text = await readFile5(path5, "utf8").catch(() => "");
|
||||
for (const line of text.split("\n")) {
|
||||
if (line.trim()) yield line;
|
||||
}
|
||||
@@ -3024,11 +3034,11 @@ async function listClaudeHistory(cwd) {
|
||||
const dirPath = join6(CLAUDE_ROOT, d);
|
||||
const files = (await readdir(dirPath).catch(() => [])).filter((f) => f.endsWith(".jsonl"));
|
||||
for (const f of files) {
|
||||
const path4 = join6(dirPath, f);
|
||||
const path5 = join6(dirPath, f);
|
||||
let match = false;
|
||||
let title = "";
|
||||
let count = 0;
|
||||
for await (const line of linesOf(path4)) {
|
||||
for await (const line of linesOf(path5)) {
|
||||
const p = parseLine(line);
|
||||
if (!p) continue;
|
||||
if (!match) {
|
||||
@@ -3040,7 +3050,7 @@ async function listClaudeHistory(cwd) {
|
||||
if (p.userText) count++;
|
||||
}
|
||||
if (!match) continue;
|
||||
const s = await stat4(path4).catch(() => null);
|
||||
const s = await stat4(path5).catch(() => null);
|
||||
out.push({
|
||||
sessionId: f.replace(/\.jsonl$/, ""),
|
||||
title: title || tr("history.untitled"),
|
||||
@@ -3055,11 +3065,11 @@ async function listClaudeHistory(cwd) {
|
||||
async function readClaudeHistory(sessionId, cwd) {
|
||||
const dirs = await readdir(CLAUDE_ROOT).catch(() => []);
|
||||
for (const d of dirs) {
|
||||
const path4 = join6(CLAUDE_ROOT, d, `${sessionId}.jsonl`);
|
||||
if (!existsSync7(path4)) continue;
|
||||
const path5 = join6(CLAUDE_ROOT, d, `${sessionId}.jsonl`);
|
||||
if (!existsSync7(path5)) continue;
|
||||
const msgs = [];
|
||||
let matched = false;
|
||||
for await (const line of linesOf(path4)) {
|
||||
for await (const line of linesOf(path5)) {
|
||||
const p = parseLine(line);
|
||||
if (!matched) {
|
||||
if (p?.cwd && samePath(p.cwd, cwd)) matched = true;
|
||||
@@ -3217,11 +3227,11 @@ async function* walk(dir, depth = 0) {
|
||||
}
|
||||
async function listCodexHistory(cwd) {
|
||||
const out = [];
|
||||
for await (const path4 of walk(CODEX_ROOT)) {
|
||||
const m = /rollout-.*-([0-9a-f-]{36})\.jsonl$/i.exec(path4);
|
||||
for await (const path5 of walk(CODEX_ROOT)) {
|
||||
const m = /rollout-.*-([0-9a-f-]{36})\.jsonl$/i.exec(path5);
|
||||
const sessionId = m?.[1];
|
||||
if (!sessionId) continue;
|
||||
const text = await readFile6(path4, "utf8").catch(() => "");
|
||||
const text = await readFile6(path5, "utf8").catch(() => "");
|
||||
let match = false;
|
||||
let title = "";
|
||||
let count = 0;
|
||||
@@ -3252,7 +3262,7 @@ async function listCodexHistory(cwd) {
|
||||
}
|
||||
}
|
||||
if (!match) continue;
|
||||
const s = await stat5(path4).catch(() => null);
|
||||
const s = await stat5(path5).catch(() => null);
|
||||
out.push({ sessionId, title: title || tr("history.untitled"), updatedAt: s ? Math.round(s.mtimeMs) : 0, messageCount: count });
|
||||
}
|
||||
out.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
@@ -3812,11 +3822,11 @@ async function readPromptFiles(dir) {
|
||||
}
|
||||
for (const f of names) {
|
||||
if (!f.endsWith(".md")) continue;
|
||||
const path4 = join8(dir, f);
|
||||
const path5 = join8(dir, f);
|
||||
try {
|
||||
const st = await stat6(path4);
|
||||
const st = await stat6(path5);
|
||||
if (!st.isFile()) continue;
|
||||
const raw = await readFile7(path4, "utf8");
|
||||
const raw = await readFile7(path5, "utf8");
|
||||
const { meta, body } = parseFrontMatter(raw);
|
||||
const name = basename3(f, ".md");
|
||||
out.push({
|
||||
@@ -5808,9 +5818,9 @@ import { join as join11 } from "node:path";
|
||||
function magpieTokenFor(agentId) {
|
||||
return `${MAGPIE_GATEWAY_TOKEN}-${agentId}`;
|
||||
}
|
||||
async function readJson(path4) {
|
||||
async function readJson(path5) {
|
||||
try {
|
||||
return JSON.parse(await readFile11(path4, "utf8"));
|
||||
return JSON.parse(await readFile11(path5, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -6522,6 +6532,203 @@ var init_openExternal = __esm({
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/util/osOpen.ts
|
||||
import { spawn as spawn4 } from "node:child_process";
|
||||
import { existsSync as existsSync9, readdirSync as readdirSync2 } from "node:fs";
|
||||
import { homedir as homedir9 } from "node:os";
|
||||
import path4 from "node:path";
|
||||
function envGet3(env, key) {
|
||||
const k = Object.keys(env).find((x) => x.toLowerCase() === key.toLowerCase());
|
||||
return k ? env[k] : void 0;
|
||||
}
|
||||
function exeNearShim(shim, exes, exists) {
|
||||
const P = path4.win32;
|
||||
let dir = P.dirname(shim);
|
||||
for (let up = 0; up < 4; up++) {
|
||||
for (const exe of exes) {
|
||||
const f = P.join(dir, exe);
|
||||
if (exists(f)) return f;
|
||||
}
|
||||
const parent = P.dirname(dir);
|
||||
if (parent === dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function ideLaunchFor(spec, dir, deps = {}) {
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const env = deps.env ?? process.env;
|
||||
const exists = deps.exists ?? existsSync9;
|
||||
const find = deps.find ?? ((n) => findOnPath(n, { platform, env }));
|
||||
const win = platform === "win32";
|
||||
for (const bin of spec.bins) {
|
||||
const hit = find(bin)[0];
|
||||
if (!hit) continue;
|
||||
if (!win) return { cmd: hit, args: [dir] };
|
||||
const ext = path4.win32.extname(hit).toLowerCase();
|
||||
if (ext === ".exe" || ext === ".com") return { cmd: hit, args: [dir] };
|
||||
if (ext === ".cmd" || ext === ".bat") {
|
||||
const exe = exeNearShim(hit, spec.winExe, exists);
|
||||
if (exe) return { cmd: exe, args: [dir] };
|
||||
const r = {
|
||||
ok: true,
|
||||
cmd: deps.comspec ?? envGet3(env, "ComSpec") ?? "cmd.exe",
|
||||
prefixArgs: [],
|
||||
display: hit,
|
||||
via: "cmd-shim",
|
||||
shim: hit
|
||||
};
|
||||
return { ...argvFor(r, [dir]), hide: true };
|
||||
}
|
||||
}
|
||||
if (win) {
|
||||
for (const d of spec.winDirs) {
|
||||
const base = envGet3(env, d.base);
|
||||
if (!base) continue;
|
||||
const f = path4.win32.join(base, d.rel);
|
||||
if (exists(f)) return { cmd: f, args: [dir] };
|
||||
}
|
||||
if (spec.winJetBrains) {
|
||||
const list = deps.list ?? ((p) => {
|
||||
try {
|
||||
return readdirSync2(p);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
for (const key of ["ProgramFiles", "ProgramFiles(x86)"]) {
|
||||
const base = envGet3(env, key);
|
||||
if (!base) continue;
|
||||
const jb = path4.win32.join(base, "JetBrains");
|
||||
const names = list(jb).filter((n) => n.startsWith(spec.winJetBrains.prefix)).sort().reverse();
|
||||
for (const n of names) {
|
||||
const f = path4.win32.join(jb, n, spec.winJetBrains.exe);
|
||||
if (exists(f)) return { cmd: f, args: [dir] };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (platform === "darwin") {
|
||||
const home = deps.home ?? homedir9();
|
||||
for (const app of spec.macApps) {
|
||||
for (const root of ["/Applications", path4.posix.join(home, "Applications")]) {
|
||||
const bundle = path4.posix.join(root, `${app}.app`);
|
||||
if (exists(bundle)) return { cmd: "open", args: ["-a", bundle, dir] };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function detectIde(dir, deps = {}) {
|
||||
for (const spec of IDES) {
|
||||
const launch = ideLaunchFor(spec, dir, deps);
|
||||
if (launch) return { ide: spec.name, launch };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function revealLaunch(platform, target, isDir2) {
|
||||
if (platform === "win32") {
|
||||
const p = path4.win32.normalize(target);
|
||||
return isDir2 ? { cmd: "explorer.exe", args: [p] } : { cmd: "explorer.exe", args: [`/select,"${p}"`], windowsVerbatimArguments: true };
|
||||
}
|
||||
if (platform === "darwin") return isDir2 ? { cmd: "open", args: [target] } : { cmd: "open", args: ["-R", target] };
|
||||
return { cmd: "xdg-open", args: [isDir2 ? target : path4.posix.dirname(target)] };
|
||||
}
|
||||
function launchDetached(l, opts = {}) {
|
||||
const run = opts.spawn ?? spawn4;
|
||||
return new Promise((resolve4) => {
|
||||
let settled = false;
|
||||
const done = (v) => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
resolve4(v);
|
||||
}
|
||||
};
|
||||
let child;
|
||||
try {
|
||||
child = run(l.cmd, l.args, {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: !!l.hide,
|
||||
shell: false,
|
||||
...l.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
||||
});
|
||||
} catch (e) {
|
||||
done({ ok: false, reason: String(e?.message ?? e) });
|
||||
return;
|
||||
}
|
||||
child.once("error", (e) => done({ ok: false, reason: e.message }));
|
||||
child.once("exit", (code) => {
|
||||
if (opts.ignoreExit || code === 0) done({ ok: true });
|
||||
else done({ ok: false, reason: `exit ${code}` });
|
||||
});
|
||||
child.once("spawn", () => {
|
||||
setTimeout(() => done({ ok: true }), opts.graceMs ?? 1500).unref?.();
|
||||
});
|
||||
child.unref();
|
||||
});
|
||||
}
|
||||
var IDES;
|
||||
var init_osOpen = __esm({
|
||||
"daemon/src/util/osOpen.ts"() {
|
||||
init_pathscan();
|
||||
init_bin();
|
||||
IDES = [
|
||||
{
|
||||
name: "Cursor",
|
||||
bins: ["cursor"],
|
||||
winExe: ["Cursor.exe"],
|
||||
winDirs: [{ base: "LOCALAPPDATA", rel: "Programs\\cursor\\Cursor.exe" }, { base: "ProgramFiles", rel: "cursor\\Cursor.exe" }],
|
||||
macApps: ["Cursor"]
|
||||
},
|
||||
{
|
||||
name: "VS Code",
|
||||
bins: ["code"],
|
||||
winExe: ["Code.exe"],
|
||||
winDirs: [{ base: "LOCALAPPDATA", rel: "Programs\\Microsoft VS Code\\Code.exe" }, { base: "ProgramFiles", rel: "Microsoft VS Code\\Code.exe" }],
|
||||
macApps: ["Visual Studio Code"]
|
||||
},
|
||||
{
|
||||
name: "Windsurf",
|
||||
bins: ["windsurf"],
|
||||
winExe: ["Windsurf.exe"],
|
||||
winDirs: [{ base: "LOCALAPPDATA", rel: "Programs\\Windsurf\\Windsurf.exe" }, { base: "ProgramFiles", rel: "Windsurf\\Windsurf.exe" }],
|
||||
macApps: ["Windsurf"]
|
||||
},
|
||||
{
|
||||
name: "Zed",
|
||||
bins: ["zed", "zeditor"],
|
||||
winExe: ["Zed.exe", "zed.exe"],
|
||||
winDirs: [{ base: "LOCALAPPDATA", rel: "Programs\\Zed\\Zed.exe" }, { base: "ProgramFiles", rel: "Zed\\Zed.exe" }],
|
||||
macApps: ["Zed"]
|
||||
},
|
||||
{
|
||||
name: "IntelliJ IDEA",
|
||||
bins: ["idea"],
|
||||
winExe: ["idea64.exe"],
|
||||
winDirs: [],
|
||||
winJetBrains: { prefix: "IntelliJ IDEA", exe: "bin\\idea64.exe" },
|
||||
macApps: ["IntelliJ IDEA", "IntelliJ IDEA Ultimate", "IntelliJ IDEA CE"]
|
||||
},
|
||||
{
|
||||
name: "WebStorm",
|
||||
bins: ["webstorm"],
|
||||
winExe: ["webstorm64.exe"],
|
||||
winDirs: [],
|
||||
winJetBrains: { prefix: "WebStorm", exe: "bin\\webstorm64.exe" },
|
||||
macApps: ["WebStorm"]
|
||||
},
|
||||
{
|
||||
name: "Sublime Text",
|
||||
bins: ["subl"],
|
||||
winExe: ["sublime_text.exe", "subl.exe"],
|
||||
winDirs: [{ base: "ProgramFiles", rel: "Sublime Text\\subl.exe" }, { base: "ProgramFiles", rel: "Sublime Text 3\\subl.exe" }],
|
||||
macApps: ["Sublime Text"]
|
||||
}
|
||||
];
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/preview/inject.ts
|
||||
function injectScriptTag(html) {
|
||||
const tag = `<script src="${PREVIEW_SCRIPT_PATH}"></script>`;
|
||||
@@ -6932,8 +7139,8 @@ var init_proxy = __esm({
|
||||
return;
|
||||
}
|
||||
l.lastUsed = this.now();
|
||||
const path4 = (req.url ?? "/").split("?")[0];
|
||||
if (path4 === PREVIEW_PING_PATH) {
|
||||
const path5 = (req.url ?? "/").split("?")[0];
|
||||
if (path5 === PREVIEW_PING_PATH) {
|
||||
const body = g.role === "canary" ? l.canaryNonce : l.nonce;
|
||||
res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", "access-control-allow-origin": "null", "referrer-policy": "no-referrer" });
|
||||
res.end(req.method === "HEAD" ? void 0 : body);
|
||||
@@ -6948,7 +7155,7 @@ var init_proxy = __esm({
|
||||
this.refuse(res, req, 403, "magpie");
|
||||
return;
|
||||
}
|
||||
if (path4 === PREVIEW_SCRIPT_PATH) {
|
||||
if (path5 === PREVIEW_SCRIPT_PATH) {
|
||||
res.writeHead(200, {
|
||||
"content-type": "text/javascript; charset=utf-8",
|
||||
"cache-control": "no-store",
|
||||
@@ -7185,10 +7392,10 @@ var init_host = __esm({
|
||||
|
||||
// daemon/src/ws/methods.ts
|
||||
import { z } from "zod";
|
||||
import { existsSync as existsSync9, statSync as statSync5 } from "node:fs";
|
||||
import { mkdir as mkdir3, writeFile as writeFile4 } from "node:fs/promises";
|
||||
import { homedir as homedir9 } from "node:os";
|
||||
import { dirname as dirname4, join as join12, win32 as win32Path } from "node:path";
|
||||
import { existsSync as existsSync10, statSync as statSync5 } from "node:fs";
|
||||
import { mkdir as mkdir3, realpath as realpath2, stat as stat10, writeFile as writeFile4 } from "node:fs/promises";
|
||||
import { homedir as homedir10 } from "node:os";
|
||||
import { dirname as dirname4, isAbsolute as isAbsolute4, join as join12, sep as sep3, win32 as win32Path } from "node:path";
|
||||
import { execFile as execFile4 } from "node:child_process";
|
||||
function wrap(schema, fn) {
|
||||
return (params, ctx) => {
|
||||
@@ -7361,7 +7568,7 @@ function registerMethods(gw, svc) {
|
||||
gw.method("projects.open", wrap(z.object({ id: z.string() }), async (p) => {
|
||||
const proj = await svc.projects.get(p.id);
|
||||
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
|
||||
if (!existsSync9(proj.path)) throw new ApiError("bad_path", tr("err.dirMissing"));
|
||||
if (!existsSync10(proj.path)) throw new ApiError("bad_path", tr("err.dirMissing"));
|
||||
const cmd = process.platform === "win32" ? "explorer.exe" : process.platform === "darwin" ? "open" : "xdg-open";
|
||||
const target = process.platform === "win32" ? win32Path.normalize(proj.path) : proj.path;
|
||||
execFile4(cmd, [target], { windowsHide: true }, () => {
|
||||
@@ -7369,11 +7576,28 @@ function registerMethods(gw, svc) {
|
||||
});
|
||||
return { ok: true };
|
||||
}));
|
||||
gw.method("projects.openInIde", wrap(z.object({ id: z.string() }), async (p) => {
|
||||
const proj = await svc.projects.get(p.id);
|
||||
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
|
||||
let dir;
|
||||
try {
|
||||
dir = await realpath2(proj.path);
|
||||
if (!(await stat10(dir)).isDirectory()) throw new Error("not a folder");
|
||||
} catch {
|
||||
throw new ApiError("bad_path", tr("err.dirMissing"));
|
||||
}
|
||||
if (process.platform === "win32") dir = win32Path.normalize(dir);
|
||||
const hit = detectIde(dir);
|
||||
if (!hit) throw new ApiError("no_ide", tr("err.noIde"));
|
||||
const r = await launchDetached(hit.launch);
|
||||
if (!r.ok) throw new ApiError("ide_failed", tr("err.ideFailed", { ide: hit.ide, detail: r.reason }));
|
||||
return { ok: true, ide: hit.ide };
|
||||
}));
|
||||
gw.method("fs.check", wrap(z.object({ path: z.string().min(1) }), (p) => {
|
||||
let exists = false;
|
||||
let isDir2 = false;
|
||||
try {
|
||||
exists = existsSync9(p.path);
|
||||
exists = existsSync10(p.path);
|
||||
isDir2 = exists && statSync5(p.path).isDirectory();
|
||||
} catch {
|
||||
}
|
||||
@@ -7402,7 +7626,7 @@ function registerMethods(gw, svc) {
|
||||
async (p) => {
|
||||
const proj = await svc.projects.get(p.projectId);
|
||||
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
|
||||
if (!existsSync9(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone"));
|
||||
if (!existsSync10(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone"));
|
||||
if (!p.providerSessionId && !isProviderEnabled(await svc.settings.get(), p.provider)) {
|
||||
throw new ApiError("bad_params", tr("provider.disabledNamed", { name: catalogById(p.provider)?.name ?? p.provider }));
|
||||
}
|
||||
@@ -7477,7 +7701,7 @@ function registerMethods(gw, svc) {
|
||||
const projectPath = async (projectId) => {
|
||||
const proj = await svc.projects.get(projectId);
|
||||
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
|
||||
if (!existsSync9(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone"));
|
||||
if (!existsSync10(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone"));
|
||||
return proj.path;
|
||||
};
|
||||
gw.method("git.status", wrap(
|
||||
@@ -7500,6 +7724,35 @@ function registerMethods(gw, svc) {
|
||||
z.object({ projectId: z.string(), path: z.string() }),
|
||||
async (p) => svc.files.read(await projectPath(p.projectId), p.path)
|
||||
));
|
||||
gw.method("files.reveal", wrap(z.object({ projectId: z.string(), path: z.string() }), async (p) => {
|
||||
const proj = await svc.projects.get(p.projectId);
|
||||
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
|
||||
let root;
|
||||
try {
|
||||
root = await realpath2(proj.path);
|
||||
} catch {
|
||||
throw new ApiError("bad_path", tr("err.dirMissing"));
|
||||
}
|
||||
const rel = p.path.replace(/\\/g, "/");
|
||||
if (!rel || isAbsolute4(rel) || win32Path.isAbsolute(rel) || rel.split("/").includes("..")) {
|
||||
throw new ApiError("bad_path", tr("err.pathOutside"));
|
||||
}
|
||||
let target;
|
||||
try {
|
||||
target = await realpath2(join12(root, rel));
|
||||
} catch {
|
||||
throw new ApiError("bad_path", tr("err.targetMissing"));
|
||||
}
|
||||
const fold = (s) => process.platform === "win32" || process.platform === "darwin" ? s.toLowerCase() : s;
|
||||
const rootSep = root.endsWith(sep3) ? root : root + sep3;
|
||||
if (fold(target) !== fold(root) && !fold(target).startsWith(fold(rootSep))) {
|
||||
throw new ApiError("bad_path", tr("err.pathOutside"));
|
||||
}
|
||||
const isDir2 = (await stat10(target)).isDirectory();
|
||||
const r = await launchDetached(revealLaunch(process.platform, target, isDir2), { ignoreExit: process.platform === "win32" });
|
||||
if (!r.ok) throw new ApiError("reveal_failed", tr("err.revealFailed", { detail: r.reason }));
|
||||
return { ok: true };
|
||||
}));
|
||||
gw.method("history.list", wrap(z.object({ projectId: z.string() }), async (p) => {
|
||||
const proj = await svc.projects.get(p.projectId);
|
||||
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
|
||||
@@ -7558,8 +7811,8 @@ function registerMethods(gw, svc) {
|
||||
gw.method("terminal.create", wrap(
|
||||
z.object({ projectId: z.string(), cols: z.number().int().min(20).max(500).default(80), rows: z.number().int().min(5).max(200).default(24) }),
|
||||
async (p) => {
|
||||
const path4 = await projectPath(p.projectId);
|
||||
const r = await svc.terminals.create(p.projectId, path4, p.cols, p.rows);
|
||||
const path5 = await projectPath(p.projectId);
|
||||
const r = await svc.terminals.create(p.projectId, path5, p.cols, p.rows);
|
||||
if ("error" in r) throw new ApiError("bad_params", r.error);
|
||||
return r;
|
||||
}
|
||||
@@ -7709,7 +7962,7 @@ ${e.text}
|
||||
const markdown = L.join("\n");
|
||||
const safe = meta.title.replace(/[\\/:*?"<>|\s]+/g, "_").slice(0, 60) || "thread";
|
||||
const filename = `${safe}.md`;
|
||||
let dir = join12(homedir9(), "Downloads");
|
||||
let dir = join12(homedir10(), "Downloads");
|
||||
try {
|
||||
await mkdir3(dir, { recursive: true });
|
||||
} catch {
|
||||
@@ -7717,7 +7970,7 @@ ${e.text}
|
||||
await mkdir3(dir, { recursive: true });
|
||||
}
|
||||
let dest = join12(dir, filename);
|
||||
if (existsSync9(dest)) {
|
||||
if (existsSync10(dest)) {
|
||||
const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
||||
dest = join12(dir, `${safe}-${stamp2}.md`);
|
||||
}
|
||||
@@ -7759,6 +8012,7 @@ var init_methods = __esm({
|
||||
init_i18n();
|
||||
init_mentions();
|
||||
init_openExternal();
|
||||
init_osOpen();
|
||||
init_agentShell();
|
||||
init_gitBash();
|
||||
init_proxy();
|
||||
@@ -7963,7 +8217,7 @@ __export(legacy_exports, {
|
||||
migrateLegacy: () => migrateLegacy
|
||||
});
|
||||
import { cp as cp2, mkdir as mkdir8, readdir as readdir6, readFile as readFile18 } from "node:fs/promises";
|
||||
import { existsSync as existsSync13 } from "node:fs";
|
||||
import { existsSync as existsSync14 } from "node:fs";
|
||||
import { join as join20 } from "node:path";
|
||||
function stamp() {
|
||||
const d = /* @__PURE__ */ new Date();
|
||||
@@ -7975,17 +8229,17 @@ async function migrateLegacy(dataDir, stores) {
|
||||
if (settings.v1Migrated) return { migrated: 0, skipped: true };
|
||||
const oldDir = join20(dataDir, "sessions");
|
||||
const oldSettingsPath = join20(dataDir, "settings.json");
|
||||
if (!existsSync13(oldDir) && !existsSync13(oldSettingsPath)) {
|
||||
if (!existsSync14(oldDir) && !existsSync14(oldSettingsPath)) {
|
||||
await stores.settings.set({ v1Migrated: true });
|
||||
return { migrated: 0, skipped: true };
|
||||
}
|
||||
const backup = join20(dataDir, "trash", `legacy-${stamp()}`);
|
||||
await mkdir8(backup, { recursive: true });
|
||||
if (existsSync13(oldDir)) await cp2(oldDir, join20(backup, "sessions"), { recursive: true }).catch(() => {
|
||||
if (existsSync14(oldDir)) await cp2(oldDir, join20(backup, "sessions"), { recursive: true }).catch(() => {
|
||||
});
|
||||
if (existsSync13(oldSettingsPath)) await cp2(oldSettingsPath, join20(backup, "settings.json")).catch(() => {
|
||||
if (existsSync14(oldSettingsPath)) await cp2(oldSettingsPath, join20(backup, "settings.json")).catch(() => {
|
||||
});
|
||||
const oldSettings = existsSync13(oldSettingsPath) ? JSON.parse(await readFile18(oldSettingsPath, "utf8").catch(() => "{}")) : {};
|
||||
const oldSettings = existsSync14(oldSettingsPath) ? JSON.parse(await readFile18(oldSettingsPath, "utf8").catch(() => "{}")) : {};
|
||||
const projectIdByPath = /* @__PURE__ */ new Map();
|
||||
const lc = (p) => p.replace(/\\/g, "/").toLowerCase().replace(/\/+$/, "");
|
||||
for (const p of oldSettings.projects ?? []) {
|
||||
@@ -7999,7 +8253,7 @@ async function migrateLegacy(dataDir, stores) {
|
||||
}
|
||||
let sessionIds = [];
|
||||
try {
|
||||
sessionIds = (await readdir6(oldDir)).filter((d) => validId(d) && existsSync13(join20(oldDir, d, "meta.json")));
|
||||
sessionIds = (await readdir6(oldDir)).filter((d) => validId(d) && existsSync14(join20(oldDir, d, "meta.json")));
|
||||
} catch {
|
||||
}
|
||||
const metas = [];
|
||||
@@ -8019,7 +8273,7 @@ async function migrateLegacy(dataDir, stores) {
|
||||
extraDirs.push(m.cwd);
|
||||
}
|
||||
for (const d of extraDirs) {
|
||||
if (!existsSync13(d)) continue;
|
||||
if (!existsSync14(d)) continue;
|
||||
try {
|
||||
const name = d.replace(/\\/g, "/").split("/").filter(Boolean).pop() ?? d;
|
||||
const proj = await stores.projects.create(d, name);
|
||||
@@ -8076,7 +8330,7 @@ async function migrateLegacy(dataDir, stores) {
|
||||
seq: 0
|
||||
};
|
||||
const tdir = join20(threadsDir, meta.id);
|
||||
if (existsSync13(tdir)) meta.id = `t_${m.id}_v1`.slice(0, 80);
|
||||
if (existsSync14(tdir)) meta.id = `t_${m.id}_v1`.slice(0, 80);
|
||||
await mkdir8(join20(threadsDir, meta.id), { recursive: true });
|
||||
const oldEvts = (await readFile18(join20(oldDir, m.id, "events.jsonl"), "utf8").catch(() => "")).split("\n").filter((l) => l.trim()).map((l) => {
|
||||
try {
|
||||
@@ -8586,7 +8840,7 @@ init_atomic();
|
||||
init_paths();
|
||||
init_methods();
|
||||
import { readFile as readFile13 } from "node:fs/promises";
|
||||
import { existsSync as existsSync10, statSync as statSync6 } from "node:fs";
|
||||
import { existsSync as existsSync11, statSync as statSync6 } from "node:fs";
|
||||
import { join as join14 } from "node:path";
|
||||
import { randomBytes as randomBytes4 } from "node:crypto";
|
||||
function newId() {
|
||||
@@ -8619,19 +8873,19 @@ var ProjectsStore = class {
|
||||
this.writing = this.writing.then(() => writeJsonAtomic(this.file, snap));
|
||||
await this.writing;
|
||||
}
|
||||
async create(path4, name) {
|
||||
if (!path4 || typeof path4 !== "string") throw new ApiError("bad_params", "\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A");
|
||||
if (!existsSync10(path4) || !statSync6(path4).isDirectory()) {
|
||||
async create(path5, name) {
|
||||
if (!path5 || typeof path5 !== "string") throw new ApiError("bad_params", "\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A");
|
||||
if (!existsSync11(path5) || !statSync6(path5).isDirectory()) {
|
||||
throw new ApiError("bad_path", "\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u6587\u4EF6\u5939");
|
||||
}
|
||||
const np = normPath(path4);
|
||||
const np = normPath(path5);
|
||||
const list = await this.list();
|
||||
const dup = list.find((p) => normPath(p.path) === np);
|
||||
if (dup) return dup;
|
||||
const proj = {
|
||||
id: newId(),
|
||||
name: name?.trim() || path4.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path4,
|
||||
path: path4,
|
||||
name: name?.trim() || path5.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path5,
|
||||
path: path5,
|
||||
createdAt: Date.now()
|
||||
};
|
||||
list.push(proj);
|
||||
@@ -9934,9 +10188,9 @@ var AgentManager = class {
|
||||
init_i18n();
|
||||
init_decode();
|
||||
import { execFile as execFile5 } from "node:child_process";
|
||||
import { existsSync as existsSync11 } from "node:fs";
|
||||
import { cp, mkdir as mkdir7, readFile as readFile16, rename as rename4, rm, stat as stat11 } from "node:fs/promises";
|
||||
import { join as join16, normalize as normalize2, sep as sep3 } from "node:path";
|
||||
import { existsSync as existsSync12 } from "node:fs";
|
||||
import { cp, mkdir as mkdir7, readFile as readFile16, rename as rename4, rm, stat as stat12 } from "node:fs/promises";
|
||||
import { join as join16, normalize as normalize2, sep as sep4 } from "node:path";
|
||||
var TIMEOUT2 = 15e3;
|
||||
var DIFF_LIMIT = 1024 * 1024;
|
||||
function runGit(cwd, args) {
|
||||
@@ -9953,7 +10207,7 @@ function insidePath(projectPath, p) {
|
||||
const rel = normalize2(p).replace(/\\/g, "/");
|
||||
const abs = normalize2(join16(projectPath, rel));
|
||||
const proj = normalize2(projectPath);
|
||||
if (abs !== proj && !abs.startsWith(proj + sep3)) return null;
|
||||
if (abs !== proj && !abs.startsWith(proj + sep4)) return null;
|
||||
return rel.replace(/\\/g, "/");
|
||||
}
|
||||
async function moveAcrossDevices(from, to, ops = {}) {
|
||||
@@ -9982,7 +10236,7 @@ var GitService = class {
|
||||
if (!rec5 || rec5.length < 4) continue;
|
||||
const index = rec5[0];
|
||||
const worktree = rec5[1];
|
||||
let path4 = rec5.slice(3);
|
||||
let path5 = rec5.slice(3);
|
||||
let kind = "modified";
|
||||
if (index === "?" && worktree === "?") kind = "untracked";
|
||||
else if (index === "R" || worktree === "R") {
|
||||
@@ -9990,7 +10244,7 @@ var GitService = class {
|
||||
i++;
|
||||
} else if (index === "A" || worktree === "A") kind = "added";
|
||||
else if (index === "D" || worktree === "D") kind = "deleted";
|
||||
files.push({ path: path4, index, worktree, kind });
|
||||
files.push({ path: path5, index, worktree, kind });
|
||||
}
|
||||
return { isRepo: true, branch: br.out.trim() || void 0, files };
|
||||
}
|
||||
@@ -10001,8 +10255,8 @@ var GitService = class {
|
||||
const ls = await runGit(projectPath, ["ls-files", "--error-unmatch", "--", rel]);
|
||||
if (ls.code !== 0) {
|
||||
const full = join16(projectPath, rel);
|
||||
if (!existsSync11(full)) return { error: tr("fs.fileMissing") };
|
||||
const s = await stat11(full);
|
||||
if (!existsSync12(full)) return { error: tr("fs.fileMissing") };
|
||||
const s = await stat12(full);
|
||||
if (!s.isFile()) return { error: tr("fs.notFile") };
|
||||
if (s.size > DIFF_LIMIT) return { tooLarge: true };
|
||||
const text = await readFile16(full, "utf8").catch(() => null);
|
||||
@@ -10035,7 +10289,7 @@ ${lines}` };
|
||||
return { ok: true };
|
||||
}
|
||||
const full = join16(projectPath, rel);
|
||||
if (!existsSync11(full)) return { ok: false, error: tr("fs.fileMissing") };
|
||||
if (!existsSync12(full)) return { ok: false, error: tr("fs.fileMissing") };
|
||||
const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
||||
const dest = join16(dataDir, "trash", "discarded", stamp2, rel);
|
||||
await mkdir7(join16(dest, ".."), { recursive: true });
|
||||
@@ -10050,8 +10304,8 @@ ${lines}` };
|
||||
|
||||
// daemon/src/files/service.ts
|
||||
init_i18n();
|
||||
import { readdir as readdir5, readFile as readFile17, stat as stat12 } from "node:fs/promises";
|
||||
import { join as join17, normalize as normalize3, sep as sep4, extname as extname3 } from "node:path";
|
||||
import { readdir as readdir5, readFile as readFile17, stat as stat13 } from "node:fs/promises";
|
||||
import { join as join17, normalize as normalize3, sep as sep5, extname as extname3 } from "node:path";
|
||||
import ignore from "ignore";
|
||||
function decodeText(buf) {
|
||||
try {
|
||||
@@ -10116,7 +10370,7 @@ function insidePath2(projectPath, p) {
|
||||
const rel = normalize3(p || ".").replace(/\\/g, "/");
|
||||
const abs = normalize3(join17(projectPath, rel));
|
||||
const proj = normalize3(projectPath);
|
||||
if (abs !== proj && !abs.startsWith(proj + sep4)) return null;
|
||||
if (abs !== proj && !abs.startsWith(proj + sep5)) return null;
|
||||
return rel;
|
||||
}
|
||||
var FileService = class {
|
||||
@@ -10125,7 +10379,7 @@ var FileService = class {
|
||||
igCache = /* @__PURE__ */ new Map();
|
||||
async igFor(projectPath) {
|
||||
const gi = join17(projectPath, ".gitignore");
|
||||
const st = await stat12(gi).catch(() => null);
|
||||
const st = await stat13(gi).catch(() => null);
|
||||
const mtime = st?.isFile() ? st.mtimeMs : -1;
|
||||
const hit = this.igCache.get(projectPath);
|
||||
if (hit && hit.mtime === mtime) return hit.ig;
|
||||
@@ -10144,7 +10398,7 @@ var FileService = class {
|
||||
const rel = insidePath2(projectPath, dir);
|
||||
if (rel === null) return { error: tr("fs.pathDenied") };
|
||||
const abs = join17(projectPath, rel);
|
||||
const s = await stat12(abs).catch(() => null);
|
||||
const s = await stat13(abs).catch(() => null);
|
||||
if (!s?.isDirectory()) return { error: tr("fs.dirMissing") };
|
||||
const ig = await this.igFor(projectPath);
|
||||
const dirents = await readdir5(abs, { withFileTypes: true }).catch(() => null);
|
||||
@@ -10157,7 +10411,7 @@ var FileService = class {
|
||||
const childRel = rel === "." ? name : `${rel}/${name}`;
|
||||
let isDir2 = d.isDirectory();
|
||||
if (d.isSymbolicLink()) {
|
||||
const st = await stat12(join17(projectPath, childRel)).catch(() => null);
|
||||
const st = await stat13(join17(projectPath, childRel)).catch(() => null);
|
||||
if (!st) continue;
|
||||
isDir2 = st.isDirectory();
|
||||
} else if (!d.isFile() && !isDir2) {
|
||||
@@ -10175,7 +10429,7 @@ var FileService = class {
|
||||
const rel = insidePath2(projectPath, p);
|
||||
if (rel === null) return { error: tr("fs.pathDenied") };
|
||||
const abs = join17(projectPath, rel);
|
||||
const s = await stat12(abs).catch(() => null);
|
||||
const s = await stat13(abs).catch(() => null);
|
||||
if (!s) return { error: tr("fs.fileMissing") };
|
||||
if (!s.isFile()) return { error: tr("fs.notFile") };
|
||||
if (s.size > MAX_READ) return { tooLarge: true };
|
||||
@@ -10193,8 +10447,8 @@ init_pathscan();
|
||||
init_log();
|
||||
init_i18n();
|
||||
init_decode();
|
||||
import { spawn as spawn4, execFileSync as execFileSync2 } from "node:child_process";
|
||||
import { accessSync as accessSync2, chmodSync, constants as fsc, existsSync as existsSync12, statSync as statSync7 } from "node:fs";
|
||||
import { spawn as spawn5, execFileSync as execFileSync2 } from "node:child_process";
|
||||
import { accessSync as accessSync2, chmodSync, constants as fsc, existsSync as existsSync13, statSync as statSync7 } from "node:fs";
|
||||
import { createRequire as moduleRequire } from "node:module";
|
||||
import { release } from "node:os";
|
||||
import { dirname as dirname7, join as join18 } from "node:path";
|
||||
@@ -10243,7 +10497,7 @@ function fixSpawnHelper() {
|
||||
const root = dirname7(req.resolve("node-pty/package.json"));
|
||||
for (const sub of [`prebuilds/darwin-${process.arch}`, "build/Release"]) {
|
||||
const f = join18(root, sub, "spawn-helper");
|
||||
if (existsSync12(f) && !isExecFile(f)) {
|
||||
if (existsSync13(f) && !isExecFile(f)) {
|
||||
chmodSync(f, 493);
|
||||
log("info", "\u5DF2\u4FEE\u590D node-pty spawn-helper \u7684\u53EF\u6267\u884C\u4F4D", { file: f });
|
||||
}
|
||||
@@ -10321,7 +10575,7 @@ var TerminalService = class {
|
||||
if (!term.pty) {
|
||||
term.simple = true;
|
||||
const args = simpleShellArgs(shell);
|
||||
const proc = spawn4(shell, args, {
|
||||
const proc = spawn5(shell, args, {
|
||||
cwd,
|
||||
stdio: "pipe",
|
||||
windowsHide: true,
|
||||
@@ -10389,7 +10643,7 @@ var TerminalService = class {
|
||||
const args = ["/pid", String(pid), "/T", "/F"];
|
||||
try {
|
||||
if (sync) execFileSync2("taskkill", args, { windowsHide: true, stdio: "ignore", timeout: 5e3 });
|
||||
else spawn4("taskkill", args, { windowsHide: true, stdio: "ignore" }).on("error", () => {
|
||||
else spawn5("taskkill", args, { windowsHide: true, stdio: "ignore" }).on("error", () => {
|
||||
});
|
||||
} catch {
|
||||
}
|
||||
@@ -10475,9 +10729,9 @@ function pidAlive(pid, kill = (p, s) => process.kill(p, s)) {
|
||||
}
|
||||
function augmentPath(env, nodeDir, platform = process.platform, home) {
|
||||
const win = platform === "win32";
|
||||
const sep5 = win ? ";" : platform === process.platform ? delimiter : ":";
|
||||
const sep6 = win ? ";" : platform === process.platform ? delimiter : ":";
|
||||
const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
|
||||
const cur = (env[key] ?? "").split(sep5).filter(Boolean);
|
||||
const cur = (env[key] ?? "").split(sep6).filter(Boolean);
|
||||
const norm2 = (d) => win ? d.replace(/[\\/]+$/, "").toLowerCase() : d.replace(/\/+$/, "");
|
||||
const seen = new Set(cur.map(norm2));
|
||||
const out = [...cur];
|
||||
@@ -10486,7 +10740,7 @@ function augmentPath(env, nodeDir, platform = process.platform, home) {
|
||||
seen.add(norm2(d));
|
||||
out.push(d);
|
||||
}
|
||||
return out.join(sep5);
|
||||
return out.join(sep6);
|
||||
}
|
||||
|
||||
// daemon/src/main.ts
|
||||
@@ -10494,8 +10748,8 @@ init_proxy();
|
||||
|
||||
// daemon/src/preview/ports.ts
|
||||
import { readFileSync as readFileSync2 } from "node:fs";
|
||||
import { homedir as homedir10 } from "node:os";
|
||||
import { basename as basename5, dirname as dirname8, isAbsolute as isAbsolute4, join as join19 } from "node:path";
|
||||
import { homedir as homedir11 } from "node:os";
|
||||
import { basename as basename5, dirname as dirname8, isAbsolute as isAbsolute5, join as join19 } from "node:path";
|
||||
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
||||
var MAGPIE_DEFAULT_PORTS = [3425, 3430];
|
||||
var GATE_DEFAULT_PORT = 3488;
|
||||
@@ -10514,7 +10768,7 @@ function magpieDirFromInstall(p) {
|
||||
function magpieConfigDirs(env = process.env, where = {}) {
|
||||
const out = [];
|
||||
const add = (d) => {
|
||||
if (d && isAbsolute4(d) && !out.includes(d)) out.push(d);
|
||||
if (d && isAbsolute5(d) && !out.includes(d)) out.push(d);
|
||||
};
|
||||
let self = where.self;
|
||||
if (self === void 0) {
|
||||
@@ -10528,9 +10782,9 @@ function magpieConfigDirs(env = process.env, where = {}) {
|
||||
const cwd = where.cwd ?? (env === process.env ? process.cwd() : "");
|
||||
if (cwd && basename5(cwd) === "plugin-work") add(dirname8(cwd));
|
||||
const x = env.XDG_CONFIG_HOME;
|
||||
if (x && isAbsolute4(x)) add(join19(x, "magpie"));
|
||||
if (x && isAbsolute5(x)) add(join19(x, "magpie"));
|
||||
const platform = where.platform ?? process.platform;
|
||||
const home = where.home ?? (env === process.env ? homedir10() : platform === "win32" ? env.USERPROFILE : env.HOME);
|
||||
const home = where.home ?? (env === process.env ? homedir11() : platform === "win32" ? env.USERPROFILE : env.HOME);
|
||||
if (home) add(join19(home, ".config", "magpie"));
|
||||
return out;
|
||||
}
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -63,6 +63,11 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"err.projectMissing": "项目不存在",
|
||||
"err.threadMissing": "对话不存在",
|
||||
"err.dirMissing": "目录不存在或不是文件夹",
|
||||
"err.noIde": "没有找到可用的 IDE(已尝试 Cursor、VS Code、Windsurf、Zed、IntelliJ IDEA、WebStorm、Sublime Text)",
|
||||
"err.ideFailed": "{ide} 启动失败:{detail}",
|
||||
"err.pathOutside": "路径不在项目目录内",
|
||||
"err.targetMissing": "文件或文件夹不存在",
|
||||
"err.revealFailed": "无法打开文件管理器:{detail}",
|
||||
"err.projectDirGone": "项目目录已不存在",
|
||||
"err.terminalMissing": "终端不存在",
|
||||
"err.noManager": "会话管理器未启动",
|
||||
@@ -176,6 +181,11 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"err.projectMissing": "Project not found",
|
||||
"err.threadMissing": "Conversation not found",
|
||||
"err.dirMissing": "The folder does not exist or is not a folder",
|
||||
"err.noIde": "No IDE found (tried Cursor, VS Code, Windsurf, Zed, IntelliJ IDEA, WebStorm, Sublime Text)",
|
||||
"err.ideFailed": "{ide} failed to start: {detail}",
|
||||
"err.pathOutside": "The path is outside the project folder",
|
||||
"err.targetMissing": "The file or folder does not exist",
|
||||
"err.revealFailed": "Couldn't open the file manager: {detail}",
|
||||
"err.projectDirGone": "The project folder no longer exists",
|
||||
"err.terminalMissing": "Terminal not found",
|
||||
"err.noManager": "The session manager is not running",
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// 1.3.8 (issue #3): open the project in a local IDE, and reveal a file / folder in the system file manager.
|
||||
//
|
||||
// Every launch is argv-array only, never a shell string: spawn(cmd, args) with shell:false (the same no-shell rule as
|
||||
// execFile; spawn is used because an IDE's GUI process keeps running and must be detached, not waited on).
|
||||
// The one exception is a Windows .cmd/.bat IDE launcher with no GUI .exe beside it: that goes through cmd.exe with
|
||||
// bin.ts's argvFor escaping (the same path the Agent CLIs' .cmd shims take), each argument quoted and ^-escaped.
|
||||
import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process";
|
||||
import { existsSync, readdirSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { findOnPath } from "../../../lib/pathscan.mjs";
|
||||
import { argvFor, type ResolveResult } from "./bin.js";
|
||||
|
||||
export type IdeSpec = {
|
||||
/** shown in the toast / returned as `ide` */
|
||||
name: string;
|
||||
/** CLI names on PATH, in order */
|
||||
bins: string[];
|
||||
/** Windows: GUI exe names that may sit next to (or a few folders above) a .cmd launcher */
|
||||
winExe: string[];
|
||||
/** Windows: install folders relative to %LOCALAPPDATA% / %ProgramFiles% (exe paths) */
|
||||
winDirs: { base: "LOCALAPPDATA" | "ProgramFiles" | "ProgramFiles(x86)"; rel: string }[];
|
||||
/** Windows: JetBrains-style versioned folders under %ProgramFiles%\JetBrains (prefix, exe relative to it) */
|
||||
winJetBrains?: { prefix: string; exe: string };
|
||||
/** macOS: app bundle names tried under /Applications and ~/Applications */
|
||||
macApps: string[];
|
||||
};
|
||||
|
||||
/** Detection order (issue #3) */
|
||||
export const IDES: IdeSpec[] = [
|
||||
{
|
||||
name: "Cursor", bins: ["cursor"], winExe: ["Cursor.exe"],
|
||||
winDirs: [{ base: "LOCALAPPDATA", rel: "Programs\\cursor\\Cursor.exe" }, { base: "ProgramFiles", rel: "cursor\\Cursor.exe" }],
|
||||
macApps: ["Cursor"],
|
||||
},
|
||||
{
|
||||
name: "VS Code", bins: ["code"], winExe: ["Code.exe"],
|
||||
winDirs: [{ base: "LOCALAPPDATA", rel: "Programs\\Microsoft VS Code\\Code.exe" }, { base: "ProgramFiles", rel: "Microsoft VS Code\\Code.exe" }],
|
||||
macApps: ["Visual Studio Code"],
|
||||
},
|
||||
{
|
||||
name: "Windsurf", bins: ["windsurf"], winExe: ["Windsurf.exe"],
|
||||
winDirs: [{ base: "LOCALAPPDATA", rel: "Programs\\Windsurf\\Windsurf.exe" }, { base: "ProgramFiles", rel: "Windsurf\\Windsurf.exe" }],
|
||||
macApps: ["Windsurf"],
|
||||
},
|
||||
{
|
||||
name: "Zed", bins: ["zed", "zeditor"], winExe: ["Zed.exe", "zed.exe"],
|
||||
winDirs: [{ base: "LOCALAPPDATA", rel: "Programs\\Zed\\Zed.exe" }, { base: "ProgramFiles", rel: "Zed\\Zed.exe" }],
|
||||
macApps: ["Zed"],
|
||||
},
|
||||
{
|
||||
name: "IntelliJ IDEA", bins: ["idea"], winExe: ["idea64.exe"],
|
||||
winDirs: [],
|
||||
winJetBrains: { prefix: "IntelliJ IDEA", exe: "bin\\idea64.exe" },
|
||||
macApps: ["IntelliJ IDEA", "IntelliJ IDEA Ultimate", "IntelliJ IDEA CE"],
|
||||
},
|
||||
{
|
||||
name: "WebStorm", bins: ["webstorm"], winExe: ["webstorm64.exe"],
|
||||
winDirs: [],
|
||||
winJetBrains: { prefix: "WebStorm", exe: "bin\\webstorm64.exe" },
|
||||
macApps: ["WebStorm"],
|
||||
},
|
||||
{
|
||||
name: "Sublime Text", bins: ["subl"], winExe: ["sublime_text.exe", "subl.exe"],
|
||||
winDirs: [{ base: "ProgramFiles", rel: "Sublime Text\\subl.exe" }, { base: "ProgramFiles", rel: "Sublime Text 3\\subl.exe" }],
|
||||
macApps: ["Sublime Text"],
|
||||
},
|
||||
];
|
||||
|
||||
export type Launch = {
|
||||
cmd: string;
|
||||
args: string[];
|
||||
windowsVerbatimArguments?: boolean;
|
||||
/** Windows: hide the console window (only for the cmd.exe launcher; a GUI exe must keep its window shown) */
|
||||
hide?: boolean;
|
||||
};
|
||||
export type IdeHit = { ide: string; launch: Launch };
|
||||
|
||||
export type OsDeps = {
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
home?: string;
|
||||
find?: (name: string) => string[];
|
||||
exists?: (p: string) => boolean;
|
||||
/** folder names inside a folder ([] when unreadable) */
|
||||
list?: (dir: string) => string[];
|
||||
comspec?: string;
|
||||
};
|
||||
|
||||
function envGet(env: NodeJS.ProcessEnv, key: string): string | undefined {
|
||||
const k = Object.keys(env).find((x) => x.toLowerCase() === key.toLowerCase());
|
||||
return k ? env[k] : undefined;
|
||||
}
|
||||
|
||||
/** Windows: a .cmd launcher (VS Code's bin\code.cmd, Cursor's resources\app\bin\cursor.cmd) → the GUI exe it wraps */
|
||||
function exeNearShim(shim: string, exes: string[], exists: (p: string) => boolean): string | null {
|
||||
const P = path.win32;
|
||||
let dir = P.dirname(shim);
|
||||
for (let up = 0; up < 4; up++) {
|
||||
for (const exe of exes) {
|
||||
const f = P.join(dir, exe);
|
||||
if (exists(f)) return f;
|
||||
}
|
||||
const parent = P.dirname(dir);
|
||||
if (parent === dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** How to start `spec` on `dir` on this machine, or null if it isn't installed */
|
||||
export function ideLaunchFor(spec: IdeSpec, dir: string, deps: OsDeps = {}): Launch | null {
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const env = deps.env ?? process.env;
|
||||
const exists = deps.exists ?? existsSync;
|
||||
const find = deps.find ?? ((n: string) => findOnPath(n, { platform, env }) as string[]);
|
||||
const win = platform === "win32";
|
||||
for (const bin of spec.bins) {
|
||||
const hit = find(bin)[0];
|
||||
if (!hit) continue;
|
||||
if (!win) return { cmd: hit, args: [dir] };
|
||||
const ext = path.win32.extname(hit).toLowerCase();
|
||||
if (ext === ".exe" || ext === ".com") return { cmd: hit, args: [dir] };
|
||||
if (ext === ".cmd" || ext === ".bat") {
|
||||
const exe = exeNearShim(hit, spec.winExe, exists);
|
||||
if (exe) return { cmd: exe, args: [dir] };
|
||||
// no GUI exe beside it: cmd.exe /d /s /c with every argument quoted and ^-escaped (bin.ts argvFor)
|
||||
const r: ResolveResult & { ok: true } = {
|
||||
ok: true, cmd: deps.comspec ?? envGet(env, "ComSpec") ?? "cmd.exe", prefixArgs: [], display: hit, via: "cmd-shim", shim: hit,
|
||||
};
|
||||
return { ...argvFor(r, [dir]), hide: true };
|
||||
}
|
||||
// .ps1 or anything else: skip it, the install folders below may still have the exe
|
||||
}
|
||||
if (win) {
|
||||
for (const d of spec.winDirs) {
|
||||
const base = envGet(env, d.base);
|
||||
if (!base) continue;
|
||||
const f = path.win32.join(base, d.rel);
|
||||
if (exists(f)) return { cmd: f, args: [dir] };
|
||||
}
|
||||
if (spec.winJetBrains) {
|
||||
const list = deps.list ?? ((p: string) => { try { return readdirSync(p); } catch { return []; } });
|
||||
for (const key of ["ProgramFiles", "ProgramFiles(x86)"]) {
|
||||
const base = envGet(env, key);
|
||||
if (!base) continue;
|
||||
const jb = path.win32.join(base, "JetBrains");
|
||||
const names = list(jb).filter((n) => n.startsWith(spec.winJetBrains!.prefix)).sort().reverse();
|
||||
for (const n of names) {
|
||||
const f = path.win32.join(jb, n, spec.winJetBrains.exe);
|
||||
if (exists(f)) return { cmd: f, args: [dir] };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (platform === "darwin") {
|
||||
const home = deps.home ?? homedir();
|
||||
for (const app of spec.macApps) {
|
||||
for (const root of ["/Applications", path.posix.join(home, "Applications")]) {
|
||||
const bundle = path.posix.join(root, `${app}.app`);
|
||||
if (exists(bundle)) return { cmd: "open", args: ["-a", bundle, dir] };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The first installed IDE in IDES order */
|
||||
export function detectIde(dir: string, deps: OsDeps = {}): IdeHit | null {
|
||||
for (const spec of IDES) {
|
||||
const launch = ideLaunchFor(spec, dir, deps);
|
||||
if (launch) return { ide: spec.name, launch };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** File manager command for a target inside the project: a file is selected in its folder, a folder is opened */
|
||||
export function revealLaunch(platform: NodeJS.Platform, target: string, isDir: boolean): Launch {
|
||||
if (platform === "win32") {
|
||||
const p = path.win32.normalize(target);
|
||||
// explorer.exe parses /select,"<path>" itself (Node would quote the whole "/select,<path>" token); a Windows
|
||||
// path can't contain a double quote, so the quoting can't be broken out of
|
||||
return isDir ? { cmd: "explorer.exe", args: [p] } : { cmd: "explorer.exe", args: [`/select,"${p}"`], windowsVerbatimArguments: true };
|
||||
}
|
||||
if (platform === "darwin") return isDir ? { cmd: "open", args: [target] } : { cmd: "open", args: ["-R", target] };
|
||||
return { cmd: "xdg-open", args: [isDir ? target : path.posix.dirname(target)] };
|
||||
}
|
||||
|
||||
export type SpawnLike = (cmd: string, args: string[], opts: SpawnOptions) => Pick<ChildProcess, "once" | "unref">;
|
||||
|
||||
/**
|
||||
* Start a detached process. ok once it has spawned and either exited 0 or is still running after `graceMs`;
|
||||
* a spawn error (not installed) or a quick non-zero exit is a failure. `ignoreExit`: explorer.exe exits 1 on success.
|
||||
*/
|
||||
export function launchDetached(
|
||||
l: Launch,
|
||||
opts: { spawn?: SpawnLike; graceMs?: number; ignoreExit?: boolean } = {},
|
||||
): Promise<{ ok: true } | { ok: false; reason: string }> {
|
||||
const run = opts.spawn ?? (spawn as unknown as SpawnLike);
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const done = (v: { ok: true } | { ok: false; reason: string }) => { if (!settled) { settled = true; resolve(v); } };
|
||||
let child: Pick<ChildProcess, "once" | "unref">;
|
||||
try {
|
||||
child = run(l.cmd, l.args, {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: !!l.hide,
|
||||
shell: false,
|
||||
...(l.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
||||
});
|
||||
} catch (e) {
|
||||
done({ ok: false, reason: String((e as Error)?.message ?? e) });
|
||||
return;
|
||||
}
|
||||
child.once("error", (e: Error) => done({ ok: false, reason: e.message }));
|
||||
child.once("exit", (code: number | null) => {
|
||||
if (opts.ignoreExit || code === 0) done({ ok: true });
|
||||
else done({ ok: false, reason: `exit ${code}` });
|
||||
});
|
||||
child.once("spawn", () => {
|
||||
setTimeout(() => done({ ok: true }), opts.graceMs ?? 1500).unref?.();
|
||||
});
|
||||
child.unref();
|
||||
});
|
||||
}
|
||||
@@ -14,9 +14,9 @@ import { GitService } from "../git/service.js";
|
||||
import { FileService } from "../files/service.js";
|
||||
import type { TerminalService } from "../terminal/service.js";
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { mkdir, realpath, stat, writeFile } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, win32 as win32Path } from "node:path";
|
||||
import { dirname, isAbsolute, join, sep, win32 as win32Path } from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { pickFolder } from "../util/pickFolder.js";
|
||||
import { clearBinCache } from "../util/bin.js";
|
||||
@@ -27,6 +27,7 @@ import { endLegacyDefault, guardLegacyMode, upgradeNotice } from "../migrate/aut
|
||||
import { setAppLocale, tr, intlLocale } from "../util/i18n.js";
|
||||
import { MAX_MENTIONS } from "../util/mentions.js";
|
||||
import { openExternal } from "../util/openExternal.js";
|
||||
import { detectIde, launchDetached, revealLaunch } from "../util/osOpen.js";
|
||||
import { agentShellStatus, refreshAgentShell } from "../util/agentShell.js";
|
||||
import { checkBashPath, GIT_FOR_WINDOWS_URL } from "../util/gitBash.js";
|
||||
import { PreviewError, type PreviewProxy } from "../preview/proxy.js";
|
||||
@@ -288,6 +289,26 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
return { ok: true };
|
||||
}));
|
||||
|
||||
// 1.3.8 (issue #3): open the project folder in the first IDE found (Cursor, VS Code, Windsurf, Zed, IntelliJ IDEA,
|
||||
// WebStorm, Sublime Text); argv arrays only (util/osOpen.ts)
|
||||
gw.method("projects.openInIde", wrap(z.object({ id: z.string() }), async (p) => {
|
||||
const proj = await svc.projects.get(p.id);
|
||||
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
|
||||
let dir: string;
|
||||
try {
|
||||
dir = await realpath(proj.path);
|
||||
if (!(await stat(dir)).isDirectory()) throw new Error("not a folder");
|
||||
} catch {
|
||||
throw new ApiError("bad_path", tr("err.dirMissing"));
|
||||
}
|
||||
if (process.platform === "win32") dir = win32Path.normalize(dir);
|
||||
const hit = detectIde(dir);
|
||||
if (!hit) throw new ApiError("no_ide", tr("err.noIde"));
|
||||
const r = await launchDetached(hit.launch);
|
||||
if (!r.ok) throw new ApiError("ide_failed", tr("err.ideFailed", { ide: hit.ide, detail: r.reason }));
|
||||
return { ok: true, ide: hit.ide };
|
||||
}));
|
||||
|
||||
// ---- fs.* ----
|
||||
gw.method("fs.check", wrap(z.object({ path: z.string().min(1) }), (p) => {
|
||||
let exists = false;
|
||||
@@ -436,6 +457,38 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
svc.files.read(await projectPath(p.projectId), p.path)
|
||||
));
|
||||
|
||||
// 1.3.8 (issue #3): show a file (selected in its folder) or a folder in Explorer / Finder / the file manager.
|
||||
// The target must resolve (symlinks followed) inside the project's real root.
|
||||
gw.method("files.reveal", wrap(z.object({ projectId: z.string(), path: z.string() }), async (p) => {
|
||||
const proj = await svc.projects.get(p.projectId);
|
||||
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
|
||||
let root: string;
|
||||
try {
|
||||
root = await realpath(proj.path);
|
||||
} catch {
|
||||
throw new ApiError("bad_path", tr("err.dirMissing"));
|
||||
}
|
||||
const rel = p.path.replace(/\\/g, "/");
|
||||
if (!rel || isAbsolute(rel) || win32Path.isAbsolute(rel) || rel.split("/").includes("..")) {
|
||||
throw new ApiError("bad_path", tr("err.pathOutside"));
|
||||
}
|
||||
let target: string;
|
||||
try {
|
||||
target = await realpath(join(root, rel));
|
||||
} catch {
|
||||
throw new ApiError("bad_path", tr("err.targetMissing"));
|
||||
}
|
||||
const fold = (s: string) => (process.platform === "win32" || process.platform === "darwin" ? s.toLowerCase() : s);
|
||||
const rootSep = root.endsWith(sep) ? root : root + sep;
|
||||
if (fold(target) !== fold(root) && !fold(target).startsWith(fold(rootSep))) {
|
||||
throw new ApiError("bad_path", tr("err.pathOutside"));
|
||||
}
|
||||
const isDir = (await stat(target)).isDirectory();
|
||||
const r = await launchDetached(revealLaunch(process.platform, target, isDir), { ignoreExit: process.platform === "win32" });
|
||||
if (!r.ok) throw new ApiError("reveal_failed", tr("err.revealFailed", { detail: r.reason }));
|
||||
return { ok: true };
|
||||
}));
|
||||
|
||||
// ---- history.* (§7.6) ----
|
||||
gw.method("history.list", wrap(z.object({ projectId: z.string() }), async (p) => {
|
||||
const proj = await svc.projects.get(p.projectId);
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.7",
|
||||
"version": "1.3.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.7",
|
||||
"version": "1.3.8",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.1.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.7",
|
||||
"version": "1.3.8",
|
||||
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
|
||||
"author": "qingnian108 (https://github.com/qingnian108)",
|
||||
"homepage": "https://github.com/qingnian108/magpie-agent-console",
|
||||
|
||||
@@ -198,11 +198,46 @@ describe.skipIf(!browserPath)("Chat virtual-list scroll to bottom in real Chromi
|
||||
expect(mStream.scrollHeight).toBeGreaterThan(prevHeight + 1000);
|
||||
expect(mStream.gap).toBeLessThanOrEqual(2);
|
||||
expect(mStream.jumpVisible).toBe(false);
|
||||
|
||||
// 1.3.8 (issue #2): during a slow stream, a few small wheel steps up near the bottom leave it at once and
|
||||
// stay left while the reply keeps growing; wheeling back down sticks again
|
||||
await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2);
|
||||
for (let i = 0; i < 4; i++) { await page.mouse.wheel(0, -5); await page.waitForTimeout(60); }
|
||||
await page.waitForTimeout(300);
|
||||
const mIdle = await readMetrics();
|
||||
expect(mIdle.gap).toBeGreaterThanOrEqual(15); // 1.3.7 snapped this back to 0 (within 60px → re-stuck)
|
||||
expect(mIdle.gap).toBeLessThan(60);
|
||||
expect(mIdle.jumpVisible).toBe(true);
|
||||
await page.locator(".cp-ta").fill("/bigreply slow");
|
||||
await page.keyboard.press("Enter");
|
||||
// the first /bigreply already has a 第 2 部分: wait for the new reply's
|
||||
await page.waitForFunction(() => document.body.innerText.split("第 2 部分").length - 1 >= 2, null, { timeout: 15000, polling: 50 });
|
||||
await page.waitForTimeout(150);
|
||||
await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2);
|
||||
for (let i = 0; i < 4; i++) { await page.mouse.wheel(0, -5); await page.waitForTimeout(40); }
|
||||
await page.waitForTimeout(150);
|
||||
const mSmall = await readMetrics();
|
||||
expect(mSmall.gap).toBeGreaterThanOrEqual(15);
|
||||
expect(mSmall.jumpVisible).toBe(true);
|
||||
await page.waitForTimeout(900); // several more parts arrive
|
||||
const mGrown = await readMetrics();
|
||||
expect(mGrown.scrollHeight).toBeGreaterThan(mSmall.scrollHeight);
|
||||
expect(mGrown.scrollTop).toBeLessThanOrEqual(mSmall.scrollTop + 1);
|
||||
expect(mGrown.gap).toBeGreaterThan(mSmall.gap);
|
||||
expect(mGrown.jumpVisible).toBe(true);
|
||||
await page.mouse.wheel(0, 20000);
|
||||
await page.waitForTimeout(400);
|
||||
// still stuck: it follows the rest of the stream down to the real bottom (wait for the new reply's last part)
|
||||
await page.waitForFunction(() => document.body.innerText.split("第 14 部分").length - 1 >= 2, null, { timeout: 15000, polling: 50 });
|
||||
await page.waitForTimeout(600);
|
||||
const mBack = await readMetrics();
|
||||
expect(mBack.gap).toBeLessThanOrEqual(2);
|
||||
expect(mBack.jumpVisible).toBe(false);
|
||||
} finally {
|
||||
await browser.close();
|
||||
daemon.kill("SIGTERM");
|
||||
rmSync(xdg, { recursive: true, force: true });
|
||||
rmSync(projDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 45000);
|
||||
}, 60000);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
// 1.3.8 (issue #3): open the project in an IDE, reveal a file / folder in the file manager.
|
||||
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from "vitest";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync, realpathSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { IDES, type Launch } from "../../daemon/src/util/osOpen.js";
|
||||
|
||||
const launched: Launch[] = [];
|
||||
let ideFound = true;
|
||||
vi.mock("../../daemon/src/util/osOpen.js", async (orig) => {
|
||||
const real = await orig<typeof import("../../daemon/src/util/osOpen.js")>();
|
||||
return {
|
||||
...real,
|
||||
detectIde: (dir: string) => (ideFound ? { ide: "Cursor", launch: { cmd: "/fake/cursor", args: [dir] } } : null),
|
||||
launchDetached: async (l: Launch) => {
|
||||
launched.push(l);
|
||||
return l.cmd === "/fake/broken" ? { ok: false, reason: "exit 1" } : { ok: true };
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// detectIde / launchDetached are faked for the RPC tests below; the real ones are tested through importActual
|
||||
const real = await vi.importActual<typeof import("../../daemon/src/util/osOpen.js")>("../../daemon/src/util/osOpen.js");
|
||||
|
||||
describe("IDE detection (osOpen.ts)", () => {
|
||||
const set = (files: string[]) => (p: string) => files.includes(p);
|
||||
|
||||
it("tries Cursor, VS Code, Windsurf, Zed, IntelliJ IDEA, WebStorm, Sublime Text in that order", () => {
|
||||
expect(IDES.map((i) => i.name)).toEqual(["Cursor", "VS Code", "Windsurf", "Zed", "IntelliJ IDEA", "WebStorm", "Sublime Text"]);
|
||||
const onPath: Record<string, string> = { code: "/usr/bin/code", subl: "/usr/bin/subl" };
|
||||
const hit = real.detectIde("/p/my proj", { platform: "linux", env: {}, find: (n) => (onPath[n] ? [onPath[n]] : []), exists: () => false });
|
||||
expect(hit).toEqual({ ide: "VS Code", launch: { cmd: "/usr/bin/code", args: ["/p/my proj"] } });
|
||||
});
|
||||
|
||||
it("nothing installed → null", () => {
|
||||
expect(real.detectIde("/p", { platform: "linux", env: {}, find: () => [], exists: () => false })).toBeNull();
|
||||
expect(real.detectIde("/p", { platform: "darwin", env: {}, home: "/Users/u", find: () => [], exists: () => false })).toBeNull();
|
||||
});
|
||||
|
||||
it("macOS: no CLI on PATH → /Applications/<App>.app via open -a (path stays one argv entry)", () => {
|
||||
const hit = real.detectIde("/Users/u/a b;$(rm -rf ~)", {
|
||||
platform: "darwin", env: {}, home: "/Users/u", find: () => [],
|
||||
exists: set(["/Users/u/Applications/Visual Studio Code.app"]),
|
||||
});
|
||||
expect(hit).toEqual({ ide: "VS Code", launch: { cmd: "open", args: ["-a", "/Users/u/Applications/Visual Studio Code.app", "/Users/u/a b;$(rm -rf ~)"] } });
|
||||
});
|
||||
|
||||
it("Windows: a .cmd launcher on PATH starts the GUI exe beside it, not cmd.exe", () => {
|
||||
const cursorCmd = "C:\\Users\\u\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd";
|
||||
const l = real.ideLaunchFor(IDES[0], "D:\\work\\proj & calc", {
|
||||
platform: "win32", env: {}, find: (n) => (n === "cursor" ? [cursorCmd] : []),
|
||||
exists: set(["C:\\Users\\u\\AppData\\Local\\Programs\\cursor\\Cursor.exe"]),
|
||||
});
|
||||
expect(l).toEqual({ cmd: "C:\\Users\\u\\AppData\\Local\\Programs\\cursor\\Cursor.exe", args: ["D:\\work\\proj & calc"] });
|
||||
});
|
||||
|
||||
it("Windows: a .cmd with no exe beside it goes through cmd.exe with quoted, ^-escaped arguments", () => {
|
||||
const l = real.ideLaunchFor(IDES[1], "D:\\a&b%PATH%", {
|
||||
platform: "win32", env: { ComSpec: "C:\\Windows\\system32\\cmd.exe" }, find: (n) => (n === "code" ? ["C:\\tools\\code.cmd"] : []),
|
||||
exists: () => false,
|
||||
})!;
|
||||
expect(l.cmd).toBe("C:\\Windows\\system32\\cmd.exe");
|
||||
expect(l.windowsVerbatimArguments).toBe(true);
|
||||
expect(l.hide).toBe(true);
|
||||
expect(l.args.slice(0, 3)).toEqual(["/d", "/s", "/c"]);
|
||||
// bin.ts argvFor (cross-spawn rules): quoted, every metacharacter ^-escaped twice (the .cmd parses it again),
|
||||
// so & and % can't start a second command or expand
|
||||
expect(l.args[3]).toBe('"C:\\tools\\code.cmd ^^^"D:\\a^^^&b^^^%PATH^^^%^^^""');
|
||||
});
|
||||
|
||||
it("Windows: not on PATH → %LOCALAPPDATA% install folder; JetBrains versioned folders under Program Files", () => {
|
||||
const env = { LOCALAPPDATA: "C:\\Users\\u\\AppData\\Local", ProgramFiles: "C:\\Program Files" };
|
||||
expect(real.detectIde("D:\\p", { platform: "win32", env, find: () => [], exists: set(["C:\\Users\\u\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"]) }))
|
||||
.toEqual({ ide: "VS Code", launch: { cmd: "C:\\Users\\u\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe", args: ["D:\\p"] } });
|
||||
const hit = real.detectIde("D:\\p", {
|
||||
platform: "win32", env, find: () => [],
|
||||
list: (d) => (d === "C:\\Program Files\\JetBrains" ? ["IntelliJ IDEA 2025.2", "IntelliJ IDEA 2026.1", "WebStorm 2026.1"] : []),
|
||||
exists: set(["C:\\Program Files\\JetBrains\\IntelliJ IDEA 2026.1\\bin\\idea64.exe", "C:\\Program Files\\JetBrains\\WebStorm 2026.1\\bin\\webstorm64.exe"]),
|
||||
});
|
||||
expect(hit).toEqual({ ide: "IntelliJ IDEA", launch: { cmd: "C:\\Program Files\\JetBrains\\IntelliJ IDEA 2026.1\\bin\\idea64.exe", args: ["D:\\p"] } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("reveal commands (osOpen.ts)", () => {
|
||||
it("Windows selects a file with /select,\"…\" and opens a folder", () => {
|
||||
expect(real.revealLaunch("win32", "D:/proj/src/a b.ts", false)).toEqual({ cmd: "explorer.exe", args: ['/select,"D:\\proj\\src\\a b.ts"'], windowsVerbatimArguments: true });
|
||||
expect(real.revealLaunch("win32", "D:\\proj\\src", true)).toEqual({ cmd: "explorer.exe", args: ["D:\\proj\\src"] });
|
||||
});
|
||||
it("macOS open -R a file, open a folder; Linux xdg-open the folder", () => {
|
||||
expect(real.revealLaunch("darwin", "/p/a.ts", false)).toEqual({ cmd: "open", args: ["-R", "/p/a.ts"] });
|
||||
expect(real.revealLaunch("darwin", "/p/src", true)).toEqual({ cmd: "open", args: ["/p/src"] });
|
||||
expect(real.revealLaunch("linux", "/p/src/a.ts", false)).toEqual({ cmd: "xdg-open", args: ["/p/src"] });
|
||||
expect(real.revealLaunch("linux", "/p/src", true)).toEqual({ cmd: "xdg-open", args: ["/p/src"] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("launchDetached", () => {
|
||||
const fakeSpawn = (behave: (c: EventEmitter) => void) => {
|
||||
const calls: { cmd: string; args: string[]; opts: Record<string, unknown> }[] = [];
|
||||
const fn = (cmd: string, args: string[], opts: Record<string, unknown>) => {
|
||||
calls.push({ cmd, args, opts });
|
||||
const c = new EventEmitter() as EventEmitter & { unref(): void };
|
||||
c.unref = () => {};
|
||||
setTimeout(() => behave(c), 1);
|
||||
return c;
|
||||
};
|
||||
return { fn, calls };
|
||||
};
|
||||
|
||||
it("no shell, detached; ok when still running after the grace period", async () => {
|
||||
const s = fakeSpawn((c) => c.emit("spawn"));
|
||||
const r = await real.launchDetached({ cmd: "/x/code", args: ["/p"] }, { spawn: s.fn as never, graceMs: 20 });
|
||||
expect(r).toEqual({ ok: true });
|
||||
expect(s.calls[0].opts).toMatchObject({ shell: false, detached: true, stdio: "ignore", windowsHide: false });
|
||||
});
|
||||
it("spawn error / quick non-zero exit → failure; explorer's exit 1 is ignored with ignoreExit", async () => {
|
||||
expect(await real.launchDetached({ cmd: "nope", args: [] }, { spawn: fakeSpawn((c) => c.emit("error", new Error("spawn nope ENOENT"))).fn as never }))
|
||||
.toEqual({ ok: false, reason: "spawn nope ENOENT" });
|
||||
expect(await real.launchDetached({ cmd: "x", args: [] }, { spawn: fakeSpawn((c) => { c.emit("spawn"); c.emit("exit", 2); }).fn as never, graceMs: 50 }))
|
||||
.toEqual({ ok: false, reason: "exit 2" });
|
||||
expect(await real.launchDetached({ cmd: "explorer.exe", args: [] }, { spawn: fakeSpawn((c) => { c.emit("spawn"); c.emit("exit", 1); }).fn as never, ignoreExit: true, graceMs: 50 }))
|
||||
.toEqual({ ok: true });
|
||||
});
|
||||
});
|
||||
|
||||
// ---- the RPCs, through registerMethods (the gateway itself, hello auth included, is covered by ws.test.ts) ----
|
||||
describe("projects.openInIde / files.reveal RPCs", () => {
|
||||
let dir = "";
|
||||
let proj = "";
|
||||
let outside = "";
|
||||
const handlers = new Map<string, (p: unknown, ctx: unknown) => unknown>();
|
||||
let projectId = "";
|
||||
let missingId = "";
|
||||
|
||||
beforeAll(async () => {
|
||||
const { registerMethods } = await import("../../daemon/src/ws/methods.js");
|
||||
const { SettingsStore } = await import("../../daemon/src/store/settings.js");
|
||||
const { ProjectsStore } = await import("../../daemon/src/store/projects.js");
|
||||
const { ThreadsStore } = await import("../../daemon/src/store/threads.js");
|
||||
const { GitService } = await import("../../daemon/src/git/service.js");
|
||||
const { FileService } = await import("../../daemon/src/files/service.js");
|
||||
dir = mkdtempSync(join(tmpdir(), "ac-osopen-"));
|
||||
proj = join(dir, "proj");
|
||||
outside = join(dir, "outside");
|
||||
mkdirSync(join(proj, "src"), { recursive: true });
|
||||
mkdirSync(outside);
|
||||
writeFileSync(join(proj, "src", "a.ts"), "x");
|
||||
writeFileSync(join(outside, "secret.txt"), "s");
|
||||
if (process.platform !== "win32") symlinkSync(outside, join(proj, "link-out"));
|
||||
const gw = { method: (n: string, fn: (p: unknown, ctx: unknown) => unknown) => handlers.set(n, fn), publish: () => {} };
|
||||
const projects = new ProjectsStore(dir);
|
||||
const cfg = { port: 0, dataDir: dir, token: "t", version: "9.9.9", idleExitMinutes: 60, buildStamp: "0" };
|
||||
registerMethods(gw as never, { cfg, settings: new SettingsStore(dir), gateway: gw as never, projects, threads: new ThreadsStore(dir), git: new GitService(), files: new FileService(), terminals: {} as never });
|
||||
projectId = (await projects.create(proj, "p")).id;
|
||||
const gone = join(dir, "gone");
|
||||
mkdirSync(gone);
|
||||
missingId = (await projects.create(gone, "gone")).id;
|
||||
rmSync(gone, { recursive: true });
|
||||
});
|
||||
afterAll(() => rmSync(dir, { recursive: true, force: true }));
|
||||
beforeEach(() => { launched.length = 0; ideFound = true; });
|
||||
|
||||
const call = async (m: string, p: unknown) => {
|
||||
try { return { r: await handlers.get(m)!(p, {}) }; } catch (e) { return { code: (e as { code?: string }).code, message: (e as Error).message }; }
|
||||
};
|
||||
|
||||
it("openInIde returns the IDE's name and launches it on the project's real folder", async () => {
|
||||
expect(await call("projects.openInIde", { id: projectId })).toEqual({ r: { ok: true, ide: "Cursor" } });
|
||||
expect(launched[0]).toEqual({ cmd: "/fake/cursor", args: [realpathSync(proj)] });
|
||||
});
|
||||
it("openInIde errors: no_ide, bad_path (folder gone), not_found", async () => {
|
||||
ideFound = false;
|
||||
expect((await call("projects.openInIde", { id: projectId })).code).toBe("no_ide");
|
||||
ideFound = true;
|
||||
expect((await call("projects.openInIde", { id: missingId })).code).toBe("bad_path");
|
||||
expect((await call("projects.openInIde", { id: "p_nope" })).code).toBe("not_found");
|
||||
expect(launched).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("files.reveal: a file is selected in its folder, a folder is opened", async () => {
|
||||
expect(await call("files.reveal", { projectId, path: "src/a.ts" })).toEqual({ r: { ok: true } });
|
||||
expect(await call("files.reveal", { projectId, path: "src" })).toEqual({ r: { ok: true } });
|
||||
expect(launched).toEqual([
|
||||
real.revealLaunch(process.platform, join(realpathSync(proj), "src", "a.ts"), false),
|
||||
real.revealLaunch(process.platform, join(realpathSync(proj), "src"), true),
|
||||
]);
|
||||
});
|
||||
|
||||
it("files.reveal refuses anything outside the project root, and missing targets", async () => {
|
||||
for (const path of ["../outside/secret.txt", "src/../../outside", join(outside, "secret.txt"), "", "C:\\Windows"]) {
|
||||
const r = await call("files.reveal", { projectId, path });
|
||||
expect(r.code, path).toBe("bad_path");
|
||||
}
|
||||
expect((await call("files.reveal", { projectId, path: "src/nope.ts" })).code).toBe("bad_path");
|
||||
expect(launched).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")("files.reveal refuses a symlink that resolves outside the project", async () => {
|
||||
const r = await call("files.reveal", { projectId, path: "link-out/secret.txt" });
|
||||
expect(r.code).toBe("bad_path");
|
||||
expect(launched).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useTimeline } from "../stores/timeline";
|
||||
import { TimelineRow } from "./Timeline";
|
||||
import { foldTimeline, TOOL_COLLAPSE_AT } from "../timeline/fold";
|
||||
import { collectAutoApproved } from "../timeline/autoApproved";
|
||||
import { decideOnScroll, newTracker, SCROLL_UP_KEYS } from "../timeline/stick";
|
||||
import { decideOnScroll, newTracker, SCROLL_DOWN_KEYS, SCROLL_UP_KEYS } from "../timeline/stick";
|
||||
import { Composer } from "./Composer";
|
||||
import { QuoteSelect } from "./QuoteSelect";
|
||||
import { Icon } from "./Icons";
|
||||
@@ -39,6 +39,7 @@ export function Chat() {
|
||||
if (!el) return;
|
||||
el.scrollTop = el.scrollHeight;
|
||||
track.current.lastTop = el.scrollTop;
|
||||
track.current.lastDist = el.scrollHeight - el.scrollTop - el.clientHeight;
|
||||
}, []);
|
||||
|
||||
const project = projects.find((p) => p.id === ui.currentProjectId) ?? null;
|
||||
@@ -55,6 +56,7 @@ export function Chat() {
|
||||
setHasNew(false);
|
||||
track.current.pointerDown = false;
|
||||
track.current.intentAt = -Infinity;
|
||||
track.current.intentDir = "any";
|
||||
}, [activeThreadId, setStick]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const est = useCallback((i: number) => {
|
||||
@@ -154,15 +156,18 @@ export function Chat() {
|
||||
}, [tl.sentAt, setStick, toBottom]);
|
||||
|
||||
// 1.3.6: only a user gesture may leave the bottom (layout growth fires scroll events too)
|
||||
const intent = () => { track.current.intentAt = performance.now(); };
|
||||
// 1.3.8: with its direction where the gesture tells it (touch and the scrollbar don't)
|
||||
const intent = (dir: "up" | "down" | "any" = "any") => { track.current.intentAt = performance.now(); track.current.intentDir = dir; };
|
||||
const onWheel = (e: React.WheelEvent) => {
|
||||
intent();
|
||||
intent(e.deltaY < 0 ? "up" : e.deltaY > 0 ? "down" : "any");
|
||||
const el = scrollRef.current;
|
||||
// upward wheel on an overflowing list: leave at once, before the next growth snaps it back
|
||||
if (e.deltaY < 0 && el && el.scrollHeight > el.clientHeight && track.current.stick) setStick(false);
|
||||
};
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (SCROLL_UP_KEYS.has(e.key) || (e.key === " " && e.shiftKey)) intent();
|
||||
// 1.3.8: scrolling down by key is a gesture too (it may re-stick within 60px of the bottom)
|
||||
if (SCROLL_UP_KEYS.has(e.key) || (e.key === " " && e.shiftKey)) intent("up");
|
||||
else if (SCROLL_DOWN_KEYS.has(e.key) || e.key === " ") intent("down");
|
||||
};
|
||||
const onPointerDown = () => { track.current.pointerDown = true; intent(); };
|
||||
useEffect(() => {
|
||||
@@ -254,7 +259,7 @@ export function Chat() {
|
||||
return (
|
||||
<>
|
||||
<div className="scroll" ref={scrollRef} onScroll={onScroll} onWheel={onWheel} onKeyDown={onKeyDown}
|
||||
onPointerDown={onPointerDown} onTouchStart={intent} onTouchMove={intent}>
|
||||
onPointerDown={onPointerDown} onTouchStart={() => intent()} onTouchMove={() => intent()}>
|
||||
<div className="tl-wrap" data-quote-root="chat">
|
||||
<div style={{ height: totalSize, position: "relative" }}>
|
||||
{virt.getVirtualItems().map((v) => {
|
||||
|
||||
@@ -18,6 +18,7 @@ const PATHS: Record<string, string> = {
|
||||
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",
|
||||
code: "M8 7l-5 5 5 5M16 7l5 5-5 5M13.5 5l-3 14",
|
||||
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",
|
||||
|
||||
@@ -8,7 +8,7 @@ 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 { errMsg, revealLabel, rpcMessage, t, tf } from "../i18n/index.js";
|
||||
import { TerminalPanel } from "./TerminalPanel";
|
||||
import { PreviewPanel } from "./PreviewPanel";
|
||||
import { Menu, type MenuItem } from "./Menu";
|
||||
@@ -360,6 +360,16 @@ function FilesPanel() {
|
||||
{ kind: "sep" },
|
||||
{ kind: "item", label: t("common.copyPath"), onClick: () => { void copyText(joinProjectPath(project.path, ctx.entry.path)); toast(t("common.copiedPath")); } },
|
||||
{ kind: "item", label: t("mention.copyRel"), onClick: () => { void copyText(ctx.entry.path); toast(t("common.copiedPath")); } },
|
||||
{ kind: "sep" },
|
||||
// 1.3.8 (issue #3): a file is selected in its folder, a folder is opened (the daemon keeps it inside the project)
|
||||
{
|
||||
kind: "item",
|
||||
label: revealLabel(),
|
||||
onClick: () => {
|
||||
ws.call("files.reveal", { projectId: project.id, path: ctx.entry.path })
|
||||
.catch((e) => toast(t("panel.revealFail") + rpcMessage(e), true));
|
||||
},
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ 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";
|
||||
import { displayThreadTitle, getIntlLocale, rpcMessage, t, tf } from "../i18n/index.js";
|
||||
|
||||
function useNow(running: boolean): number {
|
||||
const [now, setNow] = useState(Date.now());
|
||||
@@ -108,6 +108,21 @@ export function Topbar({ pendingCount, pendingKey }: { pendingCount: number; pen
|
||||
: <span className={`tb-pill ${pill.cls}`}>{pill.cls === "run" && <span className="tb-pill-dot" />}{pill.text}</span>)}
|
||||
<div className="tb-right">
|
||||
{thread?.model && <span className="tb-model">{thread.model}</span>}
|
||||
{project && (
|
||||
// 1.3.8 (issue #3): open the project folder in the first IDE the daemon finds
|
||||
<button
|
||||
className="ibtn"
|
||||
title={t("topbar.openInIde")}
|
||||
aria-label={t("topbar.openInIde")}
|
||||
onClick={() => {
|
||||
ws.call("projects.openInIde", { id: project.id })
|
||||
.then((r) => toast(tf("topbar.openedInIde", { ide: String((r as { ide?: string })?.ide ?? "IDE") })))
|
||||
.catch((e) => toast(t("topbar.openInIdeFail") + rpcMessage(e), true));
|
||||
}}
|
||||
>
|
||||
<Icon name="code" />
|
||||
</button>
|
||||
)}
|
||||
{panelBtns.map((b) => (
|
||||
<button
|
||||
key={b.tab}
|
||||
|
||||
@@ -76,6 +76,19 @@ export function errMsg(e: unknown): string {
|
||||
return localizeDaemonMessage(msg);
|
||||
}
|
||||
|
||||
/** 1.3.8: the daemon's own (already localized) message for an RPC error, falling back to the generic code text */
|
||||
export function rpcMessage(e: unknown): string {
|
||||
const msg = (e as Error)?.message;
|
||||
return msg ? localizeDaemonMessage(String(msg)) : errMsg(e);
|
||||
}
|
||||
|
||||
/** 1.3.8: the file manager's name on this machine (the page runs on the daemon's machine, so the UA tells the OS) */
|
||||
export function revealLabel(ua = typeof navigator !== "undefined" ? navigator.userAgent : ""): string {
|
||||
if (/Macintosh|Mac OS X/i.test(ua)) return t("panel.revealMac");
|
||||
if (/Windows/i.test(ua)) return t("panel.revealWin");
|
||||
return t("panel.revealLinux");
|
||||
}
|
||||
|
||||
export function localizeDaemonMessage(msg: string): string {
|
||||
if (locale === "zh") return msg;
|
||||
if (msg === "后台已重启,本轮已中断") return "Daemon restarted — this turn was interrupted";
|
||||
|
||||
@@ -26,6 +26,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
waitAuth: "等待授权", showRequest: "查看授权请求", running: "运行中 {s}s", error: "出错",
|
||||
closedResume: "已关闭 · 发送消息将续接", threadInfo: "对话信息",
|
||||
panelChanges: "改动(Ctrl+J)", panelFiles: "文件", panelTerminal: "终端",
|
||||
openInIde: "用 IDE 打开项目", openedInIde: "已用 {ide} 打开", openInIdeFail: "无法用 IDE 打开:",
|
||||
},
|
||||
sidebar: {
|
||||
newProject: "新建项目", collapse: "收起侧栏", expand: "展开侧栏", filterPlaceholder: "过滤对话标题", searchTitle: "搜索(Ctrl+K)",
|
||||
@@ -152,6 +153,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
},
|
||||
panel: {
|
||||
changes: "改动", files: "文件", terminal: "终端", closeTitle: "关闭(Ctrl+J)",
|
||||
revealMac: "在 Finder 中显示", revealWin: "在资源管理器中显示", revealLinux: "在文件管理器中显示", revealFail: "无法显示:",
|
||||
pickProject: "先选一个项目", notGit: "这个项目不是 git 仓库", clean: "工作区干净",
|
||||
branch: "当前分支", loadingDiff: "加载 diff…", diffTooLarge: "diff 超过 1MB,不显示",
|
||||
discardTitle: "放弃改动", discardUntracked: "放弃 {path} 的改动?\n未跟踪文件会被移到回收目录(trash/discarded),不会直接删除。",
|
||||
@@ -245,6 +247,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
waitAuth: "Waiting for approval", showRequest: "Show the request", running: "Running {s}s", error: "Error",
|
||||
closedResume: "Closed · send a message to resume", threadInfo: "Conversation info",
|
||||
panelChanges: "Changes (Ctrl+J)", panelFiles: "Files", panelTerminal: "Terminal",
|
||||
openInIde: "Open project in IDE", openedInIde: "Opened in {ide}", openInIdeFail: "Couldn't open in an IDE: ",
|
||||
},
|
||||
sidebar: {
|
||||
newProject: "New project", collapse: "Collapse sidebar", expand: "Expand sidebar", filterPlaceholder: "Filter conversations", searchTitle: "Search (Ctrl+K)",
|
||||
@@ -369,6 +372,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
},
|
||||
panel: {
|
||||
changes: "Changes", files: "Files", terminal: "Terminal", closeTitle: "Close (Ctrl+J)",
|
||||
revealMac: "Reveal in Finder", revealWin: "Show in Explorer", revealLinux: "Show in file manager", revealFail: "Couldn't show it: ",
|
||||
pickProject: "Select a project first", notGit: "This folder is not a git repository", clean: "Working tree clean",
|
||||
branch: "Current branch", loadingDiff: "Loading diff…", diffTooLarge: "Diff is over 1MB — not shown",
|
||||
discardTitle: "Discard changes", discardUntracked: "Discard changes to {path}?\nUntracked files move to trash/discarded.",
|
||||
|
||||
@@ -33,7 +33,8 @@ describe("stick-to-bottom decisions (1.3.6)", () => {
|
||||
expect(decideOnScroll(t, m(2800, 4200), 110)).toBe(false);
|
||||
// growth afterwards doesn't re-stick it
|
||||
expect(decideOnScroll(t, m(2800, 5200), 2000)).toBe(false);
|
||||
// back within 60px of the bottom → stuck again
|
||||
// scrolled back down (a gesture) to within 60px of the bottom → stuck again
|
||||
t.intentAt = 2090;
|
||||
expect(decideOnScroll(t, m(5200 - 800 - 30, 5200), 2100)).toBe(true);
|
||||
});
|
||||
|
||||
@@ -46,3 +47,97 @@ describe("stick-to-bottom decisions (1.3.6)", () => {
|
||||
expect(decideOnScroll(t, m(2000, 3800), INTENT_MS + 20)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("near the bottom, the user's direction wins (1.3.8, issue #2)", () => {
|
||||
// the view is snapped to the bottom of a 4000px conversation in an 800px scroller
|
||||
const atBottom = () => {
|
||||
const t = newTracker();
|
||||
decideOnScroll(t, m(3200, 4000), 0);
|
||||
return t;
|
||||
};
|
||||
|
||||
it("a slow upward scroll 20px from the bottom unsticks and stays unstuck", () => {
|
||||
const t = atBottom();
|
||||
let now = 1000;
|
||||
// trackpad: 1–5px steps, each with a fresh wheel gesture
|
||||
for (const top of [3199, 3195, 3190, 3185, 3180]) {
|
||||
t.intentAt = now;
|
||||
expect(decideOnScroll(t, m(top, 4000), now + 5)).toBe(false);
|
||||
now += 16;
|
||||
}
|
||||
expect(t.stick).toBe(false);
|
||||
// the gesture ends; the view stays 20px above the bottom
|
||||
expect(decideOnScroll(t, m(3180, 4000), now + INTENT_MS + 50)).toBe(false);
|
||||
});
|
||||
|
||||
it("a sub-pixel first step still counts as leaving (fractional scrollTop)", () => {
|
||||
const t = atBottom();
|
||||
t.intentAt = 1000;
|
||||
expect(decideOnScroll(t, m(3199.25, 4000), 1005)).toBe(false);
|
||||
});
|
||||
|
||||
it("streaming growth (scrollHeight grows, scrollTop unchanged) never re-sticks an unstuck view", () => {
|
||||
const t = atBottom();
|
||||
t.intentAt = 1000;
|
||||
expect(decideOnScroll(t, m(3180, 4000), 1010)).toBe(false); // 20px up
|
||||
// tokens arrive while the wheel gesture is still fresh and long after it
|
||||
let now = 1020;
|
||||
for (let h = 4004; h < 4600; h += 23) {
|
||||
expect(decideOnScroll(t, m(3180, h), now)).toBe(false);
|
||||
now += 40;
|
||||
}
|
||||
expect(t.stick).toBe(false);
|
||||
});
|
||||
|
||||
it("virtual-list measurement shifting scrollTop down by the same amount (anchor kept) doesn't re-stick", () => {
|
||||
const t = atBottom();
|
||||
t.intentAt = 1000;
|
||||
expect(decideOnScroll(t, m(3180, 4000), 1010)).toBe(false); // 20px from the bottom
|
||||
// a row above the viewport is measured 40px taller: scrollTop and scrollHeight both +40, distance stays 20,
|
||||
// and this happens while the user's wheel gesture is still fresh
|
||||
expect(decideOnScroll(t, m(3220, 4040), 1100)).toBe(false);
|
||||
// the container shrinking (composer grew) only moves the bottom away
|
||||
expect(decideOnScroll(t, m(3220, 4040, 700), 1150)).toBe(false);
|
||||
});
|
||||
|
||||
it("scrolling back down into the 60px zone re-sticks; reaching the real bottom re-sticks even without a gesture", () => {
|
||||
const t = atBottom();
|
||||
t.intentAt = 1000;
|
||||
expect(decideOnScroll(t, m(3000, 4000), 1010)).toBe(false); // 200px up
|
||||
// wheel down: 200 → 100 → 40 from the bottom
|
||||
t.intentAt = 3000;
|
||||
expect(decideOnScroll(t, m(3100, 4000), 3010)).toBe(false);
|
||||
expect(decideOnScroll(t, m(3160, 4000), 3030)).toBe(true);
|
||||
|
||||
const u = atBottom();
|
||||
u.intentAt = 1000;
|
||||
expect(decideOnScroll(u, m(3100, 4000), 1010)).toBe(false);
|
||||
// the view lands on the real bottom some other way (e.g. a scrollbar click that ended long ago)
|
||||
expect(decideOnScroll(u, m(3199.5, 4000), 9000)).toBe(true);
|
||||
});
|
||||
|
||||
it("an upward gesture inside the 60px zone after re-sticking unsticks again", () => {
|
||||
const t = atBottom();
|
||||
t.intentAt = 1000;
|
||||
expect(decideOnScroll(t, m(3150, 4000), 1010)).toBe(false);
|
||||
t.intentAt = 2000;
|
||||
expect(decideOnScroll(t, m(3200, 4000), 2010)).toBe(true);
|
||||
t.intentAt = 3000;
|
||||
expect(decideOnScroll(t, m(3190, 4000), 3010)).toBe(false);
|
||||
});
|
||||
|
||||
it("the gesture's direction: a downward wheel doesn't unstick on an upward clamp, an upward one doesn't re-stick on a downward shift", () => {
|
||||
const t = atBottom();
|
||||
// wheel down at the bottom, and the streamed reply settles 30px shorter: scrollTop clamps up 30px
|
||||
t.intentAt = 1000; t.intentDir = "down";
|
||||
expect(decideOnScroll(t, m(3170, 3970), 1010)).toBe(true);
|
||||
// a real wheel up does unstick
|
||||
t.intentAt = 1100; t.intentDir = "up";
|
||||
expect(decideOnScroll(t, m(3150, 3970), 1110)).toBe(false);
|
||||
// still wheeling up, the view moves 10px closer to the bottom (the container grew): stays unstuck
|
||||
expect(decideOnScroll(t, m(3150, 3970, 810), 1150)).toBe(false);
|
||||
// the scrollbar (pointer held) counts either way
|
||||
t.pointerDown = true;
|
||||
expect(decideOnScroll(t, m(3165, 3970, 800), 5000)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,32 +16,53 @@ export interface StickTracker {
|
||||
stick: boolean;
|
||||
/** scrollTop seen at the previous scroll event / programmatic snap */
|
||||
lastTop: number;
|
||||
/** distance from the bottom seen at the previous scroll event / programmatic snap (1.3.8) */
|
||||
lastDist: number;
|
||||
/** time of the last user scroll gesture (wheel, touch, scroll key, pointer on the scroller) */
|
||||
intentAt: number;
|
||||
/** 1.3.8: which way that gesture went ("any" for touch / the scrollbar, whose direction isn't known up front) */
|
||||
intentDir: "up" | "down" | "any";
|
||||
/** a pointer is held on the scroller (dragging the scrollbar) */
|
||||
pointerDown: boolean;
|
||||
}
|
||||
|
||||
export const newTracker = (): StickTracker => ({ stick: true, lastTop: 0, intentAt: -Infinity, pointerDown: false });
|
||||
export const newTracker = (): StickTracker => ({ stick: true, lastTop: 0, lastDist: 0, intentAt: -Infinity, intentDir: "any", pointerDown: false });
|
||||
|
||||
export const distanceFromBottom = (m: ScrollMetrics): number => m.scrollHeight - m.scrollTop - m.clientHeight;
|
||||
|
||||
/** Moves smaller than this (px) are rounding noise (fractional scrollTop on HiDPI screens), not a scroll */
|
||||
const EPS = 0.5;
|
||||
|
||||
/**
|
||||
* A `scroll` event happened: is the view still stuck to the bottom?
|
||||
* - near the bottom → stuck (whatever moved it there)
|
||||
* - stuck, and scrollTop did not go up, or went up without a user gesture (layout growth, the virtualizer
|
||||
* correcting offsets, the container shrinking) → stays stuck; the caller snaps back to the bottom
|
||||
* - stuck, scrollTop went up during a user gesture → unstuck
|
||||
* - stuck, scrollTop went up during a user gesture that wasn't a downward one → unstuck at once, however close to
|
||||
* the bottom it still is (1.3.8, issue #2: 1.3.7 re-stuck anything within 60px, so a slow wheel/trackpad scroll up
|
||||
* was snapped back). A downward wheel/key gesture doesn't count: scrollTop clamping up while it runs (a streamed
|
||||
* reply settling to its final, shorter height) is layout, not the user.
|
||||
* - stuck otherwise (layout growth, the virtualizer correcting offsets, the container shrinking) → stays stuck;
|
||||
* the caller snaps back to the bottom
|
||||
* - unstuck → stays unstuck while content grows, rows are measured or the layout changes. It sticks again only
|
||||
* when the view reaches the real bottom (≤ 1px), or the user scrolls down (the distance to the bottom shrinks
|
||||
* during a gesture that wasn't an upward one) to within STICK_PX of it.
|
||||
*/
|
||||
export function decideOnScroll(t: StickTracker, m: ScrollMetrics, now: number): boolean {
|
||||
const up = m.scrollTop < t.lastTop - 1;
|
||||
const dist = distanceFromBottom(m);
|
||||
const up = m.scrollTop < t.lastTop - EPS;
|
||||
const closer = dist < t.lastDist - EPS;
|
||||
t.lastTop = m.scrollTop;
|
||||
if (distanceFromBottom(m) < STICK_PX) return (t.stick = true);
|
||||
if (!t.stick) return false;
|
||||
t.lastDist = dist;
|
||||
const userGesture = t.pointerDown || now - t.intentAt < INTENT_MS;
|
||||
if (up && userGesture) return (t.stick = false);
|
||||
return true;
|
||||
const dir = t.pointerDown ? "any" : t.intentDir;
|
||||
if (t.stick) {
|
||||
if (up && userGesture && dir !== "down") return (t.stick = false);
|
||||
return true;
|
||||
}
|
||||
if (dist <= 1) return (t.stick = true);
|
||||
if (closer && userGesture && dir !== "up" && dist < STICK_PX) return (t.stick = true);
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Keys that scroll the conversation up when it has focus */
|
||||
export const SCROLL_UP_KEYS = new Set(["ArrowUp", "PageUp", "Home"]);
|
||||
/** Keys that scroll the conversation down when it has focus (1.3.8: a gesture that may re-stick near the bottom) */
|
||||
export const SCROLL_DOWN_KEYS = new Set(["ArrowDown", "PageDown", "End"]);
|
||||
|
||||
Reference in New Issue
Block a user