Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ runcoder ~/code/my-project
3. It opens Qwen Code in a new terminal window, in your folder, pointed at the server.
4. The first window stays as the control panel: every 10 minutes it prints the time and cost so
far. **Press q there (or Ctrl+C, or close the window) and it deletes the server**, then prints
what the session cost.
what the session cost. q works from the deploy on, also while the model downloads (not during
the setup and session questions before it). While the session runs, r reopens Qwen Code where
you left off.

If the folder has earlier Qwen Code sessions, runcoder asks whether to continue the latest
(c), pick one (r), or start fresh. `-c`, `-p` and `-n` answer that in advance.
(c), pick one (p), or start fresh (Enter). `-c`, `-p` and `-n` answer that in advance.

Other commands:

Expand Down
22 changes: 15 additions & 7 deletions bin/runcoder.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,15 @@ async function finish(rc) {
}
// Ctrl+C, a closed window (SIGHUP, also on Windows) or a kill all end in the same cleanup.
for (const [sig, rc] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]) process.on(sig, () => finish(rc));
// Any error nothing else caught still ends in cleanup, so the server is deleted; during cleanup it is
// logged and cleanup carries on.
// Any error nothing else caught is shown like any other and still ends in cleanup, so the server is
// deleted; during cleanup it is only logged and cleanup carries on.
for (const ev of ["uncaughtException", "unhandledRejection"]) {
process.on(ev, (e) => {
log(`${ev}: ${e?.stack || e}`);
if (exiting) log(`${ev}: ${e?.stack || e}`);
else {
say(`ERROR: ${e?.stack || e}`);
say(`Full log: ${logFile}`);
}
finish(1);
});
}
Expand All @@ -61,11 +65,15 @@ try {
else if (cmd === "status") await cmdStatus(s);
else if (cmd === "credit") await cmdCredit(s);
else if (cmd === "down") cmdDown(s);
else await cmdUp(s, cmd === undefined ? [] : [cmd, ...rest]);
else await cmdUp(s, cmd === undefined ? [] : [cmd, ...rest], () => finish(0));
await finish(0);
} catch (e) {
if (e instanceof Stop) say(`ERROR: ${e.message}`);
else say(`ERROR: ${e.stack || e}`);
say(`Full log: ${logFile}`);
// q, Ctrl+C or a closed window during start-up leaves start-up to fail on the closed tunnel; that
// is not news, so only log it.
if (exiting) log(`after cleanup started: ${e.stack || e}`);
else {
say(`ERROR: ${e instanceof Stop ? e.message : e.stack || e}`);
say(`Full log: ${logFile}`);
}
await finish(1);
}
6 changes: 4 additions & 2 deletions src/cloud.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,11 @@ export async function preflight(s) {
if (!(await apiEnabled(s, "run.googleapis.com"))) die(`The Cloud Run API is off in ${s.project}. Run: runcoder setup`);
}

// Starts the GPU service, trying each region in turn. Returns the region it runs in.
export async function deploy(s, onAttempt) {
// Starts the GPU service, trying each region in turn. Returns the region it runs in, or null once
// aborted() is true (cleanup has started): no further region is tried.
export async function deploy(s, onAttempt, aborted = () => false) {
for (const region of s.regions) {
if (aborted()) return null;
say(`Starting the GPU server in ${region} (takes 1-2 minutes)...`);
onAttempt(region);
const r = await gcloud(s, [
Expand Down
85 changes: 54 additions & 31 deletions src/session.mjs
Original file line number Diff line number Diff line change
@@ -1,44 +1,50 @@
// One run from start to delete, plus status, credit and down.

import { mkdirSync, readFileSync, writeFileSync, rmSync, statSync, realpathSync } from "node:fs";
import { mkdirSync, readFileSync, writeFileSync, linkSync, rmSync, statSync, realpathSync } from "node:fs";
import { resolve } from "node:path";
import { paths, configExists } from "./config.mjs";
import { serviceRegions, deleteEverything, activeInstances, preflight, deploy } from "./cloud.mjs";
import * as cost from "./cost.mjs";
import { Tunnel, httpCode, modelReady, freePort, waitForTunnel, waitForModel, warmModel, keepAwake } from "./tunnel.mjs";
import { writeQwenSettings, qwenSessions, openQwen, qwenAlive, stopQwen } from "./qwen.mjs";
import { alive, commandOf, killTree, sleep } from "./proc.mjs";
import { say, warn, die, notify, key, startKeyboard, stopKeyboard, logFile, isInteractive } from "./ui.mjs";
import { say, warn, die, notify, key, quitOnQ, startKeyboard, stopKeyboard, logFile, isInteractive } from "./ui.mjs";

// What cleanup needs to know about this run.
export const state = { deploying: null, own: false, locked: false, deployStart: 0, tunnel: null, awake: null, c: null, s: null, cleaning: false };
const liveSeconds = () => (state.deployStart ? (Date.now() - state.deployStart) / 1000 : 0);
const costSoFar = () => cost.money(state.c, cost.sessionCost(state.c, liveSeconds()));

function acquireLock() {
mkdirSync(paths.state, { recursive: true });
// The lock is a file with its owner's process ID and command line. It is written whole first and
// then linked into place in one step, so another run never finds a lock without its contents.
function acquireLock(contents) {
const tmp = `${paths.lock}.${process.pid}`;
writeFileSync(tmp, contents);
try {
mkdirSync(paths.lock);
linkSync(tmp, paths.lock);
state.locked = true;
return true;
} catch {
let pid = 0;
try {
pid = Number(readFileSync(`${paths.lock}/pid`, "utf8"));
} catch {}
return pid;
return false;
} finally {
rmSync(tmp, { force: true });
}
writeFileSync(`${paths.lock}/pid`, String(process.pid));
state.locked = true;
return 0;
}
async function lock() {
const other = acquireLock();
if (!other) return;
// Only a live runcoder counts; a stale lock whose process ID was reused does not.
if (alive(other) && (await commandOf(other)).includes("runcoder")) {
die(`runcoder is already running (process ${other}). Use that window, or run: runcoder down`);
mkdirSync(paths.state, { recursive: true });
const mine = JSON.stringify({ pid: process.pid, command: await commandOf(process.pid) });
if (acquireLock(mine)) return;
let other = {};
try {
other = JSON.parse(readFileSync(paths.lock, "utf8"));
} catch {}
// Only the runcoder that wrote the lock counts: a process ID reused since has another command
// line. If the command line could not be read then, any live process with that ID counts.
if (other.pid && alive(other.pid) && (!other.command || (await commandOf(other.pid)) === other.command)) {
die(`runcoder is already running (process ${other.pid}). Use that window, or run: runcoder down`);
}
rmSync(paths.lock, { recursive: true, force: true });
if (acquireLock()) die("Could not take the lock; another runcoder is starting.");
if (!acquireLock(mine)) die("Could not take the lock; another runcoder is starting.");
}

// Runs once, on q, a limit, Ctrl+C, a closed window or an error: closes Qwen Code and the tunnel,
Expand All @@ -52,13 +58,22 @@ export async function cleanup(rc) {
if (state.awake) killTree(state.awake.pid);
if (state.own) {
const { s, c } = state;
if (state.deploying) {
const deploying = state.deploying?.then(() => true, () => true); // true once the deploy has ended, however
let late = false;
if (deploying) {
// Deleting while gcloud is still deploying fails or races it; let the deploy finish first.
say("Waiting for the deploy in progress to finish, then deleting...");
await Promise.race([state.deploying.catch(() => {}), sleep(600)]);
late = !(await Promise.race([deploying, sleep(600 * s.timeScale)]));
}
say("Shutting down and deleting the Cloud Run service...");
if (await deleteEverything(s)) {
let gone = await deleteEverything(s);
if (late) {
// A deploy that ends after that delete leaves a service behind; delete again once it ends.
say("The deploy is still running; deleting again as soon as it ends...");
await deploying;
gone = await deleteEverything(s);
}
if (gone) {
if (state.deployStart && c) {
say(`This session ran ${Math.floor(liveSeconds() / 60)} minutes and cost about ${costSoFar()}.`);
if (cost.creditEnabled(c)) say(cost.creditLine(c, liveSeconds()));
Expand Down Expand Up @@ -113,11 +128,8 @@ async function session(s, workdir, tunnel, region) {
say("Press q here when you are done (or Ctrl+C, or close this window): everything is shut down and deleted.");
say(`Press r to reopen Qwen Code where you left off. It stops by itself after ${s.maxMinutes} minutes.`);
for (;;) {
const k = isInteractive() ? await key(s.tick) : (await sleep(s.tick), "");
if (/^[qQ]$/.test(k)) {
say("q pressed.");
return;
}
const k = isInteractive() ? await key(s.tick) : (await sleep(s.tick), ""); // q is quitOnQ's, from cmdUp
if (state.cleaning) return; // q or Ctrl+C: cleanup ends the run; don't reopen the tunnel it closed
if (/^[rR]$/.test(k)) {
await openQwen(s, workdir, "--continue");
qwenSeen = false;
Expand Down Expand Up @@ -180,7 +192,8 @@ async function chooseQwenSession(s, workdir, chosen) {
return mode;
}

export async function cmdUp(s, argv) {
// quit() ends the run with cleanup and exit code 0 (q pressed).
export async function cmdUp(s, argv, quit) {
let dir = "";
let mode = null; // null: ask
for (const a of argv) {
Expand Down Expand Up @@ -229,12 +242,22 @@ export async function cmdUp(s, argv) {
state.own = true;
}
state.awake = await keepAwake();
state.deploying = deploy(s, () => {
state.own = true;
state.deployStart ||= Date.now(); // a fallback region keeps counting from the first attempt
// From the deploy on, q stops the run at once, also during the deploy, download and warm-up.
quitOnQ(() => {
say("q pressed.");
quit();
});
state.deploying = deploy(
s,
() => {
state.own = true;
state.deployStart ||= Date.now(); // a fallback region keeps counting from the first attempt
},
() => state.cleaning, // cleanup has started: no next region
);
const region = await state.deploying;
state.deploying = null;
if (state.cleaning) return; // cleanup ends the run (and deletes what the deploy made)
if (region !== s.regions[0]) state.c = await cost.loadCost(s, region); // prices differ by region
const tunnel = (state.tunnel = new Tunnel(s, region));
tunnel.start();
Expand Down
8 changes: 8 additions & 0 deletions src/ui.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,15 @@ export function startKeyboard(isInteractive) {
process.stdin.on("error", () => {});
process.stdin.resume();
}
// From now on q (or Q) calls fn at once, whatever runcoder is doing or waiting for; a q typed
// earlier and not yet read counts too.
let onQuit = null;
export function quitOnQ(fn) {
onQuit = fn;
if (queue.some((k) => /^[qQ]$/.test(k))) fn();
}
function push(k) {
if (onQuit && /^[qQ]$/.test(k)) return onQuit();
if (waiting) {
const w = waiting;
waiting = null;
Expand Down
31 changes: 28 additions & 3 deletions tests/1-run.test.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// A normal run, Ctrl+C, closing the window, and falling back to the second region.
// A normal run, Ctrl+C, closing the window, q during start-up, and falling back to the second region.
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { readdirSync, readFileSync, existsSync } from "node:fs";
import { readdirSync, readFileSync, existsSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { sandbox, start, startGoogle, noService, touch, calls, killLeftovers, windows } from "./helpers.mjs";
import { sandbox, start, startGoogle, noService, touch, fake, calls, killLeftovers, windows } from "./helpers.mjs";

let server;
before(async () => (server = await startGoogle()));
Expand Down Expand Up @@ -69,3 +69,28 @@ test("falls back to the next region and cleans both", async () => {
assert.equal(await r.done(), 0, r.out());
assert.ok(noService(ctx));
});

test("q during the download deletes everything", async () => {
const ctx = sandbox("t2q", { readyAfter: 30 });
const r = start(ctx);
assert.ok(await r.waitFor("Downloading", 30), r.out());
r.press("q");
assert.equal(await r.done(30), 0, r.out());
assert.ok(!r.has("Model downloaded"), r.out()); // stopped at once, not when the session began
assert.ok(r.has("q pressed."), r.out());
assert.ok(r.has("Done: runcoder is deleted"), r.out());
assert.ok(noService(ctx), calls(ctx));
});

test("q during the deploy: no next region is tried, everything is deleted", async () => {
const ctx = sandbox("t4q");
touch(ctx, "deployfail-us-central1");
writeFileSync(fake(ctx, "deploy_seconds"), "3");
const r = start(ctx);
assert.ok(await r.waitFor("Starting the GPU server in us-central1", 30), r.out());
r.press("q");
assert.equal(await r.done(60), 0, r.out());
assert.ok(r.has("Done: runcoder is deleted"), r.out());
assert.doesNotMatch(calls(ctx), /run deploy \S+ --region=europe-west4/);
assert.ok(noService(ctx), calls(ctx));
});
47 changes: 44 additions & 3 deletions tests/2-recovery.test.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
// Tunnel and server trouble, a second copy, a busy port, status/down, failed deletes, leftovers.
// Tunnel and server trouble, a second copy, a stale lock, a slow deploy, an unexpected error, a busy
// port, status/down, failed deletes, leftovers.
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { rmSync, existsSync } from "node:fs";
import { sandbox, start, once, startGoogle, noService, touch, fake, setReady, calls, killLeftovers, sleep, PORT, windows } from "./helpers.mjs";
import { rmSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { sandbox, start, once, startGoogle, noService, touch, fake, setReady, calls, killLeftovers, sleep, PORT, ROOT, windows } from "./helpers.mjs";
import { startOllama } from "./fake/ollama.mjs";

let server;
Expand Down Expand Up @@ -73,6 +76,44 @@ test("a second copy is refused and leaves the first alone", async () => {
assert.ok(noService(ctx));
});

test("a lock left by a process ID another program now has is taken over", async () => {
const ctx = sandbox("t7b");
mkdirSync(ctx.state, { recursive: true });
// This test process is alive, but is not the runcoder whose command line the lock records.
writeFileSync(join(ctx.state, "lock"), JSON.stringify({ pid: process.pid, command: "node /old/runcoder/bin/runcoder.mjs -n /work" }));
const r = start(ctx);
assert.ok(await r.waitFor("Press q here", 60), r.out());
assert.ok(!r.has("already running"), r.out());
r.press("q");
assert.equal(await r.done(), 0, r.out());
assert.ok(noService(ctx));
assert.ok(!existsSync(join(ctx.state, "lock")));
});

test("a deploy still running when cleanup's wait ends is deleted once it ends", async () => {
const ctx = sandbox("t29");
writeFileSync(fake(ctx, "deploy_seconds"), "8");
// A time scale of 0.005 makes cleanup's 600-second wait for the deploy 3 seconds.
const r = start(ctx, ["-n", ctx.work], { env: { RUNCODER_TIME_SCALE: "0.005" } });
assert.ok(await r.waitFor("Starting the GPU server in us-central1", 30), r.out());
r.press("q");
assert.ok(await r.waitFor("deleting again as soon as it ends", 30), r.out());
assert.equal(await r.done(60), 0, r.out());
assert.ok(r.has("Done: runcoder is deleted"), r.out());
assert.ok(noService(ctx), calls(ctx)); // the fake service only appears when the deploy ends
});

test("an unexpected error is shown with the log path, and everything is deleted", async () => {
const ctx = sandbox("t30", { readyAfter: 30 });
const preload = pathToFileURL(join(ROOT, "tests", "fake", "unexpected-error.mjs")).href;
const r = start(ctx, ["-n", ctx.work], { env: { NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --import=${preload}` } });
assert.equal(await r.done(60), 1, r.out());
assert.ok(r.has("ERROR: Error: fake unexpected error"), r.out());
assert.ok(r.has("Full log: "), r.out());
assert.ok(r.has("Done: runcoder is deleted"), r.out());
assert.ok(noService(ctx), calls(ctx));
});

test("a port used by another program is refused before anything starts", async () => {
const ctx = sandbox("t8");
const other = await startOllama({ port: PORT, model: "x" });
Expand Down
4 changes: 3 additions & 1 deletion tests/fake/gcloud.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// deletefail / listfail delete or list fails loggedout no active account
// apioff-<api> that API is off nobilling billing is off
// ready_after seconds before the fake model is ready (read by the fake tunnel)
// deploy_seconds how long a deploy takes (1 by default); the service exists once it ends
import { appendFileSync, existsSync, writeFileSync, rmSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { startOllama } from "./ollama.mjs";
Expand Down Expand Up @@ -39,7 +40,8 @@ else if (cmd === "run services list") {
if (has("listfail")) fail("ERROR: network");
if (has(`svc-${region}`)) out(`${service}\n`);
} else if (cmd.startsWith("run deploy")) {
await new Promise((r) => setTimeout(r, 1000));
const seconds = Number(has("deploy_seconds") ? readFileSync(join(F, "deploy_seconds"), "utf8") : 1);
await new Promise((r) => setTimeout(r, seconds * 1000));
writeFileSync(join(F, `svc-${region}`), "");
if (has(`deployfail-${region}`)) fail(`ERROR: (gcloud.run.deploy) fake capacity error in ${region}`);
out("Service deployed\n");
Expand Down
14 changes: 14 additions & 0 deletions tests/fake/unexpected-error.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Loaded into runcoder with --import by a test: once the fake service exists, an error nothing
// catches (an unhandled rejection), as a bug in runcoder would raise. Other node processes (the
// fake gcloud) are left alone.
import { existsSync } from "node:fs";
import { join } from "node:path";

if (/runcoder\.mjs$/.test(process.argv[1] ?? "")) {
const timer = setInterval(() => {
if (!existsSync(join(process.env.FAKE_DIR, "svc-us-central1"))) return;
clearInterval(timer);
Promise.reject(new Error("fake unexpected error"));
}, 100);
timer.unref();
}
Loading