Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(streaming): implement command output streaming from runtime #1834

Closedtyulyukov(GitHub profile, opens in a new tab)wants to merge 138 commits intomain fromrefs/pull/1834/headopened View on GitHub

Summary

  • Added WebSocket streaming of runtime command output (subscribeCommandOutput RPC method)
  • Created runtimeToolOutputStore to buffer and manage live tool output with memory limits
  • Updated CommandExecutionCard to display streamed output in real-time while commands execute
  • Removed git working tree diff view and related infrastructure (simplified diff panel to session-only mode)
  • Integrated ProviderService event stream for command output delta delivery
  • Added threadId prop threading through timeline components for context

Testing

  • Command output streams and updates live in the UI
  • Output is properly truncated when exceeding per-item size limits (24KB)
  • Store clears on thread switch and new turn start
  • Diff panel works without git mode toggle
  • Streaming state survives WebSocket reconnection via onResubscribe handler
  • All tests pass: bun run test, bun fmt, bun lint, bun typecheck

🤖 Generated with Claude Code


Note

Medium Risk Medium risk due to broad repo-wide renaming (package names, env vars, CLI entrypoints, git refs) plus adding a new Next.js apps/landing service and changing release/CI workflows, which could break builds, updates, or runtime configuration if any old T3CODE_* paths remain.

Overview Renames the project from T3 Code to MarCode across docs, packages, and tooling: updates package scopes/imports to @marcode/*, switches CLI binary/name from t3 to marcode, changes default state dirs/env vars from T3CODE_* to MARCODE_*, and updates git checkpoint refs to refs/marcode/checkpoints.

Updates the desktop Electron app branding (scheme/bundle IDs/app names), adds a desktop:fullscreen-state IPC bridge event, and embeds Jira proxy defaults (MARCODE_JIRA_REDIRECT_URI, MARCODE_JIRA_TOKEN_PROXY_URL) into the packaged build and shell-env sync.

Reworks repo ops: removes the PR vouch workflow/list, tweaks CI runner, updates release naming and injects Jira-related secrets into release builds, drops npm CLI publish in release.yml, and replaces the Astro marketing site with a new Next.js apps/landing (standalone build + Dockerfile) including a minimal Jira token-exchange proxy endpoint.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9e322f1c35f693f75efdde199de5698233c48b50. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Stream command output from runtime to the web client over WebSocket

  • Adds subscribeCommandOutput WebSocket RPC that streams command_output deltas (threadId, itemId, delta) from ProviderService.streamEvents to connected clients
  • Introduces useRuntimeToolOutputStore in the web app to buffer streaming output per thread/item with bounded memory (24k chars per item, 50 items per thread)
  • Adds new timeline row kinds (command, file-change, exploration, web-search, web-fetch, mcp-tool, agent-group) with dedicated card components that show live output via useRuntimeToolOutput
  • Adds Jira integration: OAuth flow, token service with AES-256-GCM encryption, JiraApiClient, WS RPC endpoints for Jira operations, and inline Jira task context in the composer
  • Adds GitLab support via glab CLI through a new RoutingGitHostCli abstraction; PR/MR labels and icons adapt based on detected provider
  • Renames the product from T3 Code to MarCode across all packages, environment variables, storage keys, service identifiers, and branding assets
  • Adds a new apps/landing Next.js app with OS-aware download button, feature cards, and a Jira token-exchange proxy API route
  • Introduces a multi-theme system with 12+ named themes (Catppuccin, Tokyo Night, Rosé Pine, etc.) and a ThemePicker settings component
  • Risk: storage key renames (marcode:* replacing t3code:*) mean existing persisted state (UI state, terminal state, composer drafts, client settings) will not migrate automatically and users will lose stored preferences on first launch after update
📊 Macroscope summarized 9e322f1. 88 files reviewed, 24 issues evaluated, 8 issues filtered, 10 comments posted

🗂️ Filtered Issues

apps/server/src/git/Layers/GitHubCli.ts — 1 comment posted, 3 evaluated, 2 filtered
  • line 173: The error instanceof Error check on line 173 will be false for SchemaError because SchemaError does not extend Error (it only has a message getter and name property). When schema validation fails, the mapError receives a SchemaError instance, but since SchemaError is not an Error, the condition fails and detail becomes just invalidDetail without the actual validation error message (e.g., which field failed, why). This loses valuable debugging information. [ Out of scope ]
  • line 360: writeTempBodyFile(input.body) is called eagerly (synchronously) when constructing the Effect, not when the Effect is executed. This violates Effect's laziness model: if the returned Effect is never run, the temp file is created but removeTempBodyFile is never called via Effect.ensuring, causing a file leak. The file creation should be wrapped in Effect.sync or Effect.acquireRelease so it only executes when the Effect pipeline runs. [ Cross-file consolidated ]
apps/server/src/jira/Layers/JiraApiClient.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 579: Race condition: adfRenderContext is a module-level global variable that is mutated in mapRawIssue. If concurrent requests trigger multiple listIssues or getIssue calls simultaneously (which the Effect runtime can schedule), one request's adfRenderContext can be overwritten by another before renderAdfToMarkdown completes. This would cause descriptions to render with the wrong attachment mappings, producing incorrect or broken image URLs. [ Failed validation ]
apps/web/src/components/chat/InlineDiffPreview.tsx — 0 comments posted, 1 evaluated, 1 filtered
  • line 109: The extractLineHtmls function incorrectly handles lines with multiple nested <span> elements (typical shiki output for syntax-highlighted tokens). When a line is <span class="line"><span style="...">token1</span><span>token2</span></span>, the logic removes the opening line wrapper correctly, but line.slice(0, -7) blindly removes the last 7 characters—which removes part of an inner token's closing tag rather than the outer line wrapper's </span>. This produces malformed HTML like ...token2</sp that gets injected via dangerouslySetInnerHTML, causing rendering corruption. [ Failed validation ]
apps/web/src/components/chat/MessagesTimeline.tsx — 0 comments posted, 1 evaluated, 1 filtered
  • line 731: Duplicate React keys when the same Jira issue key appears multiple times in the text. The key ${keyPrefix}-jira-${issueKey} at line 731 will be identical for repeated occurrences of the same issue (e.g., text containing @jira:ABC-123 ... @jira:ABC-123). This causes React reconciliation issues and a console warning. The key should include a unique identifier like the match position, e.g., ${keyPrefix}-jira-${issueKey}-${matchStart}. [ Cross-file consolidated ]
apps/web/src/hooks/useHandleNewThread.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 61: The envMode option is silently ignored when reusing an existing draft thread. The diff removes passing envMode to setDraftThreadContext (lines 62-65 and 86-89), but callers still pass envMode expecting it to be applied (see usage: handleNewThread(projectId, { envMode: ... })). This creates inconsistent behavior: branch and worktreePath options ARE applied to existing drafts, but envMode is not. The option is still used when creating a brand new thread (line 102), so there's a behavioral inconsistency depending on whether a draft already exists. [ Cross-file consolidated ]
apps/web/src/themes/definitions/monokai.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 25: The --destructive-foreground, --info-foreground, --success-foreground, and --warning-foreground values are identical to their respective background colors (--destructive, --info, --success, --warning). Following the pattern established by --primary/--primary-foreground where foreground is the text color displayed ON that background, having identical values would render text invisible when used on buttons or badges with these semantic colors. [ Out of scope (triage) ]
apps/web/src/themes/definitions/nord.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 25: The --destructive-foreground, --info-foreground, --success-foreground, and --warning-foreground values are identical to their respective background colors. This follows a different pattern than --primary/--primary-foreground (which have contrasting colors), and would make text invisible on destructive/info/success/warning colored elements. [ Cross-file consolidated ]
    1. Important

      Review skipped

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

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: 96b02984-4fbc-4163-a38d-0f03b479244f

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

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

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

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. Cursor Bugbot has reviewed your changes and found 3 potential issues.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9e322f1c35f693f75efdde199de5698233c48b50. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +1,10 @@
      1+const REQUIRED_ENV_VARS = ["JIRA_CLIENT_ID", "JIRA_CLIENT_SECRET"] as const;
      2+
      3+export function validateEnv(): void {
      4+ const missing = REQUIRED_ENV_VARS.filter((key) => !process.env[key]);
      5+ if (missing.length > 0) {
      6+ throw new Error(
      7+ `Missing required environment variables: ${missing.join(", ")}. Jira proxy will not function.`,
      8+ );
      9+ }
      10+}

      Landing app crashes on startup without optional Jira env vars

      High Severity

      The validateEnv function, invoked at Next.js startup, throws an error if JIRA_CLIENT_ID or JIRA_CLIENT_SECRET are missing. This prevents the entire landing page from starting, despite the Jira proxy being an optional feature whose API routes already handle missing credentials gracefully.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9e322f1c35f693f75efdde199de5698233c48b50. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +14,21 @@
      14+ outputsByThreadId: {},
      15+
      16+ appendOutput: (threadId, itemId, delta) =>
      17+ set((state) => {
      18+ const threadOutputs = state.outputsByThreadId[threadId] ?? {};
      19+ const previous = threadOutputs[itemId] ?? "";
      20+ const next = `${previous}${delta}`;
      21+ const trimmed =
      22+ next.length > MAX_OUTPUT_CHARS_PER_ITEM
      23+ ? next.slice(next.length - MAX_OUTPUT_CHARS_PER_ITEM)
      24+ : next;
      25+ let nextThreadOutputs = { ...threadOutputs, [itemId]: trimmed };
      26+ const keys = Object.keys(nextThreadOutputs);
      27+ if (keys.length > MAX_ITEMS_PER_THREAD) {
      28+ const evictCount = keys.length - MAX_ITEMS_PER_THREAD;
      29+ for (let i = 0; i < evictCount; i++) {
      30+ const evictKey = keys[i]!;
      31+ if (evictKey !== itemId) {
      32+ delete nextThreadOutputs[evictKey];
      33+ }
      34+ }

      Eviction skips current item leaving store over limit

      Low Severity

      The appendOutput function's eviction logic can leave one extra item in the store. If the itemId being appended is among the oldest items slated for eviction, the loop skips its deletion without compensating, causing the thread's item count to exceed MAX_ITEMS_PER_THREAD.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9e322f1c35f693f75efdde199de5698233c48b50. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +23,21 @@
      23+ const grantType = body.grant_type;
      24+ if (typeof grantType !== "string" || !ALLOWED_GRANT_TYPES.has(grantType)) {
      25+ return Response.json({ error: "Invalid grant_type" }, { status: 400 });
      26+ }
      27+
      28+ const requiredFields = REQUIRED_FIELDS_BY_GRANT[grantType];
      29+ if (requiredFields) {
      30+ for (const field of requiredFields) {
      31+ if (!body[field]) {
      32+ return Response.json({ error: `Missing required field: ${field}` }, { status: 400 });
      33+ }
      34+ }
      35+ }
      36+
      37+ const { client_secret: _stripped, ...rest } = body;
      38+ const forwardBody = { ...rest, client_secret: clientSecret };
      39+
      40+ const atlassianResponse = await fetch(ATLASSIAN_TOKEN_URL, {
      41+ method: "POST",
      42+ headers: { "Content-Type": "application/json" },
      43+ body: JSON.stringify(forwardBody),

      Token proxy forwards arbitrary unvalidated fields to Atlassian

      Medium Severity

      The token exchange proxy strips only client_secret from the incoming request body, then forwards all remaining fields verbatim to Atlassian's token endpoint. A caller can inject arbitrary OAuth parameters (e.g., scope, audience) into the forwarded payload. The proxy acts as an unauthenticated public endpoint backed by the server's client_secret, so restricting the forwarded body to only known, validated fields would reduce the attack surface.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9e322f1c35f693f75efdde199de5698233c48b50. Configure [here](https://www.cursor.com/dashboard/bugbot).
    4. @@ -0,0 +23,21 @@
      23+
      24+ const getEncryptionKey = Effect.gen(function* () {
      25+ if (encryptionKey) return encryptionKey;
      26+ const seedExists = yield* fs.exists(config.anonymousIdPath);
      27+ const seed = seedExists
      28+ ? yield* fs.readFileString(config.anonymousIdPath)
      29+ : "marcode-default-seed";
      30+ encryptionKey = deriveKey(seed.trim());
      31+ return encryptionKey;
      32+ }).pipe(
      33+ Effect.mapError(
      34+ (cause) =>
      35+ new JiraTokenError({
      36+ operation: "deriveEncryptionKey",
      37+ detail: "Failed to derive encryption key",
      38+ cause,
      39+ }),
      40+ ),
      41+ );
      42+
      43+ const loadTokensFromDisk = Effect.gen(function* () {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/JiraTokenService.ts:43

      loadTokensFromDisk calls decryptTokens and JSON.parse synchronously inside Effect.gen without wrapping them in Effect.try. If decryption fails or the JSON is malformed, the resulting exception becomes an untyped fiber defect instead of the intended JiraTokenError. The Effect.mapError only catches Effect-level failures, not synchronous throws from the yield* expressions themselves. Consider wrapping the synchronous operations in Effect.try or Effect.tryMap so failures are properly caught and transformed.

      Also found in 1 other location(s)

      apps/server/src/git/Layers/GitHubCli.ts:360

      writeTempBodyFile(input.body) is called eagerly (synchronously) when constructing the Effect, not when the Effect is executed. This violates Effect&#39;s laziness model: if the returned Effect is never run, the temp file is created but removeTempBodyFile is never called via Effect.ensuring, causing a file leak. The file creation should be wrapped in Effect.sync or Effect.acquireRelease so it only executes when the Effect pipeline runs.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/jira/Layers/JiraTokenService.ts around line 43:
      
      `loadTokensFromDisk` calls `decryptTokens` and `JSON.parse` synchronously inside `Effect.gen` without wrapping them in `Effect.try`. If decryption fails or the JSON is malformed, the resulting exception becomes an untyped fiber defect instead of the intended `JiraTokenError`. The `Effect.mapError` only catches Effect-level failures, not synchronous throws from the `yield*` expressions themselves. Consider wrapping the synchronous operations in `Effect.try` or `Effect.tryMap` so failures are properly caught and transformed.
      
      Evidence trail:
      1. apps/server/src/jira/Layers/JiraTokenService.ts lines 41-54: `loadTokensFromDisk` function with synchronous `decryptTokens()` and `JSON.parse()` calls not wrapped in Effect.try
      2. apps/server/src/jira/crypto.ts lines 20-28: `decryptTokens` function using crypto.createDecipheriv, setAuthTag, and final() - all can throw
      3. Effect documentation at https://effect.website/docs/getting-started/creating-effects confirms: Effect.sync "must not throw errors; if it does, the error will be treated as a 'defect'", and Effect.try is for "synchronous computation that might fail"
      4. Effect documentation at https://effect.website/docs/error-management/unexpected-errors confirms distinction between failures (caught by mapError) and defects (caught only by catchAllDefect)
      
      Also found in 1 other location(s):
      - apps/server/src/git/Layers/GitHubCli.ts:360 -- `writeTempBodyFile(input.body)` is called eagerly (synchronously) when constructing the Effect, not when the Effect is executed. This violates Effect's laziness model: if the returned Effect is never run, the temp file is created but `removeTempBodyFile` is never called via `Effect.ensuring`, causing a file leak. The file creation should be wrapped in `Effect.sync` or `Effect.acquireRelease` so it only executes when the Effect pipeline runs.
      
      @@ -0,0 +233,21 @@
      233+ }).pipe(
      234+ Effect.map((result) => result.stdout.trim()),
      235+ Effect.flatMap((raw) =>
      236+ decodeGitLabJson(
      237+ raw,
      238+ RawGitLabRepoSchema,
      239+ "getDefaultBranch",
      240+ "GitLab CLI returned invalid repository JSON.",
      241+ ),
      242+ ),
      243+ Effect.map((repo) => {
      244+ const branch = repo.default_branch?.trim() ?? "";
      245+ return branch.length > 0 ? branch : null;
      246+ }),
      247+ );
      248+
      249+ const checkoutPullRequest: GitHostCliShape["checkoutPullRequest"] = (input) =>
      250+ executeGlab({
      251+ cwd: input.cwd,
      252+ args: ["mr", "checkout", input.reference],
      253+ }).pipe(Effect.asVoid);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low Layers/GitLabCli.ts:249

      checkoutPullRequest ignores the input.force parameter, so callers passing force: true receive a checkout failure instead of the expected forced checkout. glab mr checkout supports --force; consider adding it when input.force is true.

        const checkoutPullRequest: GitHostCliShape["checkoutPullRequest"] = (input) =>
          executeGlab({
            cwd: input.cwd,
      -      args: ["mr", "checkout", input.reference],
      +      args: ["mr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
          }).pipe(Effect.asVoid);
      Also found in 1 other location(s)

      apps/web/src/hooks/useHandleNewThread.ts:61

      The envMode option is silently ignored when reusing an existing draft thread. The diff removes passing envMode to setDraftThreadContext (lines 62-65 and 86-89), but callers still pass envMode expecting it to be applied (see usage: handleNewThread(projectId, { envMode: ... })). This creates inconsistent behavior: branch and worktreePath options ARE applied to existing drafts, but envMode is not. The option is still used when creating a brand new thread (line 102), so there&#39;s a behavioral inconsistency depending on whether a draft already exists.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/git/Layers/GitLabCli.ts around lines 249-253:
      
      `checkoutPullRequest` ignores the `input.force` parameter, so callers passing `force: true` receive a checkout failure instead of the expected forced checkout. `glab mr checkout` supports `--force`; consider adding it when `input.force` is true.
      
      Evidence trail:
      1. apps/server/src/git/Services/GitHostCli.ts lines 71-75: Interface defines `checkoutPullRequest` with `force?: boolean`
      2. apps/server/src/git/Layers/GitLabCli.ts lines 249-253: GitLab implementation ignores `input.force`, only passes `["mr", "checkout", input.reference]`
      3. apps/server/src/git/Layers/GitHubCli.ts line 344: GitHub implementation correctly handles force: `...(input.force ? ["--force"] : [])`
      
      Also found in 1 other location(s):
      - apps/web/src/hooks/useHandleNewThread.ts:61 -- The `envMode` option is silently ignored when reusing an existing draft thread. The diff removes passing `envMode` to `setDraftThreadContext` (lines 62-65 and 86-89), but callers still pass `envMode` expecting it to be applied (see usage: `handleNewThread(projectId, { envMode: ... })`). This creates inconsistent behavior: `branch` and `worktreePath` options ARE applied to existing drafts, but `envMode` is not. The option is still used when creating a brand new thread (line 102), so there's a behavioral inconsistency depending on whether a draft already exists.
      
      @@ -0,0 +211,21 @@
      211+ <TooltipTrigger
      212+ render={
      213+ <div className="min-w-0 flex-1 pt-0.5">
      214+ <p className="text-xs text-foreground/60">{toolLabel}</p>
      215+ {entry.summary && entry.summary !== entry.description && (
      216+ <p className="mt-0.5 text-[10px] text-muted-foreground/50 italic">
      217+ {entry.summary}
      218+ </p>
      219+ )}
      220+ </div>
      221+ }
      222+ />
      223+ <TooltipPopup side="top" className="max-w-lg break-words whitespace-pre-wrap leading-tight">
      224+ {tooltipText}
      225+ </TooltipPopup>
      226+ </Tooltip>
      227+ </div>
      228+ );
      229+});
      230+
      231+const ProgressTimeline = memo(function ProgressTimeline(props: { task: AgentTaskSummary }) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low chat/SubagentDetailDrawer.tsx:231

      When the last item in items is a task-progress entry with both description and lastToolName null, TaskProgressTimelineRow returns null. However, the isLast calculation at line 249 only checks index position, not whether the component will actually render. This causes the preceding row to render a vertical connector line (border-l) that visually points to nothing.

      Consider computing visible items before mapping, or filtering out items that won't render, so isLast reflects actual UI presence rather than array position.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/web/src/components/chat/SubagentDetailDrawer.tsx around line 231:
      
      When the last item in `items` is a `task-progress` entry with both `description` and `lastToolName` null, `TaskProgressTimelineRow` returns `null`. However, the `isLast` calculation at line 249 only checks index position, not whether the component will actually render. This causes the preceding row to render a vertical connector line (`border-l`) that visually points to nothing.
      
      Consider computing visible items before mapping, or filtering out items that won't render, so `isLast` reflects actual UI presence rather than array position.
      
      Evidence trail:
      - apps/web/src/components/chat/SubagentDetailDrawer.tsx lines 189-191: `TaskProgressTimelineRow` returns null when `toolLabel` is null (when both `entry.description` and `entry.lastToolName` are null)
      - apps/web/src/components/chat/SubagentDetailDrawer.tsx line 249: `const isLast = idx === items.length - 1;` shows isLast is purely index-based
      - apps/web/src/components/chat/SubagentDetailDrawer.tsx line 207: `{!isLast && <div className="mt-1 min-h-2 flex-1 border-l border-border/30" />}` shows connector line renders when !isLast
      - All verified at REVIEWED_COMMIT
      @@ -0,0 +298,21 @@
      298+
      299+ if (!tokenResponse.ok) {
      300+ const body = yield* Effect.tryPromise({
      301+ try: () => tokenResponse.text(),
      302+ catch: () =>
      303+ new JiraOAuthError({
      304+ operation: "exchangeCode",
      305+ detail: `Token exchange failed with status ${tokenResponse.status}`,
      306+ }),
      307+ });
      308+ sendResultPage(
      309+ res,
      310+ "\u274C",
      311+ "Jira connection failed",
      312+ "Token exchange failed.",
      313+ body.slice(0, 500),
      314+ );
      315+ return true;
      316+ }
      317+
      318+ const json = yield* Effect.tryPromise({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low jira/oauthRoutes.ts:318

      The type assertion at line 320 (as Promise<{access_token: string; ...}>) doesn't validate the response at runtime. If the proxy returns HTTP 200 with malformed JSON (e.g. {"error": "invalid_grant"}), the destructured fields will be undefined and the code creates a JiraTokenSet with undefined values where strings are expected, corrupting saved token data. Consider validating the response shape before casting, or checking that required fields exist and throwing a parse error if they don't.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/jira/oauthRoutes.ts around line 318:
      
      The type assertion at line 320 (`as Promise<{access_token: string; ...}>`) doesn't validate the response at runtime. If the proxy returns HTTP 200 with malformed JSON (e.g. `{"error": "invalid_grant"}`), the destructured fields will be `undefined` and the code creates a `JiraTokenSet` with `undefined` values where strings are expected, corrupting saved token data. Consider validating the response shape before casting, or checking that required fields exist and throwing a parse error if they don't.
      
      Evidence trail:
      apps/server/src/jira/oauthRoutes.ts lines 299 (ok check), 318-325 (type assertion without validation), 334-339 (JiraTokenSet creation) at REVIEWED_COMMIT; apps/server/src/jira/Layers/JiraTokenService.ts lines 185-192 (saveTokens implementation with no validation) at REVIEWED_COMMIT; apps/server/src/jira/Services/JiraTokenService.ts lines 4-9 (JiraTokenSet interface definition) at REVIEWED_COMMIT
      @@ -0,0 +91,21 @@
      91+ const normalized = (state ?? "").toLowerCase().trim();
      92+ if (normalized === "merged") return "merged";
      93+ if (normalized === "closed") return "closed";
      94+ return "open";
      95+}
      96+
      97+const RawGitLabMrSchema = Schema.Struct({
      98+ iid: PositiveInt,
      99+ title: TrimmedNonEmptyString,
      100+ web_url: TrimmedNonEmptyString,
      101+ source_branch: TrimmedNonEmptyString,
      102+ target_branch: TrimmedNonEmptyString,
      103+ state: Schema.optional(Schema.NullOr(Schema.String)),
      104+ updated_at: Schema.optional(Schema.NullOr(Schema.String)),
      105+});
      106+
      107+const RawGitLabRepoSchema = Schema.Struct({
      108+ default_branch: Schema.optional(Schema.NullOr(Schema.String)),
      109+});
      110+
      111+function decodeGitLabJson<S extends Schema.Top>(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low Layers/GitLabCli.ts:111

      decodeGitLabJson checks error instanceof Error to extract a message, but Schema.decodeEffect returns a SchemaError which does not extend Error. The check always fails, so the detailed validation error (which fields failed, why) is discarded and only the generic invalidDetail message is preserved. Consider using error instanceof Schema.SchemaError instead, or checking for a message property directly.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/git/Layers/GitLabCli.ts around line 111:
      
      `decodeGitLabJson` checks `error instanceof Error` to extract a message, but `Schema.decodeEffect` returns a `SchemaError` which does not extend `Error`. The check always fails, so the detailed validation error (which fields failed, why) is discarded and only the generic `invalidDetail` message is preserved. Consider using `error instanceof Schema.SchemaError` instead, or checking for a `message` property directly.
      
      Evidence trail:
      1. apps/server/src/git/Layers/GitLabCli.ts lines 110-127 (REVIEWED_COMMIT) - shows `decodeGitLabJson` function using `error instanceof Error` check at line 121
      2. Web task result confirming ParseResult.ParseError in Effect-TS v4 is not a JavaScript Error subclass - errors are tagged values handled via `Effect.catchTag` rather than instanceof checks
      3. Effect-TS GitHub platform/HttpApiError.ts showing pattern `static fromParseError(error: ParseResult.ParseError)` treating ParseError as a separate type from Error
      4. package.json showing effect version 4.0.0-beta.43
      @@ -573,4 +1127,7 @@
      5731127 const detail = next.detail ?? previous.detail;
      5741128 const command = next.command ?? previous.command;
      5751129 const rawCommand = next.rawCommand ?? previous.rawCommand;
      1130+ const exitCode = next.exitCode ?? previous.exitCode;
      5761131 const toolTitle = next.toolTitle ?? previous.toolTitle;
      1132+ const toolName = next.toolName ?? previous.toolName;
      1133+ const toolInput = previous.toolInput ?? next.toolInput;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High src/session-logic.ts:1133

      toolInput is merged as previous.toolInput ?? next.toolInput while every other field uses next.X ?? previous.X. This causes merged entries to retain stale tool input while updating to newer tool names, producing mismatched toolName/toolInput pairs.

      Suggested change
      1133- const toolInput = previous.toolInput ?? next.toolInput;
      1133+ const toolInput = next.toolInput ?? previous.toolInput;
      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/web/src/session-logic.ts around line 1133:
      
      `toolInput` is merged as `previous.toolInput ?? next.toolInput` while every other field uses `next.X ?? previous.X`. This causes merged entries to retain stale tool input while updating to newer tool names, producing mismatched `toolName`/`toolInput` pairs.
      
      Evidence trail:
      apps/web/src/session-logic.ts lines 1127-1153 at REVIEWED_COMMIT. Line 1131: `const toolName = next.toolName ?? previous.toolName;` (next-first pattern). Line 1133: `const toolInput = previous.toolInput ?? next.toolInput;` (previous-first pattern, inconsistent). Lines 1145-1157 show both computed values are used in the returned object.
      @@ -0,0 +107,21 @@
      107+ return <EyeIcon className={iconClass} />;
      108+ }
      109+ if (normalized.includes("web") || normalized.includes("fetch") || normalized.includes("browse")) {
      110+ return <GlobeIcon className={iconClass} />;
      111+ }
      112+ if (normalized.includes("mcp")) {
      113+ return <WrenchIcon className={iconClass} />;
      114+ }
      115+ if (normalized.includes("agent")) {
      116+ return <BotIcon className={iconClass} />;
      117+ }
      118+ return <WrenchIcon className={iconClass} />;
      119+}
      120+
      121+function formatElapsedSeconds(seconds: number): string {
      122+ if (seconds < 1) return "<1s";
      123+ if (seconds < 60) return `${seconds.toFixed(1)}s`;
      124+ const mins = Math.floor(seconds / 60);
      125+ const secs = Math.round(seconds % 60);
      126+ return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
      127+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low chat/SubagentDetailDrawer.tsx:121

      When seconds % 60 rounds up to 60 (e.g., seconds = 119.5 produces mins = 1, secs = Math.round(59.5) = 60), formatElapsedSeconds returns invalid strings like "1m 60s" instead of "2m". Consider handling the overflow so seconds are always 0-59, or recalculate mins/secs using Math.floor(seconds / 60) after rounding.

      -function formatElapsedSeconds(seconds: number): string {
      +function formatElapsedSeconds(seconds: number): string {
         if (seconds < 1) return "<1s";
         if (seconds < 60) return `${seconds.toFixed(1)}s`;
      -  const mins = Math.floor(seconds / 60);
      -  const secs = Math.round(seconds % 60);
      -  return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
      +  const mins = Math.floor(seconds / 60);
      +  const secs = Math.floor(seconds % 60);
      +  return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
       }
      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/web/src/components/chat/SubagentDetailDrawer.tsx around lines 121-127:
      
      When `seconds % 60` rounds up to 60 (e.g., `seconds = 119.5` produces `mins = 1`, `secs = Math.round(59.5) = 60`), `formatElapsedSeconds` returns invalid strings like `"1m 60s"` instead of `"2m"`. Consider handling the overflow so seconds are always 0-59, or recalculate mins/secs using `Math.floor(seconds / 60)` after rounding.
      
      Evidence trail:
      apps/web/src/components/chat/SubagentDetailDrawer.tsx lines 121-127 (REVIEWED_COMMIT) - the `formatElapsedSeconds` function uses `Math.floor(seconds / 60)` for mins and `Math.round(seconds % 60)` for secs independently, without handling the overflow case when rounding produces 60.
      @@ -163,0 +202,21 @@
      202+}) =>
      203+ Effect.tryPromise({
      204+ try: () =>
      205+ runProcess("gh", input.args, {
      206+ cwd: input.cwd,
      207+ timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
      208+ }),
      209+ catch: (error) => normalizeGitHubCliError("execute", error),
      210+ });
      211+
      212+function listPullRequestsViaGh(
      213+ run: (input: {
      214+ readonly cwd: string;
      215+ readonly args: ReadonlyArray<string>;
      216+ }) => Effect.Effect<{ stdout: string }, GitHostCliError>,
      217+): GitHostCliShape["listPullRequests"] {
      218+ return (input) => {
      219+ const jsonFields =
      220+ input.state === "all"
      221+ ? "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt"
      222+ : "number,title,url,baseRefName,headRefName";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/GitHubCli.ts:220

      When state === "open", jsonFields omits isCrossRepository,headRepository,headRepositoryOwner, so normalizePullRequestSummary always receives undefined for cross-repo fields and sets them to null. This breaks cross-repository PR detection for open PRs. Consider including all fields regardless of state, or adjusting the schema to match the requested fields.

      Suggested change
      220- input.state === "all"
      221- ? "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt"
      222- : "number,title,url,baseRefName,headRefName";
      220+ return (input) => {
      221+ const jsonFields = "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner"
      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/git/Layers/GitHubCli.ts around lines 220-222:
      
      When `state === "open"`, `jsonFields` omits `isCrossRepository,headRepository,headRepositoryOwner`, so `normalizePullRequestSummary` always receives `undefined` for cross-repo fields and sets them to `null`. This breaks cross-repository PR detection for open PRs. Consider including all fields regardless of state, or adjusting the schema to match the requested fields.
      
      Evidence trail:
      apps/server/src/git/Layers/GitHubCli.ts lines 220-223 (jsonFields definition for listPullRequestsViaGh), lines 127-150 (normalizePullRequestSummary), line 280 (getPullRequest includes cross-repo fields), apps/server/src/git/Layers/GitManager.test.ts line 462 (test expects cross-repo fields in listPullRequests), apps/server/src/git/Layers/GitManager.ts lines 130, 146, 202, 239-240, 255 (usage of isCrossRepository for cross-repo detection)
      @@ -0,0 +73,21 @@
      73+ aria-expanded={expanded}
      74+ className="flex w-full items-center gap-2 text-left transition-colors duration-150 hover:bg-muted/20"
      75+ onClick={() => setExpanded((prev) => !prev)}
      76+ >
      77+ <span className="flex size-5 shrink-0 items-center justify-center">
      78+ {allCompleted ? (
      79+ <CheckCircle2Icon className="size-3.5 text-success" aria-hidden="true" />
      80+ ) : (
      81+ <ListTodoIcon className="size-3.5 text-primary/80" aria-hidden="true" />
      82+ )}
      83+ </span>
      84+ <span className="flex-1 text-[11px] leading-5 text-foreground/80">
      85+ Todos — {buildTodoSummaryLabel(items)}
      86+ </span>
      87+ <ExpandIcon className="size-3 shrink-0 text-muted-foreground/50" aria-hidden="true" />
      88+ </button>
      89+
      90+ {expanded && (
      91+ <div ref={scrollContainerRef} className="mt-1 max-h-40 space-y-0.5 overflow-y-auto pl-5">
      92+ {items.map((item) => (
      93+ <TodoItemRow key={item.content} item={item} />
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low chat/ComposerActiveTasksPanel.tsx:93

      The key prop on line 93 uses item.content, which causes React duplicate key warnings and incorrect rendering when two TodoItem objects have the same content. Since TodoItem has no unique id field and the data pipeline doesn't deduplicate, duplicate content values are possible, leading to skipped re-renders or DOM node reuse errors.

      Also found in 1 other location(s)

      apps/web/src/components/chat/MessagesTimeline.tsx:731

      Duplicate React keys when the same Jira issue key appears multiple times in the text. The key ${keyPrefix}-jira-${issueKey} at line 731 will be identical for repeated occurrences of the same issue (e.g., text containing @jira:ABC-123 ... @jira:ABC-123). This causes React reconciliation issues and a console warning. The key should include a unique identifier like the match position, e.g., ${keyPrefix}-jira-${issueKey}-${matchStart}.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/web/src/components/chat/ComposerActiveTasksPanel.tsx around line 93:
      
      The `key` prop on line 93 uses `item.content`, which causes React duplicate key warnings and incorrect rendering when two `TodoItem` objects have the same content. Since `TodoItem` has no unique id field and the data pipeline doesn't deduplicate, duplicate content values are possible, leading to skipped re-renders or DOM node reuse errors.
      
      Evidence trail:
      apps/web/src/components/chat/ComposerActiveTasksPanel.tsx:93 shows `<TodoItemRow key={item.content} item={item} />` using content as key. apps/web/src/session-logic.ts:505-509 defines TodoItem with only content, activeForm, and status fields (no unique id). apps/web/src/session-logic.ts:530-544 shows deriveTodoItems maps rawTodos directly without deduplication, meaning duplicate content values can exist in the resulting array.
      
      Also found in 1 other location(s):
      - apps/web/src/components/chat/MessagesTimeline.tsx:731 -- Duplicate React keys when the same Jira issue key appears multiple times in the text. The key `${keyPrefix}-jira-${issueKey}` at line 731 will be identical for repeated occurrences of the same issue (e.g., text containing `@jira:ABC-123 ... @jira:ABC-123`). This causes React reconciliation issues and a console warning. The key should include a unique identifier like the match position, e.g., `${keyPrefix}-jira-${issueKey}-${matchStart}`.
      
      @@ -0,0 +112,21 @@
      112+ config: ServerConfigShape,
      113+): boolean {
      114+ if (url.pathname !== "/api/jira/auth") return false;
      115+
      116+ if (!config.jiraTokenProxyUrl) {
      117+ res.writeHead(500, { "Content-Type": "text/plain" });
      118+ res.end("MARCODE_JIRA_TOKEN_PROXY_URL is not configured");
      119+ return true;
      120+ }
      121+
      122+ cleanExpiredStates();
      123+
      124+ const state = crypto.randomBytes(16).toString("hex");
      125+ const { codeVerifier, codeChallenge } = generatePkce();
      126+
      127+ pendingStates.set(state, { codeVerifier, createdAt: Date.now() });
      128+
      129+ const redirectUri = getRedirectUri(config);
      130+ const proxyUrl = config.jiraTokenProxyUrl;
      131+
      132+ const doAuth = async () => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium jira/oauthRoutes.ts:132

      tryHandleJiraAuthRequest always calls startCallbackServer(config), but that server is only needed when using the default http://localhost:19571/api/jira/callback redirect URI. When config.jiraRedirectUri is set to a custom URL, the callback server is unused—yet if port 19571 is occupied, the OAuth flow still fails with "OAuth callback port 19571 is already in use". The server should only start when config.jiraRedirectUri is undefined.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/jira/oauthRoutes.ts around line 132:
      
      `tryHandleJiraAuthRequest` always calls `startCallbackServer(config)`, but that server is only needed when using the default `http://localhost:19571/api/jira/callback` redirect URI. When `config.jiraRedirectUri` is set to a custom URL, the callback server is unused—yet if port 19571 is occupied, the OAuth flow still fails with "OAuth callback port 19571 is already in use". The server should only start when `config.jiraRedirectUri` is undefined.
      
      Evidence trail:
      apps/server/src/jira/oauthRoutes.ts lines 40-45 (`getRedirectUri` function), lines 58-99 (`startCallbackServer` function with EADDRINUSE error handling), lines 132-145 (unconditional call to `startCallbackServer(config)` inside `doAuth`), line 13 (`OAUTH_CALLBACK_PORT = 19571`).
    5. Approvability

      Verdict: Needs human review

      4 blocking correctness issues found. Diff is too large for automated approval analysis. A human reviewer should evaluate this PR.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).

Sign in to join this conversation.