Skip to content

refactor runtime contracts and web transports - #16197

Merged
nwparker merged 5 commits into
stablyai:mainfrom
nwparker:nwparker/less-big-runtime-contracts-web
Aug 25, 2026
Merged

nwparker merged 5 commits into
stablyai:mainfrom
nwparker:nwparker/less-big-runtime-contracts-web

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

Summary\n\n- split shared runtime contracts into focused terminal, workspace, browser, repository, mobile, and provider contract modules\n- split remote runtime connection, handshake, request/response, subscription, heartbeat, and reconnect responsibilities\n- split web runtime transport and subscription management\n- preserve all wire shapes, opcodes, capability behavior, optional-field omission, and public façades\n- retain distinct malformed-auth and pairing-token rejection diagnostics\n- remove the three completed max-lines baseline entries\n\n## Validation\n\n- 89 focused runtime/router/web transport tests\n- 5 mixed-version wire tests\n- exact public export parity: 173 / 6 / 3\n- optional-field omission coverage\n- Node and web typechecks\n- targeted lint, cycle, and formatting checks\n- changed-code quality with zero findings\n- max-lines and runtime-Electron ratchets\n- independent review, focused fix, and clean re-review

@coderabbitai

coderabbitai Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR splits runtime contracts into dedicated browser, file, session, terminal, and worktree modules. It adds shared remote runtime handshake routers and subscription transports. It adds web runtime connection transport components for RPC, subscriptions, reconnection, heartbeats, and waiters. WebRuntimeClient now delegates these behaviors to the new transport. File-watch subscriptions use a dedicated adapter. Export-parity and authentication error tests cover the new structure.

Merge Risk: 🟡 Moderate · up to e3987

This refactor changes runtime connection and web transport handling, but the current head still has bounded edge-case risks: malformed frames may surface as handler exceptions, timed-out waiters can remain retained, and a healthy slow connection may be closed after returning from a hidden state. These issues should be fixed or explicitly accepted before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a relevant summary and validation details, but it omits most required template sections, including ELI5, Why, Linked Issue, Visual Proof, Testing checklist, AI Disclosure, Rev… Complete the required template sections. Add the linked issue after “Fixes #”, provide Visual Proof or state exactly “N/A” with a reason, document testing and platform coverage, complete the required checklists, and address security, compat…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 32 functions across 27 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary changes: runtime contract refactoring and web transport refactoring.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description provides a relevant summary and validation details, but it omits most required template sections, including ELI5, Why, Linked Issue, Visual Proof, Testing checklist, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist.

Resolution

Complete the required template sections. Add the linked issue after “Fixes #”, provide Visual Proof or state exactly “N/A” with a reason, document testing and platform coverage, complete the required checklists, and address security, compatibility, performance, and upstream-boundary considerations.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/renderer/src/web/web-runtime-client.ts (1)

20-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Share one constant for the replayable/shared-connection method set.

SHARED_CONNECTION_SUBSCRIPTION_METHODS here and REPLAYABLE_SUBSCRIPTION_METHODS in src/renderer/src/web/web-runtime-subscription-registry.ts (Line 3) both hold ['files.watch']. The two sets must stay equal: a method routed through the shared connection but absent from the registry set is closed instead of replayed after an interruption. Export one constant from web-runtime-subscription-contract.ts and import it in both places.

src/renderer/src/web/web-runtime-client-export-parity.test.ts (1)

6-7: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

These two assertions compare each type to itself and cannot fail.

expectTypeOf<T>().toEqualTypeOf<T>() is a tautology. It only proves the name is exported. If SubscribeOptions loses buildUnsubscribe, or WebRuntimeSubscriptionHandle loses sendBinary, the test still passes. Pin the expected structure to make the parity check real.

💚 Proposed fix
-  expectTypeOf<WebClient.SubscribeOptions>().toEqualTypeOf<WebClient.SubscribeOptions>()
-  expectTypeOf<WebClient.WebRuntimeSubscriptionHandle>().toEqualTypeOf<WebClient.WebRuntimeSubscriptionHandle>()
+  expectTypeOf<WebClient.SubscribeOptions>().toEqualTypeOf<{
+    timeoutMs?: number
+    buildUnsubscribe?: (params: unknown) => { method: string; params: unknown } | null
+  }>()
+  expectTypeOf<WebClient.WebRuntimeSubscriptionHandle>().toEqualTypeOf<{
+    unsubscribe: () => void
+    sendBinary: (bytes: Uint8Array<ArrayBufferLike>) => void
+  }>()

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6183f314-6d19-45bb-8629-f379cc1191cd

📥 Commits

Reviewing files that changed from the base of the PR and between 5bcbaff and 8947500.

📒 Files selected for processing (27)
  • config/max-lines-baseline.txt
  • src/renderer/src/web/web-runtime-client-export-parity.test.ts
  • src/renderer/src/web/web-runtime-client.ts
  • src/renderer/src/web/web-runtime-connection-frame-router.ts
  • src/renderer/src/web/web-runtime-connection-heartbeat.ts
  • src/renderer/src/web/web-runtime-connection-transport.ts
  • src/renderer/src/web/web-runtime-connection-waiters.ts
  • src/renderer/src/web/web-runtime-file-watch-subscription.ts
  • src/renderer/src/web/web-runtime-request-registry.ts
  • src/renderer/src/web/web-runtime-subscription-contract.ts
  • src/renderer/src/web/web-runtime-subscription-registry.ts
  • src/shared/remote-runtime-client-handshake.ts
  • src/shared/remote-runtime-client.test.ts
  • src/shared/remote-runtime-client.ts
  • src/shared/remote-runtime-request-response-router.test.ts
  • src/shared/remote-runtime-request-response-router.ts
  • src/shared/remote-runtime-subscription-frame-router.test.ts
  • src/shared/remote-runtime-subscription-frame-router.ts
  • src/shared/remote-runtime-subscription-transport.ts
  • src/shared/remote-runtime-transport-error-agreement.test.ts
  • src/shared/runtime-browser-contracts.ts
  • src/shared/runtime-client-export-parity.test.ts
  • src/shared/runtime-file-contracts.ts
  • src/shared/runtime-session-contracts.ts
  • src/shared/runtime-terminal-contracts.ts
  • src/shared/runtime-types.ts
  • src/shared/runtime-worktree-contracts.ts
💤 Files with no reviewable changes (1)
  • config/max-lines-baseline.txt

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +26 to +51
return new Promise((resolve, reject) => {
const timeout = window.setTimeout(() => {
const index = this.waiters.findIndex((waiter) => waiter.resolve === resolve)
if (index !== -1) {
this.waiters.splice(index, 1)
}
reject(
new Error(
withRemoteRuntimeTailscaleHint(
'Timed out while connecting to the remote Orca runtime.',
this.options.endpoint
)
)
)
}, timeoutMs)
this.waiters.push({
resolve: () => {
window.clearTimeout(timeout)
resolve()
},
reject: (error) => {
window.clearTimeout(timeout)
reject(error)
}
})
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

The timeout cleanup never removes the waiter.

The array stores a wrapper function as resolve, not the promise resolve captured on Line 26. The comparison waiter.resolve === resolve on Line 28 is therefore always false, and the timed-out waiter stays in this.waiters until the next resolveAll or rejectAll. Track the entry object instead.

♻️ Proposed fix
     return new Promise((resolve, reject) => {
+      const entry = {
+        resolve: () => {
+          window.clearTimeout(timeout)
+          resolve()
+        },
+        reject: (error: Error) => {
+          window.clearTimeout(timeout)
+          reject(error)
+        }
+      }
       const timeout = window.setTimeout(() => {
-        const index = this.waiters.findIndex((waiter) => waiter.resolve === resolve)
+        const index = this.waiters.indexOf(entry)
         if (index !== -1) {
           this.waiters.splice(index, 1)
         }
         reject(
           new Error(
             withRemoteRuntimeTailscaleHint(
               'Timed out while connecting to the remote Orca runtime.',
               this.options.endpoint
             )
           )
         )
       }, timeoutMs)
-      this.waiters.push({
-        resolve: () => {
-          window.clearTimeout(timeout)
-          resolve()
-        },
-        reject: (error) => {
-          window.clearTimeout(timeout)
-          reject(error)
-        }
-      })
+      this.waiters.push(entry)
     })

timeout is referenced inside entry only when the callbacks run, so the TDZ is not hit. If you prefer, declare let timeout: number before entry for clarity.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return new Promise((resolve, reject) => {
const timeout = window.setTimeout(() => {
const index = this.waiters.findIndex((waiter) => waiter.resolve === resolve)
if (index !== -1) {
this.waiters.splice(index, 1)
}
reject(
new Error(
withRemoteRuntimeTailscaleHint(
'Timed out while connecting to the remote Orca runtime.',
this.options.endpoint
)
)
)
}, timeoutMs)
this.waiters.push({
resolve: () => {
window.clearTimeout(timeout)
resolve()
},
reject: (error) => {
window.clearTimeout(timeout)
reject(error)
}
})
})
return new Promise((resolve, reject) => {
const entry = {
resolve: () => {
window.clearTimeout(timeout)
resolve()
},
reject: (error: Error) => {
window.clearTimeout(timeout)
reject(error)
}
}
const timeout = window.setTimeout(() => {
const index = this.waiters.indexOf(entry)
if (index !== -1) {
this.waiters.splice(index, 1)
}
reject(
new Error(
withRemoteRuntimeTailscaleHint(
'Timed out while connecting to the remote Orca runtime.',
this.options.endpoint
)
)
)
}, timeoutMs)
this.waiters.push(entry)
})

Comment on lines +33 to +42
if ((authenticated as { type?: unknown }).type === 'e2ee_authenticated') {
return { kind: 'authenticated' }
}
return {
kind: 'rejected',
unauthorized:
typeof authenticated === 'object' &&
authenticated !== null &&
(authenticated as { error?: { code?: unknown } }).error?.code === 'unauthorized'
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect parseRemoteRuntimeJsonText to confirm null-literal handling.
fd -t f 'remote-runtime-request-frames.ts' | xargs -r -I{} sed -n '1,60p' {}

Repository: stablyai/orca

Length of output: 2079


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- handshake ---'
cat -n src/shared/remote-runtime-client-handshake.ts | sed -n '1,90p'
printf '%s\n' '--- references ---'
rg -n -C 3 'classifyRemoteRuntimeReadyFrame|handleAuthenticatedFrame|parseReadyFrame|RemoteRuntimeClientError' src
printf '%s\n' '--- JSON null behavior ---'
node - <<'JS'
const value = JSON.parse('null')
console.log({ value, type: typeof value, isNull: value === null })
try {
  console.log(value.type)
} catch (error) {
  console.log({ name: error.name, message: error.message })
}
JS

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- JSON null behavior ---'
node - <<'JS'
const value = JSON.parse('null')
console.log(JSON.stringify({ value, type: typeof value, isNull: value === null }))
try {
  console.log(value.type)
} catch (error) {
  console.log(JSON.stringify({ name: error.name, message: error.message }))
}
JS

printf '%s\n' '--- subscription router ---'
cat -n src/shared/remote-runtime-subscription-frame-router.ts | sed -n '25,115p'

printf '%s\n' '--- request-response router ---'
cat -n src/shared/remote-runtime-request-response-router.ts | sed -n '35,125p'

printf '%s\n' '--- request connection message handling ---'
cat -n src/shared/remote-runtime-request-connection.ts | sed -n '175,260p'

Repository: stablyai/orca

Length of output: 10360


Guard authenticated before reading .type.

JSON.parse('null') returns null, so Line 33 throws a TypeError outside the parser’s try/catch. Both frame routers then skip their structured error callbacks and can leave the request pending until timeout. Use the existing object-and-null check before the e2ee_authenticated comparison.

@coderabbitai

coderabbitai Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 92cb03e6-7fca-4385-86a4-13dcb2d0bfe8

📥 Commits

Reviewing files that changed from the base of the PR and between 5ebc4bb and e398744.

📒 Files selected for processing (28)
  • config/max-lines-baseline.txt
  • src/renderer/src/web/web-runtime-client-export-parity.test.ts
  • src/renderer/src/web/web-runtime-client-timeout-budget.test.ts
  • src/renderer/src/web/web-runtime-client.ts
  • src/renderer/src/web/web-runtime-connection-frame-router.ts
  • src/renderer/src/web/web-runtime-connection-heartbeat.ts
  • src/renderer/src/web/web-runtime-connection-transport.ts
  • src/renderer/src/web/web-runtime-connection-waiters.ts
  • src/renderer/src/web/web-runtime-file-watch-subscription.ts
  • src/renderer/src/web/web-runtime-request-registry.ts
  • src/renderer/src/web/web-runtime-subscription-contract.ts
  • src/renderer/src/web/web-runtime-subscription-registry.ts
  • src/shared/remote-runtime-client-handshake.ts
  • src/shared/remote-runtime-client.test.ts
  • src/shared/remote-runtime-client.ts
  • src/shared/remote-runtime-request-response-router.test.ts
  • src/shared/remote-runtime-request-response-router.ts
  • src/shared/remote-runtime-subscription-frame-router.test.ts
  • src/shared/remote-runtime-subscription-frame-router.ts
  • src/shared/remote-runtime-subscription-transport.ts
  • src/shared/remote-runtime-transport-error-agreement.test.ts
  • src/shared/runtime-browser-contracts.ts
  • src/shared/runtime-client-export-parity.test.ts
  • src/shared/runtime-file-contracts.ts
  • src/shared/runtime-session-contracts.ts
  • src/shared/runtime-terminal-contracts.ts
  • src/shared/runtime-types.ts
  • src/shared/runtime-worktree-contracts.ts
💤 Files with no reviewable changes (1)
  • config/max-lines-baseline.txt
🚧 Files skipped from review as they are similar to previous changes (22)
  • src/shared/runtime-worktree-contracts.ts
  • src/shared/remote-runtime-request-response-router.ts
  • src/shared/remote-runtime-subscription-frame-router.test.ts
  • src/renderer/src/web/web-runtime-connection-waiters.ts
  • src/shared/runtime-client-export-parity.test.ts
  • src/shared/runtime-file-contracts.ts
  • src/renderer/src/web/web-runtime-client-export-parity.test.ts
  • src/renderer/src/web/web-runtime-subscription-contract.ts
  • src/renderer/src/web/web-runtime-request-registry.ts
  • src/shared/runtime-terminal-contracts.ts
  • src/renderer/src/web/web-runtime-file-watch-subscription.ts
  • src/shared/runtime-browser-contracts.ts
  • src/shared/remote-runtime-client-handshake.ts
  • src/shared/remote-runtime-transport-error-agreement.test.ts
  • src/shared/remote-runtime-client.test.ts
  • src/renderer/src/web/web-runtime-client.ts
  • src/renderer/src/web/web-runtime-subscription-registry.ts
  • src/renderer/src/web/web-runtime-connection-transport.ts
  • src/shared/remote-runtime-subscription-frame-router.ts
  • src/shared/remote-runtime-request-response-router.test.ts
  • src/shared/remote-runtime-subscription-transport.ts
  • src/shared/remote-runtime-client.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +78 to +81
private rebaseline(): void {
this.lastHeartbeatTickAt = this.options.now()
this.heartbeatProbeSentAt = null
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Reset inbound timing when visibility returns.

rebaseline() leaves lastInboundFrameAt stale. After a long hidden period, the next tick sends a probe early and can close a healthy but slow-to-respond socket. Set lastInboundFrameAt to the same now value.

@nwparker
nwparker merged commit 8217e68 into stablyai:main Aug 25, 2026
48 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 25, 2026
* refactor runtime contracts and transports

* test(web): repoint two-phase timeout seam at the transport that now owns call()

(cherry picked from commit 8217e68)
Jinwoo-H added a commit that referenced this pull request Aug 25, 2026
Four conflicts, all against module splits main landed on top of the
previous merge (d456549).

src/shared/runtime-types.ts
  Main's #16197 dissolved this into a re-export shell over five contract
  modules. Took the shell; our three additions moved to
  src/shared/runtime-session-contracts.ts, where the types now live:
  RuntimeMobileSessionBrowserTab's browserProfileId/executionHostKey/
  placement, UNPUBLISHED_WORKTREE_PUBLICATION_EPOCH ('none', unchanged —
  the merge base already sends it), and
  RuntimeMobileSessionTabsResult.clientHostedPagesUnreconciled. The shell
  re-exports the epoch as a value so existing importers keep working.

src/shared/remote-runtime-client.ts
  Main split the file into a handshake module, a request/response router
  and a subscription transport. Took main's shape and relocated our
  delta: the clientCapabilities threading stayed on the request path,
  and the subscription-side machinery moved into the transport. Two
  further splits were forced by the max-lines ratchet, which main shrank
  past both files when it split them and which may not grow again:
  sendRemoteRuntimeRequestOnSocket moved to
  remote-runtime-request-socket.ts, and the transport's outbound queues
  and nested-request machinery became
  remote-runtime-subscription-outbound.ts and
  remote-runtime-subscription-request-channel.ts. Behaviour is
  unchanged; remote-runtime-subscription-request.test.ts (out-of-order
  routing, capacity bound, reject-on-close, exactly-once memory release)
  passes untouched against the rewrite.

src/main/ipc/ssh.ts
  Main's #16394 split it into focused modules. The browser-partition
  teardown followed removeRegisteredSshTarget into
  src/main/ipc/ssh-session-teardown.ts, ordering intact: release, clear,
  a 500ms delayed second pass for the prepare-racing-removal window, all
  inside the same target-lifecycle callback. The connection-manager
  resolver wiring stayed in registerSshHandlers, and getSshConnectionManager
  is re-exported from ssh-target-registry rather than defined here, so
  the browser network route can read it without pulling in ipcMain.

src/shared/child-process/__fixtures__/child-process-import-allowlist.txt
  Comment-block union; both sides' entries had already merged cleanly.

runtime-client-export-parity.test.ts pins the public surface, so it
records the widened signatures and the new value export.
No wire changes: every field added is optional and no opcode moved.
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
* refactor runtime contracts and transports

* test(web): repoint two-phase timeout seam at the transport that now owns call()
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* refactor runtime contracts and transports

* test(web): repoint two-phase timeout seam at the transport that now owns call()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant