Skip to content
Source
Sign inSign up
pingdotgg/t3code

New application architecture #9

Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 250+ commits intomain fromcursor/new-application-architecture-f8d0opened View on GitHub

Replaces the Electron app with a Node.js CLI (t3) that launches a WebSocket server and opens a browser-based UI to simplify deployment and improve accessibility.

This PR implements the requested architectural overhaul, migrating from an Electron-based application with IPC to a Node.js runtime (apps/t3) that hosts a WebSocket API and serves a browser-based frontend (apps/renderer). The apps/desktop package has been refactored into apps/runtime to contain the core provider and process management logic, now consumed by the new Node.js server. The npx t3 command now builds the frontend, starts the local server, automatically opens the web interface, and initializes the current working directory as a project with a new session. Electron and its related dependencies have been entirely removed.


Open in Cursor Open in Web


Open with Devin
    1. Cursor Agent can help with this pull request. Just @cursor in comments and I'll start working on changes in this branch. Learn more about Cursor Agents

    2. Important

      Review skipped

      Draft detected.

      Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `cursor/new-application-architecture-f8d0`

      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Replace Electron desktop app with apps/t3 Node runtime that serves a browser UI and exposes a WebSocket NativeApi for app bootstrap and RPC

      Introduce a Node-based runtime and CLI that starts a WebSocket API server and a static web server, opens the browser, and wires the renderer to a WS-backed NativeApi. Add app.bootstrap to contracts and handle BOOTSTRAP_FROM_SERVER in the renderer store. Document the new architecture and update dev/build scripts to use the t3 CLI.

      📍Where to Start

      Start with the runtime entrypoint in main and server wiring: apps/t3/src/cli.ts, then the WebSocket API implementation in apps/t3/src/runtimeApiServer.ts. Review the renderer WS client in apps/renderer/src/wsNativeApi.ts and the bootstrap handling in apps/renderer/src/store.ts and apps/renderer/src/App.tsx.

      Changes since #9 opened

      • Introduced async runCli function that orchestrates CLI startup sequence and implements graceful shutdown with error recovery [e2a8f16]
      • Refactored main CLI entrypoint to delegate startup to runCli with explicit error handling and exit codes [e2a8f16]
      • Changed the condition for sending SIGKILL to timed-out terminal commands in runTerminalCommand to only force-kill when the child process has not exited and has not been terminated by a signal, checking child.exitCode === null && child.signalCode === null instead of checking !child.killed [cef4be1]
      • Added test coverage in the runtime API server test suite to verify that terminal commands which trap and ignore SIGTERM are force-killed after the timeout period [cef4be1]
      • Added test case for shell.openInEditor request handling with file-manager editor [abe616b]
      • Added test case for shell.openInEditor method in runtime API server [a9fbb00]

      📊 Macroscope summarized eb38f3c. 28 files reviewed, 26 issues evaluated, 11 issues filtered, 1 comment posted. View details

    4. @@ -0,0 +157,21 @@
      157+
      158+ let parsedRaw: unknown;
      159+ try {
      160+ parsedRaw = JSON.parse(decoded);
      161+ } catch {
      162+ return;
      163+ }
      164+
      165+ const parsed = wsServerMessageSchema.safeParse(parsedRaw);
      166+ if (!parsed.success) {
      167+ return;
      168+ }
      169+
      170+ if (parsed.data.type === "response") {
      171+ this.handleResponse(parsed.data);
      172+ return;
      173+ }
      174+
      175+ if (parsed.data.type === "event") {
      176+ this.handleEvent(parsed.data);
      177+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      src/wsNativeApi.ts:175 If any listener in handleEvent throws, handleMessage rejects and becomes an unhandled promise rejection (since it's called with void). Consider wrapping the handleEvent call in a try-catch.

      -    if (parsed.data.type === "event") {
      -      this.handleEvent(parsed.data);
      -    }
      +    if (parsed.data.type === "event") {
      +      try {
      +        this.handleEvent(parsed.data);
      +      } catch {
      +        // Prevent listener errors from causing unhandled rejections
      +      }
      +    }

      🚀 Want me to fix this? Reply ex: "fix it for me".

    5. @@ -0,0 +14,21 @@
      14+ reject(new Error("Could not resolve free port."));
      15+ return;
      16+ }
      17+ const { port } = address;
      18+ server.close((error) => {
      19+ if (error) {
      20+ reject(error);
      21+ return;
      22+ }
      23+ resolve(port);
      24+ });
      25+ });
      26+ server.on("error", (error) => reject(error));
      27+ });
      28+}
      29+
      30+function waitForProcessExit(processRef) {
      31+ return new Promise((resolve) => {
      32+ processRef.once("exit", (code) => resolve(code));
      33+ });
      34+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:30 If the process exits before once('exit') is attached, the promise never resolves. Consider checking processRef.exitCode !== null first and resolving immediately if already exited.

      Suggested change
      224+function waitForProcessExit(processRef) {
      225+ return new Promise((resolve) => {
      226+ if (processRef.exitCode !== null) {
      227+ resolve(processRef.exitCode);
      228+ return;
      229+ }
      230+ processRef.once("exit", (code) => resolve(code));
      231+ });
      232+}

      🚀 Want me to fix this? Reply ex: "fix it for me".

    6. @@ -25,3 +25,8 @@
      2525 return null;
      2626 }
      2727
      28+function BootstrapRouter() {
      29+ const api = readNativeApi();
      30+ const { dispatch } = useStore();
      31+
      32+ useEffect(() => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/App.tsx:32 BootstrapRouter only bootstraps once on mount. If the initial call fails and the runtime later becomes healthy, the app stays in an uninitialized state. Consider adding runtimeError to the effect dependencies and retrying bootstrap when the error clears, or consolidating retry logic with RuntimeHealthRouter.

      🚀 Want me to fix this? Reply ex: "fix it for me".

    7. ✅ Devin Review: No Issues Found

      Devin Review analyzed this PR and found no bugs or issues to report.

      Open in Devin Review
    8. @@ -27,0 +69,21 @@
      69+ let cancelled = false;
      70+
      71+ const checkHealth = async () => {
      72+ try {
      73+ await api.app.health();
      74+ if (cancelled) return;
      75+ dispatch({ type: "SET_RUNTIME_ERROR", error: null });
      76+ } catch (error) {
      77+ if (cancelled) return;
      78+ dispatch({
      79+ type: "SET_RUNTIME_ERROR",
      80+ error:
      81+ error instanceof Error
      82+ ? error.message
      83+ : "Could not connect to the local t3 runtime.",
      84+ });
      85+ }
      86+ };
      87+
      88+ void checkHealth();
      89+ const interval = window.setInterval(() => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/App.tsx:89 If api.app.health() takes longer than 8 seconds, multiple calls can overlap and stale responses may overwrite newer state. Consider adding an AbortController or sequence ID to ignore results from previous ticks.

      🚀 Want me to fix this? Reply ex: "fix it for me".

    9. @@ -0,0 +56,21 @@
      56+ });
      57+
      58+ socket.addEventListener("message", (event) => {
      59+ void this.handleMessage(event.data);
      60+ });
      61+
      62+ socket.addEventListener("close", () => {
      63+ this.socket = null;
      64+ for (const [id, pending] of this.pending.entries()) {
      65+ clearTimeout(pending.timeout);
      66+ pending.reject(new Error(`Request ${id} failed: websocket disconnected.`));
      67+ }
      68+ this.pending.clear();
      69+ });
      70+ });
      71+
      72+ return this.connectPromise;
      73+ }
      74+
      75+ private async request(method: string, params?: unknown) {
      76+ const socket = await this.connect();
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/wsNativeApi.ts:76 The connect() call hangs indefinitely if the WebSocket stays in CONNECTING state (e.g., firewall silently dropping packets), since the timeout isn't set up until after connection succeeds. Consider wrapping connect() with its own timeout, or starting the request timeout before awaiting connection.

      🚀 Want me to fix this? Reply ex: "fix it for me".

    10. @@ -0,0 +276,21 @@
      276+ stopSession: async (input) => {
      277+ await this.request("providers.stopSession", input);
      278+ },
      279+ listSessions: async () =>
      280+ this.request("providers.listSessions").then(
      281+ (value) => value as Awaited<ReturnType<NativeApi["providers"]["listSessions"]>>,
      282+ ),
      283+ onEvent: (callback) => {
      284+ this.providerEventListeners.add(callback);
      285+ return () => {
      286+ this.providerEventListeners.delete(callback);
      287+ };
      288+ },
      289+ },
      290+ shell: {
      291+ openInEditor: async (cwd, editor) => {
      292+ await this.request("shell.openInEditor", { cwd, editor });
      293+ },
      294+ },
      295+ };
      296+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/wsNativeApi.ts:296 Consider using || instead of ?? here. An empty ?ws= query param returns "", which isn't nullish, so the fallback is skipped and new WebSocket("") throws.

      Suggested change
      508+ return params.get("ws") || "ws://127.0.0.1:4317";

      🚀 Want me to fix this? Reply ex: "fix it for me".

    11. @@ -0,0 +150,21 @@
      150+ }
      151+ }
      152+ }
      153+
      154+ private async decodeIncomingMessage(raw: unknown): Promise<string | null> {
      155+ if (typeof raw === "string") {
      156+ return raw;
      157+ }
      158+
      159+ if (raw instanceof ArrayBuffer) {
      160+ return textDecoder.decode(raw);
      161+ }
      162+
      163+ if (raw instanceof Blob) {
      164+ return raw.text();
      165+ }
      166+
      167+ return null;
      168+ }
      169+
      170+ private async handleMessage(raw: unknown) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/wsNativeApi.ts:170 Messages may process out of order because handleMessage is async but called without await. If a slow Blob.text() decode is followed by a fast string decode, the second message finishes first. Consider adding a message queue to preserve ordering, or document if out-of-order delivery is acceptable.

      🚀 Want me to fix this? Reply ex: "fix it for me".

    12. Devin Review found 1 new potential issue.

      View 8 additional findings in Devin Review.

      Open in Devin Review
      @@ -330,0 +357,21 @@
      357+ return {
      358+ ...state,
      359+ projects: existingProject
      360+ ? state.projects.map((entry) =>
      361+ entry.id === existingProject.id
      362+ ? {
      363+ ...entry,
      364+ model: resolveModelSlug(bootstrap.model),
      365+ }
      366+ : entry,
      367+ )
      368+ : [project, ...state.projects],
      369+ threads: state.threads
      370+ .map((entry) =>
      371+ entry.id === thread.id
      372+ ? {
      373+ ...entry,
      374+ session: bootstrap.session,
      375+ codexThreadId: bootstrap.session.threadId ?? entry.codexThreadId,
      376+ error: bootstrap.bootstrapError ?? entry.error,
      377+ }
      devin-ai-integration[bot](GitHub profile, opens in a new tab)commented

      🟡 BOOTSTRAP_FROM_SERVER preserves stale thread errors on successful re-bootstrap

      When the runtime re-bootstraps successfully after a previous failure, stale error messages persist on existing threads instead of being cleared.

      Root Cause

      In the BOOTSTRAP_FROM_SERVER reducer case at apps/renderer/src/store.ts:377, the error field for an existing thread is set via:

      error: bootstrap.bootstrapError ?? entry.error,

      When a bootstrap succeeds, bootstrap.bootstrapError is undefined (the field is optional in AppBootstrapResult at packages/contracts/src/ipc.ts:29). The nullish coalescing operator ?? then falls through to entry.error, preserving the old error.

      Contrast this with the new thread path at apps/renderer/src/store.ts:353:

      error: bootstrap.bootstrapError ?? null,

      Here, undefined ?? null correctly evaluates to null, clearing the error.

      Impact: A user who encounters a bootstrap failure (e.g. Codex can't initialize) will continue to see the stale error banner on their thread even after the runtime reconnects successfully. The error is only cleared by creating a brand new thread. This is especially problematic because the RuntimeHealthRouter in App.tsx clears runtimeError on successful health checks, so the global "Offline" indicator disappears while the thread-level error persists — giving contradictory signals.

      Suggested change
      377- }
      377+ error: bootstrap.bootstrapError ?? null,
      Open in Devin Review

      Was this helpful? React with 👍 or 👎 to provide feedback.

    13. @@ -0,0 +26,21 @@
      26+ });
      27+}
      28+
      29+function waitForProcessExit(processRef) {
      30+ return new Promise((resolve) => {
      31+ processRef.once("exit", (code) => resolve(code));
      32+ });
      33+}
      34+
      35+async function terminateProcess(processRef, timeoutMs = 5_000) {
      36+ if (processRef.exitCode !== null || processRef.signalCode !== null) {
      37+ return;
      38+ }
      39+
      40+ processRef.kill("SIGTERM");
      41+ const exited = await Promise.race([
      42+ waitForProcessExit(processRef).then(() => true),
      43+ new Promise((resolve) => {
      44+ setTimeout(() => resolve(false), timeoutMs);
      45+ }),
      46+ ]);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:41 The setTimeout at line 44 leaks if the process exits before the timeout fires. Consider clearing the timer when the race resolves.

      -  const exited = await Promise.race([
      -    waitForProcessExit(processRef).then(() => true),
      -    new Promise((resolve) => {
      -      setTimeout(() => resolve(false), timeoutMs);
      -    }),
      -  ]);
      +  let timer;
      +  const exited = await Promise.race([
      +    waitForProcessExit(processRef).then(() => true),
      +    new Promise((resolve) => {
      +      timer = setTimeout(() => resolve(false), timeoutMs);
      +    }),
      +  ]);
      +  clearTimeout(timer);

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around lines 41-46:
      
      The `setTimeout` at line 44 leaks if the process exits before the timeout fires. Consider clearing the timer when the race resolves.
    14. @@ -0,0 +33,21 @@
      33+}
      34+
      35+async function terminateProcess(processRef, timeoutMs = 5_000) {
      36+ if (processRef.exitCode !== null || processRef.signalCode !== null) {
      37+ return;
      38+ }
      39+
      40+ processRef.kill("SIGTERM");
      41+ const exited = await Promise.race([
      42+ waitForProcessExit(processRef).then(() => true),
      43+ new Promise((resolve) => {
      44+ setTimeout(() => resolve(false), timeoutMs);
      45+ }),
      46+ ]);
      47+
      48+ if (exited) {
      49+ return;
      50+ }
      51+
      52+ processRef.kill("SIGKILL");
      53+ await waitForProcessExit(processRef);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:52 The SIGKILL fallback on line 53 awaits waitForProcessExit without a timeout, unlike the SIGTERM path. Consider adding a timeout here too to prevent indefinite hangs if the process fails to terminate.

      -  processRef.kill("SIGKILL");
      -  await waitForProcessExit(processRef);
      +  processRef.kill("SIGKILL");
      +  await Promise.race([
      +    waitForProcessExit(processRef),
      +    new Promise((resolve) => setTimeout(resolve, timeoutMs)),
      +  ]);

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around lines 52-53:
      
      The `SIGKILL` fallback on line 53 awaits `waitForProcessExit` without a timeout, unlike the `SIGTERM` path. Consider adding a timeout here too to prevent indefinite hangs if the process fails to terminate.
    15. @@ -0,0 +79,21 @@
      79+ `Smoke test failed: unauthorized websocket received ${messageCount} message(s) before close.`,
      80+ ),
      81+ );
      82+ return;
      83+ }
      84+ resolve();
      85+ });
      86+ socket.addEventListener("error", () => {
      87+ clearTimeout(timer);
      88+ reject(new Error("Smoke test failed: websocket client error before close."));
      89+ });
      90+ });
      91+}
      92+
      93+function waitForStartupUrl(readOutput, processRef, timeoutMs = 20_000) {
      94+ return new Promise((resolve, reject) => {
      95+ const finish = (callback, value) => {
      96+ clearInterval(timer);
      97+ processRef.off("exit", onExit);
      98+ callback(value);
      99+ };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:94 If the process exits between line 108 and 111, finish calls clearInterval(timer) while timer is still in the TDZ, causing a ReferenceError. Consider using let timer before attaching the exit listener, or moving the listener attachment after the setInterval.

       return new Promise((resolve, reject) => {
      +    let timer;
           const finish = (callback, value) => {
      -      clearInterval(timer);
      +      if (timer) clearInterval(timer);
             processRef.off("exit", onExit);
             callback(value);
           };

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around lines 94-99:
      
      If the process exits between line 108 and 111, `finish` calls `clearInterval(timer)` while `timer` is still in the TDZ, causing a `ReferenceError`. Consider using `let timer` before attaching the exit listener, or moving the listener attachment after the `setInterval`.
    16. @@ -0,0 +78,21 @@
      78+ new Error(
      79+ `Smoke test failed: unauthorized websocket received ${messageCount} message(s) before close.`,
      80+ ),
      81+ );
      82+ return;
      83+ }
      84+ resolve();
      85+ });
      86+ socket.addEventListener("error", () => {
      87+ clearTimeout(timer);
      88+ reject(new Error("Smoke test failed: websocket client error before close."));
      89+ });
      90+ });
      91+}
      92+
      93+function waitForStartupUrl(readOutput, processRef, timeoutMs = 20_000) {
      94+ return new Promise((resolve, reject) => {
      95+ const finish = (callback, value) => {
      96+ clearInterval(timer);
      97+ processRef.off("exit", onExit);
      98+ callback(value);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:94 After onExit calls finish(), the interval may fire once more before clearInterval takes effect, invoking the callback twice. Consider adding a finished flag to guard against multiple invocations.

       return new Promise((resolve, reject) => {
      +    let finished = false;
           const finish = (callback, value) => {
      +      if (finished) return;
      +      finished = true;
             clearInterval(timer);
             processRef.off("exit", onExit);
             callback(value);
           };

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around lines 94-98:
      
      After `onExit` calls `finish()`, the interval may fire once more before `clearInterval` takes effect, invoking the callback twice. Consider adding a `finished` flag to guard against multiple invocations.
    17. @@ -0,0 +32,21 @@
      32+ });
      33+}
      34+
      35+async function terminateProcess(processRef, timeoutMs = 5_000) {
      36+ if (processRef.exitCode !== null || processRef.signalCode !== null) {
      37+ return;
      38+ }
      39+
      40+ processRef.kill("SIGTERM");
      41+ const exited = await Promise.race([
      42+ waitForProcessExit(processRef).then(() => true),
      43+ new Promise((resolve) => {
      44+ setTimeout(() => resolve(false), timeoutMs);
      45+ }),
      46+ ]);
      47+
      48+ if (exited) {
      49+ return;
      50+ }
      51+
      52+ processRef.kill("SIGKILL");
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:52 Consider wrapping processRef.kill("SIGKILL") in a try-catch—the process could exit between the timeout and the kill call, causing an ESRCH error.

      -  processRef.kill("SIGKILL");
      +  try {
      +    processRef.kill("SIGKILL");
      +  } catch {
      +    // Process may have exited after timeout check
      +  }

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around line 52:
      
      Consider wrapping `processRef.kill("SIGKILL")` in a try-catch—the process could exit between the timeout and the kill call, causing an `ESRCH` error.
    18. @@ -0,0 +1,15 @@
      1+import { spawn } from "node:child_process";
      2+import fs from "node:fs";
      3+import { createServer } from "node:net";
      4+import path from "node:path";
      5+import { fileURLToPath } from "node:url";
      6+
      7+function getFreePort() {
      8+ return new Promise((resolve, reject) => {
      9+ const server = createServer();
      10+ server.listen(0, "127.0.0.1", () => {
      11+ const address = server.address();
      12+ if (!address || typeof address !== "object") {
      13+ reject(new Error("Could not resolve free port."));
      14+ return;
      15+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:12 If server.address() returns an invalid value, the server isn't closed before rejecting, leaving the port and file descriptor open. Consider calling server.close() before rejecting.

      Suggested change
      207+ if (!address || typeof address !== "object") {
      208+ server.close();
      209+ reject(new Error("Could not resolve free port."));
      210+ return;
      211+ }

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around lines 12-15:
      
      If `server.address()` returns an invalid value, the server isn't closed before rejecting, leaving the port and file descriptor open. Consider calling `server.close()` before rejecting.
    19. @@ -0,0 +74,21 @@
      74+ return;
      75+ }
      76+ if (messageCount > 0) {
      77+ reject(
      78+ new Error(
      79+ `Smoke test failed: unauthorized websocket received ${messageCount} message(s) before close.`,
      80+ ),
      81+ );
      82+ return;
      83+ }
      84+ resolve();
      85+ });
      86+ socket.addEventListener("error", () => {
      87+ clearTimeout(timer);
      88+ reject(new Error("Smoke test failed: websocket client error before close."));
      89+ });
      90+ });
      91+}
      92+
      93+function waitForCloseCode(socket, expectedCode, label, timeoutMs = 10_000) {
      94+ return new Promise((resolve, reject) => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:94 If the socket is already closed when called, the close event won't fire and this will always timeout. Consider checking socket.readyState === WebSocket.CLOSED at the start and resolving/rejecting immediately based on the socket's closeCode.

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around line 94:
      
      If the socket is already closed when called, the `close` event won't fire and this will always timeout. Consider checking `socket.readyState === WebSocket.CLOSED` at the start and resolving/rejecting immediately based on the socket's `closeCode`.
    20. @@ -0,0 +126,21 @@
      126+ );
      127+ }, timeoutMs);
      128+
      129+ const onMessage = (event) => {
      130+ let message;
      131+ try {
      132+ message = JSON.parse(String(event.data));
      133+ } catch {
      134+ return;
      135+ }
      136+
      137+ if (message.type !== "response" || message.id !== request.id) {
      138+ return;
      139+ }
      140+
      141+ clearTimeout(timer);
      142+ socket.removeEventListener("message", onMessage);
      143+ resolve(message);
      144+ };
      145+
      146+ socket.addEventListener("message", onMessage);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:146 If socket.send() throws synchronously, the timer and event listener remain attached. Consider wrapping socket.send() in a try-catch that clears the timer and removes the listener before re-throwing.

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around line 146:
      
      If `socket.send()` throws synchronously, the timer and event listener remain attached. Consider wrapping `socket.send()` in a try-catch that clears the timer and removes the listener before re-throwing.
    21. @@ -0,0 +158,21 @@
      158+function waitForWsEvent(socket, matcher, label, timeoutMs = 20_000) {
      159+ return new Promise((resolve, reject) => {
      160+ const timer = setTimeout(() => {
      161+ socket.removeEventListener("message", onMessage);
      162+ reject(new Error(`Smoke test failed: ${label} websocket event timed out.`));
      163+ }, timeoutMs);
      164+
      165+ const onMessage = (event) => {
      166+ let message;
      167+ try {
      168+ message = JSON.parse(String(event.data));
      169+ } catch {
      170+ return;
      171+ }
      172+
      173+ if (message.type !== "event") {
      174+ return;
      175+ }
      176+ if (!matcher(message)) {
      177+ return;
      178+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:176 Unhandled errors inside async callbacks (event listeners/timers) can leave the returned Promise pending and leak resources. Suggest wrapping these callback bodies in try/catch, then clear timers/remove listeners and reject.

      Suggested change
      423+ let matched;
      424+ try {
      425+ matched = matcher(message);
      426+ } catch (err) {
      427+ clearTimeout(timer);
      428+ socket.removeEventListener("message", onMessage);
      429+ reject(err);
      430+ return;
      431+ }
      432+ if (!matched) {
      433+ return;
      434+ }

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around lines 176-178:
      
      Unhandled errors inside async callbacks (event listeners/timers) can leave the returned `Promise` pending and leak resources. Suggest wrapping these callback bodies in `try/catch`, then clear timers/remove listeners and reject.
    22. @@ -0,0 +111,21 @@
      111+ if (event.code !== expectedCode) {
      112+ reject(
      113+ new Error(
      114+ `Smoke test failed: expected ${label} close code ${expectedCode}, received ${event.code}.`,
      115+ ),
      116+ );
      117+ return;
      118+ }
      119+ if (label === "replaced-client" && event.reason !== "replaced-by-new-client") {
      120+ reject(
      121+ new Error(
      122+ `Smoke test failed: expected replaced-client close reason "replaced-by-new-client", received ${JSON.stringify(
      123+ event.reason,
      124+ )}.`,
      125+ ),
      126+ );
      127+ return;
      128+ }
      129+ resolve();
      130+ });
      131+ socket.addEventListener("error", () => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      scripts/smoke-test.mjs:131 After "error" rejects the promise, the "close" listener remains attached and may still execute on a settled promise. Consider using { once: true } for both listeners, or removing them explicitly after either fires.

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/t3/scripts/smoke-test.mjs around line 131:
      
      After `"error"` rejects the promise, the `"close"` listener remains attached and may still execute on a settled promise. Consider using `{ once: true }` for both listeners, or removing them explicitly after either fires.
    23. @@ -27,0 +55,21 @@
      55+ return () => {
      56+ cancelled = true;
      57+ };
      58+ }, [api, dispatch]);
      59+
      60+ return null;
      61+}
      62+
      63+function RuntimeHealthRouter() {
      64+ const api = readNativeApi();
      65+ const { dispatch } = useStore();
      66+
      67+ useEffect(() => {
      68+ if (!api) return;
      69+ let cancelled = false;
      70+
      71+ const checkHealth = async () => {
      72+ try {
      73+ await api.app.health();
      74+ if (cancelled) return;
      75+ dispatch({ type: "SET_RUNTIME_ERROR", error: null });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      src/App.tsx:75 The health check clears runtimeError on success, which can overwrite errors from BootstrapRouter. Consider either using separate error state keys, or only clearing errors that the health check itself previously set.

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/renderer/src/App.tsx around line 75:
      
      The health check clears `runtimeError` on success, which can overwrite errors from `BootstrapRouter`. Consider either using separate error state keys, or only clearing errors that the health check itself previously set.

Sign in to join this conversation.