Skip to content

feat(jcode): first-class agent — live status, questions, notifications, send-to-agent, orchestration - #22539

Merged
nwparker merged 18 commits into
mainfrom
nwparker/jcode-harness
Oct 3, 2026
Merged

nwparker merged 18 commits into
mainfrom
nwparker/jcode-harness

Conversation

@nwparker

@nwparker nwparker commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 37 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1924 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1907
Prod 86 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2605 $\color{#cf222e}{\Huge{\mathbf{−}}}$​681 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1924

ELI5

Jcode is a fast coding agent that runs in a terminal. Orca could already start it, but once it was running Orca had no idea what it was doing — no live status, no "it's asking you something", no way to send it work, and it couldn't be used as an orchestration worker.

This makes Jcode behave like Claude, Codex and the rest: you can see what it's doing while it does it, you get told when it finishes or needs you, you can send it a prompt from anywhere in the app, hand it a task as a supervised worker, use it to write commit messages, and find and resume its past sessions.

What Changed

This takes over #10521 (@czzczz), rebases it onto current main, and finishes the integration.

Status — from "after the fact" to live. The original wiring only subscribed to jcode's post_tool and turn_end, so a pane sat blank from the moment you hit Enter until the first tool finished, and a three-minute bash showed nothing at all. Orca now also subscribes to:

  • turn_start — jcode fires this the instant a prompt is submitted, before the model generates. That is the window that used to be blank.
  • pre_tool — the only event that carries the tool's arguments, so the row can say "read README.md" while it runs rather than after.

Every mapping is written against jcode's own captured payloads, recorded and documented in a new docs/reference/jcode-hook-events.md.

pre_tool is a gate, so it is handled as one. jcode blocks the tool call until the hook exits and reads its stderr to EOF. The managed script therefore drains the tool input off stdin (a large write exceeds the pipe buffer and would stall the agent mid-write) and runs the POST detached with both pipes closed. A contract test pins this: with a server that accepts and never replies, a synchronous POST takes 1522 ms per tool call and the detached one takes ~10 ms.

Questions. jcode has no per-tool approval prompt — its safety model denies or asks the model to justify, both inside the tool. The one tool a human answers is ambient mode's request_permission. A pre_tool for it now maps to waiting and publishes the full tool input as the question card; post_tool deliberately does not, because by then the human has already answered. The original substring matcher (ask/confirm/permission…) is replaced with jcode's real tool names.

Agent rows showed jcode's screensaver instead of your work. jcode repaints its OSC title about once a second as 🌐 jcode Puppy · +3 -0 · last ~23s. Orca accepted that as the row's conversation name, so a jcode row read jcode Pupp… where the Claude row beside it read the prompt and the reply. Orca now recognises that title shape as identity, not content, and falls back to the prompt like every other agent.

Orchestration didn't work at all. A dispatched jcode worker died at agent_readiness with Timed out waiting for responsive server socket. Cause: Orca gives every pane its own JCODE_RUNTIME_DIR, so every jcode pane is a cold daemon start, and jcode's client waits a hardcoded 5 s for that socket. Orca now starts the pane's daemon as the PTY spawns, giving it the shell's own startup time as head start. Same dispatch now reaches worker: succeeded.

A crash the original introduced. Its new OSC-color-reply skip called the pane launch-agent ladder on every pane connect, where an unguarded ?.identity.agentType threw — 24 failures across 8 connectPanePty suites. The ladder is now a pure, tested module, and the skip is evaluated per query rather than captured at install time (a pane connects before its launch agent is registered, so the captured verdict answered jcode's burst anyway — the exact leak the skip exists to prevent).

One reverse-scan, not three. The jcode journal reader the original added was a near-copy of command-code-transcript.ts's reverse chunked line scan, which is itself a near-copy of transcript-reader.ts's. All three now share one tested scanFileRegionsBackward — a net deletion, and the subtle carry-chunk arithmetic lives in one place. jcode's managed hook script likewise drops its hand-rolled curl for the shared buildPosixAgentHookPostCommand, which gains it the raw-JSON transport and the --noproxy 127.0.0.1 guard the bespoke copy was missing (a user with http_proxy set was routing hook POSTs through their proxy). Two behaviour notes for the reviewer: transcript-reader now clamps its last chunk to the 4 MB budget instead of overshooting by up to one chunk, and jcode's event name is read from its own event key, since the shared transport posts the payload verbatim rather than restating fields on a form.

Smaller fixes on top of #10521

  • removeJcodeManagedHooks rebuilt the config from the lines it kept but stopped at the table after [hooks] — uninstalling deleted every table declared after it. Regression-tested.
  • Source Control AI now discovers models with jcode model list instead of a hardcoded list that named models jcode does not have (claude-sonnet-4, gpt-5.4).
  • jcode registered in the managed-hook command contract, the script refresher, and the AI Vault every-agent fixture — three ratchets the original missed.
  • turn_end keeps the finished turn's tool, because the completion notification only fires when the done row carries a reply or a tool.

Why

The gap this closes is the one @lnilluv described on #10521: launching was done, the hook layer was not. The follow-up work landed there, but against the events that are cheapest to consume rather than the ones that describe what jcode is doing. Reading pre_tool is what makes the status live, and it is only safe because the gate contract is handled explicitly — hence the latency test rather than a comment promising it is fine.

The alternative for per-pane attribution was to drop the per-pane daemon and let all panes share one, which is cheaper (~57 MB per extra daemon) but attributes every pane's events to whichever pane started the daemon. jcode does forward a client's terminal identity to hooks, but its allowlist covers tmux/zellij/herdr, not ORCA_PANE_KEY; if that lands upstream the isolation and the pre-warm can both go.

Linked Issue

Fixes #10830

Visual Proof

All captured in a real Orca dev build driving a real jcode 0.87.1, one worktree, one session.

Launch — jcode in the agent picker

https://github.com/user-attachments/assets/3b973806-1c03-4070-a17a-847b116d72b8

Status, live through one turn. Prompt: "Use bash to run: sleep 18 && echo SLOW. Then read README.md and say TRACE_DONE."

turn_start → working, before any tool has run (this frame was blank before):

https://github.com/user-attachments/assets/e2a3a68d-f9e5-4b55-a31f-4843be2c10ea

pre_tool → the tool and its argument, while the tool runs:

https://github.com/user-attachments/assets/ad9e7cf3-cb26-46be-b3c7-d1f5e6abc916

Working through a long bash, with the model on the row:

https://github.com/user-attachments/assets/e8b7512a-d105-4799-a373-788e4d101477

turn_end → done, with the reply:

https://github.com/user-attachments/assets/397ef5be-c0b6-454e-b31d-3d1b496eba36

Questions — request_permission maps to waiting, orange "?" on both the workspace and the agent row, tool line naming the question:

https://github.com/user-attachments/assets/9cf0d8e0-09b8-4be5-baa2-09b37ce2d9f0

Notifications — completion while backgrounded raises the unread bell on the workspace:

https://github.com/user-attachments/assets/2555747d-df61-465a-b7a2-0dba8f5b1e84

Send to agent — the jcode pane is an eligible target:

https://github.com/user-attachments/assets/e29b4c09-bc98-412a-aa07-0fa4715768a4

…and the prompt lands in the running TUI, which answers it:

https://github.com/user-attachments/assets/09de677e-92c0-4405-9d6a-748e7baf4976

Orchestration — a supervised jcode worker, nested under its coordinator, labelled with the orchestration task title and its reply (worker: succeeded):

https://github.com/user-attachments/assets/c7951eb9-a643-42e4-8c4c-2e99270306f5

Source Control AI — Jcode in the agent list:

https://github.com/user-attachments/assets/82104cbc-25fe-402e-b305-ba89f7039f14

…generating a commit message (the [Tokens] usage line stripped):

https://github.com/user-attachments/assets/0243188b-26a0-4df9-bf54-a7cd18ed3025

AI Vault — jcode sessions indexed with titles, previews, message counts and models:

https://github.com/user-attachments/assets/6a4d3dc6-5467-4622-99ec-ea66dcd7db83

orca worktree ps — the reader orchestration coordinators poll — showing the full round trip:

[
 {
  "branch": "jcode-worker-2",
  "agentType": "jcode",
  "state": "done",
  "prompt": "… === TASK === Read README.md in this worktree and reply with exactly: ORCHESTRATION_WORKER_OK",
  "lastAssistantMessage": "… here is the required response:\n\n**ORCHESTRATION_WORKER_OK**",
  "taskTitle": "jcode orchestration proof",
  "toolName": "bash"
 },
 {
  "branch": "jcode-first-class",
  "agentType": "jcode",
  "state": "done",
  "prompt": "You have 1 orchestration message. Run `orca orchestration check --run run_89a54ed596b6`.",
  "lastAssistantMessage": "… The orchestration system has recorded that the README.md was read successfully."
 }
]

Resume — the vault's own command, replayed against the session it names:

$ cd '…/jcode-first-class' && jcode --resume 'session_monkey_…' run \
    "In one short sentence: what did I ask you to do in this session?"
You asked me to generate a git commit message for the staged changes in your repository.

Testing

macOS, real jcode 0.87.1, real turns — everything above was driven through the app, not stubbed. The one exception is the request_permission question: jcode's ambient permission flow is not reachable from a normal TUI turn, so that event was delivered by running jcode's own installed hook script with the payload jcode produces for it. Everything downstream of the script is the real path.

Automated — ~150 jcode-focused tests, including the gate-latency contract (mutation-checked: making the POST synchronous fails it at 1522 ms), the config-truncation regression, the pane-connect crash, the title/conversation-name rule, and listener mappings written against captured payloads.

pnpm tc, pnpm run check:code-quality:changed, and pnpm lint pass.

Full pnpm test: 5 files fail, and the same 5 fail on origin/main unchanged — verified by
running that exact set in a worktree at the branch point. My branch fails fewer individual
tests than the base (19 vs 21; the difference is claude-structured-real-cli flaking on a
10s timeout). None are jcode-related:

File Why
browser-manager-viewport-ownership pre-existing assertion failure on main (12/12, 6ms)
claude-structured-real-cli needs the real Claude CLI; times out here
opencode/hook-plugin-module-contract hooks?.event is not a function — needs the OpenCode plugin module installed
cross-version-wire/release-checkout git rev-parse ~2^{commit} — this checkout is shallow
relay-region-correction Cannot find package 'pg' — relay workspace deps not installed

An earlier run of mine reported ~20 failing files; that run was contaminated by the Orca dev
app and jcode daemons competing for CPU during live validation, and every extra failure was
load-sensitive (terminal-history GC, SSH commands, a dialog test). On an idle machine they pass.

Not tested here: Windows and SSH. Both are code-reviewed — the runtime dir and the daemon pre-warm are non-Windows only, SSH terminals never receive the host-local socket path, and the Windows .cmd hook drains stdin through the shared contract helper — but neither was exercised on real hardware.

Known gap, called out rather than hidden: the desktop completion banner did not fire in this dev instance. Neither did Claude's, under an identical control run in the same instance, so it is environmental here rather than jcode-specific — but it means the banner itself is unproven. The in-app unread path is proven above, and a unit test pins the row detail the banner consumes.

  • I manually tested these changes locally
  • Automated tests added/updated

Authorship

The base commit is @czzczz's, preserved with their authorship; every commit on top carries them as co-author.

AI Disclosure

Implemented with Claude (Opus 5). The jcode source was cloned and read to ground the hook mapping; every behavioural claim was checked against a running jcode rather than the model's recollection.

Review

  • Security: hook POSTs stay loopback + token-validated; session ids are path-validated before any filesystem read; the pre-warm spawns through spawnProcess with stdio: 'ignore' and no shell.
  • Performance: the gate adds a detached POST (~10 ms, contract-tested, not a promise); journal scans stay bounded; the pre-warm runs at most once per runtime dir.
  • Cross-platform: runtime dir and pre-warm are non-Windows only; the Windows hook drains stdin via the shared contract helper; paths use path.join.
  • SSH/remote: SSH panes are excluded from the host-local runtime dir; the remote installer writes POSIX scripts and is covered by the registry ratchet.
  • Backwards compatibility: additive registrations; getStatus keeps reporting partial and preserving user-owned hooks and jcode's own pre_tool_timeout_ms.
  • Worth knowing: if a user's config.toml fails to parse for an unrelated reason, jcode silently stops firing all hooks while Orca still reports the install as healthy — getStatus only parses the [hooks] table. Hit this during testing. Not fixed here; it needs a real parse probe.

Agent skill upstream boundary

  • Not applicable.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • Before/after screenshots or videos attached for UI changes
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • pnpm lint, pnpm typecheck pass; pnpm test differences from base explained above

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

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

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b25a87c2-6d79-42b1-968d-374c31af9a3d

📥 Commits

Reviewing files that changed from the base of the PR and between f542df2 and ba1426a.

📒 Files selected for processing (1)
  • config/scripts/mobile-web-app-session-terminal-closure.test.mjs

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


📝 Walkthrough

Walkthrough

The pull request adds Jcode support across agent registration, managed hooks, hook-event processing, AI Vault session discovery and resume, pane runtime setup, terminal query handling, and commit-message generation. It adds shared backward file scanning and Jcode-specific prompt and title utilities. Additional changes update Pi session metadata, agent assets, translations, documentation, tests, and formatting.

Priority: ➖ Normal

Merge Risk: 🟠 High · up to ba142

Resolve the unrestricted commit-message agent and terminal-spawn failure risk before merging. Several Jcode features also remain unreliable across configurations and platforms.

🚥 Pre-merge checks | ✅ 4 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes several unrelated formatting-only edits in documentation, Pi/runtime tests, orchestration tests, a bug reproduction, and smoke tooling. These changes are not necessary to implement fir… Remove unrelated formatting-only changes, or explain why each is required for the Jcode integration.
Out of Scope Changes check ⚠️ Warning The pull request includes changes with no demonstrated connection to [#10830]. Examples include formatting-only edits in docs/reference/antigravity-readiness-evidence.md, `docs/reference/ssh-executi… Remove the unrelated documentation, formatting-only, Pi metadata, orchestration-test, OpenCode, and generic transcript-scan changes. Retain changes only when they implement [#10830], support Jcode integration tests, or have a documented tec…
Docstring Coverage ⚠️ Warning Docstring coverage is 38.10% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 84 functions across 64 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description is complete and follows the required structure. It explains the user impact, implementation, rationale, linked issue, visual proof, testing, AI disclosure, known gaps, and compatibilit…
Linked Issues check ✅ Passed The description includes Fixes #10830, which matches the stated objective of completing first-class Jcode integration. The reference to #10521 is explanatory and does not replace the linked issue.
Title check ✅ Passed The title clearly identifies the first-class Jcode integration and names its primary capabilities, including live status, questions, notifications, send-to-agent, and orchestration.
Linked Issues check ✅ Passed Issue [#10830] requires Jcode in the TUI agent type and the standard agent-launch flow. The pull request adds Jcode to the catalog, picker labels, settings, launch configuration, prompt injection, hoo…
Full details: Out of Scope Changes check

Explanation

The PR includes several unrelated formatting-only edits in documentation, Pi/runtime tests, orchestration tests, a bug reproduction, and smoke tooling. These changes are not necessary to implement first-class Jcode support.

Full details: Out of Scope Changes check

Explanation

The pull request includes changes with no demonstrated connection to [#10830]. Examples include formatting-only edits in docs/reference/antigravity-readiness-evidence.md, docs/reference/ssh-execution-boundary.md, src/main/runtime/web-session-tabs-sync/mirrored-status-tab-retractions.test.ts, and tests/tools/omp-source-control-runtime-smoke.mjs. It also changes unrelated Pi status metadata in src/main/pi/agent-status-extension-source.ts, reformats unrelated orchestration tests, changes an OpenCode bug-reproduction document, and adds a generic transcript-scan refactor. These changes do not implement Jcode catalog or launch integration.

Resolution

Remove the unrelated documentation, formatting-only, Pi metadata, orchestration-test, OpenCode, and generic transcript-scan changes. Retain changes only when they implement [#10830], support Jcode integration tests, or have a documented technical dependency on the Jcode launch flow.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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: 16

🧹 Nitpick comments (1)
src/renderer/src/runtime/agent-resume-host-authority-capability.ts (1)

38-39: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Document why jcode remains ungated.

jcode was added after agent-session.host-authority.v1. An older host rejects jcode in ExplicitEnsure, so it cannot resume a jcode provider session through this path. The generic probe is safe, but the current comment incorrectly says that the v1 enum already covers jcode.

Suggested comment update
-  // Why: jcode resumed by id (--resume <id>) through the same host-authority session enum the generic probe covers.
+  // Why: jcode was added after agent-session.host-authority.v1, so an older host cannot accept
+  // jcode in ExplicitEnsure or resume a jcode provider session. The generic probe is safe here.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 24f41017-3159-4676-8363-cda089fe82e7

📥 Commits

Reviewing files that changed from the base of the PR and between 519bde8 and 7c0eee69d77535f783d31c1937e279d6d0c4181a.

⛔ Files ignored due to path filters (1)
  • src/shared/agent-icons/jcode.png is excluded by !**/*.png
📒 Files selected for processing (122)
  • config/scripts/locale-translation-policy.mjs
  • config/tsconfig.cli.json
  • docs/reference/agent-status-store.md
  • docs/reference/antigravity-readiness-evidence.md
  • docs/reference/ssh-execution-boundary.md
  • mobile/src/components/mobile-agent-icon-assets.ts
  • src/main/agent-hooks/managed-agent-hook-registry.ts
  • src/main/agent-hooks/managed-hook-command-contract.test.ts
  • src/main/agent-hooks/managed-hook-local-filesystem.test.ts
  • src/main/agent-hooks/remote-hook-installer-registry-guard.test.ts
  • src/main/agent-hooks/remote-hook-service-installers.test.ts
  • src/main/agent-hooks/remote-managed-hook-installers.ts
  • src/main/agent-hooks/server-opencode-binder.test.ts
  • src/main/agent-hooks/server-retired-pane-new-turn.test.ts
  • src/main/ai-vault/remote-session-scanner-sources.ts
  • src/main/ai-vault/session-scanner-agent-parser.ts
  • src/main/ai-vault/session-scanner-agent-sources.ts
  • src/main/ai-vault/session-scanner-codex-workers.test.ts
  • src/main/ai-vault/session-scanner-every-agent-fixture.ts
  • src/main/ai-vault/session-scanner-jcode-parser.test.ts
  • src/main/ai-vault/session-scanner-jcode-parser.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite-coexistence.test.ts
  • src/main/ai-vault/session-scanner-parse-cache.ts
  • src/main/ai-vault/session-scanner-test-fixtures.ts
  • src/main/ai-vault/session-scanner-types.ts
  • src/main/ai-vault/session-scanner.test.ts
  • src/main/daemon/pty-subprocess/spawn-environment.ts
  • src/main/ipc/pty-spawn-env-terminal-basics.test.ts
  • src/main/ipc/pty/ipc/spawn-env.ts
  • src/main/ipc/terminal-startup-color-query-replies.test.ts
  • src/main/ipc/terminal-startup-color-query-replies.ts
  • src/main/jcode/daemon-prewarm.test.ts
  • src/main/jcode/daemon-prewarm.ts
  • src/main/jcode/hook-config.test.ts
  • src/main/jcode/hook-config.ts
  • src/main/jcode/hook-gate-script.test.ts
  • src/main/jcode/hook-service.test.ts
  • src/main/jcode/hook-service.ts
  • src/main/jcode/hook-settings.ts
  • src/main/pi/agent-status-extension-source.ts
  • src/main/pi/titlebar-extension-service.test.ts
  • src/main/pi/titlebar-extension-service.ts
  • src/main/providers/local-pty-launch-helpers.ts
  • src/main/providers/local-pty-spawn.ts
  • src/main/runtime/headless-terminal-query-reply-policy.test.ts
  • src/main/runtime/headless-terminal-query-reply-policy.ts
  • src/main/runtime/orca-runtime-controller-knows-pty-is-live.ts
  • src/main/runtime/orca-runtime-create-terminal.ts
  • src/main/runtime/orca-runtime-resolve-browser-network-execution-host-for-worktree.ts
  • src/main/runtime/orca-runtime-split-pty-backed-terminal.ts
  • src/main/runtime/orca-runtime-terminal-handle-incarnation.test.ts
  • src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts
  • src/main/runtime/orca-runtime-write-terminal-agent-prompt.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-reap-fixed.func.test.ts
  • src/main/text-generation/commit-message-model-discovery-policy.ts
  • src/main/text-generation/commit-message-text-generation-cancellation.test.ts
  • src/main/text-generation/source-control-local-process.ts
  • src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts
  • src/renderer/src/components/terminal-pane/pty-connection-hidden-atlas-recovery.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-pi-synchronized-input.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/hidden-output-seq-and-skip.ts
  • src/renderer/src/components/terminal-pane/pty-connection/hidden-startup-renderer-query-write.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pane-launch-agent-candidate.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pane-launch-agent-candidate.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.ts
  • src/renderer/src/components/terminal-pane/terminal-capability-replies.test.ts
  • src/renderer/src/components/terminal-pane/terminal-capability-replies.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/lib/agent-catalog.tsx
  • src/renderer/src/lib/agent-favicon-assets.ts
  • src/renderer/src/lib/agent-status.ts
  • src/renderer/src/runtime/agent-resume-host-authority-capability.ts
  • src/renderer/src/runtime/web-session-tabs-sync/mirrored-status-tab-retractions.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync/mirrored-status-tab-retractions.ts
  • src/shared/agent-hook-listener-extraction-characterization.test.ts
  • src/shared/agent-hook-listener-jcode.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-listener/provider-dispatch.ts
  • src/shared/agent-hook-listener/provider-event-routing.ts
  • src/shared/agent-hook-listener/providers/jcode-events.ts
  • src/shared/agent-hook-listener/providers/jcode-tool-fields.ts
  • src/shared/agent-hook-listener/source-routing.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/agent-hook-types.ts
  • src/shared/agent-kind.ts
  • src/shared/agent-name-token-match.ts
  • src/shared/agent-row-conversation-name.test.ts
  • src/shared/agent-row-conversation-name.ts
  • src/shared/agent-session-resume.test.ts
  • src/shared/agent-session-resume.ts
  • src/shared/agent-title-identity.ts
  • src/shared/agent-type-label.ts
  • src/shared/ai-vault-resume-command.ts
  • src/shared/ai-vault-types.ts
  • src/shared/commit-message-agent-output.ts
  • src/shared/commit-message-agent-spec.test.ts
  • src/shared/commit-message-agent-spec.ts
  • src/shared/commit-message-agent-specs-secondary.ts
  • src/shared/commit-message-plan.test.ts
  • src/shared/commit-message-prompt.test.ts
  • src/shared/jcode-runtime-dir.test.ts
  • src/shared/jcode-runtime-dir.ts
  • src/shared/jcode-session-files.test.ts
  • src/shared/jcode-session-files.ts
  • src/shared/jcode-terminal-title.test.ts
  • src/shared/jcode-terminal-title.ts
  • src/shared/pane-agent-identity-inventory.test.ts
  • src/shared/skills-cli-agent-keys.ts
  • src/shared/source-control-ai-action-recipes.test.ts
  • src/shared/telemetry-property-schemas.ts
  • src/shared/terminal-title-agent-type.ts
  • src/shared/tui-agent-config.ts
  • src/shared/tui-agent-display-names.ts
  • src/shared/tui-agent-selection.ts
  • src/shared/tui-agent.ts
  • tests/tools/omp-source-control-runtime-smoke.mjs

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

'jcode',
remoteHome,
hostPlatform,
['.jcode', 'sessions'],

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 | 🟠 Major | 🏗️ Heavy lift

Discover sessions under a remote custom JCODE_HOME.

If Jcode on the remote host uses JCODE_HOME, this source still scans only <remoteHome>/.jcode/sessions. Those sessions do not appear in AI Vault. Resolve the remote Jcode home or provide an explicit remote-root override. Jcode documents JCODE_HOME as an override for its state directory. (github.com)

Comment on lines +82 to +88
// Why: parse only the durable `messages` array. The live `.journal.jsonl`
// sibling is intentionally ignored: its writes do not bump this file's mtime,
// so a merged read would go stale against the parse cache until the session
// doc is rewritten (checkpoint/close).
for (const message of arrayValue(record.messages)) {
consumeJcodeMessage(accumulator, message)
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Include the session journal in AI Vault reads.

When Jcode appends a turn to session_*.journal.jsonl, this parser reads only the older JSON snapshot. The snapshot's unchanged mtime also lets the parse cache reuse that older result. AI Vault can show an incomplete conversation until Jcode checkpoints the snapshot. Jcode's loader replays the journal after reading the snapshot, and ordinary saves can append without checkpointing. Read or replay the journal and track its freshness for both local and remote scans. (raw.githubusercontent.com)

Comment on lines +105 to +107
const titleCandidate = normalizeTitleText(extractContentText(content) ?? '')
if (titleCandidate) {
accumulator.title ??= titleCandidate

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

Preserve the session's stored title.

When a user names a Jcode session, this code still takes its title from the first user message. Jcode stores custom_title and title in the session document. Prefer the custom title, then the stored title, before deriving one from a prompt. (github.com)

Comment on lines +110 to +111
accumulator.messageCount++
addPreviewContent(accumulator, role, content, messageRecord.timestamp)

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

Accumulate persisted token usage.

Jcode stores input and output token counts on messages, but this parser never updates accumulator.totalTokens. AI Vault therefore reports zero tokens for a Jcode session with persisted usage. Add the stored counts using the accumulator's token-total convention. (raw.githubusercontent.com)

Comment on lines +51 to +53
export function agentSkipsStartupOscColorQueryReplies(launchAgent: unknown): boolean {
return launchAgent === 'jcode'
}

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 startup color-reply skip checks only launchAgent, so a command-only Jcode launch still gets answered.

shouldReplyToStartupTerminalColorQueries recognizes an agent from launchAgent, from telemetry.agent_kind, or from command/launchConfig.agentCommand. The skip checks only launchAgent === 'jcode'. A spawn with command: 'jcode' or telemetry.agent_kind: 'jcode' and no launchAgent still sends the startup OSC 10/11 replies. That is the composer-text leak this change is meant to fix. Apply the same signals in the skip check.

Proposed fix
-export function agentSkipsStartupOscColorQueryReplies(launchAgent: unknown): boolean {
-  return launchAgent === 'jcode'
-}
+export function agentSkipsStartupOscColorQueryReplies(args: {
+  launchAgent?: unknown
+  telemetry?: { agent_kind?: unknown } | undefined
+  command?: string
+  launchConfig?: SleepingAgentLaunchConfig
+}): boolean {
+  if (args.launchAgent === 'jcode' || args.telemetry?.agent_kind === 'jcode') {
+    return true
+  }
+  const command = args.launchConfig?.agentCommand?.trim() || args.command?.trim() || ''
+  return recognizeAgentProcessFromCommandLine(command) === 'jcode'
+}

Update the call on line 66 to agentSkipsStartupOscColorQueryReplies(args). Also confirm what recognizeAgentProcessFromCommandLine returns for jcode.

Comment on lines +36 to +51
if (target === 'local' && process.platform === 'win32') {
return [
'@echo off',
'setlocal',
// Why: endpoint file holds the live port/token; a PTY that outlives an Orca restart carries stale env, so `call` it to refresh (else PTY env).
'if defined ORCA_AGENT_HOOK_ENDPOINT if exist "%ORCA_AGENT_HOOK_ENDPOINT%" call "%ORCA_AGENT_HOOK_ENDPOINT%" 2>nul',
...buildWindowsHookEnvironmentGuardLines(),
// Why: pre_tool is jcode's gate — it writes the tool input to our stdin and
// waits for us. Drain it first so a tool input larger than the pipe buffer
// can never stall the agent mid-write.
`if "%JCODE_HOOK_EVENT%"=="pre_tool" ${WINDOWS_HOOK_STDIN_DRAIN_COMMAND}`,
buildWindowsAgentHookPostCommand('jcode'),
'exit /b 0',
...buildWindowsHookStdinDrainEpilogue(),
''
].join('\r\n')

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 | 🟠 Major | 🏗️ Heavy lift

Forward the Jcode payload and event name in the Windows hook script.

The POSIX script pipes $JCODE_HOOK_PAYLOAD into curl. It also posts hook_event_name, session_id, and cwd as form fields.

The Windows script calls buildWindowsAgentHookPostCommand('jcode') with no extra lines. That command sends payload@-, which reads stdin, and stdin never holds the Jcode payload:

  • On pre_tool, line 46 has already drained stdin.
  • On observer events, Jcode sends the payload through the environment variable, not stdin.

As a result, the server gets no hook_event_name, no session_id, and no tool fields. normalizeJcodeEvent returns null for every event, so Windows panes never show Jcode status. The pre_tool POST also runs synchronously, so every tool call can wait up to curl's 1.5 s --max-time.

At minimum, post the event, session, and working directory as form fields. The server reads hook_event_name from the top-level record. Tool fields also need the payload. One option is curl's --variable %JCODE_HOOK_PAYLOAD with --expand-data-urlencode "payload={{JCODE_HOOK_PAYLOAD}}", which requires curl 8.3 or later. Another option is the existing PowerShell launcher. Detach pre_tool with start "" /b.

Partial fix (event identity)
-      buildWindowsAgentHookPostCommand('jcode'),
+      buildWindowsAgentHookPostCommand('jcode', [
+        '  --data-urlencode "hook_event_name=%JCODE_HOOK_EVENT%" ^',
+        '  --data-urlencode "session_id=%JCODE_HOOK_SESSION_ID%" ^',
+        '  --data-urlencode "cwd=%JCODE_HOOK_CWD%" ^'
+      ]),
📝 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
if (target === 'local' && process.platform === 'win32') {
return [
'@echo off',
'setlocal',
// Why: endpoint file holds the live port/token; a PTY that outlives an Orca restart carries stale env, so `call` it to refresh (else PTY env).
'if defined ORCA_AGENT_HOOK_ENDPOINT if exist "%ORCA_AGENT_HOOK_ENDPOINT%" call "%ORCA_AGENT_HOOK_ENDPOINT%" 2>nul',
...buildWindowsHookEnvironmentGuardLines(),
// Why: pre_tool is jcode's gate — it writes the tool input to our stdin and
// waits for us. Drain it first so a tool input larger than the pipe buffer
// can never stall the agent mid-write.
`if "%JCODE_HOOK_EVENT%"=="pre_tool" ${WINDOWS_HOOK_STDIN_DRAIN_COMMAND}`,
buildWindowsAgentHookPostCommand('jcode'),
'exit /b 0',
...buildWindowsHookStdinDrainEpilogue(),
''
].join('\r\n')
if (target === 'local' && process.platform === 'win32') {
return [
'@echo off',
'setlocal',
// Why: endpoint file holds the live port/token; a PTY that outlives an Orca restart carries stale env, so `call` it to refresh (else PTY env).
'if defined ORCA_AGENT_HOOK_ENDPOINT if exist "%ORCA_AGENT_HOOK_ENDPOINT%" call "%ORCA_AGENT_HOOK_ENDPOINT%" 2>nul',
...buildWindowsHookEnvironmentGuardLines(),
// Why: pre_tool is jcode's gate — it writes the tool input to our stdin and
// waits for us. Drain it first so a tool input larger than the pipe buffer
// can never stall the agent mid-write.
`if "%JCODE_HOOK_EVENT%"=="pre_tool" ${WINDOWS_HOOK_STDIN_DRAIN_COMMAND}`,
buildWindowsAgentHookPostCommand('jcode', [
' --data-urlencode "hook_event_name=%JCODE_HOOK_EVENT%" ^',
' --data-urlencode "session_id=%JCODE_HOOK_SESSION_ID%" ^',
' --data-urlencode "cwd=%JCODE_HOOK_CWD%" ^'
]),
'exit /b 0',
...buildWindowsHookStdinDrainEpilogue(),
''
].join('\r\n')

Comment thread src/main/jcode/hook-settings.ts Outdated
Comment on lines +55 to +60
// Why: jcode executes hook commands directly (not through a shell), so the
// managed value must be the bare script path — no `if [ -f … ]` wrapper. Paths
// with spaces are handled by jcode's shell-style command parsing.
export function getJcodeManagedCommand(scriptPath: string): string {
return scriptPath
}

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 | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Find how the managed command is consumed and compared.
rg -nP -C3 'getJcodeManagedCommand|getJcodeRemoteManagedCommand|managedCommand\s*=' src/main/jcode

Repository: stablyai/orca

Length of output: 1391


🌐 Web query:

jcode hooks config.toml command parsing shell-words split arguments

💡 Result:

<source_evidence>

<title>crates/jcode-base/src/hooks.rs</title> https://github.com/1jehuang/jcode/blob/435fb4a8/crates/jcode-base/src/hooks.rs //! Hooks are external commands that jcode runs at well-defined lifecycle //! points so other programs can observe or gate agent behavior without //! forking jcode. They are configured in `[hooks]` in config.toml (or //! `JCODE_HOOK_*` env vars) and follow the same command-line conventions as //! `[terminal] spawn_hook`: the command is parsed shell-style but executed //! directly (no shell), with `JCODE_HOOK_*` metadata env vars describing the //! event. ... /// The configured commands for `event`, in declaration order. pub fn hook_commands(event: &str) -> Vec { if hooks_suppressed() { return Vec::new(); } let hooks = &crate::config::config().hooks; let raw = match event { "turn_start" => hooks.turn_start.as_ref(), "turn_end" => hooks.turn_end.as_ref(), "session_start" => hooks.session_start.as_ref(), "session_end" => hooks.session_end.as_ref(), "pre_tool" => hooks.pre_tool.as_ref(), "post_tool" => hooks.post_tool.as_ref(), _ => None, }; raw.into_iter() .flat_map(|commands| commands.iter()) .map(str::trim) .filter(|command| !command.is_empty()) .map(str::to_owned) .collect() } ... fn build_hook_process( command_line: &str, event: &HookEvent, ) -> anyhow::Result { let parts = crate::terminal_launch::parse_hook_command(command_line)?; let (program, args) = parts .split_first() .expect("parse_hook_command guarantees at least one part"); let mut cmd = std::process::Command::new(expand_home(program)); cmd.args(args); if let Some(cwd) = event.cwd.as_deref().filter(|cwd| !cwd.is_empty()) && std::path::Path::new(cwd).is_dir() { cmd.current_dir(cwd); } apply_event_env(&mut cmd, event); let _ = CLIENT_TERMINAL_ENV.try_with(|env| { crate::terminal_launch::apply_client_terminal_env(&mut cmd, env); }); Ok(cmd) } <title>crates/jcode-base/src/config/default_file.rs</title> https://github.com/1jehuang/jcode/blob/435fb4a8/crates/jcode-base/src/config/default_file.rs impl Config { /// Create a default config file with comments pub fn create_default_config_file() -> anyhow::Result { let path = Self::path().ok_or_else(|| anyhow::anyhow!("No config path"))?; if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } std::fs::write(&path, Self::default_config_file_contents())?; Ok(path) } /// The commented config template written by [`Self::create_default_config_file`]. /// /// Exposed separately so tests can check that the template we ship actually /// parses and documents the options it claims to. pub fn default_config_file_contents() -> String { let default_content = r##"# jcode configuration file ... # Location: ~/.jcode/ ... .toml # ... # When set, jcode runs `<spawn_ ... > <args...>` instead ... # opening a terminal emulator ... . The hook receives JCODE_SPAWN_* env vars # describing the spawn so multiplexers/wrappers can decide where ... # JCODE ... SPAWN ... KIND - ... # JCODE ... CWD - ... [hooks] # Lifecycle hooks: external commands jcode runs at well-defined points so other # programs can observe or gate agent behavior. Commands are parsed shell-style # (quotes work) but executed directly, with JCODE_HOOK_* env vars describing # the event: # JCODE_HOOK_EVENT - "turn_start", "turn_end", "session_start", # "session_end", "pre_tool", "post_tool" # JCODE_HOOK_SESSION_ID - the session the event belongs to # JCODE_HOOK_CWD - session working directory (also the hook&`#39`;s cwd) # JCODE_HOOK_PAYLOAD - JSON mirror of all fields # Hook processes get JCODE_HOOKS_DISABLED=1 so nested jcode calls don&`#39`;t recurse. # # All hooks except pre_tool are observers: detached, fire-and-forget, failures # only logged. Env overrides: JCODE_HOOK_TURN_START, JCODE_HOOK_TURN_END, # JCODE_HOOK_SESSION_START, JCODE_HOOK_SESSION_END, JCODE_HOOK_PRE_TOOL, # JCODE_HOOK_POST_TOOL (set empty to disable a config hook). # ... # Runs when an agent turn begins, before the model starts generating and before # the first pre_tool. Lets integrations detect the agent is working during the # think/stream window before any tool call. Extra fields: JCODE_HOOK_MODEL, # JCODE_HOOK_SOURCE ("chat"/"resume"/"ambient"). # turn_start = "~/bin/jcode-turn-start" # ... # Runs when an agent turn completes. Extra fields: JCODE_HOOK_STATUS # ("ok"/"error"), JCODE_HOOK_DURATION_MS, JCODE_HOOK_MODEL, # JCODE_HOOK_LAST_ASSISTANT_TEXT (first 4000 chars), JCODE_HOOK_ERROR. # turn_end = "~/bin/jcode-turn-notify" # ... # Runs when a session becomes active. Extra: JCODE_HOOK_SOURCE # ("create"/"attach"/"resume"). # session_start = "" ... # Runs when a session closes normally. Extra: JCODE_HOOK_SOURCE ("close"). # session_end = "" ... # Gate hook before every tool call. Receives JCODE_HOOK_TOOL_NAME and the tool # input JSON on stdin (truncated copy in JCODE_HOOK_TOOL_INPUT). Exit 0 allows # the call; exit 2 blocks it and stderr is shown to the model as the error; # any other outcome (other exits, timeout, missing binary) fails open. # pre_tool = "~/bin/jcode-tool-policy" # # Max milliseconds to wait for pre_tool before failing open (default: 5000). # pre_tool_timeout_ms = 5000 ... # Runs after each tool call. Extra fields: JCODE_HOOK_TOOL_NAME, # JCODE_HOOK_STATUS, JCODE_HOOK_DURATION_MS, JCODE_HOOK_OUTPUT_BYTES, # JCODE_HOOK_ERROR. # post_tool = "" ... #[cfg(test)] mod tests { use super::*; /// The shipped template is a hand-maintained string, so a typo in it ships /// a config file that jcode itself cannot read. Parse it here. #[test] fn default_config_template_parses() { let template = Config::default_config_file_contents(); toml::from_str:: (&template).expect("the shipped config template must parse"); } /// Colors are only discoverable if the template mentions t…[truncated] <title>Jcode docs: install, providers, configuration, keybindings</title> https://jcode.sh/docs For self-hosted or unlisted endpoints, `jcode provider add` writes a named profile to `~/.jcode/config.toml` without putting the key in shell history: ... Config lives at `~/.jcode/config.toml` (or `$JCODE_HOME/config.toml`). Everything has a default, so the file can start empty and grow as you override things. The main sections: ... | Section | Controls | | --- | --- | | `[provider]` | Default provider and model, reasoning effort, failover behavior | | `[providers.]` | Named provider profiles: base URL, key source, models, context windows | | `[display]` | Theme, centered layout, diff mode, diagram rendering, animations | | `[features]` | Toggles for memory, swarm, mermaid rendering, update channel | | `[keybindings]` | Every binding in the table below | | `[agents]` | Swarm model routing, spawn mode, concurrency cap, memory sidecar | | `[hooks]` | Shell commands to run at turn, session, and tool boundaries | | `[notifications]` | Turn-complete notifications and sounds | | `[ambient]` | Background ambient mode: schedule, budget, work branches | ... jcode/mcp ... `.jcode ... . jcode also reads ... .json` and `. ... ), and imports ... | Command | Does | | --- | --- | | `/model` | List or switch models | | `/effort` | Show or change reasoning effort | | `/login` / `/account` | Log in to a provider, switch between accounts | | `/resume` | Open the session picker | | `/fork` | Fork the session into a new window | | `/transfer` | Compact context into a fresh handoff session | | `/compact` / `/clear` / `/rewind` | Compact, clear, or rewind the conversation | | `/todos` | Show the session todo list as a card in ... chat | | `/commit` / `/commit-push` | Make logical commits from current changes, optionally push | | `/review` / `/test` | Launch a one-shot review session, verify a claim with layered tests | | `/diff` | Cycle the diff display mode | | `/memory` / `/swarm` | Toggle the memory and swarm features | | `/skills` | Show loaded skills and endorsed recommendations | | `/usage` / `/info` | Provider usage limits, session info and token counts | | `/config` | Show or edit configuration | | `/ ... keys` / `/keys` | List hotkeys, show keybinding conflicts with your terminal and OS | | `/update` / `/selfdev` | Background update and reload, open a self-dev session | | `/quit` ... Defaults on Windows and Linux, with macOS differences noted. Apart from Enter and Shift+Enter, every binding is configurable under `[keybindings]` in `config.toml`, using values like `"alt+m"`. Set a binding to `""` to disable it. <title>crates/jcode-terminal-launch/src/lib.rs</title> https://github.com/1jehuang/jcode/blob/435fb4a8/crates/jcode-terminal-launch/src/lib.rs /// Parse an external spawn-hook command line into argv parts. /// /// Supports basic POSIX-style word splitting: whitespace separates arguments, /// single and double quotes group words, and backslash escapes the next /// character (outside single quotes). Errors on empty input, unterminated /// quotes, and trailing escapes. pub fn parse_hook_command(raw: &str) -> Result<Vec > { let mut parts = Vec::new(); let mut current = String::new(); let mut quote: Option = None; let mut escaped = false; let mut token_started = false; for ch in raw.chars() { if escaped { current.push(ch); token_started = true; escaped = false; continue; } if let Some(quote_ch) = quote { if ch == quote_ch { quote = None; } else if ch == &`#39`;\\&`#39`; && quote_ch == &`#39`;"&`#39`; { escaped = true; } else { current.push(ch); token_started = true; } continue; } match ch { &`#39`;\\&`#39`; => { escaped = true; token_started = true; } &`#39`;\&`#39`;&`#39`; | &`#39`;"&`#39`; => { quote = Some(ch); token_started = true; } ch if ch.is_whitespace() => { if token_started { parts.push(std::mem::take(&mut current)); token_started = false; } } ch => { current.push(ch); token_started = true; } } } if escaped { anyhow::bail!("spawn hook command ends with an escape character"); } if quote.is_some() { anyhow::bail!("spawn hook command has an unterminated quote"); } if token_started { parts.push(current); } if parts.is_empty() { anyhow::bail!("spawn hook command is empty"); } Ok(parts) } ... SPAWN ... /// Build the process invocation for an external spawn hook. /// /// The hook command is parsed shell-style, then the target program and its /// arguments are appended as additional argv entries (the `$TERMINAL -e` /// convention), so `hook --flag` becomes `hook --flag <args...>`. /// The hook runs in the session working directory with the full /// `JCODE_SPAWN_*` metadata env set (see [`spawn_metadata_env`]); hooks that /// need a single shell-command string (tmux, kitty `@ launch`) can use /// `$JCODE_SPAWN_COMMAND` instead of the appended argv. ... pub fn build_hook_spawn_command( hook: &str, command: &TerminalCommand, cwd: &Path, ) -> Result { let parts = parse_hook_command(hook)?; let (program, prefix_args) = parts .split_first() .expect("parse_hook_command guarantees at least one part"); let mut cmd = Command::new(expand_home(program)); cmd.args(prefix_args) .arg(&command.program) .args(&command.args) .current_dir(cwd) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()); if command.fresh_spawn { cmd.env("JCODE_FRESH_SPAWN", "1"); } for (key, value) in spawn_metadata_env(command, cwd) { cmd.env(key, value); } Ok(cmd) } ... fn build_spawn_command(term: &str, command: ... TerminalCommand, cwd: ... Path) -> Option { let title = command.title.as_deref().unwrap_or("jcode"); let mut cmd = Command::new(term); cmd.current_dir(cwd) ... ::null()) .stdout(Std ... ::null()) .stderr(Stdio::null()); ... if command. ... cmd.env("JCODE_ ... SPAWN", ... 1"); } ... #[cfg(unix)] "herdr" => { // `pane split` deliberately creates a shell and returns its pane id; // `pane run` is the atomic, bracketed-paste-aware ... to start a // command in that shell. Keep the small composition here rather // than requiring every user to configure an equivalent spawn hook. let herdr = terminal_env_value(&command.client_terminal_env, "HERDR_BIN_PATH") .unwrap_or_else(|| "herdr".to_string()); let shell = shell_command ... _parts(command)); let ... = concat!( "set -eu; ", "response=\"$(\"$1\" pane split --current --direction right --cwd \"$2\" --focus)\"; ", "pane_ ... =\"$(printf &`#39`;%s\\n&`#39`; \"$response\" | sed ... n &`#39`;", " ... /.*\\\"pane_id\\\"[[:space ... ]*:[[: ... :]]*\\\"\\([^\\\"]*\\)…[truncated] <title>Triage fixes: install.sh, /config edit, FreeBSD, .agents skills, MCP compat, retry fail-fast, terminal config (`#417`) · 5d482ca · 1jehuang/jcode</title> https://github.com/1jehuang/jcode/commit/5d482cac1256673e257baf7b154b6d1d2e3ee43e - fix(config): shell-split $EDITOR for /config edit (`#412`) ... When $EDITOR contains arguments (e.g. &`#39`;zed --wait&`#39`; or &`#39`;code -w&`#39`;), the whole string was used as the binary name and spawn failed silently. Split on whitespace, use the first token as the binary, pass the rest as args, and surface spawn errors instead of swallowing them. ... - feat(terminal): add [terminal] preferred config key for Cmd+; launch (`#401`) ... The macOS Cmd+; launch terminal was only configurable via the undocumented ~/.jcode/preferred_terminal.json. Add a discoverable, documented [terminal] preferred key in config.toml and prefer it over the legacy JSON file in effective_macos_terminal() (config > JSON > detection). ... Document the key in the generated default config.toml next to spawn_hook/ focus_hook. (Re-running &`#39`;jcode setup-hotkey&`#39`; still regenerates the launcher script; auto-regenerate-on-change is left for a follow-up.) ... Adds tests for config parsing and the documented terminal value mapping. ... ```diff @@ -383,6 +383,13 @@ swarm_spawn_mode = "visible" # Example: # focus_hook = "~/bin/jcode-focus-router" # focus_hook = "" ... +# +# macOS only: terminal that the Cmd+; launch hotkey and in-app session spawns +# open jcode into. One of: ghostty, iterm2, wezterm, warp, alacritty, vscode, +# terminal (Apple Terminal). Preferred over the legacy +# ~/.jcode/preferred_terminal.json file. After changing this, re-run +# `jcode setup-hotkey` so the generated launcher script (Cmd+;) picks it up. +# preferred = "ghostty" [notifications] # Desktop notifications for interactive sessions (macOS Notification Center / ... ```diff @@ -119,6 +119,15 @@ fn spawn_hook_defaults_to_none_and_parses_from_toml() { assert_eq!(cfg.terminal.spawn_hook.as_deref(), Some("tmux new-window")); } +#[test] +fn terminal_preferred_defaults_to_none_and_parses_from_toml() { + assert_eq!(Config::default().terminal.preferred, None); + + let cfg: Config = + toml::from_str("[terminal]\npreferred = \"ghostty\"\n").expect("preferred should parse"); + assert_eq!(cfg.terminal.preferred.as_deref(), Some("ghostty")); +} + #[test] fn hooks_config_defaults_and_parses_from_toml() { let defaults = Config::default().hooks; ... ```diff @@ ... 635,6 +6 ... 6 @@ pub struct TerminalConfig { ... /// /// Env override: `JCODE_FOCUS_ ... ` (set empty to disable a config hook). pub focus_hook: Option<String>, ... + /// Terminal used by the macOS Cmd+; launch hotkey and in-app session spawns. + /// + /// One of: `ghostty`, `iterm2`, `wezterm`, `warp`, `alacritty`, `vscode`, + /// `terminal` (Apple Terminal). When set, this is the source of truth for + /// which terminal jcode launches into and is preferred over the legacy ... + /// `~/.jcode/preferred_terminal.json` file. Re-run `jcode setup-hotkey` ... + /// after changing it so the generated launcher script picks up the change. + /// + /// macOS only; ignored on other platforms. + pub preferred: Option<String>, } ... Lifecycle hooks: external commands jcode runs at well-defined points. ... ```diff @@ -98,7 +98,25 @@ pub(super) fn save_preferred_macos_terminal(terminal: MacTerminalKind) -> Result } pub(super) fn effective_macos_terminal() -> MacTerminalKind { - load_preferred_macos_terminal().unwrap_or_else(detect_macos_terminal) + // Precedence: config.toml `[terminal] preferred` (discoverable, documented) + // > legacy `~/.jcode/preferred_terminal.json` > runtime detection. + config_preferred_macos_terminal() + .or_else(load_preferred_macos_terminal) + .unwrap_or_else(detect_macos_terminal) +} + +/// Read `[terminal] preferred` from `~/.jcode/config.toml`, if present and valid. +fn config_preferred_macos_terminal() -> Option<MacTerminalKind> { + #[derive(Deserialize, Default)] + struct Wrapper { + #[serde(default)] + terminal: jcode_config_types::TerminalConfig, + } + let dir = storage::jcode_d…[truncated]

Citations:


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- hook-settings.ts ---'
cat -n src/main/jcode/hook-settings.ts
printf '%s\n' '--- hook-service.ts focused range ---'
sed -n '1,190p' src/main/jcode/hook-service.ts | cat -n
printf '%s\n' '--- jcode references and version/config bindings ---'
rg -n -P -C2 'jcode|JCODE|hook(s)?|config\.toml' package.json package-lock.json yarn.lock pnpm-lock.yaml bun.lockb src/main/jcode README.md docs 2>/dev/null | head -240

Repository: stablyai/orca

Length of output: 26250


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- exact managed-command usages ---'
rg -n -F -C3 'getJcodeManagedCommand' src tests 2>/dev/null || true
rg -n -F -C3 'getJcodeRemoteManagedCommand' src tests 2>/dev/null || true
printf '%s\n' '--- hook-config outline and relevant definitions ---'
ast-grep outline src/main/jcode/hook-config.ts
rg -n -P -C8 'applyJcodeManagedHooks|removeJcodeManagedHooks|scriptPath|managedCommand' src/main/jcode/hook-config.ts src/main/jcode/hook-service.ts
printf '%s\n' '--- remote install continuation ---'
sed -n '186,280p' src/main/jcode/hook-service.ts | cat -n

Repository: stablyai/orca

Length of output: 20648


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- hook-config implementation ---'
sed -n '1,180p' src/main/jcode/hook-config.ts | cat -n
printf '%s\n' '--- jcode hook tests and related status tests ---'
rg -n -P -C5 'applyJcodeManagedHooks|tomlQuoteString|JcodeHookService|getStatus|managed command|hook-config' src/main --glob '*test*' | head -260

Repository: stablyai/orca

Length of output: 29834


Quote and persist managed jcode commands.

Jcode splits unquoted whitespace and consumes backslashes before it executes a hook. The local and remote installers pass raw paths to applyJcodeManagedHooks, so paths with spaces or backslashes can invoke the wrong executable.

getJcodeManagedCommand is used only by a test. Changing that helper alone does not change production configuration. applyJcodeManagedHooks also preserves existing managed entries, so new quoting must rewrite existing entries as well. Compare status with the same quoted command stored in TOML.

🐛 Suggested fix
 export function getJcodeManagedCommand(scriptPath: string): string {
-  return scriptPath
+  return /[\s\\"']/.test(scriptPath) ? `"${scriptPath.replace(/(["\\])/g, '\\$1')}"` : scriptPath
 }

 export function getJcodeRemoteManagedCommand(scriptPath: string): string {
-  return scriptPath
+  return /[\s\\"']/.test(scriptPath) ? `"${scriptPath.replace(/(["\\])/g, '\\$1')}"` : scriptPath
 }

Pass these helpers to both applyJcodeManagedHooks calls, compare getJcodeManagedCommand(scriptPath) in getStatus, and rewrite existing managed entries to the quoted value.

Comment thread src/main/providers/local-pty-spawn.ts Outdated
Comment on lines +46 to +48
const jcodeRuntimeDir = args.env?.[JCODE_RUNTIME_DIR_ENV_KEY]
if (jcodeRuntimeDir) {
await mkdir(jcodeRuntimeDir, { recursive: true })

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

Jcode runtime-directory creation is fatal for every local terminal.

JCODE_RUNTIME_DIR is stamped on every local pane, not only on Jcode panes. All three creation sites let a mkdir error propagate into the spawn. A plain shell then fails to open when creation fails. EACCES on a /tmp/orca-jcode owned by another user is one trigger. A full disk or a read-only TMPDIR is another. Treat a creation failure as "no runtime dir": catch the error and leave JCODE_RUNTIME_DIR out of the environment.

  • src/main/providers/local-pty-spawn.ts#L46-L48: wrap await mkdir in try/catch. On failure, delete args.env[JCODE_RUNTIME_DIR_ENV_KEY] and skip prewarmJcodeDaemon.
  • src/main/ipc/pty/ipc/spawn-env.ts#L155-L157: wrap mkdirSync in try/catch. On failure, skip Object.assign(ctx.baseEnv, jcodeEnv).
  • src/main/runtime/orca-runtime-resolve-browser-network-execution-host-for-worktree.ts#L170-L171: call ensureJcodeRuntimeDir(paneKey).catch(() => undefined) so that buildTerminalWorkspaceEnv cannot reject.
📍 Affects 3 files
  • src/main/providers/local-pty-spawn.ts#L46-L48 (this comment)
  • src/main/ipc/pty/ipc/spawn-env.ts#L155-L157
  • src/main/runtime/orca-runtime-resolve-browser-network-execution-host-for-worktree.ts#L170-L171

// Why: `jcode run` takes the message as a positional argv argument and has no
// stdin prompt mode, so Source Control AI prompts ride argv (fine for branch
// naming and small diffs, argv-capped on Windows).
promptDelivery: 'argv',

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 | 🏗️ Heavy lift

Limit Jcode's single prompt argument on Linux.

Jcode receives the full prompt as one argv argument, but staged patches can reach the 200,000-character prompt budget. On a Linux host with 4-KiB pages, one argument cannot exceed 32 pages. A patch that pushes the prompt past roughly 128 KiB therefore fails to spawn Jcode, while the new size check covers only Windows. Apply a byte-aware Jcode prompt budget before spawn, or return a specific size error before attempting generation. (raw.githubusercontent.com)

Comment on lines +18 to +21
export function buildJcodeRuntimeDir(paneKey: string): string {
const hash = createHash('sha256').update(paneKey).digest('hex').slice(0, 16)
return join(tmpdir(), 'orca-jcode', hash)
}

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.

🔒 Security & Privacy | 🛡️ Detected with Advanced Tier | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

jcode JCODE_RUNTIME_DIR socket directory permission ownership check

💡 Result:

Inspection citation: inspection_ff3ceb174bcba039472964cf0dbed3c2

<source_evidence>

<title>crates/jcode-storage/src/lib.rs</title> https://github.com/1jehuang/jcode/blob/435fb4a8/crates/jcode-storage/src/lib.rs /// Platform-aware runtime directory for sockets and ephemeral state. /// /// - Linux: `$XDG_RUNTIME_DIR` (typically `/run/user/ `) /// - macOS: `$TMPDIR` (per-user, e.g. `/var/folders/xx/.../T/`) /// - Fallback: `std::env::temp_dir()` /// /// Can be overridden with `$JCODE_RUNTIME_DIR`. ... pub fn runtime_dir() -> PathBuf { if let Ok(dir) = std::env::var("JCODE_RUNTIME_DIR") { return PathBuf::from(dir); } if let Ok(dir) = std::env::var("XDG_RUNTIME_DIR") { return PathBuf::from(dir); } #[cfg(target_os = "macos")] { if let Ok(dir) = std::env::var("TMPDIR") { return PathBuf::from(dir); } } let dir = fallback_runtime_dir(); ensure_private_runtime_dir(&dir); dir } ... fn fallback_ ... Buf { ... ::env::temp_dir().join(format!("jcode-{}", ... _user_discriminator())) ... fn ensure_private_runtime_dir(path: &Path) { let _ = std::fs::create_dir_all(path); #[cfg(unix)] { let _ = jcode_core::fs::set_directory_permissions_owner_only(path); } } ... /// Durable state directory for state that must survive reboots. /// /// [`runtime_dir`] typically resolves to a tmpfs (for example /// `/run/user/ ` on Linux) that is wiped on reboot, so it must only hold /// sockets and truly ephemeral state. State that has to outlive a reboot, /// such as swarm plans and member records, belongs here instead: it resolves /// to `~/.jcode/state` (respecting `JCODE_HOME`). /// /// When `JCODE_RUNTIME_DIR` is set (tests and sandboxed temp servers), it /// takes precedence so isolated runs never touch the real jcode home. pub fn durable_state_dir() -> PathBuf { if let Ok(dir) = std::env::var("JCODE_RUNTIME_DIR") { return PathBuf::from(dir).join("durable-state"); } match jcode_dir() { Ok(dir) => dir.join("state"), Err(_) => runtime_dir().join("durable-state"), } } <title>crates/jcode-storage/src/lib.rs</title> https://github.com/1jehuang/jcode/blob/a63dbc45/crates/jcode-storage/src/lib.rs /// Platform-aware runtime directory for sockets and ephemeral state. /// /// - Linux: `$XDG_RUNTIME_DIR` (typically `/run/user/ `) /// - macOS: `$TMPDIR` (per-user, e.g. `/var/folders/xx/.../T/`) /// - Fallback: `std::env::temp_dir()` /// /// Can be overridden with `$JCODE_RUNTIME_DIR`. ... pub fn runtime_dir() -> PathBuf { if let Ok(dir) = std::env::var("JCODE_RUNTIME_DIR") { return PathBuf::from(dir); } if let Ok(dir) = std::env::var("XDG_RUNTIME_DIR") { return PathBuf::from(dir); } #[cfg(target_os = "macos")] { if let Ok(dir) = std::env::var("TMPDIR") { return PathBuf::from(dir); } } let dir = fallback_runtime_dir(); ensure_private_runtime_dir(&dir); dir } ... ::env::temp_dir ... code-{}", ... _user_discriminator())) ... fn ensure_private_runtime_dir(path: &Path) { let _ = std::fs::create_dir_all(path); #[cfg(unix)] { let _ = jcode_core::fs::set_directory_permissions_owner_only(path); } } ... /// Durable state directory for state that must survive reboots. /// /// [`runtime_dir`] typically resolves to a tmpfs (for example /// `/run/user/ ` on Linux) that is wiped on reboot, so it must only hold /// sockets and truly ephemeral state. State that has to outlive a reboot, /// such as swarm plans and member records, belongs here instead: it resolves /// to `~/.jcode/state` (respecting `JCODE_HOME`). /// /// When `JCODE_RUNTIME_DIR` is set (tests and sandboxed temp servers), it /// takes precedence so isolated runs never touch the real jcode home. pub fn durable_state_dir() -> PathBuf { if let Ok(dir) = std::env::var("JCODE_RUNTIME_DIR") { return PathBuf::from(dir).join("durable-state"); } match jcode_dir() { Ok(dir) => dir.join("state"), Err(_) => runtime_dir().join("durable-state"), } } <title>crates/jcode-app-core/src/server/socket.rs</title> https://github.com/1jehuang/jcode/blob/a63dbc45/crates/jcode-app-core/src/server/socket.rs pub fn socket_path() -> PathBuf { if let Ok(custom) = std::env::var("JCODE_SOCKET") { return PathBuf::from(custom); } crate::storage::runtime_dir().join("jcode.sock") } ... fn cleanup_ ... _pair(path ... &std::path::Path) { let ... std::fs::remove_file(path); if let Some(sibling) = sibling_socket_path(path) { let _ = std::fs::remove_file(sibling ... } } ... /// /// Do not unlink the path on connection-refused here. A client-side cleanup can /// strand a live daemon behind an unlinked Unix socket pathname, leaving the /// process running with the daemon lock held while new clients can no longer /// discover or connect to it. pub async fn connect_socket(path: &std::path::Path) -> Result { match Stream::connect(path).await { Ok(stream) => Ok(stream), Err(err) if err.kind() == std::io::ErrorKind::ConnectionRefused && path.exists() => { Err(anyhow::Error::new(err).context(format!( "Socket exists but refused the connection at {}. Retry, or remove it after confirming no jcode server is running.", path.display() ))) } Err(err) if err.raw_os_error() == Some(libc::EMFILE) => Err(anyhow::anyhow!( "{} ({})", err, crate::util::process_fd_diagnostic_snapshot() )), Err(err) => Err(err.into()), } } ... pub(super) async fn ... (path: &std::path::Path) -> bool { ... #[cfg(windows)] { // `is_ ... _path` ... blocking named-pipe open and treats // ERROR_PIPE ... . Do not follow it ... second connect: ... occupy the only published pipe ... accept loop replaces it ... second connect wait ... Y retry loop ... path) && Stream ... .is_ok() } } ... /// Reap a provably-stale socket left behind by a dead daemon. /// /// Background: after an upgrade or crash, the runtime socket file can survive /// even though the daemon that owned it is gone. A client that finds the socket /// path present but cannot connect/handshake gets wedged into a connect-retry /// loop and never recovers on its own (see issues `#277` and `#291`). ... /// /// Safety: a live daemon holds an exclusive `flock` on `jcode-daemon.lock` for /// its entire lifetime. So if (a) the socket has no live listener AND (b) we can /// acquire that exclusive lock, then no daemon is running and the socket is /// provably stale. Only then do we unlink the socket pair (main + debug) and the /// lock file. This can never strand a live daemon, because a live daemon would /// either still be answering on the socket or still be holding the lock. /// /// Returns true if a stale socket was reaped. #[cfg(unix)] pub async fn reap_stale_socket_if_dead(path: &std::path::Path) -> bool { // Nothing to reap if the path isn&`#39`;t even present. if !crate::transport::is_socket_path(path) { return false; } // If a listener answers, the daemon is alive; never touch it. if socket_has_live_listener(path).await { return false; } // Try to grab the daemon lock. If a live daemon holds it, this fails and we // leave everything alone (the daemon may just be slow to answer). let lock_path = daemon_lock_path(); let Ok(Some(_lock)) = try_acquire_daemon_lock(&lock_path) else { return false; }; ... // Re-check the listener now that we hold the lock, to close the race where a // daemon bound the socket between our probe and acquiring the lock. (A real // daemon could not have given us the lock, but a brand-new daemon spawned in // the gap might be mid-startup before it acquired the lock itself.) if socket_has_live_listener(path).await { return false; } crate::logging::warn(&format!( "Reaping stale jcode socket with no live listener at {}", path.display() )); cleanup_socket_pair(path); // `_lock` (a DaemonLockGuard) removes the lock file when it drops at the end // of this scope, so the leftover lock is cleaned up too. true } ... Path) -> ... (path). ... #[cfg(unix)] pub(super) fn daemon_lock_path() -> PathBuf { crate::storage::runtime_dir().join("jcode-daemon.lock") } ... #[cfg(unix)] pub(super) fn…[truncated] <title>sdk/typescript/src/launch.ts</title> https://github.com/1jehuang/jcode/blob/435fb4a8/sdk/typescript/src/launch.ts /** * ... instance. * * ` ... ()` attaches to whatever jcode is already running on the * machine, which ... right for a tool that automates * ... * jcode (an editor * ... dashboard) and wrong for everything ... application embedding * jcode as ... sessions, its own * state, and ... * * `launch()` gives it one. It starts a private daemon and bridge under a * dedicated `JCODE_HOME` and runtime directory, and shuts them down on * `close()`. */ ... /** A running private jcode instance. */ export ... LaunchedInstance { /** API socket path to connect to. */ socketPath: string; /** The instance&`#39`;s `JCODE_HOME`. */ jcodeHome: string ... process. */ process ... /** Stop ... (): Promise; ... /** * Pid of the daemon serving an instance, read from its own server registry. * * Synchronous on purpose: the only caller is a process "exit" handler, which * cannot await, so shelling out to the CLI is not available. jcode records * every server in `$JCODE_HOME/servers.json` keyed by socket path, and an * instance&`#39`;s registry lists only that instance&`#39`;s daemon, so this can never * resolve to the server the user is running themselves. */ function readDaemonPidSync(jcodeHome: string, runtimeDir: string): number | undefined { let raw: string; try { raw = fs.readFileSync(path.join(jcodeHome, "servers.json"), "utf8"); } catch { return undefined; } let registry: Record<string, { socket?: string; pid?: number }>; try { registry = JSON.parse(raw) as Record<string, { socket?: string; pid?: number }>; } catch { return undefined; } const socket = path.join(runtimeDir, "jcode.sock"); for (const entry of Object.values(registry)) { if (entry?.socket === socket && typeof entry.pid === "number" && entry.pid > 1) { return entry.pid; } } return undefined; } ... /** * Start a private jcode instance and return once its API socket is accepting * connections. */ export async function launchInstance(options: LaunchOptions = {}): Promise { const binary = options.binary ?? bundledJcodeBinary() ?? "jcode"; const ephemeral = options.jcodeHome === undefined; const jcodeHome = options.jcodeHome ?? fs.mkdtempSync(path.join(os.tmpdir(), "jcode-sdk-instance-")); fs.mkdirSync(jcodeHome, { recursive: true, mode: 0o700 }); // The runtime directory holds the sockets. Keeping it inside the instance // home is what makes the instance private: the daemon binds its socket // there rather than in the shared $XDG_RUNTIME_DIR, so a launched instance // and the user&`#39`;s own jcode cannot collide or find each other. const runtimeDir = path.join(jcodeHome, "run"); fs.mkdirSync(runtimeDir, { recursive: true, mode: 0o700 }); const socketPath = path.join(runtimeDir, "jcode-api.sock"); // A reused `jcodeHome` still holds the previous run&`#39`;s socket files. The // startup loop waits for the API socket to *appear*, so a leftover one makes // launch() return immediately against a socket nothing is listening on, and // the first request fails with ECONNREFUSED. Clearing them is safe: a live // instance on this home would mean two daemons sharing one state directory, // which is already unsupported. for (const stale of ["jcode-api.sock", "jcode.sock", "jcode-debug.sock", "jcode.sock.hash"]) { try { fs.unlinkSync(path.join(runtimeDir, stale)); } catch { // Absent, which is the normal case for a fresh home. } } if (options.inheritLogins ?? true) { inheritCredentials(userJcodeHome(), jcodeHome); } const child = spawn( binary, ["api-bridge", "--api-socket", socketPath], { cwd: options.workingDir ?? process.cwd(), env: { ...process.env, JCODE_HOME: jcodeHome, JCODE_RUNTIME_DIR: runtimeDir, JCODE_API_SOCKET: socketPath, JCODE_SOCKET: path.join(runtimeDir, "jcode.sock"), ...options.env, }, stdio: ["ignore", "ignore", options.inheritStderr ? "inherit" : "pipe…[truncated] <title>sdk/typescript/src/launch.ts</title> https://github.com/1jehuang/jcode/blob/a63dbc45/sdk/typescript/src/launch.ts instance. * * `JcodeClient ... ()` attaches to whatever jcode is already running on the ... * machine, which ... right for a ... that automates * ... * jcode (an editor * ... * j ... its own sessions ... its own * state, and no ... * * `launch()` gives it one. It starts a private daemon and bridge under a * dedicated `JCODE_HOME` and runtime directory, and shuts them down on * `close()`. */ ... /** API socket path to ... `JCODE ... jcode ... /** * Pid of the daemon serving an instance, read from its own server registry. * * Synchronous on purpose: the only caller is a process "exit" handler, which * cannot await, so shelling out to the CLI is not available. jcode records * every server in `$JCODE_HOME/servers.json` keyed by socket path, and an * instance&`#39`;s registry lists only that instance&`#39`;s daemon, so this can never * resolve to the server the user is running themselves. */ function readDaemonPidSync(jcodeHome: string, runtimeDir: string): number | undefined { let raw: string; try { raw = fs.readFileSync(path.join(jcodeHome, "servers.json"), "utf8"); } catch { return undefined; } let registry: Record<string, { socket?: string; pid?: number }>; try { registry = JSON.parse(raw) as Record<string, { socket?: string; pid?: number }>; } catch { return undefined; } const socket = path.join(runtimeDir, "jcode.sock"); for (const entry of Object.values(registry)) { if (entry?.socket === socket && typeof entry.pid === "number" && entry.pid > 1) { return entry.pid; } } return undefined; } ... /** * Start a private jcode instance and return once its API socket is accepting * connections. */ export async function launchInstance(options: LaunchOptions = {}): Promise { const binary = options.binary ?? bundledJcodeBinary() ?? "jcode"; const ephemeral = options.jcodeHome === undefined; const jcodeHome = options.jcodeHome ?? fs.mkdtempSync(path.join(os.tmpdir(), "jcode-sdk-instance-")); fs.mkdirSync(jcodeHome, { recursive: true, mode: 0o700 }); // The runtime directory holds the sockets. Keeping it inside the instance // home is what makes the instance private: the daemon binds its socket // there rather than in the shared $XDG_RUNTIME_DIR, so a launched instance // and the user&`#39`;s own jcode cannot collide or find each other. const runtimeDir = path.join(jcodeHome, "run"); fs.mkdirSync(runtimeDir, { recursive: true, mode: 0o700 }); const socketPath = path.join(runtimeDir, "jcode-api.sock"); // A reused `jcodeHome` still holds the previous run&`#39`;s socket files. The // startup loop waits for the API socket to *appear*, so a leftover one makes // launch() return immediately against a socket nothing is listening on, and // the first request fails with ECONNREFUSED. Clearing them is safe: a live // instance on this home would mean two daemons sharing one state directory, // which is already unsupported. for (const stale of ["jcode-api.sock", "jcode.sock", "jcode-debug.sock", "jcode.sock.hash"]) { try { fs.unlinkSync(path.join(runtimeDir, stale)); } catch { // Absent, which is the normal case for a fresh home. } } if (options.inheritLogins ?? true) { inheritCredentials(userJcodeHome(), jcodeHome); } const child = spawn( binary, ["api-bridge", "--api-socket", socketPath], { cwd: options.workingDir ?? process.cwd(), env: { ...process.env, JCODE_HOME: jcodeHome, JCODE_RUNTIME_DIR: runtimeDir, JCODE_API_SOCKET: socketPath, JCODE_SOCKET: path.join(runtimeDir, "jcode.sock"), ...options.env, }, stdio: ["ignore", "ignore", options.inheritStderr ? "inherit" : "pipe"], detached: false, }, ); // Keep the last of stderr: when startup fails, the reason is in there, and // "timed out" alone sends the caller looking in the wrong place. let stderr = ""; child.stderr?.on("data", (chunk:…[truncated]

Citations:


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- helper ---'
cat -n src/shared/jcode-runtime-dir.ts
printf '%s\n' '--- helper tests ---'
cat -n src/shared/jcode-runtime-dir.test.ts
printf '%s\n' '--- direct bindings ---'
rg -n -C 5 'JCODE_RUNTIME_DIR|prewarmJcodeDaemon|ensureJcodeRuntimeDir|buildJcodeRuntimeDirEnv' src
printf '%s\n' '--- jcode package/config references ---'
rg -n -C 4 'jcode-runtime|JCODE_RUNTIME_DIR|jcode.sock|jcode daemon|prewarm' package.json pnpm-lock.yaml yarn.lock package-lock.json src 2>/dev/null || true

Repository: stablyai/orca

Length of output: 41447


🏁 Script executed:

set -eu
cat -n src/shared/jcode-runtime-dir.ts
printf '\n--- callers ---\n'
rg -n -C 6 'JCODE_RUNTIME_DIR|prewarmJcodeDaemon|ensureJcodeRuntimeDir|buildJcodeRuntimeDirEnv' src

Repository: stablyai/orca

Length of output: 35729


Security Misconfiguration

Reachability: Internal
Exploitability: Difficult
CWE: CWE-379

Keep Jcode sockets in a validated per-user directory.

On Linux, this path can resolve to /tmp/orca-jcode/<hash>. The local PTY path and daemon-host path create it recursively without a mode or ownership check, then pass it to Jcode as JCODE_RUNTIME_DIR. Another local user can control the parent, replace the pane directory, and serve a fake jcode.sock. This can expose prompts and code, forge responses, or cause EACCES failures.

Use XDG_RUNTIME_DIR only after validating that it is an owned, mode 0700 directory. Otherwise use a per-user fallback. Keep the fallback as the direct parent to preserve the Unix socket path limit. Apply the same secure creation and lstat checks to ensureJcodeRuntimeDir, the local PTY provider, and the daemon-host spawn path. Jcode accepts the configured runtime directory directly, so Orca must enforce these checks.

Proposed path change
 export function buildJcodeRuntimeDir(paneKey: string): string {
   const hash = createHash('sha256').update(paneKey).digest('hex').slice(0, 16)
-  return join(tmpdir(), 'orca-jcode', hash)
+  const base = process.env.XDG_RUNTIME_DIR
+    ? join(process.env.XDG_RUNTIME_DIR, 'orca-jcode')
+    : join(tmpdir(), `orca-jcode-${process.getuid?.() ?? 'u'}`)
+  return join(base, hash)
 }
📝 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
export function buildJcodeRuntimeDir(paneKey: string): string {
const hash = createHash('sha256').update(paneKey).digest('hex').slice(0, 16)
return join(tmpdir(), 'orca-jcode', hash)
}
export function buildJcodeRuntimeDir(paneKey: string): string {
const hash = createHash('sha256').update(paneKey).digest('hex').slice(0, 16)
const base = process.env.XDG_RUNTIME_DIR
? join(process.env.XDG_RUNTIME_DIR, 'orca-jcode')
: join(tmpdir(), `orca-jcode-${process.getuid?.() ?? 'u'}`)
return join(base, hash)
}

@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.

Review continued from previous batch...

Comment on lines +35 to +36
function isInjectedContextMessage(message: Record<string, unknown>): boolean {
return message.display_role === 'system' || message.role === 'system'

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

🔎 Supported by static analysis

🏁 Script executed:

cat -n src/main/ai-vault/session-scanner-jcode-parser.ts
sed -n '1,95p' src/main/ai-vault/session-scanner-jcode-parser.test.ts
rg -n 'system-reminder|Scheduled task|isInjected|envelope' src/main/ai-vault/*.ts | head -40

Repository: stablyai/orca

Length of output: 12357


🏁 Script executed:

sed -n '1,240p' src/main/ai-vault/session-scanner-values.ts
sed -n '1,240p' src/main/ai-vault/session-scanner-accumulator.ts
rg -n -C 4 'extractContentText|normalizeTitleText|addPreviewContent|background_task|Scheduled task|display_role' src/main/ai-vault

Repository: stablyai/orca

Length of output: 41910


🏁 Script executed:

cat -n src/main/ai-vault/session-scanner-values.ts
cat -n src/main/ai-vault/session-scanner-accumulator.ts
cat -n src/main/ai-vault/session-scanner-values.test.ts
cat -n src/main/ai-vault/session-scanner-text-normalization.ts

Repository: stablyai/orca

Length of output: 43247


Filter Jcode internal messages before aggregation.

The current filter excludes only role or display_role equal to system. Jcode messages with display_role: "background_task" and user messages beginning with [Scheduled task] can still affect the title, count, and preview.

An unmarked <system-reminder> is already removed from title and preview text by the shared normalizers, but it still increments messageCount and can be published by addPreviewContent. Apply Jcode’s complete visible-message rule before timeline, count, title, preview, and transcript handling.

Comment on lines +46 to +58
const jcodeRuntimeDir = args.env?.[JCODE_RUNTIME_DIR_ENV_KEY]
if (jcodeRuntimeDir) {
await mkdir(jcodeRuntimeDir, { recursive: true })
// Why here and not earlier: the dir must exist before the daemon binds its
// socket in it, and this is the last point before the shell starts — the
// head start the client's 5s ready budget needs on a cold runtime dir.
prewarmJcodeDaemon({
launchAgent: args.launchAgent,
runtimeDir: jcodeRuntimeDir,
cwd: args.cwd,
env: args.env
})
}

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,90p' src/main/providers/local-pty-spawn.ts
cat -n src/main/jcode/daemon-prewarm.ts
rg -n 'ORCA_AGENT_HOOK_PORT|ORCA_AGENT_HOOK_ENDPOINT' src/main/providers src/main/ipc/pty | head -20

Repository: stablyai/orca

Length of output: 8187


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- changed diff ---'
git diff --stat 519bde81df438478ff1c6ac010f1339f32a306ee 7c0eee69d77535f783d31c1937e279d6d0c4181a -- src/main/providers/local-pty-spawn.ts src/main/jcode
git diff --unified=35 519bde81df438478ff1c6ac010f1339f32a306ee 7c0eee69d77535f783d31c1937e279d6d0c4181a -- src/main/providers/local-pty-spawn.ts src/main/jcode

printf '%s\n' '--- environment builder definitions ---'
rg -n -C 8 'function buildLocalPtySpawnEnvironment|buildLocalPtySpawnEnvironment|finalizeLocalPtySpawnEnvironment|ORCA_AGENT_HOOK_PORT|ORCA_AGENT_HOOK_ENDPOINT|ORCA_AGENT_HOOK_TOKEN|ORCA_PANE_KEY|JCODE_RUNTIME_DIR' src/main src/shared

printf '%s\n' '--- jcode and hook integration ---'
rg -n -S -C 6 'jcode|hook|ORCA_AGENT_HOOK|ORCA_PANE_KEY' src/main src/shared --glob '!**/*.map' --glob '!**/node_modules/**' | head -500

printf '%s\n' '--- relevant files ---'
git ls-files | rg '(^|/)(jcode|.*hook.*|.*pty.*env.*|tui-agent|child-process)'

Repository: stablyai/orca

Length of output: 45545


🏁 Script executed:

set -u
git diff --stat 519bde81df438478ff1c6ac010f1339f32a306ee 7c0eee69d77535f783d31c1937e279d6d0c4181a -- src/main/providers/local-pty-spawn.ts src/main/jcode
git diff --unified=25 519bde81df438478ff1c6ac010f1339f32a306ee 7c0eee69d77535f783d31c1937e279d6d0c4181a -- src/main/providers/local-pty-spawn.ts src/main/jcode
printf '%s\n' '--- env refs ---'
rg -n -C 6 'buildLocalPtySpawnEnvironment|finalizeLocalPtySpawnEnvironment|ORCA_AGENT_HOOK_PORT|ORCA_AGENT_HOOK_ENDPOINT|ORCA_AGENT_HOOK_TOKEN|ORCA_PANE_KEY|JCODE_RUNTIME_DIR' src/main src/shared
printf '%s\n' '--- jcode/hook refs ---'
rg -n -S -C 5 'jcode|hook|ORCA_AGENT_HOOK|ORCA_PANE_KEY' src/main src/shared --glob '!**/*.map' --glob '!**/node_modules/**' | head -500
printf '%s\n' '--- files ---'
git ls-files | rg '(^|/)(jcode|.*hook.*|.*pty.*env.*|tui-agent|child-process)'

Repository: stablyai/orca

Length of output: 45545


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 14167


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- source files ---'
git ls-files | rg '(^|/)(jcode|.*hook.*|.*pty.*env.*|tui-agent|child-process)'
printf '%s\n' '--- exact symbols ---'
rg -n -C 12 'buildLocalPtySpawnEnvironment|finalizeLocalPtySpawnEnvironment|ORCA_AGENT_HOOK_PORT|ORCA_AGENT_HOOK_ENDPOINT|ORCA_AGENT_HOOK_TOKEN|ORCA_PANE_KEY|JCODE_RUNTIME_DIR|prewarmJcodeDaemon' src/main src/shared

Repository: stablyai/orca

Length of output: 45538


🏁 Script executed:

#!/bin/bash
set -u
for f in \
  src/shared/jcode-runtime-dir.ts \
  src/main/jcode/hook-gate-script.ts \
  src/main/jcode/hook-service.ts \
  src/main/jcode/hook-config.ts \
  src/main/jcode/hook-settings.ts \
  src/main/jcode/daemon-prewarm.ts \
  src/main/providers/local-pty-spawn-environment.ts \
  src/main/providers/local-pty-finalize-environment.ts \
  src/main/ipc/pty/host-env/assembly.ts \
  src/main/ipc/pty/host-env/spawn-env-keys.ts \
  src/shared/agent-hook-listener-jcode.test.ts
do
  if [ -f "$f" ]; then
    printf '\n--- %s ---\n' "$f"
    cat -n "$f"
  fi
done
printf '\n--- focused call sites ---\n'
rg -n -C 10 'buildJcodeRuntimeDirEnv|ORCA_AGENT_HOOK|ORCA_PANE_KEY|buildLocalPtySpawnEnvironment|finalEnv|prewarmJcodeDaemon' \
  src/main/providers src/main/ipc/pty src/main/jcode src/shared/jcode-runtime-dir.ts src/shared/agent-hook-listener-jcode.test.ts

Repository: stablyai/orca

Length of output: 42935


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- local environment builder ---'
cat -n src/main/providers/local-pty-spawn-environment.ts
printf '%s\n' '--- local finalizer ---'
cat -n src/main/providers/local-pty-finalize-environment.ts
printf '%s\n' '--- IPC spawn environment entry and call flow ---'
sed -n '1,210p' src/main/ipc/pty/ipc/spawn-env.ts
rg -n -C 12 'assemblePtyIpcSpawn|baseEnv|spawnLocalPty|provider\.spawn|LocalPtyProvider' src/main/ipc/pty src/main/providers --glob '*.ts'
printf '%s\n' '--- host assembly entry ---'
sed -n '1,190p' src/main/ipc/pty/host-env/assembly.ts
printf '%s\n' '--- changed hunk only ---'
git diff --unified=12 519bde81df438478ff1c6ac010f1339f32a306ee 7c0eee69d77535f783d31c1937e279d6d0c4181a -- src/main/providers/local-pty-spawn.ts

Repository: stablyai/orca

Length of output: 45537


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- local-pty-spawn-environment.ts ---'
wc -l src/main/providers/local-pty-spawn-environment.ts
cat -n src/main/providers/local-pty-spawn-environment.ts
printf '%s\n' '--- direct builder references ---'
rg -n -C 8 'buildLocalPtySpawnEnvironment|buildPtyHostEnv|buildPtySpawnEnvironment' \
  src/main/providers/local-pty-spawn-environment.ts \
  src/main/providers/local-pty-spawn.ts \
  src/main/providers/local-pty-provider-spawn-env.test.ts \
  src/main/ipc/pty/ipc/spawn-env.ts
printf '%s\n' '--- provider invocation context ---'
rg -n -C 12 'spawnLocalPty\(|provider\.spawn\(|env:' src/main/ipc/pty src/main/providers/local-pty-provider.ts src/main/providers/local-pty-provider-types.ts 2>/dev/null | head -240

Repository: stablyai/orca

Length of output: 28171


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- buildSpawnEnv assignments ---'
rg -n -C 16 'buildSpawnEnv\s*[:=]|buildSpawnEnv\(' src/main --glob '*.ts' | head -400
printf '%s\n' '--- provider option types and construction ---'
cat -n src/main/providers/local-pty-provider-types.ts
rg -n -C 16 'LocalPtyProviderOptions|new LocalPtyProvider|buildPtyHostEnv' src/main --glob '*.ts' | head -500

Repository: stablyai/orca

Length of output: 40398


🏁 Script executed:

#!/bin/bash
set -u
cat -n src/main/ipc/pty/provider/local-configure.ts | sed -n '35,145p'

Repository: stablyai/orca

Length of output: 5032


🏁 Script executed:

#!/bin/bash
set -u
rg -n -C 12 'buildPtyEnv|ORCA_AGENT_HOOK_PORT|ORCA_AGENT_HOOK_TOKEN|ORCA_AGENT_HOOK_ENDPOINT' src/main/agent-hooks/server.ts

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -u
file=$(rg -l 'class AgentHookServer|buildPtyEnv' src/main/agent-hooks src/main | head -1)
printf 'file=%s\n' "$file"
if [ -n "$file" ]; then
  rg -n -C 14 'buildPtyEnv|ORCA_AGENT_HOOK_PORT|ORCA_AGENT_HOOK_TOKEN|ORCA_AGENT_HOOK_ENDPOINT' "$file"
fi

Repository: stablyai/orca

Length of output: 4711


🏁 Script executed:

#!/bin/bash
set -u
rg -l --glob '!**/*.test.ts' --glob '!**/*.spec.ts' 'class AgentHookServer|export const agentHookServer|buildPtyEnv' src/main/agent-hooks src/main | head -30

Repository: stablyai/orca

Length of output: 1664


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- server env symbols ---'
rg -n -C 18 'buildPtyEnv|ORCA_AGENT_HOOK_PORT|ORCA_AGENT_HOOK_TOKEN|ORCA_AGENT_HOOK_ENDPOINT' \
  src/main/agent-hooks/server.ts src/main/agent-hooks/server/server-runtime-env.ts

Repository: stablyai/orca

Length of output: 4002


Prewarm Jcode with finalEnv, not args.env.

spawnLocalPty starts the daemon before buildLocalPtySpawnEnvironment calls buildPtyHostEnv. When hooks are enabled, that builder adds the current ORCA_AGENT_HOOK_PORT and ORCA_AGENT_HOOK_TOKEN. Jcode hooks run inside the daemon, and the managed script exits when those values are missing. A normal Jcode launch can therefore drop lifecycle events while the shell receives valid hook coordinates.

Suggested fix
   if (jcodeRuntimeDir) {
     await mkdir(jcodeRuntimeDir, { recursive: true })
-    // Why here and not earlier: the dir must exist before the daemon binds its
-    // socket in it, and this is the last point before the shell starts — the
-    // head start the client's 5s ready budget needs on a cold runtime dir.
-    prewarmJcodeDaemon({
-      launchAgent: args.launchAgent,
-      runtimeDir: jcodeRuntimeDir,
-      cwd: args.cwd,
-      env: args.env
-    })
   }
@@
   const historyResult = finalizeLocalPtySpawnEnvironment({
     spawn: args,
     getOptions,
     plan,
     env: finalEnv
   })
+  // The daemon must inherit the finalized hook environment before the shell starts.
+  if (jcodeRuntimeDir) {
+    prewarmJcodeDaemon({
+      launchAgent: args.launchAgent,
+      runtimeDir: jcodeRuntimeDir,
+      cwd: args.cwd,
+      env: finalEnv
+    })
+  }

function exceedsWindowsCommandLineBudget(command: string, args: string[]): boolean {
let units = command.length + args.length
for (const arg of args) {
units += arg.length + 2

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '80,200p' src/main/text-generation/source-control-local-process.ts
rg -n "on\('error'|\.on\(\"error\"|shell: |\.cmd" src/main/text-generation | head -30

Repository: stablyai/orca

Length of output: 5183


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- source-control-local-process imports, guard, and spawn setup ---'
sed -n '1,125p' src/main/text-generation/source-control-local-process.ts
printf '%s\n' '--- source-control-local-process handlers ---'
sed -n '145,245p' src/main/text-generation/source-control-local-process.ts
printf '%s\n' '--- spawnAgent bindings ---'
rg -n -C 5 "spawnAgent" src/main/text-generation src/main | head -160
printf '%s\n' '--- jcode plan/default command ---'
rg -n -C 8 "jcode|binary:|customAgentCommand" src/main/text-generation | head -220

Repository: stablyai/orca

Length of output: 41763


🏁 Script executed:

sed -n '1,125p' src/main/text-generation/source-control-local-process.ts; sed -n '145,245p' src/main/text-generation/source-control-local-process.ts; rg -n -C 5 "spawnAgent" src/main/text-generation src/main | head -160; rg -n -C 8 "jcode|binary:|customAgentCommand" src/main/text-generation | head -220

Repository: stablyai/orca

Length of output: 41308


🏁 Script executed:

rg -n -C 12 "spawnAgent" src/main
rg -n -C 12 "jcode" src/main

Repository: stablyai/orca

Length of output: 43264


🏁 Script executed:

set -e
printf '%s\n' '--- exact spawn helper locations ---'
rg -l "spawnSourceControlAgent|function spawnSourceControlAgent|const spawnSourceControlAgent" src
printf '%s\n' '--- exact jcode plan locations ---'
rg -l "planCommitMessageGeneration|getAgentModelProbeSpec|jcode" src/main/text-generation src/main/shared 2>/dev/null | head -40
printf '%s\n' '--- exact definitions ---'
rg -n -C 18 "spawnSourceControlAgent|planCommitMessageGeneration|getAgentModelProbeSpec" src/main/text-generation src/main | head -260

Repository: stablyai/orca

Length of output: 26896


🏁 Script executed:

set -e
printf '%s\n' '--- source-control-agent-launch.ts ---'
sed -n '1,180p' src/main/text-generation/source-control-agent-launch.ts
printf '%s\n' '--- Windows command helpers ---'
rg -n -C 12 "function resolveCliCommand|const resolveCliCommand|function getSpawnArgsForWindows|const getSpawnArgsForWindows|resolveCliCommand|getSpawnArgsForWindows" src/main
printf '%s\n' '--- plan implementation ---'
rg -l "export function planCommitMessageGeneration|function planCommitMessageGeneration" src shared
rg -n -C 18 "planCommitMessageGeneration" src shared

Repository: stablyai/orca

Length of output: 41837


🏁 Script executed:

set -e
printf '%s\n' '--- commit-message-plan.ts ---'
sed -n '1,240p' src/shared/commit-message-plan.ts
printf '%s\n' '--- windows-batch-spawn.ts ---'
sed -n '1,240p' src/shared/windows-batch-spawn.ts

Repository: stablyai/orca

Length of output: 12928


🏁 Script executed:

set -e
sed -n '240,430p' src/shared/commit-message-plan.ts
rg -n -C 18 "jcode|getCommitMessageAgentSpec|promptDelivery|prompt" src/shared/commit-message-agent-spec.ts src/shared/commit-message-plan.ts

Repository: stablyai/orca

Length of output: 31955


🏁 Script executed:

set -e
rg -n -C 8 "jcode|buildSecondaryCommitMessageAgentSpecs|promptDelivery: 'argv'|binary:" src/shared/commit-message-agent-spec.ts src/shared/commit-message-prompt.ts src/shared

Repository: stablyai/orca

Length of output: 42080


🏁 Script executed:

set -e
rg -n -C 24 "export function resolveCliCommand|function resolveCliCommand|resolveCliCommand" src/main/codex-cli/command.ts src/shared/node-cli-command-resolution.ts

Repository: stablyai/orca

Length of output: 10178


🏁 Script executed:

sed -n '90,160p' src/shared/node-cli-command-resolution.ts

Repository: stablyai/orca

Length of output: 2943


Budget the effective Windows launcher command.

Jcode puts the prompt in argv as jcode run --json <prompt>. When Windows resolves jcode to a .cmd shim, spawnSourceControlAgent launches it through cmd.exe /d /c. The current 30,000-unit guard runs before resolution and does not enforce cmd.exe’s lower command-length limit. A large prompt can pass the guard and still fail during launch.

The failure is returned as success: false through the child error or close handler. It does not cause a hang or crash. Quotation marks are not a useful trigger for the batch-shim case because getSpawnArgsForWindows rejects them before spawning. Calculate the effective command after resolution and apply the limit for the selected launcher.

// clap rejects them after `run`.
'--no-update',
'--quiet',
'--no-selfdev',

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.

🔒 Security & Privacy | 🛡️ Detected with Advanced Tier | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

set -eu
printf '%s\n' '--- target symbols and cited lines ---'
ast-grep outline src/shared/commit-message-agent-specs-secondary.ts
sed -n '230,315p' src/shared/commit-message-agent-specs-secondary.ts
printf '%s\n' '--- Jcode references ---'
rg -n -C 3 --glob '!node_modules' --glob '!dist' --glob '!build' 'jcode|Jcode|no-selfdev|commit-message-agent' src package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null | head -240
printf '%s\n' '--- changed hunk summary ---'
git diff --stat 519bde81df438478ff1c6ac010f1339f32a306ee 7c0eee69d77535f783d31c1937e279d6d0c4181a -- src/shared/commit-message-agent-specs-secondary.ts src/shared/commit-message-agent-spec.ts
git diff --unified=25 519bde81df438478ff1c6ac010f1339f32a306ee 7c0eee69d77535f783d31c1937e279d6d0c4181a -- src/shared/commit-message-agent-specs-secondary.ts | sed -n '1,260p'

Repository: stablyai/orca

Length of output: 24955


🌐 Web query:

Jcode CLI run --no-selfdev MCP tools shell write permissions

💡 Result:

Inspection citation: inspection_8d9f3557cd8ff1e1b03bd384d21d09d2

<source_evidence>

<title>src/cli/args.rs</title> https://github.com/1jehuang/jcode/blob/f8004dbd/src/cli/args.rs provided #[arg(long, global = true, num_args = ... 0..=1, default_missing_value = "")] ... pub(crate) resume: Option, /// Internal: launched as a freshly spawned window, so skip heavy local resume bootstrap. #[arg(long, global = true, hide = true)] pub(crate) fresh_spawn: bool, /// Disable auto-detection of jcode repository and self-dev mode #[arg(long, global = true)] pub(crate) no_selfdev: bool, /// Custom socket path for server/client communication #[arg(long, global = true)] pub(crate) socket: Option, /// Enable debug socket (broadcasts all TUI state changes) #[arg(long, global = true)] pub(crate) debug_socket: bool, /// Model to use (e.g., claude-opus-4-6, gpt-5.5) #[arg(short, long, global = true)] pub(crate) model: Option, /// Named provider profile from [providers.] in config.toml. /// Implies --provider openai-compatible for OpenAI-compatible profiles. #[arg(long, global = true)] pub(crate) provider_profile: Option, /// Tool profile to expose to the model: full, minimal/lite, or none. #[arg(long, global = true)] pub(crate) tool_profile: Option, /// Comma-separated explicit allow-list of tools to expose, e.g. bash,read,write,apply_patch. Use &`#39`;*&`#39`; or &`#39`;all&`#39`; to expose all tools, including default-disabled tools. #[arg(long, global = true)] pub(crate) tools: Option, /// Comma-separated list of tools to hide after applying the selected profile. #[arg(long, global = true)] pub(crate) disabled_tools: Option, /// Hide all built-in tools unless --tools or [tools].enabled opts tools back in. #[arg(long, global = true)] pub(crate) disable_base_tools: bool, #[command(subcommand)] pub(crate) command: Option, } ... limits for connected ... /// Emit ... #[arg(long ... , }, /// Self-development mode: run as a canary session on the shared server #[command(alias = "selfdev")] SelfDev { /// Build and test a new canary version before launching #[arg(long)] build: bool, }, /// Debug socket CLI - interact with running jcode server Debug { /// Debug command to run (list, start, sessions, create_session, message, tool, state, history, etc.) #[arg(default_value = "help")] command: String, /// Optional argument for the command #[arg(default_value = "")] arg: String, /// Target a specific session by ID #[arg(short = &`#39`;S&`#39`;, long)] session: Option, /// ... specific server socket path ... #[arg(short = &`#39`; ... &`#39`;, long)] ... : Option, /// Wait for ... { /// ... instead of generating a ... #[arg(long)] list: bool, /// Revoke a ... device by name or ID #[arg(long)] revoke: Option, }, /// Review and respond to pending ambient permission requests Permissions, /// Inject externally transcribed text into the active Jcode TUI Transcript { /// Transcript text. If omitted, reads from stdin. text: Option, /// ... to apply the transcript inside ... #[arg( ... , default_ <title>docs/WRAPPERS.md</title> https://github.com/1jehuang/jcode/blob/master/docs/WRAPPERS.md # docs/WRAPPERS.md - Branch: master - Repository: 1jehuang/jcode --- # jcode wrapper / scripting guide This document describes the non-interactive CLI surface intended for wrappers, scripts, and other tools that invoke `jcode`. ## Recommended flags Use these flags by default in wrappers: ```bash jcode --quiet --no-update --no-selfdev ... ``` - `--quiet` suppresses non-error CLI/status chatter - `--no-update` avoids update-check noise/work - `--no-selfdev` avoids repository auto-detection changing runtime behavior ## Discover available models List model names that can be passed to `-m/--model`: ```bash jcode --quiet model list jcode --quiet model list --json jcode --quiet --provider openai model list --json ``` ## Discover providers and current selection List provider IDs you can pass to `-p/--provider`: ```bash jcode --quiet provider list jcode --quiet provider list --json ``` Inspect the currently requested and resolved provider/model selection: ```bash jcode --quiet provider current jcode --quiet --provider openai --model gpt-5.4 provider current --json ``` Verbose human summary: ```bash jcode --quiet model list --verbose ``` ## Run one prompt and return JSON ```bash jcode --quiet run --json "Reply with exactly OK" ``` ## Stream one prompt as NDJSON ```bash jcode --quiet run --ndjson "Reply with exactly OK" ``` Typical event types: - `start` - `connection_phase` - `connection_type` - `text_delta` - `text_replace` - `tool_start` - `tool_input` - `tool_exec` - `tool_done` - `tokens` - `done` - `error` The final `done` event includes the assembled text and usage summary. Example shape: ```json { "session_id": "session_...", "provider": "OpenAI", "model": "gpt-5.4", "text": "OK", "usage": { "input_tokens": 123, "output_tokens": 7, "cache_read_input_tokens": 0, "cache_creation_input_tokens": null } } ``` ## Inspect authentication state ```bash jcode --quiet auth status jcode --quiet auth status --json ``` JSON output includes: - `any_available` - `providers[]` - `id` - `display_name` - `status` - `method` - `auth_kind` - `recommended` ## Inspect build/version details ```bash jcode --quiet version jcode --quiet version --json ``` JSON output includes: - `version` - `git_hash` - `git_tag` - `build_time` - `git_date` - `release_build` ## Notes - JSON commands are designed so the intended machine-readable result is printed to `stdout` - With `--quiet`, wrapper-oriented commands should keep `stderr` empty unless there is a real warning/error - `jcode model list` and `jcode run --json` do not require the TUI - `jcode model list` does not require an already-running shared server <title>1jehuang/jcode</title> http://github.com/1jehuang/jcode ### Config-file setup for self-hosted endpoints and MCP ... If you prefer to configure things by editing files instead of using the login UI, jcode supports both a custom OpenAI-compatible endpoint config and MCP config files. ... #### MCP config files ... MCP config is separate from `config.toml`. Primary config files: ... - `~/.jcode/mcp.json` for global MCP servers - `.jcode/mcp.json` for project-local MCP servers ... Claude Code compatibility: - `~/.claude.json` (Claude Code&`#39`;s user config): top-level `mcpServers`, plus per-project servers under `projects.<abs_path>.mcpServers` for the current directory - `.mcp.json` at the repo root (Claude Code&`#39`;s project config) - `.claude/mcp.json` (legacy fallback) ... Claude Code config is read live on every load rather than copied into jcode&`#39`;s global config. Additions, edits, and deletions therefore take effect without leaving a stale snapshot (and inline environment values are not duplicated). ... For migration from Codex CLI, jcode still performs a one-time import from `~/.codex/config.toml` into `~/.jcode/mcp.json` when the latter does not exist. That imported file is then jcode-owned; later Codex changes are not synced automatically. Imported environment values are copied too and may contain secrets. ... Both the canonical `mcpServers` key and jcode&`#39`;s historical `servers` key are accepted. jcode currently supports stdio (command-based) servers only; HTTP/SSE entries (`"type": "http"`/`"sse"`) are recognized and skipped with a log line. ... Example MCP config: ... ```json { "mcpServers": { "filesystem": { "command": "/path/to/mcp-server", "args": ["--root", "/workspace"], "env": {}, "shared": true } } } ``` ... For headless or SSH sessions, OAuth-style providers support `jcode login --provider --no-browser` (alias: `--headless`) so jcode prints the auth URL/QR and falls back to manual code or callback paste instead of trying to launch a local browser. ... ## Customizability / Self-Dev ... Jcode is inventing a new form of customizability. One that doesn&`#39`;t limit you to what a plugin or extension can do. Tell your jcode agent to enter self dev mode, and it will start modifying its own source code. Jcode is optimized to iterate on itself. There is significant infrastructure around self developement, which allows it to edit, build, and test its own source code, then reload its own binary and continue work in your (potentially many) sessions, fully automatically. It is reccom ... you use a frontier model ... ## Quick Start ```bash # Launch the TUI jcode ... # Run a single command non-interactively jcode run "say hello" ... # Resume a previous session by memorable name jcode --resume fox ... # Run as a persistent background server, then attach more clients jcode serve jcode connect ... jcode supports interactive TUI use, non-interactive runs, persistent server/client workflows, and hotkey-friendly dictation without requiring a bundled speech-to-text stack. jcode workflow demonstration --- ... in tool actions include: ... - `status` - `setup` - `open` - `snapshot` - `get_content` - `interactables` - `click` - `type` - `fill_form` - `select` - `wait` - `screenshot` - `eval` - `scroll` - `upload` - `press` ... 1jehuang ... brew ... - macOS or Linux ... : curl -fsSL https://jcode.sh/ ... | bash - Windows PowerShell ... https://j ... .sh/install ... ps1 | iex - From source if the ... appropriate: git ... .com/1jehuang/jcode ... git cd jcode cargo build --release scripts/install_release.sh - For local self-dev / refactor work on Linux x8 ... 4, prefer: scripts/ ... _cargo.sh build --release -p jcode --bin jcode ... 6. Only if ... , guide me through ... jcode login --provider claude` - GitHub Copilot: `jcode login --provider copilot` - OpenAI: `jcode login --provider openai` - ... : `jcode login --provider gemini` - Azure OpenAI: …[truncated] <title>feat: add MCP support to `jcode run` (headless single-message mode)</title> GitHub issue 390 in 1jehuang/jcode (link omitted to avoid creating a cross-reference) `jcode run "prompt"` creates a bare `Registry::new()` without calling `register_mcp_tools`, so MCP servers configured in `~/.jcode/mcp.json` are never loaded. The agent has no MCP tools available in headless mode. ... Any workflow that uses `jcode run` for scripting or automation (e.g. CI pipelines, per-job agent spawning via shell scripts) gets zero MCP tools, even with a fully populated `~/.jcode/mcp.json`. ... Add `register_mcp_tools` to `run_single_message_command`, similar to how `create_headless_session` does it: ... ```rust let registry = crate::tool::Registry::new(provider.clone()).await; registry.register_mcp_tools(None, None, None).await; // load from ~/.jcode/mcp.json let mut agent = crate::agent::Agent::new(provider.clone(), registry); ``` ... Since MCP connections happen in background (non-blocking), this adds negligible startup latency for short runs. A `--no-mcp` flag could skip it for latency-sensitive scripting if needed. ... > Thanks for the careful investigation, and especially for ... up corrections, they&`#39`;re spot on. Here ... s how the ... > `Registry::register_mcp_tools()` (in `crates/jcode-app-core/src/tool/mod.rs`) does **not** block on connections. At spawn it: > > 1. Loads the on-disk **schema cache** (`McpSchemaCache::load()`) and registers proxy `mcp__*` tools for each configured server *synchronously, before any connection settles*. So the first locked snapshot already contains the MCP tools. The log line is: ... > ``` > MCP: advertised N cached tool(s) from M server(s) at spawn ... > (connect-on-first-call); zero prompt-cache miss expected (`#206`) ... > 2. Spawns a background task that actually connects (`connect_all()`), then re-registers the live schemas (idempotent, handles schema drift) and **reconciles the on-disk schema cache** with the live tools so the *next* spawn is also zero-miss. > > The proxies are **connect-on-first-call**: if the model invokes an MCP tool before the background connection finishes, that single call connects synchronously and then proceeds. So there&`#39`;s no "tools missing" window for the model and no blocking wait for the user. > > ### 3. Cold-cache fallback (the one intentional miss) ... a server has **no cached schema yet** (first time ever using it, or its config fingerprint changed), advertise-early has nothing to register for it. For that case there&`#39`;s a one-shot recovery in `tool_definitions()`: exactly once per locked snapshot, if `mcp__*` tools have since appeared in the registry, it drops the stale snapshot and rebuilds (`mcp_late_register_resolved` guards it to a single rescan). That rebuild is the one intentional prompt-cache miss, accepted only because we refuse to block spawn on MCP connection. ... > > ** ... : steady state = zero cache miss, zero ... . The `tool ... 9` / fixed `tools_hash` ... is the cold- ... run that reaches `connect_all()` + cache reconcile ... subsequent spawns advertise the ... the model sees them ... agent-driven `mcp` connect ... `unlock_tools()` and forces ... > > ## The `jcode run` bug (confirmed + fixed) > > You&`#39`;re right that `jcode run` was the genuine, unambiguous defect: `run_single_message_command` built a bare `Registry::new()` and **never called `register_mcp_tools` at all**, so neither layer above ran. No advertise-early, no background connect, no cache. MCP was simply absent from headless single-message mode. > > Fixed in `53cae6cb`: `jcode run` now calls `register_mcp_tools(None, None, None)` (loads `~/.jcode/mcp.json`), so it gets the same advertise-early + background-connect behavior as the other paths. As you noted, this adds negligible startup latency for short runs because connection is backgrounded. I also added a `JCODE_RUN_MCP=0` opt-out for latency-sensitive scripting. > > Verified against a configured server: > > ``` > $ jcode run "List every tool you have starting with &`#39`;mcp__&`#39`;.…[truncated] <title>src/cli/dispatch.rs</title> https://github.com/1jehuang/jcode/blob/a63dbc45/src/cli/dispatch.rs if let Some(profile_name) = args .provider_profile .as_deref() .map(str::trim) .filter(|value| !value.is_empty()) { provider_catalog::apply_named_provider_profile_env(profile_name)?; crate::env::set_var("JCODE_PROVIDER_PROFILE_NAME", profile_name); crate::env::set_var("JCODE_PROVIDER_PROFILE_ACTIVE", "1"); args.provider = ProviderChoice::OpenaiCompatible; } if let Some(tool_profile) = args.tool_profile.as_deref() { crate::env::set_var("JCODE_TOOL_PROFILE", tool_profile); } if let Some(tools) = args.tools.as_deref() { crate::env::set_var("JCODE_TOOLS", tools); } if let Some(disabled_tools) = args.disabled_tools.as_deref() { crate::env::set_var("JCODE_DISABLED_TOOLS", disabled_tools); } if args.disable_base_tools { crate::env::set_var("JCODE_DISABLE_BASE_TOOLS", "1"); } if let Some(mcp_tools) = args.mcp_tools.as_deref() { crate::env::set_var("JCODE_MCP_TOOLS", mcp_tools); } if let Some(threshold) = args.mcp_tools_token_threshold { crate::env::set_var("JCODE_MCP_TOOLS_TOKEN_THRESHOLD", threshold.to_string()); } if args.tool_profile.is_some() || args.tools.is_some() || args.disabled_tools.is_some() || args.disable_base_tools || args.mcp_tools.is_some() || args.mcp_tools_token_threshold.is_some() { crate::config::invalidate_config_cache(); } match args.command { Some(Command::Serve { temporary_server, owner_pid, temp_idle_timeout_secs, server_name, }) => { let serve_start = Instant::now(); crate::env::set_var("JCODE_NON_INTERACTIVE", "1"); if temporary_server { server::configure_temporary_server(owner_pid, temp_idle_timeout_secs); } ... json } => ... commands::run_provider_ ... } ProviderCommand:: ... { json } => ... commands::run_provider_current_command(&args.provider, args.model.as_deref(), ... .await?; } ... url, model, context_window, api ... key_env, api_key, api_key_stdin, no_api_key, auth, auth_header, env_file, set_default, overwrite, provider_routing, model_catalog, json, } => { commands::run_provider_add_command(commands::ProviderAddOptions { name, base_url, model, context_window, api_key_env, api_key, api_key_stdin, no_api_key, auth, auth_header, env_file, set_default, overwrite, provider_routing, model_catalog, json, })?; } }, Some(Command::Memory(subcmd)) => { commands::run_memory_command(map_memory_subcommand(subcmd))?; } Some(Command::Session(subcmd)) => match subcmd { SessionCommand::Rename { session, name, clear, json, } => commands::run_session_rename_command(&session, name.as_deref(), clear, json)?, }, Some(Command::Ambient(subcmd)) => { commands::run_ambient_command(map_ambient_subcommand(subcmd)).await?; } Some(Command::Cloud(subcmd)) => { commands::run_cloud_command(map_cloud_subcommand(subcmd))?; } Some(Command::Pair { list, revoke }) => { commands::run_pair_command(list, revoke)?; } Some(Command::Permissions) => { tui::permissions::run_permissions()?; } Some(Command::Transcript { text, mode, session, }) => { commands::run_transcript_command(text, map_transcript_mode(mode), session).await?; } Some(Command::Dictate { r#type }) => { commands::run_dictate_command(r#type).await?; } Some(Command::SetupHotkey { listen_macos_hotkey, notify_cli_launch, listen_windows_hotkey, uninstall, }) => { setup_hints::run_setup_hotkey( listen_macos_hotkey, listen_windows_hotkey, uninstall, notify_cli_launch.as_deref(), )?; } Some(Command::SetupLauncher) => { setup_hints::run_setup_launcher()?; } Some(Command::Browser { action }) => { commands::run_browser(&action).await?; } Some(Command::Replay { session, swarm, export, speed, timeline, auto_edit, video, cols, rows, fps, centered, no_centered, }) => { let centered_override = if centered { ... (true) ... else if no_centered { ... (false) } else { ... tui_launch::run_replay_command( ... , auto_edit, speed, timeline ... (), cols, ... centered_override, ... } Some(Command::Model ... cmd)) =…[truncated]

Citations:


🌐 Web query:

site:github.com/1jehuang/jcode default tool profile shell write MCP tool-profile none

💡 Result:

Inspection citation: inspection_9c230d15a4d6c5877a1df338332e5d22

<source_evidence>

<title>src/cli/args.rs</title> https://github.com/1jehuang/jcode/blob/f8004dbd/src/cli/args.rs (e.g., ... -opus-4-6, ... -5.5 ... #[arg(short, long, global = true ... pub(crate ... , /// Named provider profile from [providers.] in config.toml. /// Implies --provider openai-compatible for OpenAI-compatible profiles. #[arg(long, global = true)] pub(crate) provider_profile: Option, /// Tool profile to expose to the model: full, minimal/lite, or none. #[arg(long, global = true)] pub(crate) tool_profile: Option, /// Comma-separated explicit allow-list of tools to expose, e.g. bash,read,write,apply_patch. Use &`#39`;*&`#39`; or &`#39`;all&`#39`; to expose all tools, including default-disabled tools. #[arg(long, global = true)] pub(crate) tools: Option, /// Comma-separated list of tools to hide after applying the selected profile. #[arg(long, global = true)] pub(crate) disabled_tools: Option, /// Hide all built-in tools unless --tools or [tools].enabled opts tools back in. #[arg(long, global = true)] pub(crate) disable_base_tools: bool, #[command(subcommand)] pub(crate) command: Option, } ... #[derive(Subcommand, Debug)] pub(crate) enum ProviderCommand { /// List provider IDs you can pass to -p/--provider List { /// Emit ... instead of plain text #[arg(long ... : bool, }, /// Show the currently requested and resolved provider selection Current { /// Emit JSON instead of plain text #[arg(long)] json: bool, }, /// Add a named OpenAI-compatible API provider profile Add { /// Profile name used with --provider-profile and config defaults, e.g. my-gateway name: String, /// OpenAI-compatible API base URL, e.g. https://llm.example.com/v1 #[arg(long, alias = "api-base")] base_url: String, /// Default model id for this provider profile #[arg(short, long)] model: String, /// Optional model context window in tokens #[arg(long)] context_window: Option, /// Environment variable name that contains the API key #[arg(long, conflicts_with = "no_api_key")] api_key_env: Option, /// API key value to store in jcode&`#39`;s private provider env file. Prefer --api-key-stdin for shell history safety. #[arg(long, conflicts_with_all = ["api_key_stdin", "no_api_key"])] api_key: Option, /// Read the API key from stdin and store it in jcode&`#39`;s private provider env file #[arg(long, conflicts_with = "no_api_key")] api_key_stdin: bool, /// Configure the provider with no API key/authentication #[arg(long, conflicts_with_all = ["api_key", "api_key_stdin", "api_key_env"])] no_api_key: bool, /// Authentication style for the API key #[arg(long, value_enum)] auth: Option, /// Header name when --auth api-key is used (default: api-key) #[arg(long)] auth_header: Option, /// Private env file name under jcode&`#39`;s app config directory for stored API keys #[arg(long)] env_file: Option, /// Make this profile the startup default provider/model #[arg(long, alias = "default")] set_default: bool, /// Replace an existing profile with the same name #[arg(long)] overwrite: bool, /// Allow provider-routing features for OpenRouter-style gateways #[arg(long)] provider_routing: bool, /// Fetch/list models from the provider&`#39`;s /models endpoint #[arg(long)] model_catalog: bool, /// Emit JSON instead of human-readable setup output #[arg(long)] json: bool, }, } <title>src/cli/dispatch.rs</title> https://github.com/1jehuang/jcode/blob/435fb4a8/src/cli/dispatch.rs whose config.toml still carries ... -in ` ... _spawn_mode = " ... flipped to the ... current `inline ... // One-time config migration: force idle_animation off for all existing // users; anyone re-enabling it afterwards keeps their choice. crate::config::Config::migrate_idle_animation_off_once(); if let Some(profile_name) = args .provider_profile .as_deref() .map(str::trim) .filter(|value| !value.is_empty()) { provider_catalog::apply_named_provider_profile_env(profile_name)?; crate::env::set_var("JCODE_PROVIDER_PROFILE_NAME", profile_name); crate::env::set_var("JCODE_PROVIDER_PROFILE_ACTIVE", "1"); args.provider = ProviderChoice::OpenaiCompatible; } if let Some(tool_profile) = args.tool_profile.as_deref() { crate::env::set_var("JCODE_TOOL_PROFILE", tool_profile); } if let Some(tools) = args.tools.as_deref() { crate::env::set_var("JCODE_TOOLS", tools); } if let Some(disabled_tools) = args.disabled_tools.as_deref() { crate::env::set_var("JCODE_DISABLED_TOOLS", disabled_tools); } if args.disable_base_tools { crate::env::set_var("JCODE_DISABLE_BASE_TOOLS", "1"); } if args.tool_profile.is_some() || args.tools.is_some() || args.disabled_tools.is_some() || args.disable_base_tools { crate::config::invalidate_config_cache(); } match args.command { Some(Command::Serve { temporary_server, owner_pid, temp_idle_timeout_secs, server_name, }) => { let serve_start = Instant::now(); crate::env::set_var("JCODE_NON_INTERACTIVE", "1"); if temporary_server { server::configure_temporary_server(owner_pid, temp_idle_timeout_secs); } let provider ... start = Instant::now(); let provider = provider_init::init_provider(&args.provider, args.model.as_deref()).await?; let provider_ms = provider ... .elapsed().as_millis(); let server_new_start = Instant::now(); let server = server::Server::new_with_name(provider, server_name); let server_new_ ... = server_new_start.elapsed().as_millis(); crate::logging::info(&format!( "[TIMING] serve bootstrap: provider ... init={}ms, server_new={}ms, before_ ... ={}ms", provider_ms, server_new_ms, serve_start.elapsed().as_millis() )); ... } Some(Command:: ... ) => { acp::run_ ... p_command( ... clone(), args ... clone(), args ... .await ... async fn run_default_command(args: Args) -> Result<()> { startup_profile::mark("run_main_none_branch"); let explicit_provider_or_model = args.provider != ProviderChoice::Auto || args.model.is_some() || args.provider_profile.is_some(); let explicit_tool_options = args.tool_profile.is_some() || args.tools.is_some() || args.disabled_tools.is_some() || args.disable_base_tools; if args.resume.is_none() && !explicit_provider_or_model && !explicit_tool_options && commands::maybe_run_pending_restart_restore_on_startup().await? { return Ok(()); } let startup_hints = if args.fresh_spawn { None } else { // One-time: bake per-repo launch hotkeys from session history into config, // then reinstall so the new chords take effect. Scanning session history // can take a few hundred ms, so run it on a detached thread to keep it off // the first-frame critical path. It is gated by an `imported` flag, so it // does real work at most once and no-ops on every later launch. if std::io::IsTerminal::is_terminal(&std::io::stdin()) { std::thread::Builder::new() .name("launch-hotkey-bake".to_string()) .spawn(|| { if crate::config::Config::bake_launch_hotkeys_once() { setup_hints::reinstall_launch_hotkeys_after_config_change(); } }) .ok(); } // Prefer existing setup hints (alignment/welcome/terminal nudges); only // surface the keybinding-conflict heads-up when nothing else is queued, // so we never clobber an early-launch tip. The conflict hint is // self-debouncing (shown once per distinct conflict set). setup_hints::maybe_show_setup_hints() .or_else(|| { setup_hints::maybe_show_keymap_conflict_hint(&crate::config:…[truncated] <title>crates/jcode-tool-types/src/lib.rs</title> https://github.com/1jehuang/jcode/blob/435fb4a8/crates/jcode-tool-types/src/lib.rs # crates/jcode-tool-types/src/lib.rs - Branch: 435fb4a8 - Repository: 1jehuang/jcode --- #[derive(Debug, Clone)] pub struct ToolOutput { pub output: String, pub title: Option, pub metadata: Option<serde_json::Value>, pub images: Vec, } #[derive(Debug, Clone)] pub struct ToolImage { pub media_type: String, pub data: String, pub label: Option, } impl ToolOutput { pub fn new(output: impl Into) -> Self { Self { output: output.into(), title: None, metadata: None, images: Vec::new(), } } pub fn with_title(mut self, title: impl Into) -> Self { self.title = Some(title.into()); self } pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self { self.metadata = Some(metadata); self } pub fn with_image(mut self, media_type: impl Into, data: impl Into) -> Self { self.images.push(ToolImage { media_type: media_type.into(), data: data.into(), label: None, }); self } pub fn with_labeled_image( mut self, media_type: impl Into, data: impl Into, label: impl Into, ) -> Self { self.images.push(ToolImage { media_type: media_type.into(), data: data.into(), label: Some(label.into()), }); self } } /// Resolve tool name aliases to their canonical internal names. /// /// Providers can present tools with Claude Code aliases (e.g. `file_grep`, /// `shell_exec`) or API namespace prefixes (e.g. `functions.bash`). Models can /// repeat those names in sub-tool calls such as `batch`, while our registry /// uses canonical internal names (`agentgrep`, `bash`). This mapping ensures /// all of those forms resolve correctly. /// /// This lives in `jcode-tool-types` (rather than the tool `Registry`) so that /// low-level crates such as config can normalize tool names without depending /// on the full tool subsystem. pub fn resolve_tool_name(name: &str) -> &str { // Some function-calling APIs expose a recipient such as `functions.bash`. // Models occasionally preserve that transport namespace when constructing // a nested tool call, especially inside `batch`. let name = name.strip_prefix("functions.").unwrap_or(name); match name { "communicate" => "swarm", "task" | "task_runner" => "subagent", "launch" => "open", "shell" => "bash", "shell_exec" => "bash", "read_file" => "read", "file_read" => "read", "write_file" => "write", "file_write" => "write", "edit_file" => "edit", "file_edit" => "edit", // The native grep tool was removed in favor of agentgrep, but models // still frequently call `grep` (and OAuth&`#39`;s `file_grep`). agentgrep&`#39`;s // grep mode accepts `pattern` as an alias for `query`, so these calls // work as-is. "grep" | "file_grep" => "agentgrep", "skill" | "Skill" => "skill_manage", // The integration catalog tool was renamed from `discover_tools`; // models trained on or resuming from the old vocabulary still emit it. "discover_tools" => "integration_tools", "todoread" | "todowrite" | "todo_read" | "todo_write" | "todos" => "todo", // The Anthropic OAuth surface advertises PascalCase tool names and // reverse-maps them provider-side for top-level calls, but nested // `batch` subcall names bypass that mapping and resolve here (issue // `#486`). Keep these in sync with anthropic_map_tool_name_from_oauth. "Bash" => "bash", "Read" => "read", "Write" => "write", "Edit" => "edit", "Grep" => "agentgrep", "Agent" => "subagent", "ScheduleWakeup" => "schedule", other => other, } } #[cfg(test)] mod tests { use super::resolve_tool_name…[truncated] <title>crates/jcode-app-core/src/tool/tests.rs</title> https://github.com/1jehuang/jcode/blob/435fb4a8/crates/jcode-app-core/src/tool/tests.rs #[test] fn test_resolve_tool_name_oauth_aliases() { assert_eq!(Registry::resolve_tool_name("file_read"), "read"); assert_eq!(Registry::resolve_tool_name("file_write"), "write"); assert_eq!(Registry::resolve_tool_name("file_edit"), "edit"); assert_eq!(Registry::resolve_tool_name("shell_exec"), "bash"); assert_eq!(Registry::resolve_tool_name("shell"), "bash"); assert_eq!(Registry::resolve_tool_name("read_file"), "read"); assert_eq!(Registry::resolve_tool_name("write_file"), "write"); assert_eq!(Registry::resolve_tool_name("edit_file"), "edit"); assert_eq!(Registry::resolve_tool_name("task_runner"), "subagent"); assert_eq!(Registry::resolve_tool_name("task"), "subagent"); assert_eq!(Registry::resolve_tool_name("launch"), "open"); assert_eq!(Registry::resolve_tool_name("grep"), "agentgrep"); assert_eq!(Registry::resolve_tool_name("file_grep"), "agentgrep"); assert_eq!(Registry::resolve_tool_name("todo_read"), "todo"); assert_eq!(Registry::resolve_tool_name("todo_write"), "todo"); assert_eq!(Registry::resolve_tool_name("todoread"), "todo"); assert_eq!(Registry::resolve_tool_name("todowrite"), "todo"); assert_eq!(Registry::resolve_tool_name("bash"), "bash"); assert_eq!(Registry::resolve_tool_name("functions.bash"), "bash"); assert_eq!(Registry::resolve_tool_name("functions.shell_exec"), "bash"); assert_eq!(Registry::resolve_tool_name("batch"), "batch"); assert_eq!(Registry::resolve_tool_name("memory"), "memory"); } ... _names() ... let provider: ... new(MockProvider); let ... new(provider).await; let ... _dir = std::env::temp_dir(); let ctx = ToolContext { session_id: "test".to_string(), ... message_id: "test".to_string(), tool_call_id: "test".to_string(), working_dir: Some(temp_dir), stdin_request_tx: None, graceful_shutdown_signal: None, execution_mode: ToolExecutionMode::Direct, }; let result = registry .execute(" ... _exec", serde_json::json!({"command": "true"}), ctx) .await; assert!(result.is_ok(), " <title>crates/jcode-app-core/src/tool/bash.rs</title> https://github.com/1jehuang/jcode/blob/435fb4a8/crates/jcode-app-core/src/tool/bash.rs const BASH_TOOL_DESCRIPTION: &str = " ... a bash command."; ... const WINDOWS_SHELL_TOOL_DESCRIPTION: &str = "Run a Windows cmd.exe command (compatibility name `bash`). Use cmd.exe syntax, not Bash."; ... fn build_shell_command(cmd_str: &str) -> TokioCommand { #[cfg(windows)] { let mut cmd = TokioCommand::new(" ... . // ... title "text with spaces ... // ... `raw_arg` ... exe /C ... // full ... by cmd so its inner quotes // reach child ... . `/D ... and `/S` // ... quote handling used with this ... . cmd.args(["/D", "/S", "/C ... .raw ... arg(format!("\"{cmd_str ... #[cfg(not(windows))] { ... mut cmd = Tokio ... ::new("bash"); cmd.arg("-c").arg(cmd ... str); ... cmd } ... #[derive(Deserialize)] struct BashInput { command: String, #[serde(default)] intent: Option, #[ ... (default)] timeout ... (default)] run_in_background: Option, #[serde(default = "default_true")] notify: bool, #[ ... (default)] wake ... /// Set only when re-issuing a call the ... refused (`#604`). #[serde ... default)] justification: Option, } ... #[async_trait] impl Tool for BashTool { fn name(&self) -> &str { "bash" } fn description(&self) -> &str { if cfg!(windows) { WINDOWS_SHELL_TOOL_DESCRIPTION } else { BASH_TOOL_DESCRIPTION } } fn parameters_schema(&self) -> Value { destructive_gate::bash_parameters_schema() } async fn execute(&self, input: Value, ctx: ToolContext) -> Result { let mut params: BashInput = serde_json::from_value(input)?; let run_in_background = params.run_in_background.unwrap_or(false); // Destructive-command gate (`#604`), before background dispatch. if let Some(refusal) = destructive_command_refusal( &params.command, params.justification.as_deref(), ctx.working_dir.clone(), ) { return Err(anyhow::anyhow!(refusal)); } if run_in_background { return self.execute_background(params, ctx).await; } // Auto-detect browser bridge commands and rewrite them to the installed // binary when available, but do not run setup automatically. Browser // setup should stay an explicit status/setup flow rather than a default // side effect of trying to use the browser. if crate::browser::is_browser_command(&params.command) { params.command = crate::browser::rewrite_command_with_full_path(&params.command); ... // Start/attach a browser session for ... jcode session. // This gives each agent its own browser tab, preventing // multi ... . if !cfg!(windows) && std::env::var("BROW ... _SESSION").is_err() && let Some(session_name) = crate::browser::ensure_browser_session(&ctx.session_id) { params.command = format!("BROW ... ={} {}", session_name, params.command); } } ... with stdin detection self. ... _foreground(& ... , &ctx).await } ... impl BashTool { async fn execute_foreground( &self, params: &BashInput, ctx: &ToolContext, ) -> Result { #[cfg(unix)] if self.supports_reload_persistence(ctx) { return self .execute_reload_persistable_foreground(params, ctx) .await; } let timeout_ms = params.timeout.unwrap_or(DEFAULT_TIMEOUT_MS).min(600000); let timeout_duration = Duration::from_millis(timeout_ms); let has_stdin_channel = ctx.stdin_request_tx.is_some(); let mut command = build_shell_command(&params.command); command .kill_on_drop(true) .stdout(Stdio::piped()) .stderr(Stdio::piped()); if has_stdin_channel { command.stdin(Stdio::piped()); } if let Some(ref dir) = ctx.working_dir { command.current_dir(dir); } let mut child = command.spawn()?; let child_pid = child.id().unwrap_or(0); let stdin_handle = child.stdin.take(); let stdout_handle = child.stdout.take(); let stderr_handle = child.stderr.take(); // Owned copies so the ... if it is ... to a // background task on timeout. let ... clone() ... unwrap_or_else(|| ... .command.clone()); let stdin_tx = ctx.stdin_request_tx.clone(); let ... _call_ ... = ctx.tool_call_id.clone(); …[truncated]

Citations:


LLM Security

Reachability: External
Exploitability: Moderate
CWE: CWE-1427

Restrict tools for commit-message generation.

jcode run receives the staged patch as its prompt, but this invocation only sets --no-selfdev. It does not pass --tool-profile none or disable MCP. Jcode exposes shell, read, write, and MCP tools; its shell tool runs commands in the agent working directory. A malicious patch can therefore prompt Jcode to use the user's workspace or configured external tools. Run this action with an explicit no-tool profile and MCP disabled.

@pullfrog pullfrog 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.

Important

A few real defects to address before merge. The strongest are in the hand-rolled [hooks] TOML editing — removeJcodeManagedHooks can delete a user-owned line and is a silent no-op on Windows — and the daemon pre-warm only runs on the LocalPtyProvider spawn path, so the orchestration fix may not fire on the default local backend.

Reviewed changes

  • jcode hook layer — new src/main/jcode/ (hook-settings, byte-preserving hook-config TOML edit, hook-service install/remove/status/remote, daemon-prewarm), registered in the managed-hook and remote-installer registries plus the script refresher.
  • Per-pane runtime dir + pre-warm — new shared/jcode-runtime-dir.ts; JCODE_RUNTIME_DIR stamped in spawn-env.ts and the (now async) buildTerminalWorkspaceEnv; spawnLocalPty creates the dir and pre-warms the daemon.
  • Live status / questions / notifications — new jcode listener provider, tool fields and transcript reader, wired through provider-dispatch, event routing, source routing and the hook relay.
  • Title / row naming — jcode-terminal-title.ts rejects jcode's repainting identity title so agent rows fall back to the prompt.
  • OSC color-reply skip — startup ingress, headless policy and the renderer capability handlers; the pane launch-agent ladder is extracted to a pure, tested module (fixes the original pane-connect crash).
  • AI Vault / Source Control AI / resume — jcode session parser + sources, argv-prompt commit-message spec with jcode model list discovery, [Tokens]/JSON output cleanup, Windows argv budget guard, and resume/agent-type/icon/catalog/i18n registrations.

⚠️ Evidence document referenced by the new code is not in the PR

Three added files cite docs/reference/jcode-hook-events.md as the source of jcode's captured payloads and terminal titles (agent-hook-listener-jcode.test.ts:11, jcode-terminal-title.ts:5, jcode-terminal-title.test.ts:5), and the PR body says it was added — but no such file is in the diff or the tree. Without it the payload contracts the listener is written against are unverifiable, which is exactly what the repo's transcript-capture convention exists to prevent.

Technical details
# Missing evidence doc

## Affected sites
- src/shared/agent-hook-listener-jcode.test.ts:11 — "see docs/reference/jcode-hook-events.md"
- src/shared/jcode-terminal-title.ts:5 — same reference
- src/shared/jcode-terminal-title.test.ts:5 — same reference
- docs/reference/ — no jcode file exists

## Required outcome
- Commit the captured jcode payloads/titles under docs/reference/jcode-hook-events.md, or drop the references and the PR-body claim.

ℹ️ Windows .cmd gate POST is synchronous, unlike the POSIX script

The POSIX managed script background-s the pre_tool POST and exits immediately precisely because jcode blocks the tool call until the gate exits; the Windows .cmd branch runs buildWindowsAgentHookPostCommand('jcode') inline after draining stdin. In the normal case the curl round trip is small, but a slow or unreachable hook server makes every Windows tool call sit on the 1.5 s --max-time the detached POSIX path exists to avoid.

Technical details
# Windows pre_tool gate is not detached

## Affected sites
- src/main/jcode/hook-service.ts — getManagedScript() win32 branch builds the .cmd with an inline POST
- src/main/agent-hooks/hook-stdin-contract.ts:205 — the drain epilogue

## Required outcome
- Confirm whether jcode on Windows waits on the hook to EOF like POSIX; if it does, detach the pre_tool POST there too (or document the Windows cost as accepted).

ℹ️ WSL jcode panes still share one daemon

shouldInjectJcodeRuntimeDir gates on process.platform === 'win32', so a WSL pane — spawned by a Windows Orca but running in a Linux guest where unix sockets exist — gets no per-pane runtime dir and falls back to the shared guest daemon. That is the same cross-pane status misattribution this PR fixes for native panes, just displaced to WSL; the comment frames it as Windows.

Technical details
# WSL excluded from the runtime dir by a Windows platform check

## Affected sites
- src/shared/jcode-runtime-dir.ts:23-26 — shouldInjectJcodeRuntimeDir(platform)
- src/main/ipc/pty/ipc/spawn-env.ts:149 — skip also requires !args.connectionId, which WSL panes set

## Open questions for the human
- Is a WSL jcode pane a supported target? If so it needs its own decision, not the win32 branch.

ℹ️ Nitpicks

  • ensureJcodeRuntimeDir calls mkdir unguarded and is awaited on the terminal-create path for every local pane (orca-runtime-resolve-browser-environment…:170-171), so a tmpdir error fails PTY creation for non-jcode shells; the pre-warm itself is deliberately fail-open.
  • JCODE_RUNTIME_DIR isn't deleted on remote paths, only skipped (spawn-env.ts:149), unlike the pane-key/launch-token scrub just above it.
  • model is emitted only on turn_start/turn_end, so a pre_tool/post_tool row drops the model for shared-store readers (worktree ps, mobile) even though the renderer masks it.
  • isJcodeManagedCommand (hook-settings.ts:66) is exported but unused.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/jcode/hook-config.ts Resolved
Comment thread src/main/jcode/hook-config.ts Outdated
if (trimmed.length === 0) {
return null
}
return trimmed.split('.').map((segment) => segment.trim().replace(/^"|"$/g, ''))

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.

parseTomlTablePath strips only double quotes and has no dotted-key support, so valid-but-non-canonical spellings — ['hooks'], a top-level hooks.turn_end = …, or a dotted turn_end.foo inside the table — are not recognized as the hooks table. applyJcodeManagedHooks then appends a second [hooks] table (or a colliding key) and jcode stops parsing the whole config, while parseJcodeHooksTable returns {} rather than null, so the install() guard cannot catch it. The repo already has parseTomlTableHeaderPath in src/main/codex/config-toml-key-path.ts that handles quoted keys; the scalar check also rejects a valid commented value (pre_tool_timeout_ms = 5000 # ms), which makes install() report error and never install.

Technical details
# Hand-rolled `[hooks]` parser misses valid TOML spellings

## Affected sites
- src/main/jcode/hook-config.ts:68-74 — `parseTomlTablePath` ignores `'…'` and dotted paths
- src/main/jcode/hook-config.ts:64-66 — `isTomlScalarValue` matches the whole remainder, so a trailing comment is a false parse error
- src/main/jcode/hook-config.ts:146-149 — append branch writes the duplicate table
- src/main/codex/config-toml-key-path.ts:12 — existing `parseTomlTableHeaderPath` handles these

## Required outcome
- A file with `['hooks']`, `hooks.<event> = …`, or a dotted sub-key must not gain a duplicate `[hooks]` / colliding key on install.
- A scalar hook setting with an inline comment must not make install report `error`.

## Suggested approach (optional)
- Reuse the codex key-path parser; strip an inline comment before the scalar test.

Comment thread src/main/providers/local-pty-spawn.ts Resolved
Comment thread src/renderer/src/i18n/locales/en.json Outdated
@@ -607,11 +607,14 @@
"0708ed89f1": "Claude",
"fc80296033": "Devin",
"da41abbdd4": "Ante",
"mimo_code_label": "MiMo Code",
"jcode_label": "Jcode",

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.

This adds jcode_label (and mimo_code_label) a second time — both already exist further down the same object, and the identical duplicate pair is in es.json, ja.json, ko.json and zh.json. JSON.parse keeps the last value so it renders, but the redundant entries should be de-duplicated in all five locale files.

@nwparker
nwparker force-pushed the nwparker/jcode-harness branch 2 times, most recently from 81d6431 to d520fab Compare September 23, 2026 20:36

@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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 57ed837e-d4f6-4060-a5c9-fab426250866

📥 Commits

Reviewing files that changed from the base of the PR and between 7c0eee69d77535f783d31c1937e279d6d0c4181a and d520fab.

⛔ Files ignored due to path filters (1)
  • src/shared/agent-icons/jcode.png is excluded by !**/*.png
📒 Files selected for processing (17)
  • src/main/jcode/daemon-prewarm.test.ts
  • src/main/jcode/daemon-prewarm.ts
  • src/main/jcode/hook-gate-script.test.ts
  • src/main/jcode/hook-service.test.ts
  • src/main/jcode/hook-service.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pane-launch-agent-candidate.ts
  • src/shared/agent-hook-listener-jcode.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-listener/command-code-transcript.ts
  • src/shared/agent-hook-listener/providers/jcode-events.ts
  • src/shared/agent-hook-listener/providers/jcode-tool-fields.ts
  • src/shared/agent-hook-listener/reverse-file-region-scan.test.ts
  • src/shared/agent-hook-listener/reverse-file-region-scan.ts
  • src/shared/agent-hook-listener/transcript-reader.ts
  • src/shared/jcode-session-files.ts
  • src/shared/jcode-terminal-title.test.ts
  • src/shared/jcode-terminal-title.ts

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

Comment on lines +49 to +54
it('warms each runtime dir at most once', () => {
prewarmJcodeDaemon({ launchAgent: 'jcode', runtimeDir: '/tmp/orca-jcode/abc' })
prewarmJcodeDaemon({ launchAgent: 'jcode', runtimeDir: '/tmp/orca-jcode/abc' })
prewarmJcodeDaemon({ launchAgent: 'jcode', runtimeDir: '/tmp/orca-jcode/def' })
expect(spawnProcessMock).toHaveBeenCalledTimes(2)
})

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

Pin platform in the dedupe and retry tests.

Two tests omit platform: Lines 49-54 and Lines 78-86. prewarmJcodeDaemon then uses process.platform. On a Windows test host, prewarmTarget returns null and spawnProcessMock is never called. Both assertions that the mock was called twice then fail. The test at Lines 20-37 already passes platform: 'darwin'. Use the same value in these two tests.

💚 Proposed fix
-    prewarmJcodeDaemon({ launchAgent: 'jcode', runtimeDir: '/tmp/orca-jcode/abc' })
-    prewarmJcodeDaemon({ launchAgent: 'jcode', runtimeDir: '/tmp/orca-jcode/abc' })
-    prewarmJcodeDaemon({ launchAgent: 'jcode', runtimeDir: '/tmp/orca-jcode/def' })
+    const platform = 'darwin' as const
+    prewarmJcodeDaemon({ launchAgent: 'jcode', runtimeDir: '/tmp/orca-jcode/abc', platform })
+    prewarmJcodeDaemon({ launchAgent: 'jcode', runtimeDir: '/tmp/orca-jcode/abc', platform })
+    prewarmJcodeDaemon({ launchAgent: 'jcode', runtimeDir: '/tmp/orca-jcode/def', platform })

Apply the same platform: 'darwin' change to both prewarmJcodeDaemon calls in the retry test.

Also applies to: 78-86

Comment on lines +140 to +146
scanFileRegionsBackward(
journalPath,
{ chunkBytes: JCODE_JOURNAL_CHUNK_BYTES, maxScanBytes: JCODE_SESSION_SCAN_BYTES },
(region) =>
readLastUserMessageFromJournalLines(region.toString('utf8').split('\n'), sessionId) ??
undefined
) ?? 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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,204p' src/shared/jcode-session-files.ts
rg -n 'promptInteractionKey|interactionKey' src/shared src/main --glob '!*.test.ts' | head -60

Repository: stablyai/orca

Length of output: 11671


🏁 Script executed:

set -e
printf '%s\n' '--- reverse scanner ---'
cat -n src/shared/agent-hook-listener/reverse-file-region-scan.ts
printf '%s\n' '--- provider dispatch ---'
cat -n src/shared/agent-hook-listener/provider-dispatch.ts | sed -n '1,230p'
printf '%s\n' '--- listener ---'
cat -n src/shared/agent-hook-listener.ts | sed -n '150,215p'
printf '%s\n' '--- server status application ---'
cat -n src/main/agent-hooks/server/server-status-application.ts | sed -n '1,235p'
printf '%s\n' '--- prompt key consumers and tests ---'
rg -n -C 5 'promptInteractionKey|previousPromptInteractionKey|incomingPromptInteractionKey|hasTranscriptPromptEvidence' src/main src/shared --glob '*.{ts,tsx}' | head -260

Repository: stablyai/orca

Length of output: 42514


🏁 Script executed:

set -e
printf '%s\n' '--- server timing and telemetry ---'
cat -n src/main/agent-hooks/server/server-status-application.ts | sed -n '90,225p'
printf '%s\n' '--- prompt evidence and event routing ---'
rg -n -C 8 'function hasExplicitUserPrompt|export function hasExplicitUserPrompt|isNewTurnEvent|normalizeJcodeEvent' src/shared/agent-hook-listener
printf '%s\n' '--- jcode provider events ---'
cat -n src/shared/agent-hook-listener/providers/jcode-events.ts

Repository: stablyai/orca

Length of output: 42183


🏁 Script executed:

set -e
rg -n -C 12 'hasExplicitUserPrompt' src/shared/agent-hook-listener.ts src/shared/agent-hook-listener --glob '*.ts'

Repository: stablyai/orca

Length of output: 6730


🏁 Script executed:

cat -n src/shared/agent-hook-listener/provider-event-routing.ts | sed -n '81,135p'

Repository: stablyai/orca

Length of output: 2555


🏁 Script executed:

set -e
printf '%s\n' '--- all promptInteractionKey consumers ---'
rg -n -C 4 'promptInteractionKey|interactionKey' --glob '*.{ts,tsx,js,jsx}' .
printf '%s\n' '--- jcode turn-end/session-end references ---'
rg -n -C 5 "turn_end|session_end" src docs --glob '*.{ts,tsx,md}' | head -240

Repository: stablyai/orca

Length of output: 42463


Use the journal line’s absolute byte offset in the interaction key.

scanFileRegionsBackward provides regionPosition, but readLastUserMessageFromJournal drops it and salts the key with the region-local index. When a journal exceeds 64 KiB, appending records can change that index for the same message.

The prompt hash suppresses repeats during normal working and working-to-done events. However, a repeated turn_end can reach the server as two done events with different keys, which bypasses the same-hash dedupe and can emit duplicate agent_prompt_sent telemetry.

Suggested fix
-      (region) =>
-        readLastUserMessageFromJournalLines(region.toString('utf8').split('\n'), sessionId) ??
-        undefined
+      (region, regionPosition) =>
+        readLastUserMessageFromJournalLines(region, regionPosition, sessionId) ?? undefined

Update readLastUserMessageFromJournalLines to split the Buffer on 0x0a, track each line’s byte offset as regionPosition + lineStart, and use ${lineOffset}:${messageIndex}:${text} as the salt.

📝 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
scanFileRegionsBackward(
journalPath,
{ chunkBytes: JCODE_JOURNAL_CHUNK_BYTES, maxScanBytes: JCODE_SESSION_SCAN_BYTES },
(region) =>
readLastUserMessageFromJournalLines(region.toString('utf8').split('\n'), sessionId) ??
undefined
) ?? null
scanFileRegionsBackward(
journalPath,
{ chunkBytes: JCODE_JOURNAL_CHUNK_BYTES, maxScanBytes: JCODE_SESSION_SCAN_BYTES },
(region, regionPosition) =>
readLastUserMessageFromJournalLines(region, regionPosition, sessionId) ?? undefined
) ?? null

Comment on lines +193 to +204
export function readLastJcodeUserPromptFromHookPayload(
hookPayload: Record<string, unknown>
): JcodeUserPromptEvidence | null {
const sessionId = hookPayload.session_id ?? hookPayload.sessionId
if (!isSafeJcodeSessionId(sessionId)) {
return null
}
return (
readLastUserMessageFromJournal(sessionJournalPath(sessionId), sessionId) ??
readLastUserMessageFromJson(sessionFilePath(sessionId), sessionId)
)
}

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.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C8 '\bfunction hasExplicitUserPrompt\b' src/shared
rg -nP -C3 'hasTranscriptPromptEvidence' src/shared

Repository: stablyai/orca

Length of output: 7564


🏁 Script executed:

#!/bin/bash
printf '%s\n' '--- provider-dispatch.ts ---'
sed -n '1,215p' src/shared/agent-hook-listener/provider-dispatch.ts
printf '%s\n' '--- provider-event-routing.ts ---'
sed -n '1,145p' src/shared/agent-hook-listener/provider-event-routing.ts
printf '%s\n' '--- agent-hook-listener.ts prompt/cache references ---'
rg -n -C6 'resolvePrompt|lastPromptByPaneKey|isNewTurnEvent|normalizeProviderEvent|normalizeJcodeEvent' src/shared/agent-hook-listener.ts src/shared/agent-hook-listener
printf '%s\n' '--- jcode-session-files.ts ---'
sed -n '1,240p' src/shared/jcode-session-files.ts

Repository: stablyai/orca

Length of output: 42064


🏁 Script executed:

sed -n '1,215p' src/shared/agent-hook-listener/provider-dispatch.ts; sed -n '1,145p' src/shared/agent-hook-listener/provider-event-routing.ts; rg -n -C6 'resolvePrompt|lastPromptByPaneKey|isNewTurnEvent|normalizeProviderEvent|normalizeJcodeEvent' src/shared/agent-hook-listener.ts src/shared/agent-hook-listener; sed -n '1,240p' src/shared/jcode-session-files.ts

Repository: stablyai/orca

Length of output: 42681


<inspected_source>The Jcode branch in src/shared/agent-hook-listener/provider-dispatch.ts:158-168 calls readLastJcodeUserPromptFromHookPayload for every event. The reader performs synchronous bounded file scans and JSON parsing in src/shared/jcode-session-files.ts:128-204. This includes pre_tool and post_tool events.</inspected_source>
<inspected_source>resolvePrompt caches only prompt text in state.lastPromptByPaneKey (src/shared/agent-hook-listener/prompt-fields.ts:97-114). The dispatch result initializes hasTranscriptPromptEvidence to false for each event (src/shared/agent-hook-listener/provider-dispatch.ts:49-52).</inspected_source>
<inspected_source>hasExplicitUserPrompt requires transcript evidence for Jcode turn_start, pre_tool, post_tool, and turn_end (src/shared/agent-hook-listener/provider-event-routing.ts:101-113).</inspected_source>

Cache Jcode transcript evidence before non-turn events.

normalizeProviderEvent performs a synchronous journal scan and possible JSON parse for every Jcode event. During tool use, this repeats for pre_tool and post_tool and can delay the listener.

Read the transcript on isNewTurnEvent('jcode', eventName), or when the pane has no Jcode evidence cache. Cache the complete result, including the prompt text, interaction key, and transcript-evidence flag, for later events. Caching only state.lastPromptByPaneKey is not sufficient because hasExplicitUserPrompt also requires hasTranscriptPromptEvidence on non-turn events.

@pullfrog pullfrog 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.

Important

The Windows jcode hook never sends the payload, so no jcode event reaches Orca there. The POSIX branch was just migrated to post $JCODE_HOOK_PAYLOAD verbatim; the .cmd branch still posts curl's stdin and has no %JCODE_HOOK_PAYLOAD% reference. This is the only new must-address item — the reverse-scan fold and the POSIX transport migration both check out.

Reviewed changes

  • Folded the three near-copy reverse chunked line scans (transcript-reader, command-code-transcript, and the jcode journal reader) into one shared, tested scanFileRegionsBackward; region boundaries, regionPosition byte offsets, and the command-code interactionKey are preserved.
  • Switched jcode's managed POSIX hook from its hand-rolled curl to buildPosixAgentHookPostCommand, posting $JCODE_HOOK_PAYLOAD verbatim and draining the pre_tool stdin before the environment guard.
  • Read jcode's lifecycle point from the payload's own event key (the shared transport no longer restates it as a form field), with a test pinning the shape.
  • Replaced normalizeJcodeEvent's inline ternaries with a JCODE_EVENT_STATES table and hoisted the failed-turn error text ahead of the snapshot.
  • Consolidated daemon-prewarm onto a single entry point and renamed the jcode title stripper to stripJcodeTitleStatus with one combined regex.

ℹ️ Nitpicks

  • src/shared/agent-hook-listener/transcript-reader.ts:6 — EMPTY_TRANSCRIPT_REGION is now referenced nowhere after the fold (only its declaration remains); drop the export.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/jcode/hook-service.ts Resolved
@nwparker
nwparker force-pushed the nwparker/jcode-harness branch from d520fab to d3e9b85 Compare September 23, 2026 23:02

@pullfrog pullfrog 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.

ℹ️ No critical issues — the type-narrowing pass is behavior-neutral and the new Windows suite pins the generated .cmd's shape. One coverage gap noted inline: that suite cannot fail while the known Windows payload gap is present.

Reviewed changes

  • Replaced the Reflect.get-based dynamic reads with narrowing predicates — hasIntentField in jcode-tool-fields.ts and isJcodeJsonResult in commit-message-agent-output.ts — so the anti-slop audit passes without changing behavior.
  • Added a platform-mocked the Windows managed hook suite in hook-gate-script.test.ts, pinning the generated .cmd's ordering (environment guard before the pre_tool stdin drain), CRLF line endings, @echo off, exit /b 0, and the more.com drain.
  • Documented the Windows guard-before-drain rationale in hook-service.ts (comments only; the emitted script is unchanged).
  • Re-aligned a markdown table in docs/bug-reproductions/opencode2-form-created-kinds/README.md.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/jcode/hook-gate-script.test.ts Resolved
@nwparker
nwparker force-pushed the nwparker/jcode-harness branch 2 times, most recently from 4c64022 to f161781 Compare September 24, 2026 00:41
@nwparker

Copy link
Copy Markdown
Contributor Author

🧪 Jcode first-class support is ready to test — please try it

An installable build of this PR is up. If you opened, commented on, or reacted to a Jcode request, you're exactly who I need:

@czzczz @dcieslak19973 @dm13379 @dommer1 @duane-eldridge @edheltzel @eric-akkio @guiguan @IvanProg00 @JianJia2018 @Jp-CB-IN0010 @lnilluv @NickSchouten @OrcaWin @shashwattrili @sirinath @termez19 @vpelikh

Download: https://github.com/stablyai/orca-adhoc/releases/tag/v1.4.210-adhoc.20260924013047

  • macOS (Apple Silicon) → orca-macos-arm64.dmg
  • macOS (Intel) → orca-macos-x64.dmg
  • Windows → orca-windows-setup.exe — unsigned, so SmartScreen will warn: More info → Run anyway

This is a throwaway dev build from a branch. It installs alongside nothing — back up anything you care about, and switch back to your normal Orca when you're done.

Setup

  1. Install Jcode if you haven't: https://github.com/1jehuang/jcode
  2. Open the adhoc build and create a worktree with Jcode selected in the agent picker.
  3. Use it normally for a bit. Orca installs its hooks into ~/.jcode/config.toml automatically on first launch.

What to check (any subset is useful — even one line of feedback helps)

# Try this Expected
1 Send Jcode a prompt that runs a slow command, e.g. "run sleep 20 && echo hi, then read README.md" The sidebar row shows a spinner and the live tool (bash, read …) while it runs — not only after
2 Let a turn finish Row turns green with Jcode's reply; the row shows your prompt, not jcode <Codename>
3 Switch to another workspace while Jcode works Orange 🔔 unread bell on the Jcode workspace when it finishes
4 Right-click a file / use a send-to-agent surface and target the Jcode pane The prompt lands in the running Jcode TUI and it answers
5 Source Control → ✨ next to the commit box → pick Jcode → Generate A real commit message, no [Tokens] noise
6 Open the Agents / session history panel Your Jcode sessions listed with titles, message counts and model; resume works
7 Open two Jcode panes at once Each pane's status stays on its own tab — they don't cross over

🪟 Windows testers especially wanted

I could not test Windows on real hardware. One bug there was only found in review: Orca was sending Jcode's hook payload the wrong way, so Windows panes showed no status at all. That's fixed but unverified — if you're on Windows, item #1 above is the single most valuable thing anyone can report.

Also unverified: SSH/remote Jcode panes.

How to report

Reply here with your OS + whether each thing worked. Screenshots welcome. A "tried it, #1 and #2 work on Windows" is genuinely useful — I'd rather have three short confirmations than none.

Known gaps, already documented in the PR, no need to report: remote JCODE_HOME overrides aren't discovered by session history; very large commit diffs can exceed the argv limit; the desktop completion banner is unproven (the in-app unread bell is verified).

Once a few people confirm this works — especially on Windows — we can approve and merge. 🙏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor