feat(streaming): implement command output streaming from runtime #1834
Closedtyulyukov(GitHub profile, opens in a new tab)wants to merge 138 commits into
main fromrefs/pull/1834/headopened View on GitHubtyulyukov(GitHub profile, opens in a new tab) closed this
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
- @@ -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+}@@ -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_ITEM23+ ? 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+ }@@ -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),
- @@ -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 = seedExists28+ ? 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* () {@@ -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);@@ -0,0 +211,21 @@211+ <TooltipTrigger212+ 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 }) {@@ -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({@@ -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>(@@ -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;@@ -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+}@@ -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";@@ -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} />@@ -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 () => {
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
96b02984-4fbc-4163-a38d-0f03b479244fYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
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