A local-first multi-agent app development platform, built on PenguinHarness
fix(server): 机器的服务端在自己的会话里跑,通往机器的这一跳先于浏览器作答
lmliheng0b1bec7ab1b6
diff --git a/changelog/unreleased/2026-10-08-machine-hop-answers-in-time.md b/changelog/unreleased/2026-10-08-machine-hop-answers-in-time.mdnew file mode 100644index 00000000..cc75ca54--- /dev/null+++ b/changelog/unreleased/2026-10-08-machine-hop-answers-in-time.md@@ -0,0 +1,35 @@+# Machines: the hop to a machine answers before the browser gives up++- **Date:** 2026-10-08+- **Type:** fix+- **Scope:** `server`++[中文版](2026-10-08-machine-hop-answers-in-time.zh.md)++A request this server forwards to a machine (`/server/<id>/api/…`) no longer waits forever when that+machine is not serving. When the machine's server is not listening, the request fails at once and+says so. When the ssh session has stalled, it fails within 8 s, naming the SOCKS layer. A read the+machine accepts but never answers gets a 504 after 15 s. Before, such requests could hang with no+answer; the browser gave up after its own 20 s and sent them again, and those retries hung as well+until Chromium refused every new request with `ERR_INSUFFICIENT_RESOURCES`. Ported from upstream+PenguinHarness (branch `fix/machine-hop-answers-in-time`, commit `a2801c8d`), which the fork did not+carry.++## Details++- Every TCP connection to a machine is a SOCKS CONNECT through its ssh session's `-D` port. When+ nothing listens on the port on the far side, OpenSSH sends no failure reply: it closes the+ connection. The dial ignored a close that came before the reply, and its handshake timer stopped+ with the socket, so the dial never settled. It now fails at once with "the session closed the+ channel to 127.0.0.1:<port> before answering — nothing is listening there, or the session is going+ down", and the forwarded request carries that sentence back (`server_unreachable`, 502).+- The SOCKS handshake deadline is 8 s (was 20 s). A stalled session now fails with "the session's+ SOCKS handshake timed out" before the proxy's own deadline, and well before the browser's 20 s.+- A forwarded `GET` or `HEAD` with no response headers after 15 s (dial included) is answered+ `504 machine_not_answering`. The upstream request is dropped, and the machine list records the+ failure in its `api` fact. Writes are not cut: a write may rightly take long, and cutting one would+ make the browser repeat its effect.+- An answer that has started is not affected: once its headers arrive, the body streams with no+ deadline.+- This fork's forward has one path (the proxy), so the port lands in `machines/proxy.ts` and+ `machines/transport/socks.ts`; the upstream relay layer it also touched is not in this tree.diff --git a/changelog/unreleased/2026-10-08-machine-hop-answers-in-time.zh.md b/changelog/unreleased/2026-10-08-machine-hop-answers-in-time.zh.mdnew file mode 100644index 00000000..fdad75ef--- /dev/null+++ b/changelog/unreleased/2026-10-08-machine-hop-answers-in-time.zh.md@@ -0,0 +1,29 @@+# 机器:通往机器的这一跳在浏览器放弃之前作答++- **Date:** 2026-10-08+- **Type:** fix+- **Scope:** `server`++[English](2026-10-08-machine-hop-answers-in-time.md)++本服务器转发给机器的请求(`/server/<id>/api/…`),在那台机器不服务时不再无限等待。机器上的 server+没有在监听时,请求立即失败并说明原因;ssh 会话停住时,请求在 8 秒内失败,并点名是 SOCKS 那一层;+机器收下连接却不作答的读请求,15 秒后得到 504。此前这些请求可能一直得不到答复:浏览器 20 秒后放弃并+重发,而重发的请求同样挂住,直到 Chromium 对所有新请求都报 `ERR_INSUFFICIENT_RESOURCES`。本次从上游+PenguinHarness 移植(分支 `fix/machine-hop-answers-in-time`,提交 `a2801c8d`),此前本 fork 没有这一条。++## 细节++- 到机器的每一条 TCP 连接,都是经 ssh 会话 `-D` 端口发起的一次 SOCKS CONNECT。远端端口上无人监听时,+ OpenSSH 不回失败码,而是直接关闭连接。拨号此前不处理「应答之前连接被关」,握手计时器又随 socket+ 一起停掉,所以拨号永不落定。现在它立即以「会话在应答之前关闭了到 127.0.0.1:<port> 的通道——那边没有+ 在监听,或者会话正在断开」失败(英文原句见英文版),转发出去的请求把这句原话带回浏览器+ (`server_unreachable`,502)。+- SOCKS 握手期限改为 8 秒(原为 20 秒)。会话停住时,现在以「the session's SOCKS handshake timed out」+ 失败,早于代理自己的期限,也远早于浏览器的 20 秒。+- 转发的 `GET` 或 `HEAD` 在 15 秒内(含拨号)收不到响应头时,以 `504 machine_not_answering` 作答:+ 上游请求被放弃,机器列表的 `api` 事实记下这次失败。写请求不截断:写可能合法地慢,截断后浏览器重发+ 会重复它的副作用。+- 已经开始的答复不受影响:响应头一到,响应体照常以流的形式传回,没有期限。+- 本 fork 的转发只有一条路径(代理这一处),所以这份移植落在 `machines/proxy.ts` 与+ `machines/transport/socks.ts`;上游同时改到的中继层不在本树里。diff --git a/changelog/unreleased/2026-10-08-machine-server-own-session.md b/changelog/unreleased/2026-10-08-machine-server-own-session.mdnew file mode 100644index 00000000..67ff3742--- /dev/null+++ b/changelog/unreleased/2026-10-08-machine-server-own-session.md@@ -0,0 +1,20 @@+# A machine's server outlives the ssh session that started it++- **Date:** 2026-10-08+- **Type:** fix+- **Scope:** `server`++[中文版](2026-10-08-machine-server-own-session.zh.md)++When this server starts a machine's server over ssh, that server now runs in a session of its own+(`setsid`, where the host has it). Started from this side's ssh session it belonged to that session,+so dropping the connection — a network blip, this side's machine sleeping — made sshd hang the+session up and took the far server down with it, and every program it was running along. `nohup`+alone does not cover that: the server's own child resets SIGHUP. Ported from upstream PenguinHarness+(branch `fix/machine-server-own-session`, commit `7e1dca63`), which the fork did not carry.++- `startServerCommand` prefixes the launch with `setsid` when `command -v setsid` finds one — Linux+ has it, macOS does not — and is unchanged where there is none.+- `setsid` execs in the backgrounded job's place (that job is no process group leader), so the pid+ the command prints is still the server's and the readiness probe keeps working.+- The name holding that lookup is this fork's (`ADELIE_SETSID`).diff --git a/changelog/unreleased/2026-10-08-machine-server-own-session.zh.md b/changelog/unreleased/2026-10-08-machine-server-own-session.zh.mdnew file mode 100644index 00000000..a37e8aaa--- /dev/null+++ b/changelog/unreleased/2026-10-08-machine-server-own-session.zh.md@@ -0,0 +1,19 @@+# 机器的服务端比启动它的那条 ssh 会话活得久++- **Date:** 2026-10-08+- **Type:** fix+- **Scope:** `server`++[English](2026-10-08-machine-server-own-session.md)++本服务器经 ssh 启动某台机器的服务端时,现在让它跑在**自己的会话**里(宿主有 `setsid` 时就用它)。+此前它属于本侧这条 ssh 会话:连接一断(网络抖动、本侧那台机器休眠),sshd 会把该会话挂断,对端的+服务端随之而死,它当时在跑的每一个程序也一样。单靠 `nohup` 盖不住这件事:服务端自己起的子进程会重置+SIGHUP。本次从上游 PenguinHarness 移植(分支 `fix/machine-server-own-session`,提交 `7e1dca63`),+此前本 fork 没有这一条。++- `startServerCommand` 在 `command -v setsid` 找得到时(Linux 有,macOS 没有)给启动行加上 `setsid`;+ 找不到时行为一字不变。+- 后台任务里 `setsid` 是原地 exec(该任务不是进程组长),所以命令打印出来的 pid 仍是服务端的 pid,+ 就绪探测照常工作。+- 存放这次查找结果的变量用本 fork 的名字(`ADELIE_SETSID`)。diff --git a/packages/server/src/machines/commands.ts b/packages/server/src/machines/commands.tsindex 4d6a6164..98c5ff5d 100644--- a/packages/server/src/machines/commands.ts+++ b/packages/server/src/machines/commands.ts@@ -210,8 +210,14 @@ export function unpackStoreCommand(platform: RemotePlatform, layout: RemoteLayou/*** Starts the installed server in the background and returns at once; readiness is the- * caller's probe. `nohup` and the redirections are what let it outlive the shell that ran it,- * and the log is the far side's own words when it comes up and dies.+ * caller's probe. `setsid` (where the host has it — Linux does, macOS does not) puts the server+ * in a session of its own: started from this side's ssh session it would otherwise belong to+ * that session, and when the connection drops — the hub's laptop sleeps, the network blips —+ * sshd hangs the session up and the server dies with it, taking every program it runs along.+ * `nohup` alone does not cover that: the server's own child resets SIGHUP. In a backgrounded+ * job `setsid` execs in place (the job is no process group leader), so `$!` is still the+ * server's pid. `nohup` and the redirections cover the rest, and the log is the far side's own+ * words when it comes up and dies.** Prints the launched process's pid (`$!`) as its only output, so the caller can tell a* server that is still coming up from one that already died (launchedPid, isAliveCommand).@@ -223,7 +229,7 @@ export function startServerCommand(port: number, layout: RemoteLayout): string {// it is omitted, so a login shell carrying HOST=0.0.0.0 would put that machine's server on// every interface. This side only ever reaches it as a channel inside the ssh session, at// loopback on the far end, so binding wider is exposure with nothing asking for it.- return `mkdir -p "${root}" && nohup ${remotePenguin("linux", layout)} server --host 127.0.0.1 --port ${port} >> "${root}/server.log" 2>&1 < /dev/null & echo $!`;+ return `mkdir -p "${root}" && ADELIE_SETSID=$(command -v setsid || true); $ADELIE_SETSID nohup ${remotePenguin("linux", layout)} server --host 127.0.0.1 --port ${port} >> "${root}/server.log" 2>&1 < /dev/null & echo $!`;}/** The pid startServerCommand printed; null when the output holds none. */diff --git a/packages/server/src/machines/proxy.ts b/packages/server/src/machines/proxy.tsindex ad2ba573..2c16a1af 100644--- a/packages/server/src/machines/proxy.ts+++ b/packages/server/src/machines/proxy.ts@@ -62,12 +62,25 @@ const DROP_REQUEST_HEADERS = new Set([]);const DROP_RESPONSE_HEADERS = new Set(["set-cookie", "location", "connection", "keep-alive"]);+/**+ * How long a forwarded read may wait for the machine's first answer (its headers), the dial+ * included. Under the browser's own 20 s (web api/socket.ts), so the browser hears this answer+ * rather than giving up first; over the SOCKS handshake deadline (transport/socks.ts), so a+ * stalled session is reported in that layer's words, not this one's.+ */+export const FORWARD_ANSWER_TIMEOUT_MS = 15_000;+/*** Forwards one request to the machine's server and streams the answer back — both* directions are pipes, so SSE and long downloads flow as they arrive. The socket is the* agent's: a dial through the machine's session (transport/connection.ts). node:http rather* than fetch: the Host header must be the canonical app host (`localhost:<port>`), and the* socket is not one fetch could be handed.+ *+ * A READ the machine does not start answering within `answerTimeoutMs` — its headers, dial+ * included — is answered 504 here: a channel the machine accepted and never answers would+ * otherwise hold the request, and every retry the browser makes of it, for good. Only reads:+ * a write may rightly take long, and cutting one would have the browser repeat its effect.*/function proxyThroughSession(request: Request,@@ -75,6 +88,7 @@ function proxyThroughSession(agent: http.Agent,port: number,cookie: string,+ answerTimeoutMs: number,report?: ProxyReport,): Promise<Response> {return new Promise((resolve) => {@@ -96,6 +110,7 @@ function proxyThroughSession(headers,},(res) => {+ clearTimeout(answering);report?.(path.machineId, { ok: true });const out = new Headers();for (const [name, value] of Object.entries(res.headers)) {@@ -115,7 +130,29 @@ function proxyThroughSession();},);+ // Reads only: see the doc above. A write waits for the machine however long it takes.+ const reads = request.method === "GET" || request.method === "HEAD";+ let timedOut = false;+ const answering = !reads+ ? undefined+ : setTimeout(() => {+ timedOut = true;+ const detail = `no answer to ${request.method} ${path.remotePath} in ${answerTimeoutMs} ms`;+ report?.(path.machineId, { ok: false, detail });+ upstream.destroy();+ resolve(+ Response.json(+ {+ error: { code: "machine_not_answering", message: `${path.machineId}: ${detail}.` },+ },+ { status: 504 },+ ),+ );+ }, answerTimeoutMs);+ answering?.unref?.();upstream.on("error", (err) => {+ clearTimeout(answering);+ if (timedOut) return; // answered above; this is the teardownreport?.(path.machineId, { ok: false, detail: err.message });resolve(Response.json(@@ -157,7 +194,10 @@ export function machinesProxy(machineId: string,) => Promise<{ agent: http.Agent; port: number; cookie: string } | null>,report?: ProxyReport,+ /** Test hook: how long a forwarded read may wait for its answer (FORWARD_ANSWER_TIMEOUT_MS). */+ options: { answerTimeoutMs?: number } = {},): (request: Request) => Promise<Response | null> {+ const answerTimeoutMs = options.answerTimeoutMs ?? FORWARD_ANSWER_TIMEOUT_MS;return async (request) => {const path = parseProxyPath(new URL(request.url).pathname);if (path === null) return null;@@ -173,6 +213,14 @@ export function machinesProxy({ status: 503 },);}- return proxyThroughSession(request, path, target.agent, target.port, target.cookie, report);+ return proxyThroughSession(+ request,+ path,+ target.agent,+ target.port,+ target.cookie,+ answerTimeoutMs,+ report,+ );};}diff --git a/packages/server/src/machines/transport/socks.ts b/packages/server/src/machines/transport/socks.tsindex 435c923a..b7b2bfa2 100644--- a/packages/server/src/machines/transport/socks.ts+++ b/packages/server/src/machines/transport/socks.ts@@ -16,14 +16,20 @@*/import net from "node:net";-/** How long the SOCKS handshake itself may take; the request behind it sets its own after. */-const HANDSHAKE_TIMEOUT_MS = 20_000;+/**+ * How long the SOCKS handshake itself may take; the request behind it sets its own after.+ * Opening a channel is one round trip over a session already up, so this is generous — and+ * it stays under the proxy's answer deadline (proxy.ts), so a stalled session is answered in+ * this layer's own words before anything above it gives up.+ */+export const SOCKS_HANDSHAKE_TIMEOUT_MS = 8_000;/** Dials `host:port` as seen from the machine, through the session's SOCKS port. */export function dialThroughSocks(socksPort: number,host: string,port: number,+ timeoutMs: number = SOCKS_HANDSHAKE_TIMEOUT_MS,): Promise<net.Socket> {const parts = host.split(".").map((p) => Number.parseInt(p, 10));if (parts.length !== 4 || parts.some((p) => !Number.isInteger(p) || p < 0 || p > 255)) {@@ -37,11 +43,15 @@ export function dialThroughSocks(// A handshake that stalls — a session half-dead, a far side that never answers the// channel open — must fail rather than hang the request that wanted it; the request's own// timeout only starts once it has a socket.- socket.setTimeout(HANDSHAKE_TIMEOUT_MS, () => fail("the session's SOCKS handshake timed out"));+ socket.setTimeout(timeoutMs, () => fail("the session's SOCKS handshake timed out"));let buffer = Buffer.alloc(0);let stage: "greet" | "connect" = "greet";+ let settled = false;const fail = (message: string) => {+ if (settled) return;+ settled = true;socket.removeListener("data", onData);+ socket.removeListener("close", onClose);socket.destroy();reject(new Error(message));};@@ -62,16 +72,27 @@ export function dialThroughSocks(const total = 4 + addrLen + 2;if (buffer.length < total) return;const rest = buffer.subarray(total);+ settled = true;socket.removeListener("data", onData);socket.removeListener("error", onError);+ socket.removeListener("close", onClose);socket.setTimeout(0);if (rest.length > 0) socket.unshift(rest);resolve(socket);}};const onError = (err: Error) => fail(`the session's SOCKS port did not answer: ${err.message}`);+ // Closed before the reply: OpenSSH's -D answers a CONNECT it could not open (nothing+ // listening on that port over there, or the session going down) by closing the connection,+ // with no failure reply at all. The timeout above dies with the socket, so without this the+ // dial would never settle — and neither would the request waiting on it.+ const onClose = () =>+ fail(+ `the session closed the channel to ${host}:${port} before answering — nothing is listening there, or the session is going down`,+ );socket.once("connect", () => socket.write(Buffer.from([5, 1, 0]))); // no authenticationsocket.on("data", onData);socket.once("error", onError);+ socket.once("close", onClose);});}diff --git a/packages/server/test/machines-proxy.test.ts b/packages/server/test/machines-proxy.test.tsindex 77c37dbd..9f8813f4 100644--- a/packages/server/test/machines-proxy.test.ts+++ b/packages/server/test/machines-proxy.test.ts@@ -4,6 +4,7 @@* MACHINE'S own id rather than the ssh alias.*/import http from "node:http";+import net from "node:net";import type { AddressInfo } from "node:net";import { afterEach, describe, expect, it } from "vitest";import {@@ -12,6 +13,7 @@ import {parseProxyPath,rewriteLocation,} from "../src/machines/proxy.js";+import { dialThroughSocks } from "../src/machines/transport/socks.js";/** A machine, by the id it minted. */const A = "QS7J4YVgSovi-Z2c";@@ -133,6 +135,100 @@ describe("the report", () => {expect((seen[0]![1] as { detail: string }).detail).not.toBe("");});+ it("answers 504 for a read the machine accepts and never answers, and says so", async () => {+ // A machine that took the connection and is not serving: without a deadline this+ // request — and every retry of it — would wait for good.+ let aborted = false;+ upstream = http.createServer((req) => {+ req.on("close", () => (aborted = true));+ });+ const port = await new Promise<number>((resolve) =>+ upstream!.listen(0, "127.0.0.1", () => resolve((upstream!.address() as AddressInfo).port)),+ );+ const seen: [string, { ok: boolean; detail?: string }][] = [];+ const proxy = machinesProxy(+ async () => ({ agent: new http.Agent(), port, cookie: "penguin_session=x" }),+ (machineId, outcome) => seen.push([machineId, outcome]),+ { answerTimeoutMs: 100 },+ );+ const response = await proxy(request(A));+ expect(response?.status).toBe(504);+ const body = (await response!.json()) as { error: { code: string; message: string } };+ expect(body.error.code).toBe("machine_not_answering");+ expect(body.error.message).toContain("no answer to GET /api/me in 100 ms");+ expect(seen).toEqual([[A, { ok: false, detail: "no answer to GET /api/me in 100 ms" }]]);+ await new Promise((r) => setTimeout(r, 50));+ expect(aborted).toBe(true); // the forward was let go, not left holding a channel+ upstream!.closeAllConnections();+ });++ it("does not cut a write that the machine answers late", async () => {+ // A write may rightly take long, and cutting it would have the browser repeat its effect.+ upstream = http.createServer((_req, res) => {+ setTimeout(() => {+ res.statusCode = 200;+ res.end('{"done":true}');+ }, 250);+ });+ const port = await new Promise<number>((resolve) =>+ upstream!.listen(0, "127.0.0.1", () => resolve((upstream!.address() as AddressInfo).port)),+ );+ const proxy = machinesProxy(+ async () => ({ agent: new http.Agent(), port, cookie: "penguin_session=x" }),+ undefined,+ { answerTimeoutMs: 100 },+ );+ const response = await proxy(+ new Request(`http://app.local${SERVER_PROXY_PREFIX}${A}/api/me`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: "{}",+ }),+ );+ expect(response?.status).toBe(200);+ expect(await response!.json()).toEqual({ done: true });+ });++ it("answers a read at once, in the transport's words, when the session closes the channel", async () => {+ // OpenSSH's -D answers a CONNECT to a port with nothing listening by closing the+ // connection. The read must hear that now, not wait for any deadline.+ const socks = net.createServer((client) => {+ let greeted = false;+ client.on("data", (chunk: Buffer) => {+ if (!greeted) {+ greeted = true;+ client.write(Buffer.from([5, 0]));+ if (chunk.length <= 3) return;+ }+ client.end();+ });+ });+ await new Promise<void>((resolve) => socks.listen(0, "127.0.0.1", resolve));+ const socksPort = (socks.address() as AddressInfo).port;+ const agent = new http.Agent();+ (agent as unknown as { createConnection: unknown }).createConnection = (+ _options: unknown,+ callback: (err: Error | null, socket?: net.Socket) => void,+ ) => {+ dialThroughSocks(socksPort, "127.0.0.1", 7364).then(+ (socket) => callback(null, socket),+ (err: Error) => callback(err),+ );+ };+ const proxy = machinesProxy(async () => ({+ agent,+ port: 7364,+ cookie: "penguin_session=x",+ }));+ const started = Date.now();+ const response = await proxy(request(A)).finally(() => socks.close());+ expect(response?.status).toBe(502);+ const body = (await response!.json()) as { error: { code: string; message: string } };+ expect(body.error.code).toBe("server_unreachable");+ expect(body.error.message).toContain("closed the channel to 127.0.0.1:7364");+ expect(Date.now() - started).toBeLessThan(1_000);+ });+it("reports nothing when there is no forward to try — an unasked machine is unmeasured", async () => {const seen: unknown[] = [];const proxy = machinesProxy(diff --git a/packages/server/test/machines-transport-socks.test.ts b/packages/server/test/machines-transport-socks.test.tsindex 5640190d..b344b56b 100644--- a/packages/server/test/machines-transport-socks.test.ts+++ b/packages/server/test/machines-transport-socks.test.ts@@ -5,7 +5,8 @@import http from "node:http";import net from "node:net";import { afterEach, describe, expect, it } from "vitest";-import { dialThroughSocks } from "../src/machines/transport/socks.js";+import { FORWARD_ANSWER_TIMEOUT_MS } from "../src/machines/proxy.js";+import { SOCKS_HANDSHAKE_TIMEOUT_MS, dialThroughSocks } from "../src/machines/transport/socks.js";/** Just enough SOCKS5 to answer a CONNECT: greet, connect, pipe. */function socksServer(): Promise<{ port: number; close: () => void; requests: number[] }> {@@ -58,6 +59,45 @@ function socksServer(): Promise<{ port: number; close: () => void; requests: num);}+/**+ * A SOCKS server that greets and then does `onConnect` with the CONNECT instead of opening+ * it — to play the two answers a real one gives that are not a reply code.+ */+function scriptedSocks(+ onConnect: (client: net.Socket) => void,+): Promise<{ port: number; close: () => void }> {+ const clients: net.Socket[] = [];+ const server = net.createServer((client) => {+ clients.push(client);+ let buffer = Buffer.alloc(0);+ let greeted = false;+ client.on("data", (chunk: Buffer) => {+ buffer = Buffer.concat([buffer, chunk]);+ if (!greeted) {+ if (buffer.length < 2 || buffer.length < 2 + buffer[1]!) return;+ buffer = buffer.subarray(2 + buffer[1]!);+ greeted = true;+ client.write(Buffer.from([5, 0]));+ }+ if (greeted && buffer.length >= 10) {+ buffer = Buffer.alloc(0);+ onConnect(client);+ }+ });+ });+ return new Promise((resolve) =>+ server.listen(0, "127.0.0.1", () =>+ resolve({+ port: (server.address() as net.AddressInfo).port,+ close: () => {+ for (const c of clients) c.destroy();+ server.close();+ },+ }),+ ),+ );+}+describe("dialThroughSocks", () => {const cleanups: Array<() => void> = [];afterEach(() => {@@ -109,4 +149,33 @@ describe("dialThroughSocks", () => {);await expect(dialThroughSocks(free, "127.0.0.1", 7364)).rejects.toThrow(/did not answer/);});++ it("fails at once, naming the closed channel, when the SOCKS server closes without a reply", async () => {+ // What OpenSSH's -D does when the far side has nothing listening on the port (or the+ // session is going down): no failure reply, the connection just closes. The handshake+ // deadline dies with the socket, so this must be read as the failure it is.+ const socks = await scriptedSocks((client) => client.end());+ cleanups.push(socks.close);+ const started = Date.now();+ await expect(dialThroughSocks(socks.port, "127.0.0.1", 7364)).rejects.toThrow(+ /closed the channel to 127\.0\.0\.1:7364 before answering/,+ );+ expect(Date.now() - started).toBeLessThan(SOCKS_HANDSHAKE_TIMEOUT_MS / 4);+ });++ it("gives up in its own words on a CONNECT that is never answered", async () => {+ // A session whose link has stalled: the channel open never comes back, nothing closes.+ const socks = await scriptedSocks(() => undefined);+ cleanups.push(socks.close);+ await expect(dialThroughSocks(socks.port, "127.0.0.1", 7364, 100)).rejects.toThrow(+ /SOCKS handshake timed out/,+ );+ });++ it("keeps its deadline under the proxy's, and both under the browser's 20 s", () => {+ // The order is the point: a stalled session is reported by this layer before the proxy+ // gives up on the read, and the proxy answers before the browser stops listening.+ expect(SOCKS_HANDSHAKE_TIMEOUT_MS).toBeLessThan(FORWARD_ANSWER_TIMEOUT_MS);+ expect(FORWARD_ANSWER_TIMEOUT_MS).toBeLessThan(20_000);+ });});diff --git a/packages/server/test/machines.test.ts b/packages/server/test/machines.test.tsindex 315176c8..875790a4 100644--- a/packages/server/test/machines.test.ts+++ b/packages/server/test/machines.test.ts@@ -5,6 +5,7 @@* server's own pushable image, and the exact ssh/scp commands all of that turns into.* No network, no ssh binary.*/+import { execFileSync } from "node:child_process";import fs from "node:fs";import zlib from "node:zlib";import os from "node:os";@@ -574,6 +575,34 @@ describe("startServerCommand", () => {expect(command).toContain('"$HOME/.penguin-dev/data/server.log"');});+ it("starts the server in a session of its own where setsid exists, so a dropped ssh session does not hang it up", () => {+ const command = startServerCommand(7371, DEV);+ expect(command).toContain(+ "ADELIE_SETSID=$(command -v setsid || true); $ADELIE_SETSID nohup env ",+ );+ });++ it("the launched process leads its own session, and $! is its pid (Linux)", () => {+ if (process.platform !== "linux") return;+ // The command's shape with a stand-in program: it must print the pid of a process that is+ // its own session leader (setsid), not a member of the shell's session.+ const shape = startServerCommand(7371, DEV)+ .replace(/^mkdir -p "[^"]*" && /, "")+ .replace(/nohup env .*? >> "[^"]*"/, "nohup sleep 5 >> /dev/null");+ const out = execFileSync("sh", ["-c", shape], { encoding: "utf8" });+ const pid = launchedPid(out);+ expect(pid).not.toBeNull();+ // The shell returns as soon as the job is started; setsid() runs a moment later.+ const sessionOf = () => {+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");+ return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[3]); // field 6: session id+ };+ const until = Date.now() + 2000;+ while (sessionOf() !== pid && Date.now() < until) execFileSync("sleep", ["0.05"]);+ expect(sessionOf()).toBe(pid);+ process.kill(pid!);+ });+it("prints the launched pid, and nothing else reads as one", () => {expect(startServerCommand(7371, DEV).endsWith("& echo $!")).toBe(true);expect(launchedPid("4242\n")).toBe(4242);