mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 04:45:33 -08:00
Make the console survive locked files and private handles, and start with Activities off
AI Assisted
This commit is contained in:
1 parent
c52244bee1
commit
2cb174ecf0
17 files changed
+160
-69
No files matched your search
@@ -360,7 +360,11 @@ export async function cmdOpen() {
|
||||
// line, not from the state, and picks the state up on its first request or
|
||||
// poll tick. No page can reach it before it is listening, and the state is
|
||||
// on disk long before a browser gets there.
|
||||
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
|
||||
// Looked up under the project the session itself names (as `post` and `wait`
|
||||
// do), so an agent whose shell moved to another repo finds its server instead
|
||||
// of starting a second one for the same session.
|
||||
const sessionProj = state && typeof state.project === "string" && state.project ? state.project : project;
|
||||
const existing = sid && (args.resume || args.session) ? listHandles(sessionProj).find((h) => h.sid === sid) : null;
|
||||
// A live pid gets a second, longer look before it is given up on, as `stop`
|
||||
// gives one: a server busy right after a post can miss the first, and a
|
||||
// second server for the same session strands the page on the first.
|
||||
@@ -369,7 +373,7 @@ export async function cmdOpen() {
|
||||
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
|
||||
: Promise.resolve(false);
|
||||
let boot = null;
|
||||
if (!existing) boot = await startServer(project, worktree, sid, dir, { noBrowser: Boolean(setupAnnounce) });
|
||||
if (!existing) boot = await startServer(sessionProj, worktree, sid, dir, { noBrowser: Boolean(setupAnnounce) });
|
||||
|
||||
// The dashboard's spec picker reads its inventory straight off the session
|
||||
// state, so the scan belongs to `open` rather than to the agent: filesystem
|
||||
@@ -504,14 +508,14 @@ export async function cmdOpen() {
|
||||
|
||||
// A handle whose pid is alive but is not ours (the pid was reused) leaves
|
||||
// this for last: nothing could be started until that was known.
|
||||
let started = boot || (await startServer(project, worktree, sid, dir));
|
||||
let started = boot || (await startServer(sessionProj, worktree, sid, dir));
|
||||
let handle = await awaitHandle(started);
|
||||
if (!handle && started.handoff) {
|
||||
// The handover went wrong somewhere (a platform that will not pass the
|
||||
// socket, a server that died taking it). Once more the old way, where
|
||||
// the server binds its own port: slower, and certain.
|
||||
started.kill();
|
||||
started = await startServer(project, worktree, sid, dir, { handoff: false, noBrowser: Boolean(setupAnnounce) });
|
||||
started = await startServer(sessionProj, worktree, sid, dir, { handoff: false, noBrowser: Boolean(setupAnnounce) });
|
||||
handle = await awaitHandle(started);
|
||||
}
|
||||
if (!handle) {
|
||||
@@ -679,7 +683,7 @@ function isFolder(p) {
|
||||
async function startServer(project, worktree, sid, dir, { handoff = true, noBrowser = false } = {}) {
|
||||
const token = newToken();
|
||||
const handlePath = handleFile(project, sid);
|
||||
ensureDir(path.dirname(handlePath));
|
||||
ensureDir(path.dirname(handlePath), 0o700);
|
||||
fs.rmSync(handlePath, { force: true });
|
||||
|
||||
const logFd = fs.openSync(path.join(dir, "server.log"), "a");
|
||||
@@ -778,6 +782,16 @@ function tail(file, lines) {
|
||||
}
|
||||
}
|
||||
|
||||
// A missing browser command raises ENOENT as an event, after the try/catch has
|
||||
// returned: without a listener it would end `open` before it printed the link.
|
||||
function quietSpawn(command, args, options) {
|
||||
// The shell form passes its options in the second place.
|
||||
const child = Array.isArray(args) ? spawn(command, args, options) : spawn(command, [], args);
|
||||
child.on("error", () => {});
|
||||
child.unref();
|
||||
return child;
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort, never fatal. If we cannot open a browser we still printed the URL,
|
||||
* and the URL is the primary channel.
|
||||
@@ -793,7 +807,7 @@ function openBrowser(url) {
|
||||
// carries nothing a shell would read.
|
||||
const custom = process.env.PLAN2CODE_BROWSER;
|
||||
if (custom) {
|
||||
spawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true }).unref();
|
||||
quietSpawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -801,16 +815,16 @@ function openBrowser(url) {
|
||||
if (plat === "win32") {
|
||||
// The empty "" is the mandatory window-title argument: omit it and
|
||||
// `start` treats a quoted URL as the title and opens nothing.
|
||||
spawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], {
|
||||
quietSpawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], {
|
||||
windowsVerbatimArguments: true,
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true,
|
||||
}).unref();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (plat === "darwin") {
|
||||
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
|
||||
quietSpawn("open", [url], { detached: true, stdio: "ignore" });
|
||||
return;
|
||||
}
|
||||
// Linux and friends. WSL first: xdg-open there either is absent or opens a
|
||||
@@ -818,11 +832,11 @@ function openBrowser(url) {
|
||||
if (isWsl()) {
|
||||
const exe = findAgent({ command: "wslview" }).state === "found" ? "wslview" : "powershell.exe";
|
||||
const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`];
|
||||
spawn(exe, argsFor, { detached: true, stdio: "ignore" }).unref();
|
||||
quietSpawn(exe, argsFor, { detached: true, stdio: "ignore" });
|
||||
return;
|
||||
}
|
||||
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return; // headless
|
||||
spawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
|
||||
quietSpawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" });
|
||||
} catch {
|
||||
/* never fatal */
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// Two directories with deliberately different durability:
|
||||
//
|
||||
// runtime handle os.tmpdir()/plan2code-console/<cwd-hash>/<sid>.json
|
||||
// runtime handle os.tmpdir()/plan2code-console[-<uid>]/<cwd-hash>/<sid>.json (0700 folder, 0600 file: it holds the session token)
|
||||
// port, pid, token, url. Losing it on reboot is correct,
|
||||
// because the server is gone too. (Jupyter's jpserver-<pid>.json pattern.)
|
||||
//
|
||||
@@ -59,7 +59,7 @@ export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
||||
// session someone is actually using.
|
||||
export const RUNTIME_DIR = process.env.PLAN2CODE_CONSOLE_HOME
|
||||
? path.join(process.env.PLAN2CODE_CONSOLE_HOME, "runtime")
|
||||
: path.join(os.tmpdir(), "plan2code-console");
|
||||
: path.join(os.tmpdir(), "plan2code-console" + (typeof process.getuid === "function" ? "-" + process.getuid() : ""));
|
||||
|
||||
export const SCHEMA = 1;
|
||||
|
||||
@@ -81,8 +81,8 @@ export function parseArgs(argv) {
|
||||
|
||||
/* ------------------------------------------------------------------- fs */
|
||||
|
||||
export function ensureDir(dir) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
export function ensureDir(dir, mode) {
|
||||
fs.mkdirSync(dir, mode === undefined ? { recursive: true } : { recursive: true, mode });
|
||||
return dir;
|
||||
}
|
||||
|
||||
@@ -91,21 +91,21 @@ export function ensureDir(dir) {
|
||||
// The retry loop is not paranoia: on Windows, antivirus and the search indexer
|
||||
// hold transient locks that surface as EPERM/EBUSY from rename. It is intermittent,
|
||||
// unreproducible on demand, and looks exactly like a logic bug. Retry from day one.
|
||||
export function writeJsonAtomic(file, data) {
|
||||
export function writeJsonAtomic(file, data, mode) {
|
||||
const body = JSON.stringify(data, null, 2);
|
||||
writeTextAtomic(file, body);
|
||||
writeTextAtomic(file, body, mode);
|
||||
return body;
|
||||
}
|
||||
|
||||
// The same write for plain text, as UTF-8 (a Buffer is written as is): a temp
|
||||
// file beside the target, fsync, then a rename, retried while Windows still
|
||||
// holds the old file.
|
||||
export function writeTextAtomic(file, text) {
|
||||
export function writeTextAtomic(file, text, mode) {
|
||||
const tmp = file + "." + process.pid + ".tmp";
|
||||
let lastErr;
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
try {
|
||||
const fd = fs.openSync(tmp, "w");
|
||||
const fd = mode === undefined ? fs.openSync(tmp, "w") : fs.openSync(tmp, "w", mode);
|
||||
try {
|
||||
fs.writeFileSync(fd, text, "utf8");
|
||||
fs.fsyncSync(fd);
|
||||
|
||||
@@ -130,7 +130,22 @@ export function markHandoffUsed(id, now = clock()) {
|
||||
const file = path.join(handoffsDir(), id + ".json");
|
||||
const tmp = `${file}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n");
|
||||
fs.renameSync(tmp, file);
|
||||
// Windows scanners hold transient locks: retry the rename, and never leave the temp file.
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
fs.renameSync(tmp, file);
|
||||
break;
|
||||
} catch (err) {
|
||||
const transient = err.code === "EPERM" || err.code === "EBUSY" || err.code === "EACCES";
|
||||
if (!transient || attempt >= 3) {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
throw err;
|
||||
}
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 40 * (attempt + 1));
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
|
||||
@@ -262,6 +262,24 @@ function recoverIndex(dir) {
|
||||
function prepare(dir, folder) {
|
||||
migrate(dir, folder);
|
||||
let index = readIndex(dir);
|
||||
if (!index && fs.existsSync(path.join(dir, INDEX_FILE))) {
|
||||
// A scanner's brief lock reads as "damaged" through readJson: wait it out, and
|
||||
// refuse the write (rather than rebuild every tab) while the file stays locked.
|
||||
let lastErr = null;
|
||||
for (let attempt = 0; attempt < 4 && !index; attempt++) {
|
||||
try {
|
||||
fs.readFileSync(path.join(dir, INDEX_FILE));
|
||||
lastErr = null;
|
||||
index = readIndex(dir);
|
||||
break;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
|
||||
sleepSync(40 * (attempt + 1));
|
||||
}
|
||||
}
|
||||
if (!index && lastErr && (lastErr.code === "EPERM" || lastErr.code === "EBUSY" || lastErr.code === "EACCES")) throw lastErr;
|
||||
}
|
||||
if (!index) {
|
||||
index = fs.existsSync(path.join(dir, INDEX_FILE)) ? recoverIndex(dir) : { order: [], last: null, tabs: {} };
|
||||
writeIndex(dir, index);
|
||||
|
||||
@@ -3099,12 +3099,12 @@
|
||||
scores</strong>, at the bottom of the window, clears them all after a
|
||||
second click to confirm.
|
||||
</p>
|
||||
<h4>Hiding it</h4>
|
||||
<h4>Showing and hiding it</h4>
|
||||
<p>
|
||||
Don't want the die? Untick <strong>Show Activities</strong> in User
|
||||
Preferences (the gear) and it is gone from every screen. To play
|
||||
without sound, untick <strong>Play game sounds</strong> beside it.
|
||||
A game with music (turn on <strong>Play game music</strong> there) has
|
||||
The die is off until you tick <strong>Show Activities</strong> in User
|
||||
Preferences (the gear); untick it again and it is gone from every screen. To play
|
||||
without sound, untick <strong>Play activity sounds</strong> beside it.
|
||||
A game with music (turn on <strong>Play activity music</strong> there) has
|
||||
its own <strong>Music</strong> slider under the board for how loud it plays.
|
||||
</p>
|
||||
<p>
|
||||
@@ -3409,8 +3409,8 @@
|
||||
<li>
|
||||
<strong>Activities</strong>: <strong>Show Activities</strong> puts
|
||||
the die in the top bar, which opens small games to play while you
|
||||
wait. Untick it to hide the die on every screen.
|
||||
<strong>Play game sounds</strong> turns the games' sounds on or
|
||||
wait. It starts unticked; untick it again to hide the die on every screen.
|
||||
<strong>Play activity sounds</strong> turns the games' sounds on or
|
||||
off, leaving every other sound as it is; with Play sounds off, the
|
||||
games are silent too.
|
||||
</li>
|
||||
@@ -3679,10 +3679,10 @@
|
||||
</fieldset>
|
||||
<fieldset data-section="activities" class="modal-ranges looks-activities">
|
||||
<legend>Activities</legend>
|
||||
<label><input type="checkbox" id="looks-activities" checked /> <span>Show Activities</span></label>
|
||||
<label><input type="checkbox" id="looks-activity-sounds" checked /> <span>Play game sounds</span></label>
|
||||
<label><input type="checkbox" id="looks-game-music" /> <span>Play game music</span></label>
|
||||
<p class="help">The die in the top bar opens small games to play while you wait. Play game sounds turns the games' sounds on or off, and Play game music their music; Play sounds, above, silences them too.</p>
|
||||
<label><input type="checkbox" id="looks-activities" /> <span>Show Activities</span></label>
|
||||
<label><input type="checkbox" id="looks-activity-sounds" checked /> <span>Play activity sounds</span></label>
|
||||
<label><input type="checkbox" id="looks-game-music" /> <span>Play activity music</span></label>
|
||||
<p class="help">The die in the top bar opens small games to play while you wait. Play activity sounds turns the games' sounds on or off, and Play activity music their music; Play sounds, above, silences them too.</p>
|
||||
</fieldset>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -31,11 +31,11 @@ export const DEFAULT_LOOKS = {
|
||||
...soundPrefs(null),
|
||||
width: DEFAULT_CARD_WIDTH,
|
||||
hideUnavailable: true,
|
||||
// Activities: the top bar's die, whether its games play sounds (under Play
|
||||
// Activities: the top bar's die (hidden until someone turns on Show Activities), whether its games play sounds (under Play
|
||||
// sounds, which silences them too), the game last picked, and one best score
|
||||
// per listed game (activityBestSnake) or, for a game with courses, per
|
||||
// course (activityBestGolfPirate), each a flat key for cleanLooks().
|
||||
hideActivities: false,
|
||||
hideActivities: true,
|
||||
activitySounds: true,
|
||||
// Whether a game plays its music too (chiptune or recorded songs): off until asked for.
|
||||
gameMusic: false,
|
||||
|
||||
@@ -22,7 +22,7 @@ import { hushMusic, music as playMusic } from "../music.js";
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// Every sound the window and its games make goes through these two, so
|
||||
// Preferences' Play game sounds silences them all (and Play sounds, which
|
||||
// Preferences' Play activity sounds silences them all (and Play sounds, which
|
||||
// tones.js checks, does too).
|
||||
const tone = (...args) => {
|
||||
if (looks.activitySounds) playTone(...args);
|
||||
@@ -30,7 +30,7 @@ const tone = (...args) => {
|
||||
const hum = (...args) => {
|
||||
if (looks.activitySounds) playHum(...args);
|
||||
};
|
||||
// And the music, which also needs Play game music, at the game's own
|
||||
// And the music, which also needs Play activity music, at the game's own
|
||||
// music volume (the window's Music slider). A song's "playing" or "ended"
|
||||
// goes back to the game, which moves on to its next song on "ended".
|
||||
const musicFor = (entry) => (name, intensity, options) => {
|
||||
@@ -38,7 +38,7 @@ const musicFor = (entry) => (name, intensity, options) => {
|
||||
return undefined;
|
||||
};
|
||||
const MUSIC_TITLE = "This game's music volume";
|
||||
const MUSIC_OFF_TITLE = "Turn on Play game music in User Preferences to hear it";
|
||||
const MUSIC_OFF_TITLE = "Turn on Play activity music in User Preferences to hear it";
|
||||
|
||||
// Quiets every held sound and the music: the window stopped ticking a game.
|
||||
function hushTones() {
|
||||
|
||||
@@ -391,7 +391,12 @@ export function renderCard(item) {
|
||||
const skip = el("button", "btn tiny", skipped ? "Do not skip" : "Skip this one");
|
||||
skip.type = "button";
|
||||
skip.style.marginTop = "16px";
|
||||
skip.addEventListener("click", () => (skipped ? stage(item.id, null) : skipAndMoveOn(item.id)));
|
||||
skip.addEventListener("click", () => {
|
||||
if (!skipped) return skipAndMoveOn(item.id);
|
||||
// Keep a note typed with the skip: the box still shows it, so the send must carry it.
|
||||
const kept = page.local.staged[item.id];
|
||||
stage(item.id, kept && kept.text ? { type: "answer", kind: item.kind, text: kept.text } : null);
|
||||
});
|
||||
card.appendChild(skip);
|
||||
if (page.local.skipFlash === item.id) {
|
||||
card.classList.add("is-skip-flash");
|
||||
|
||||
@@ -625,7 +625,7 @@ async function copyHandoffText(text, id, label) {
|
||||
// CLI reads the stored skill and spec, marks the handoff used and falls back
|
||||
// to Quick Task if either is gone.
|
||||
async function pickUpHandoff(h) {
|
||||
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
|
||||
if (page.gone || page.pendingResult || page.local.launching || page.launchScoping || finish()) return;
|
||||
page.launchScoping = true;
|
||||
await hooks.syncWorkspaceScope(h.spec || "");
|
||||
try {
|
||||
@@ -1091,7 +1091,7 @@ export function renderConfirm(main, entry) {
|
||||
// marks the action as being about the session, and it reaches the agent
|
||||
// through the same wait loop. The dashboard reads `skill` off it.
|
||||
export async function launchSkill(entry) {
|
||||
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
|
||||
if (page.gone || page.pendingResult || page.local.launching || page.launchScoping || finish()) return;
|
||||
const target = launchTarget(entry, selSpec());
|
||||
// The card was clickable, so this should never fire — but a spec picked in
|
||||
// one tab could have shifted the ground under a stale render in another.
|
||||
@@ -1351,7 +1351,7 @@ export function wireDashboard() {
|
||||
$("delete-name").addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
deleteStep();
|
||||
if (!$("delete-go").disabled) deleteStep();
|
||||
}
|
||||
});
|
||||
// `close` is queued, so it can land after the dialog was opened again for
|
||||
|
||||
@@ -899,7 +899,7 @@ export function renderStopping() {
|
||||
extra.replaceChildren();
|
||||
if (stuck) {
|
||||
extra.appendChild(
|
||||
el(
|
||||
textWithCode(
|
||||
"p",
|
||||
"stop-note",
|
||||
page.inApp
|
||||
|
||||
@@ -101,7 +101,8 @@ function posePane(main, cls, workflow) {
|
||||
const pane = el("div", cls);
|
||||
pane.dataset.pose = pose;
|
||||
pane.appendChild(startStage(workflow));
|
||||
if (held) main.insertBefore(pane, held);
|
||||
// The old pane (another pose) is replaced, not left beside the new one.
|
||||
if (held && held.parentNode === main) held.replaceWith(pane);
|
||||
else main.appendChild(pane);
|
||||
return pane;
|
||||
}
|
||||
|
||||
+27
-11
@@ -132,6 +132,14 @@ const ROUTES = [
|
||||
{ path: "/bye", origin: true, run: bye },
|
||||
];
|
||||
|
||||
// events.ndjson is an advisory log: a transient lock or a full disk must not
|
||||
// take a route (or the detached server) down after the real write landed.
|
||||
function noteEvent(dir, event) {
|
||||
try {
|
||||
appendEvent(dir, event);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function handle(req, res, ctx) {
|
||||
const port = ctx.port();
|
||||
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
||||
@@ -149,7 +157,15 @@ export function handle(req, res, ctx) {
|
||||
if (route.path !== undefined ? pathname !== route.path : !route.match(pathname, req)) continue;
|
||||
if (route.method && req.method !== route.method) continue;
|
||||
if (route.origin && !originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return route.run(req, res, ctx, url);
|
||||
try {
|
||||
return route.run(req, res, ctx, url);
|
||||
} catch (e) {
|
||||
if (!res.headersSent) return json(res, 500, { error: "server error" });
|
||||
try {
|
||||
res.end();
|
||||
} catch {}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return json(res, 404, { error: "not found" });
|
||||
}
|
||||
@@ -540,7 +556,7 @@ function subagentsPost(req, res, ctx) {
|
||||
}
|
||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
||||
const setting = readSubagentSetting(ctx.dir);
|
||||
appendEvent(ctx.dir, { type: "subagents", on, revision: setting.revision });
|
||||
noteEvent(ctx.dir, { type: "subagents", on, revision: setting.revision });
|
||||
ctx.pushState();
|
||||
return json(res, 200, { ok: true, setting });
|
||||
});
|
||||
@@ -567,7 +583,7 @@ function prHost(req, res, ctx) {
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
appendEvent(ctx.dir, { type: "pr-host", host, kind });
|
||||
noteEvent(ctx.dir, { type: "pr-host", host, kind });
|
||||
return json(res, 200, { ok: true });
|
||||
});
|
||||
}
|
||||
@@ -1184,7 +1200,7 @@ function upload(req, res, ctx) {
|
||||
const saved = store(buf, "jpg");
|
||||
if (!saved) return;
|
||||
const { id, file } = saved;
|
||||
appendEvent(ctx.dir, { type: "upload", id, kind: "image", bytes: buf.length });
|
||||
noteEvent(ctx.dir, { type: "upload", id, kind: "image", bytes: buf.length });
|
||||
return json(res, 200, {
|
||||
ok: true,
|
||||
id,
|
||||
@@ -1213,7 +1229,7 @@ function upload(req, res, ctx) {
|
||||
const saved = store(buf, ext);
|
||||
if (!saved) return;
|
||||
const { id, file } = saved;
|
||||
appendEvent(ctx.dir, { type: "upload", id, kind: "file", bytes: buf.length });
|
||||
noteEvent(ctx.dir, { type: "upload", id, kind: "file", bytes: buf.length });
|
||||
return json(res, 200, { ok: true, id, kind: "file", path: file, name, size: buf.length });
|
||||
});
|
||||
}
|
||||
@@ -1301,7 +1317,7 @@ function uploads(req, res, ctx, url) {
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
appendEvent(ctx.dir, { type: "upload-delete", id: m[1] });
|
||||
noteEvent(ctx.dir, { type: "upload-delete", id: m[1] });
|
||||
res.writeHead(204, baseHeaders());
|
||||
return res.end();
|
||||
}
|
||||
@@ -1437,7 +1453,7 @@ function submit(req, res, ctx) {
|
||||
});
|
||||
}
|
||||
if (refused) return json(res, 500, { error: refused });
|
||||
appendEvent(ctx.dir, { type: "submit", rev: ctx.rev, count: body.actions.length });
|
||||
noteEvent(ctx.dir, { type: "submit", rev: ctx.rev, count: body.actions.length });
|
||||
if (written) {
|
||||
// Account for our own write here rather than letting the watcher find
|
||||
// it: the watcher reads a changed state.json as proof the AGENT is
|
||||
@@ -1489,7 +1505,7 @@ function chat(req, res, ctx) {
|
||||
workflow: state.workflow,
|
||||
reason: "button",
|
||||
});
|
||||
appendEvent(ctx.dir, { type: "chat-reset", reason: "button" });
|
||||
noteEvent(ctx.dir, { type: "chat-reset", reason: "button" });
|
||||
ctx.rev++;
|
||||
ctx.pushState();
|
||||
return json(res, 200, { ok: true, seq: entry.seq, conversation: entry.conversation });
|
||||
@@ -1527,7 +1543,7 @@ function chat(req, res, ctx) {
|
||||
: undefined,
|
||||
files: body.files ? body.files.map((f) => ({ path: f.path, name: cleanLabel(f.name, "file") })) : undefined,
|
||||
});
|
||||
appendEvent(ctx.dir, { type: "chat", seq: entry.seq });
|
||||
noteEvent(ctx.dir, { type: "chat", seq: entry.seq });
|
||||
ctx.rev++;
|
||||
ctx.pushState();
|
||||
return json(res, 200, { ok: true, seq: entry.seq, conversation: current });
|
||||
@@ -1564,7 +1580,7 @@ function chatDecision(req, res, ctx) {
|
||||
decision: body.decision,
|
||||
text: text || undefined,
|
||||
});
|
||||
appendEvent(ctx.dir, { type: "chat-decision", decision: body.decision });
|
||||
noteEvent(ctx.dir, { type: "chat-decision", decision: body.decision });
|
||||
ctx.rev++;
|
||||
ctx.pushState();
|
||||
return json(res, 200, { ok: true, seq: entry.seq });
|
||||
@@ -1734,7 +1750,7 @@ function cancel(req, res, ctx) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
if (pending) return json(res, 409, { error: "pending", message: "A send is still on its way." });
|
||||
appendEvent(ctx.dir, { type: "cancel", rev: ctx.rev });
|
||||
noteEvent(ctx.dir, { type: "cancel", rev: ctx.rev });
|
||||
ctx.broadcast("cancelled", { rev: ctx.rev });
|
||||
return json(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
@@ -529,11 +529,16 @@ setInterval(() => {
|
||||
// Answers nobody has collected yet keep the server up (bounded by MAX_LIFE_MS):
|
||||
// exiting would strand the tab and the send it holds.
|
||||
if (idle > IDLE_MS && !resultFlags().pending) {
|
||||
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
|
||||
// The log is advisory: a failed append must never keep an orphan server alive.
|
||||
try {
|
||||
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
|
||||
} catch {}
|
||||
process.exit(0);
|
||||
}
|
||||
if (Date.now() - STARTED > MAX_LIFE_MS) {
|
||||
appendEvent(DIR, { type: "exit", reason: "max-life" });
|
||||
try {
|
||||
appendEvent(DIR, { type: "exit", reason: "max-life" });
|
||||
} catch {}
|
||||
process.exit(0);
|
||||
}
|
||||
}, 20000).unref();
|
||||
@@ -544,6 +549,14 @@ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// A throw inside a request callback (a read or write failing on a locked file)
|
||||
// must not end the detached server: note it and carry on. The page retries.
|
||||
process.on("uncaughtException", (e) => {
|
||||
try {
|
||||
appendEvent(DIR, { type: "error", message: String(e?.message || e).slice(0, 200) });
|
||||
} catch {}
|
||||
});
|
||||
|
||||
// Every exit that gets to run code takes its handle file with it, so a pid
|
||||
// left behind in the runtime dir cannot later be mistaken for this server once
|
||||
// the number is reused. Only while the file still names THIS process: a
|
||||
@@ -602,8 +615,9 @@ function onListening(port) {
|
||||
stateDir: DIR,
|
||||
startedAt: nowIso(),
|
||||
};
|
||||
ensureDir(path.dirname(handleFile(PROJECT, SID)));
|
||||
writeJsonAtomic(handleFile(PROJECT, SID), handle);
|
||||
// The handle holds the session token: private to this user on a shared /tmp.
|
||||
ensureDir(path.dirname(handleFile(PROJECT, SID)), 0o700);
|
||||
writeJsonAtomic(handleFile(PROJECT, SID), handle, 0o600);
|
||||
appendEvent(DIR, { type: "listening", port, pid: process.pid });
|
||||
checkState();
|
||||
// A resume through a fresh server still starts a new conversation on a hop.
|
||||
|
||||
@@ -231,7 +231,14 @@ export function serverWorkspace(ctx) {
|
||||
}
|
||||
|
||||
function saveWorkspace(ws) {
|
||||
writeWorkspace(dir, ws);
|
||||
try {
|
||||
writeWorkspace(dir, ws);
|
||||
} catch (e) {
|
||||
// The caller changed the cached object before saving: drop it, so the next
|
||||
// read starts from what is on disk and a retry is not told "duplicate".
|
||||
workspaceSeen = { stamp: null, ws: null };
|
||||
throw e;
|
||||
}
|
||||
workspaceSeen = { stamp: fileStamp(WORKSPACE_PATH), ws };
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user