mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-20 07:04:17 +01:00
fix(browse): chain with no flow is a usage error before any daemon boots (#3039)
Empty piped input, a terminal with no arguments, and a readFileSync(0) error (EAGAIN, EOF) now print the chain usage with the cause and its troubleshooting link and exit 1 before ensureServer(), instead of sending an empty argument to a daemon the CLI booted for it. Tests run the real CLI with no daemon and no browser, plus the stub-daemon flow. Co-authored-by: VaibDeveloper <VaibDeveloper@users.noreply.github.com>
This commit is contained in:
1 parent
b964eed524
commit
c9766e3540
3 files changed
+106
-12
No files matched your search
+35
-3
@@ -1652,6 +1652,33 @@ async function handlePairAgent(state: ServerState, args: string[]): Promise<void
|
||||
* replace it). Bun reads NO_PROXY when the first fetch runs, so this must run
|
||||
* before any fetch. The daemon inherits the same value.
|
||||
*/
|
||||
export const CHAIN_NO_FLOW_ANCHOR = 'https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#browse-chain-no-flow';
|
||||
|
||||
/**
|
||||
* The flow `browse chain` runs when it has no arguments: stdin, read only when
|
||||
* it is not a terminal. A terminal, empty input or a read error (EAGAIN, EOF)
|
||||
* is a usage error.
|
||||
*/
|
||||
export function readChainFlow(isTTY: boolean, readStdin: () => string): { ok: true; flow: string } | { ok: false; error: string } {
|
||||
let cause = 'stdin is a terminal';
|
||||
if (!isTTY) {
|
||||
try {
|
||||
const flow = readStdin().trim();
|
||||
if (flow) return { ok: true, flow };
|
||||
cause = 'stdin was empty';
|
||||
} catch (err: any) {
|
||||
cause = `stdin could not be read (${err?.code ?? err?.message ?? String(err)})`;
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
error: `[browse] chain: no flow to run (${cause}).\n` +
|
||||
'Usage: echo \'[["goto","url"],["text"]]\' | browse chain\n' +
|
||||
' or: browse chain \'goto url | click @e5 | snapshot -ic\'\n' +
|
||||
CHAIN_NO_FLOW_ANCHOR,
|
||||
};
|
||||
}
|
||||
|
||||
export function withLoopbackNoProxy(env: Record<string, string | undefined>): string {
|
||||
const entries = (env.NO_PROXY ?? env.no_proxy ?? '').split(',').map(e => e.trim()).filter(Boolean);
|
||||
for (const host of ['127.0.0.1', 'localhost', '::1']) if (!entries.includes(host)) entries.push(host);
|
||||
@@ -2037,10 +2064,15 @@ Refs: After 'snapshot', use @e1, @e2... as selectors:
|
||||
// Special case: chain reads from stdin. Synchronously: on Windows an awaited
|
||||
// Bun.stdin.text() inside this un-awaited main() did not keep the event loop
|
||||
// alive, so a piped flow exited 0 with nothing sent to the daemon (#3039).
|
||||
// A terminal has no flow to read; the empty argument gets the server's usage.
|
||||
// No flow (a terminal, empty input, an unreadable stdin) is a usage error
|
||||
// before ensureServer(): it never boots a daemon.
|
||||
if (command === 'chain' && commandArgs.length === 0) {
|
||||
const stdin = process.stdin.isTTY ? '' : fs.readFileSync(0, 'utf8');
|
||||
commandArgs.push(stdin.trim());
|
||||
const flow = readChainFlow(Boolean(process.stdin.isTTY), () => fs.readFileSync(0, 'utf8'));
|
||||
if (!flow.ok) {
|
||||
console.error(flow.error);
|
||||
process.exit(1);
|
||||
}
|
||||
commandArgs.push(flow.flow);
|
||||
}
|
||||
|
||||
// #2219 IRON RULE (pair-agent leg): capture whether a LIVE daemon predates
|
||||
|
||||
@@ -3,28 +3,35 @@
|
||||
* an awaited Bun.stdin.text() inside the CLI's un-awaited main() let the
|
||||
* process exit 0 before reading, so a replayed flow "passed" with nothing
|
||||
* sent to the daemon. The CLI reads stdin synchronously; this drives the real
|
||||
* CLI against a stub daemon (the Windows free lane runs it natively).
|
||||
* CLI against a stub daemon (the Windows free lane runs it natively). No flow
|
||||
* (empty input, a terminal, an unreadable stdin) is a usage error before
|
||||
* ensureServer(), so it never boots a daemon.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
|
||||
import { CHAIN_NO_FLOW_ANCHOR, readChainFlow } from '../src/cli';
|
||||
|
||||
const CLI = path.resolve(import.meta.dir, '../src/cli.ts');
|
||||
|
||||
describe('#3039: chain reads its flow from piped stdin', () => {
|
||||
let scratch: string;
|
||||
let daemon: ReturnType<typeof Bun.serve>;
|
||||
let received: Array<{ command: string; args: string[] }>;
|
||||
let hits: string[];
|
||||
|
||||
beforeEach(() => {
|
||||
scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-chain-stdin-'));
|
||||
received = [];
|
||||
hits = [];
|
||||
daemon = Bun.serve({
|
||||
hostname: '127.0.0.1',
|
||||
port: 0,
|
||||
fetch: async (req) => {
|
||||
const url = new URL(req.url);
|
||||
hits.push(url.pathname);
|
||||
if (url.pathname === '/health') return Response.json({ status: 'healthy' });
|
||||
if (url.pathname === '/command') {
|
||||
const body = await req.json();
|
||||
@@ -41,16 +48,20 @@ describe('#3039: chain reads its flow from piped stdin', () => {
|
||||
fs.rmSync(scratch, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function runChain(stdin: string) {
|
||||
async function runChain(stdin: string | 'ignore', opts: { daemon?: boolean } = {}) {
|
||||
const stateFile = path.join(scratch, 'browse.json');
|
||||
fs.writeFileSync(stateFile, JSON.stringify({ pid: process.pid, port: daemon.port, token: 'chain-stdin-test', mode: 'launched' }));
|
||||
if (opts.daemon !== false) {
|
||||
fs.writeFileSync(stateFile, JSON.stringify({ pid: process.pid, port: daemon.port, token: 'chain-stdin-test', mode: 'launched' }));
|
||||
}
|
||||
const env: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (value !== undefined && !/^(BROWSE_|GSTACK_)/.test(key)) env[key] = value;
|
||||
if (value !== undefined && !/^(BROWSE_|GSTACK_|PLAYWRIGHT_)/.test(key)) env[key] = value;
|
||||
}
|
||||
Object.assign(env, { HOME: scratch, GSTACK_HOME: path.join(scratch, '.gstack'), BROWSE_STATE_FILE: stateFile });
|
||||
// Browser dependencies unavailable: a daemon boot attempt could not succeed.
|
||||
Object.assign(env, { HOME: scratch, GSTACK_HOME: path.join(scratch, '.gstack'), BROWSE_STATE_FILE: stateFile,
|
||||
PLAYWRIGHT_BROWSERS_PATH: path.join(scratch, 'no-browsers') });
|
||||
const cli = Bun.spawn([process.execPath, CLI, 'chain'], {
|
||||
cwd: scratch, env, stdin: new TextEncoder().encode(stdin), stdout: 'pipe', stderr: 'pipe',
|
||||
cwd: scratch, env, stdin: stdin === 'ignore' ? 'ignore' : new TextEncoder().encode(stdin), stdout: 'pipe', stderr: 'pipe',
|
||||
});
|
||||
const timer = setTimeout(() => cli.kill('SIGKILL'), 30_000);
|
||||
const [code, stdout, stderr] = await Promise.all([cli.exited, new Response(cli.stdout).text(), new Response(cli.stderr).text()]);
|
||||
@@ -66,9 +77,46 @@ describe('#3039: chain reads its flow from piped stdin', () => {
|
||||
expect(r.code).toBe(0);
|
||||
}, 45_000);
|
||||
|
||||
test('empty stdin is a usage error, never a silent exit 0', async () => {
|
||||
test('empty stdin is a usage error, never a silent exit 0, and never reaches the daemon', async () => {
|
||||
const r = await runChain('');
|
||||
expect(r.code).not.toBe(0);
|
||||
expect(r.out).toContain('Usage');
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toContain('[browse] chain: no flow to run (stdin was empty).');
|
||||
expect(r.out).toContain('Usage: echo');
|
||||
expect(r.out).toContain(CHAIN_NO_FLOW_ANCHOR);
|
||||
expect(hits).toEqual([]);
|
||||
}, 45_000);
|
||||
|
||||
test('with no daemon, whitespace-only or closed stdin exits 1 without booting one', async () => {
|
||||
for (const stdin of [' \n\t\n', 'ignore'] as const) {
|
||||
const r = await runChain(stdin, { daemon: false });
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toContain('[browse] chain: no flow to run (stdin was empty).');
|
||||
expect(fs.existsSync(path.join(scratch, 'browse.json'))).toBe(false);
|
||||
expect(fs.existsSync(path.join(scratch, '.gstack'))).toBe(false);
|
||||
}
|
||||
}, 45_000);
|
||||
});
|
||||
|
||||
describe('readChainFlow: no flow is a usage error', () => {
|
||||
test('a terminal never reads stdin', () => {
|
||||
let read = false;
|
||||
const r = readChainFlow(true, () => { read = true; return '[["text"]]'; });
|
||||
expect(read).toBe(false);
|
||||
expect(r).toEqual({ ok: false, error: expect.stringContaining('no flow to run (stdin is a terminal)') });
|
||||
});
|
||||
|
||||
test('a read error (EAGAIN, EOF) is a usage error naming the code', () => {
|
||||
for (const code of ['EAGAIN', 'EOF']) {
|
||||
const r = readChainFlow(false, () => { throw Object.assign(new Error(code), { code }); });
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.error).toContain(`no flow to run (stdin could not be read (${code}))`);
|
||||
expect(r.error).toContain('Usage: echo');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('piped input is trimmed and returned', () => {
|
||||
expect(readChainFlow(false, () => ' [["text"]]\n')).toEqual({ ok: true, flow: '[["text"]]' });
|
||||
});
|
||||
});
|
||||
@@ -582,6 +582,20 @@ hooks stay.
|
||||
|
||||
## Browser
|
||||
|
||||
<a id="browse-chain-no-flow"></a>
|
||||
### `[browse] chain: no flow to run (stdin was empty)` (or `stdin is a terminal`, `stdin could not be read (EAGAIN)`)
|
||||
|
||||
**Meaning.** `browse chain` with no arguments runs the JSON flow piped to it.
|
||||
Nothing arrived, so it exits 1 before starting a browser. It used to exit 0 on
|
||||
Windows having run nothing.
|
||||
|
||||
**Fix.** Pipe the flow, or pass it as an argument:
|
||||
|
||||
```bash
|
||||
echo '[["goto","https://example.com"],["text"]]' | browse chain
|
||||
browse chain 'goto https://example.com | text'
|
||||
```
|
||||
|
||||
<a id="browse-chromium-path-failed"></a>
|
||||
### `Chromium at GSTACK_CHROMIUM_PATH=<path> failed to launch: ...`
|
||||
|
||||
|
||||
Reference in new issue
Block a user