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
4 changes: 2 additions & 2 deletions desktop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ An Electron app that runs the installed EvoScientist core (`EvoSci deploy --json
- `src/main.ts`: builds those dependencies from Electron and wires its events: single instance, window, menu, IPC.
- `src/boot.ts`: the launch sequence (version check; install or repair with the bundled install script, `src/install.ts`; `EvoSci setup`, `src/setup.ts`, or the node stage; workspace; `deploy`), testable without Electron.
- `src/loginPath.ts`: on macOS the packaged app reads the login shell's `PATH` once at startup (an app opened from Finder or the Dock gets launchd's minimal one) and uses it for every child process and to find `EvoSci`. Only `PATH` is taken; when no shell answers within 10 s each, the inherited `PATH` stays. The desktop log names the shell it came from.
- `src/preload.ts`: hands the backend URL to the WebUI before its scripts run; exposes the WebUI's bridge (`window.evoscientistDesktop`: `restartBackend()`, `defaultFolder`, `projectFolders` (the default and launch folders in the core's key form), `pickFolder()`, `appUpdate`, `chatgpt` (`signIn()`, `cancelSignIn()`, `signOut()`)) and the status page's bridge (`evoStatus`, with its `update` members).
- `src/chatgpt.ts`: the ChatGPT sign-in through the core: runs `EvoSci login chatgpt --json` (opens the `url` it prints in the browser; closing its stdin cancels it) and `EvoSci logout chatgpt --json`. `app.ts` runs one sign-in at a time, from the `sign_in_required` error screen (with its waiting screen) or from the WebUI's Settings page and setup wizard through the bridge.
- `src/preload.ts`: hands the backend URL to the WebUI before its scripts run; exposes the WebUI's bridge (`window.evoscientistDesktop`: `restartBackend()`, `defaultFolder`, `projectFolders` (the default and launch folders in the core's key form), `pickFolder()`, `appUpdate`, `chatgpt` (`signIn()`, `cancelSignIn()`, `signOut()`, `isSigningIn()`, `waitForSignIn()`)) and the status page's bridge (`evoStatus`, with its `update` members).
- `src/chatgpt.ts`: the ChatGPT sign-in through the core: runs `EvoSci login chatgpt --json` (opens the `url` it prints in the browser; closing its stdin cancels it) and `EvoSci logout chatgpt --json`. `app.ts` runs one sign-in at a time, from the `sign_in_required` error screen (with its waiting screen) or from the WebUI's Settings page and setup wizard through the bridge; a page opened again during a sign-in asks whether one runs and waits for its end.
- `src/appUpdate.ts`: the app's own updates from GitHub Releases (electron-updater), on Windows and on macOS: a check 5 s after start and then hourly, Download only on request, the stall and check limits; `app.ts` runs Restart to update. On macOS it also says where the app cannot be replaced, tells `app.ts` when the system refuses an update, and forgets an install that did not end the app.
- `resources/status.html`: the static status and error page, shown until the UI server answers. It never calls the backend.
- `resources/ui-entry.mjs`: starts the bundled WebUI server (`dist/server.js` from the root build) with Electron's own Node.
Expand Down
41 changes: 41 additions & 0 deletions desktop/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3460,6 +3460,47 @@ describe("ChatGPT from the page", () => {
expect(fake.startSignIn).toHaveBeenCalledTimes(2);
});

it("tells the page whether a sign-in runs, for the UI's origin only", async () => {
const fake = fakeSignIn();
const h = await launched({ startSignIn: fake.startSignIn });
expect(h.app.chatgptRunningFor(UI)).toBe(false);
const result = h.app.chatgptSignInFor(UI);
expect(h.app.chatgptRunningFor(UI)).toBe(true);
expect(h.app.chatgptRunningFor("http://evil.example")).toBe(false);
expect(h.app.chatgptRunningFor(null)).toBe(false);
fake.finish({ ok: true, plan: "plus" });
await result;
expect(h.app.chatgptRunningFor(UI)).toBe(false);
});

it("a page that waits gets the running sign-in's answer and opens nothing", async () => {
const fake = fakeSignIn();
const h = await launched({ startSignIn: fake.startSignIn });
expect(await h.app.waitChatgptSignInFor(UI)).toBeNull();
const first = h.app.chatgptSignInFor(UI);
fake.url(SIGN_IN_URL);
const waited = h.app.waitChatgptSignInFor(UI);
expect(await h.app.waitChatgptSignInFor("http://evil.example")).toBeNull();
expect(await h.app.waitChatgptSignInFor(null)).toBeNull();
expect(fake.startSignIn).toHaveBeenCalledTimes(1);
expect(h.deps.openExternal).toHaveBeenCalledTimes(1);
const failed = { ok: false as const, code: "port_in_use", message: "" };
fake.finish(failed);
expect(await waited).toEqual(failed);
expect(await first).toEqual(failed);
expect(await h.app.waitChatgptSignInFor(UI)).toBeNull();
});

it("a waiting page hears a cancel from another page", async () => {
const fake = fakeSignIn();
const h = await launched({ startSignIn: fake.startSignIn });
void h.app.chatgptSignInFor(UI);
const waited = h.app.waitChatgptSignInFor(UI);
h.app.cancelChatgptSignInFor(UI);
expect(await waited).toMatchObject({ ok: false, code: "cancelled" });
expect(h.app.chatgptRunningFor(UI)).toBe(false);
});

/** Deploys that answer in this order: ready, or sign_in_required. */
function deploysOf(kinds: ("ready" | "sign_in")[]) {
let i = 0;
Expand Down
13 changes: 13 additions & 0 deletions desktop/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,16 @@ export interface App {
* its end. `not_allowed` for another origin, `busy` during a quit. */
chatgptSignInFor(senderOrigin: string | null): Promise<SignInOutcome>;
cancelChatgptSignInFor(senderOrigin: string | null): void;
/** Whether a ChatGPT sign-in runs, for a page from `senderOrigin`
* (false for another origin): a page that comes back during one shows
* it. */
chatgptRunningFor(senderOrigin: string | null): boolean;
/** The end of the sign-in that runs, or null at once when none does (and
* for another origin). Opens nothing, unlike a joining
* `chatgptSignInFor`. */
waitChatgptSignInFor(
senderOrigin: string | null
): Promise<SignInOutcome | null>;
/** The bridge's sign-out: the work check first (Cancel answers
* `cancelled` and keeps the token), then `EvoSci logout chatgpt`.
* `not_allowed` for another origin; `busy` during a quit, a sign-in or
Expand Down Expand Up @@ -2013,6 +2023,9 @@ export function createApp(deps: AppDeps): App {
cancelChatgptSignInFor: (senderOrigin) => {
if (fromUi(senderOrigin)) void signIn?.run.cancel();
},
chatgptRunningFor: (senderOrigin) => fromUi(senderOrigin) && !!signIn,
waitChatgptSignInFor: async (senderOrigin) =>
fromUi(senderOrigin) && signIn ? signIn.done : null,
chatgptSignOutFor: async (senderOrigin) => {
if (!fromUi(senderOrigin)) {
log.warn(`chatgpt sign-out refused for the origin ${senderOrigin}`);
Expand Down
127 changes: 127 additions & 0 deletions desktop/src/chatgpt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
signOut,
startSignIn,
type ChatgptDeps,
type SignInOutcome,
type SignInRun,
} from "./chatgpt";
import { run, type RunOptions } from "./proc";
Expand Down Expand Up @@ -353,6 +354,132 @@ describe("startSignIn", () => {
);
});

/** A login that has exited while something else holds its output open. */
function exitedHoldingOutput(code: number, stopMs = 50) {
const lines: string[] = [];
let lineOut: ((l: string) => void) | undefined;
let exit!: () => void;
const exited = new Promise<{ code: number; signal: null }>(
(res) => (exit = () => res({ code, signal: null }))
);
const deps: ChatgptDeps = {
...base,
stopMs,
ceilingMs: 60_000,
log: { info: (m) => lines.push(m), warn: (m) => lines.push(m) },
spawn: (_f, _a, opts) => {
lineOut = opts.onStdoutLine;
return {
child: { pid: undefined } as never,
exited,
closed: new Promise(() => {}),
closeStdin: () => exit(),
};
},
};
return { deps, lines, exit, say: (l: string) => lineOut?.(l) };
}

it("answers an exit without a terminal line while its output stays open", async () => {
const h = exitedHoldingOutput(3);
const r = startSignIn("EvoSci", () => {}, h.deps);
h.exit();
expect(await r.done).toEqual({
ok: false,
code: "internal_error",
message: "EvoSci login exited (code 3).",
});
expect(h.lines).toContain(
"EvoSci login exited, but its output stayed open; answering without the rest"
);
// The output was waited for once, not again after the answer.
expect(h.lines).not.toContain(
"EvoSci login exited, but its output stayed open after its answer"
);
});

it("answers a cancel whose login exited while its output stays open", async () => {
const h = exitedHoldingOutput(1);
const r = startSignIn("EvoSci", () => {}, h.deps);
const started = Date.now();
await r.cancel();
expect(await r.done).toEqual({
ok: false,
code: "cancelled",
message: "",
});
expect(Date.now() - started).toBeLessThan(1000);
});

it("keeps a terminal line that comes while the output is read after the exit", async () => {
const h = exitedHoldingOutput(1);
const r = startSignIn("EvoSci", () => {}, h.deps);
await r.cancel();
h.say(
JSON.stringify({
protocol: 1,
event: "error",
code: "cancelled",
message: "ChatGPT sign-in was cancelled.",
})
);
expect(await r.done).toEqual({
ok: false,
code: "cancelled",
message: "ChatGPT sign-in was cancelled.",
});
expect(h.lines).not.toContain(
"EvoSci login exited, but its output stayed open; answering without the rest"
);
});

it("answers within stopMs of the exit, also when the line comes late in it", async () => {
vi.useFakeTimers();
try {
const h = exitedHoldingOutput(0, 1000);
const r = startSignIn("EvoSci", () => {}, h.deps);
let answer: SignInOutcome | null = null;
void r.done.then((o) => (answer = o));
h.exit();
await vi.advanceTimersByTimeAsync(900);
h.say(JSON.stringify({ protocol: 1, event: "signed_in", plan: "plus" }));
await vi.advanceTimersByTimeAsync(150);
expect(answer).toEqual({ ok: true, plan: "plus" });
} finally {
vi.useRealTimers();
}
});

it("answers a cancelled login whose child keeps the output open", async () => {
// The login starts a child that inherits its output and outlives it,
// then exits on the cancel without a terminal line.
const lines: string[] = [];
const r = startSignIn("EvoSci", () => {}, {
...base,
stopMs: 100,
log: { info: (m) => lines.push(m), warn: (m) => lines.push(m) },
spawn: fake(
`const c = require("child_process").spawn(process.execPath, ["-e", "setTimeout(() => {}, 4000)"], { stdio: ["ignore", "inherit", "inherit"] }); console.error("child " + c.pid); process.stdin.on("end", () => process.exit(1)); process.stdin.resume();`
),
});
await new Promise((res) => setTimeout(res, 300));
const started = Date.now();
try {
await r.cancel();
expect(await r.done).toEqual({
ok: false,
code: "cancelled",
message: "",
});
expect(Date.now() - started).toBeLessThan(2000);
} finally {
const child = lines
.map((l) => /^login stderr: child (\d+)$/.exec(l)?.[1])
.find(Boolean);
if (child) await killPid(Number(child));
}
});

it("cancel waits for the exit after ending the tree", async () => {
const w = watched(
`${say({
Expand Down
53 changes: 38 additions & 15 deletions desktop/src/chatgpt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// `error` line. Closing its stdin cancels it. `EvoSci logout chatgpt --json`
// removes the stored token and ends with `signed_out` or `error`.
import { parseChatgptEvent } from "./lines";
import { killTree, run, withTimeout, type Logger } from "./proc";
import { killTree, run, withTimeout, type ExitInfo, type Logger } from "./proc";

export const SIGN_IN_ARGS = ["login", "chatgpt", "--json"];
export const SIGN_OUT_ARGS = ["logout", "chatgpt", "--json"];
Expand All @@ -25,7 +25,8 @@ export type SignOutOutcome =
export interface SignInRun {
/** The terminal line (`internal_error` when EvoSci exits without one),
* given once the process has gone, or after the bounded attempts to end
* it (a failed kill is logged). */
* it (a failed kill is logged). Output a child of the login keeps open
* is read for at most SIGN_IN_STOP_MS after the exit. */
done: Promise<SignInOutcome>;
/** Closes stdin (the core answers `cancelled`), then ends the tree when it
* has not exited after SIGN_IN_STOP_MS. Resolves once the process has
Expand Down Expand Up @@ -78,6 +79,8 @@ export function startSignIn(
let settled = false;
let cancelled = false;
let timedOut = false;
/** The login exited and its output stayed open for `stopMs`. */
let outputHeld = false;
let stopping: Promise<void> | null = null;
let urlSeen = false;
let resolveDone!: (o: SignInOutcome) => void;
Expand All @@ -102,7 +105,14 @@ export function startSignIn(
// the port, and a quit must still be able to wait for it.
void (async () => {
try {
if ((await withTimeout(proc.closed, stopMs)) !== "timeout") return;
// Its output was waited for already.
if (outputHeld) return;
// After the exit the output gets one `stopMs`, counted from the exit,
// not again from an answer that came late in it.
const end = exitedYet
? await drained
: await withTimeout(proc.closed, stopMs);
if (end !== "timeout") return;
if (exitedYet) {
deps.log.warn(
"EvoSci login exited, but its output stayed open after its answer"
Expand Down Expand Up @@ -172,6 +182,8 @@ export function startSignIn(

let exitedYet = false;
void proc.exited.then(() => (exitedYet = true));
/** The output read after the exit, for at most `stopMs`. */
const drained = proc.exited.then(() => withTimeout(proc.closed, stopMs));

function cancel(): Promise<void> {
proc.closeStdin();
Expand Down Expand Up @@ -204,19 +216,30 @@ export function startSignIn(
void cancel().then(() => settle(TIMED_OUT));
}, deps.ceilingMs ?? SIGN_IN_CEILING_MS);

/** The answer of a login that ended without a terminal line. A cancel the
* core did not answer (it was ended) is still a cancel. */
const unanswered = (exit: ExitInfo): SignInOutcome =>
cancelled
? { ok: false, code: "cancelled", message: "" }
: {
ok: false,
code: "internal_error",
message: `EvoSci login exited (code ${exit.code}).`,
};

// Read to the end of the output: `exit` can come before the last line.
void proc.closed.then((exit) =>
// A cancel the core did not answer (it was ended) is still a cancel.
settle(
cancelled
? { ok: false, code: "cancelled", message: "" }
: {
ok: false,
code: "internal_error",
message: `EvoSci login exited (code ${exit.code}).`,
}
)
);
void proc.closed.then((exit) => settle(unanswered(exit)));
// A child of the login can keep its output open after it has gone: past
// `stopMs` the run answers without the rest, so a new sign-in is not held
// up until the ceiling.
void proc.exited.then(async (exit) => {
if ((await drained) !== "timeout" || settled) return;
deps.log.warn(
"EvoSci login exited, but its output stayed open; answering without the rest"
);
outputHeld = true;
settle(unanswered(exit));
});

return {
done,
Expand Down
6 changes: 6 additions & 0 deletions desktop/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,12 @@ function registerIpc(): void {
ipcMain.handle("desktop:chatgpt-cancel-sign-in", (e) =>
desktop.cancelChatgptSignInFor(senderOrigin(e))
);
ipcMain.handle("desktop:chatgpt-running", (e) =>
desktop.chatgptRunningFor(senderOrigin(e))
);
ipcMain.handle("desktop:chatgpt-wait", (e) =>
desktop.waitChatgptSignInFor(senderOrigin(e))
);
ipcMain.handle("desktop:chatgpt-sign-out", (e) =>
desktop.chatgptSignOutFor(senderOrigin(e))
);
Expand Down
4 changes: 4 additions & 0 deletions desktop/src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ function exposeBridge(): void {
ipcRenderer.invoke("desktop:chatgpt-sign-in"),
cancelSignIn: (): Promise<void> =>
ipcRenderer.invoke("desktop:chatgpt-cancel-sign-in"),
isSigningIn: (): Promise<boolean> =>
ipcRenderer.invoke("desktop:chatgpt-running"),
waitForSignIn: (): Promise<SignInOutcome | null> =>
ipcRenderer.invoke("desktop:chatgpt-wait"),
signOut: (): Promise<SignOutOutcome> =>
ipcRenderer.invoke("desktop:chatgpt-sign-out"),
},
Expand Down
Loading
Loading