Skip to content
Source
Sign inSign up
pingdotgg/t3code

Track per-thread terminal running state in UI and store #19

Mergedjuliusmarmingemerged 5 commits intomain fromcodething/696df84fmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Summary

  • add terminalRunning to thread state and initialize it across thread creation and hydration paths
  • route terminal events through the store via APPLY_TERMINAL_EVENT instead of handling only exited inline
  • update reducer logic to keep terminal running/open state in sync for started, restarted, exited, and error events
  • wire ThreadTerminalDrawer running-state updates back to the store
  • show a pulsing Terminal status pill in the sidebar when a thread terminal is running
  • extend unit tests for reducer behavior and persistence shape updates

Testing

  • apps/web/src/store.test.ts: verifies SET_THREAD_TERMINAL_RUNNING, APPLY_TERMINAL_EVENT started handling, and exited handling (stops running + closes drawer)
  • apps/web/src/persistenceSchema.test.ts: verifies persisted thread shape includes terminal state fields
  • Not run: project lint/scripts in this PR context

Open with Devin

Summary by CodeRabbit

  • New Features

    • Terminal status indicator shows when one or more terminals are running for a thread.
    • Subprocess activity reporting emits activity events for running child processes.
  • Improvements

    • More graceful terminal close behavior with a reliable fallback.
  • Tests

    • Added coverage for terminal activity events and terminal lifecycle scenarios.
  • Chores

    • Migrated terminal history storage to a new per-terminal format with backward-compatible migration.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      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

      Walkthrough

      Adds terminal lifecycle tracking: threads gain runningTerminalIds; store handles APPLY_TERMINAL_EVENT; UI shows Terminal status and improved close behavior; server adds subprocess activity polling and migrates terminal-scoped history files; contracts add an "activity" terminal event variant; tests updated accordingly.

      Changes

      Cohort / File(s)Summary
      Types & Store
      apps/web/src/types.ts, apps/web/src/store.ts, apps/web/src/App.tsx
      Added runningTerminalIds: string[] to Thread; imported TerminalEvent; added APPLY_TERMINAL_EVENT action and reducer logic; App effect listens for terminal events and dispatches them.
      Web UI
      apps/web/src/components/Sidebar.tsx, apps/web/src/components/ChatView.tsx
      Sidebar: added Terminal status pill, terminalStatusPill() helper, and initialize runningTerminalIds for new threads. ChatView: updated terminal-close flow to call api.terminal.close(...) when available, otherwise fall back to writing "exit\n"; adjusted effect deps.
      Persistence & Hydration
      apps/web/src/persistenceSchema.ts, apps/web/src/persistenceSchema.test.ts
      Hydrate thread now initializes runningTerminalIds: []; tests updated to include the new field.
      State Tests
      apps/web/src/store.test.ts
      Added TerminalEvent imports, test helpers, and multiple tests asserting runningTerminalIds lifecycle across start, activity, exit, close, and multi-terminal scenarios.
      Server Terminal Manager
      apps/server/src/terminalManager.ts, apps/server/src/terminalManager.test.ts
      Added subprocess monitoring (checker, poll interval, polling loop, session hasRunningSubprocess state); integrated polling into lifecycle methods; migrated history to terminal-scoped paths with legacy-file fallback and cleanup; tests added/updated for subprocess activity and migration.
      Contracts
      packages/contracts/src/terminal.ts, packages/contracts/src/terminal.test.ts
      Added terminalActivityEventSchema (type "activity", hasRunningSubprocess: boolean) and extended terminalEventSchema union; test added to validate activity events.

      Sequence Diagram

      sequenceDiagram
          participant Terminal as Terminal
          participant Server as Server/TerminalManager
          participant App as App (web)
          participant Store as Redux Store
          participant UI as Sidebar/ChatView
      
          Terminal->>Server: emits low-level process events / subprocess state
          Server->>App: sends terminal events (started/activity/exited)
          App->>App: effect receives event
          App->>Store: dispatch APPLY_TERMINAL_EVENT { event }
          Store->>Store: update thread.runningTerminalIds based on event
          Store->>UI: state update triggers re-render
          UI->>UI: render Terminal status pill or update ChatView terminal state

      Estimated code review effort

      🎯 4 (Complex) | ⏱️ ~50 minutes

      🚥 Pre-merge checks | ✅ 2 | ❌ 2
      ❌ Failed checks (2 warnings)
      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 4.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      Merge Conflict Detection⚠️ Warning❌ Merge conflicts detected (16 files):

      ⚔️ README.md (content)
      ⚔️ apps/server/package.json (content)
      ⚔️ apps/server/src/terminalManager.test.ts (content)
      ⚔️ apps/server/src/terminalManager.ts (content)
      ⚔️ apps/web/src/App.tsx (content)
      ⚔️ apps/web/src/components/ChatView.tsx (content)
      ⚔️ apps/web/src/components/Sidebar.tsx (content)
      ⚔️ apps/web/src/persistenceSchema.test.ts (content)
      ⚔️ apps/web/src/persistenceSchema.ts (content)
      ⚔️ apps/web/src/store.test.ts (content)
      ⚔️ apps/web/src/store.ts (content)
      ⚔️ apps/web/src/types.ts (content)
      ⚔️ package.json (content)
      ⚔️ packages/contracts/src/terminal.test.ts (content)
      ⚔️ packages/contracts/src/terminal.ts (content)
      ⚔️ turbo.json (content)

      These conflicts must be resolved before merging into main.
      Resolve conflicts locally and push changes to this branch.
      ✅ Passed checks (2 passed)
      Check nameStatusExplanation
      Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      Title check✅ PassedThe title 'Track per-thread terminal running state in UI and store' accurately captures the main objective of the PR, which is to add and manage per-thread terminal running state across UI components and the store layer.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `codething/696df84f`

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

      Track per-thread terminal subprocess state and emit TerminalManager.activity events to update runningTerminalIds in UI and store

      Add periodic subprocess polling in TerminalManager with new activity events, migrate legacy transcript paths on read, and route terminal events to update runningTerminalIds in the web store and show a sidebar status pill. Contracts validate the new activity event.

      📍Where to Start

      Start with subprocess polling and event emission in TerminalManager: see updateSubprocessPollingState and pollSubprocessActivity in apps/server/src/terminalManager.ts.


      Macroscope summarized b185c14.
    3. Greptile Overview

      Greptile Summary

      Added terminalRunning boolean field to thread state, tracking whether a thread's terminal has an active process. Terminal events are now centrally routed through the store via APPLY_TERMINAL_EVENT action, which updates both running state and drawer visibility based on event type (started/restarted set running=true, exited/error set running=false). The UI displays a pulsing "Terminal" status pill in the sidebar when a terminal is active.

      Key changes:

      • Centralized terminal event handling in App.tsx dispatches all events to store
      • Dual event listeners: App.tsx for store updates, ThreadTerminalDrawer for xterm UI updates
      • Proper initialization: new threads and hydrated threads start with terminalRunning: false
      • Comprehensive test coverage for new actions and reducer logic

      Confidence Score: 4/5

      • Safe to merge with minor suggestion for robustness
      • The implementation is well-structured with proper state management, event routing, and comprehensive test coverage. The architecture correctly separates concerns (store updates vs terminal UI). One minor improvement suggested: the status check in APPLY_TERMINAL_EVENT could be more defensive by also accepting "starting" status for started/restarted events.
      • No files require special attention. The suggestion in apps/web/src/store.ts is a minor robustness improvement.

      Important Files Changed

      FilenameOverview
      apps/web/src/store.tsAdded terminal state actions and reducer logic; status check on started/restarted events could be more robust
      apps/web/src/App.tsxRoutes all terminal events through APPLY_TERMINAL_EVENT action; initializes terminalRunning to false
      apps/web/src/components/Sidebar.tsxAdds pulsing Terminal status pill when thread terminal is running; initializes new threads with terminalRunning: false
      apps/web/src/components/ThreadTerminalDrawer.tsxAdds onRunningStateChange callback prop; updates running state on terminal open and error events

      Sequence Diagram

      sequenceDiagram
          participant User
          participant ChatView
          participant ThreadTerminalDrawer
          participant Store
          participant App
          participant API
      
          Note over User,API: Terminal Open Flow
          User->>ChatView: Open terminal
          ChatView->>ThreadTerminalDrawer: Render drawer
          ThreadTerminalDrawer->>API: terminal.open(threadId, cwd, cols, rows)
          API-->>ThreadTerminalDrawer: snapshot (status: "running")
          ThreadTerminalDrawer->>Store: onRunningStateChange(true)
          Store->>Store: SET_THREAD_TERMINAL_RUNNING
      
          Note over User,API: Terminal Event Flow (started/restarted)
          API->>App: terminal.onEvent({type: "started", snapshot})
          App->>Store: APPLY_TERMINAL_EVENT
          Store->>Store: Update terminalRunning based on snapshot.status
          API->>ThreadTerminalDrawer: terminal.onEvent({type: "started"})
          ThreadTerminalDrawer->>ThreadTerminalDrawer: Clear terminal, write history
      
          Note over User,API: Terminal Event Flow (exited)
          API->>App: terminal.onEvent({type: "exited"})
          App->>Store: APPLY_TERMINAL_EVENT
          Store->>Store: Set terminalRunning=false, terminalOpen=false
          API->>ThreadTerminalDrawer: terminal.onEvent({type: "exited"})
          ThreadTerminalDrawer->>Store: onThreadExited()
      
          Note over User,API: Terminal Event Flow (error)
          API->>App: terminal.onEvent({type: "error"})
          App->>Store: APPLY_TERMINAL_EVENT
          Store->>Store: Set terminalRunning=false
          API->>ThreadTerminalDrawer: terminal.onEvent({type: "error"})
          ThreadTerminalDrawer->>Store: onRunningStateChange(false)
          ThreadTerminalDrawer->>ThreadTerminalDrawer: Write error message
      
          Note over User,API: UI Update
          Store-->>ChatView: State update
          ChatView-->>User: Terminal status pill visible in sidebar
      Last reviewed commit: 69a04d1
    4. 9 files reviewed, 1 comment [Edit Code Review Agent Settings](https://app.greptile.com/review/github) | [Greptile](https://greptile.com?utm_source=greptile_expert&utm_medium=github&utm_campaign=code_reviews)
      @@ -373,3 +387,17 @@
      373387 };
      374388 }
      375389
      390+ case "APPLY_TERMINAL_EVENT":
      391+ if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
      392+ return state;
      393+ }
      394+ return {
      395+ ...state,
      396+ threads: updateThread(state.threads, action.event.threadId, (t) => ({
      397+ ...t,
      398+ terminalRunning:
      399+ action.event.type === "started" || action.event.type === "restarted"
      400+ ? action.event.snapshot.status === "running"
      401+ : action.event.type === "exited" || action.event.type === "error"
      402+ ? false
      403+ : t.terminalRunning,
      greptile-apps[bot](GitHub profile, opens in a new tab)commented

      Status check could be more robust. While started events currently always have status: "running" (terminal sets "starting" → spawns PTY → sets "running" → emits event), consider checking for "starting" as well or setting terminalRunning: true unconditionally for these event types. This would make the code more resilient to future changes in the terminal manager.

      Suggested change
      398- terminalRunning:
      399- action.event.type === "started" || action.event.type === "restarted"
      400- ? action.event.snapshot.status === "running"
      401- : action.event.type === "exited" || action.event.type === "error"
      402- ? false
      403- : t.terminalRunning,
      398+ terminalRunning:
      399+ action.event.type === "started" || action.event.type === "restarted"
      400+ ? action.event.snapshot.status === "running" || action.event.snapshot.status === "starting"
      401+ : action.event.type === "exited" || action.event.type === "error"
      402+ ? false
      403+ : t.terminalRunning,
      Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
    5. Actionable comments posted: 1

      🤖 Fix all issues with AI agents
      In `@apps/web/src/store.test.ts`:
      - Around line 79-109: The type error is caused because overrides:
      Partial<TerminalEvent> allows changing the discriminant "type" and yields an
      incompatible union; update both makeTerminalStartedEvent and
      makeTerminalActivityEvent to accept overrides: Partial<Omit<TerminalEvent,
      "type">> (i.e., exclude the "type" field from the override) so the functions
      keep their fixed discriminant ("started" or "activity") while still allowing
      other fields to be overridden; keep the return type as TerminalEvent and spread
      overrides as before.
      @@ -77,0 +89,21 @@
      89+ status: "running",
      90+ pid: 1234,
      91+ history: "",
      92+ exitCode: null,
      93+ exitSignal: null,
      94+ updatedAt: "2026-02-09T00:00:01.000Z",
      95+ },
      96+ ...overrides,
      97+ };
      98+}
      99+
      100+function makeTerminalActivityEvent(overrides: Partial<TerminalEvent> = {}): TerminalEvent {
      101+ return {
      102+ type: "activity",
      103+ threadId: "thread-local-1",
      104+ terminalId: DEFAULT_THREAD_TERMINAL_ID,
      105+ createdAt: "2026-02-09T00:00:02.000Z",
      106+ hasRunningSubprocess: true,
      107+ ...overrides,
      108+ };
      109+}

      ⚠️ Potential issue | 🟠 Major

      Fix type error causing pipeline failure.

      The pipeline fails with TS2719 because Partial<TerminalEvent> allows overriding the type discriminator, causing TypeScript to infer an incompatible union type. The spread of overrides could change type: "started" to any other event type.

      🔧 Proposed fix: Use specific override types
      -function makeTerminalStartedEvent(overrides: Partial<TerminalEvent> = {}): TerminalEvent {
      +function makeTerminalStartedEvent(
      +  overrides: Partial<Omit<Extract<TerminalEvent, { type: "started" }>, "type">> = {},
      +): TerminalEvent {
         return {
           type: "started",
           threadId: "thread-local-1",
           terminalId: DEFAULT_THREAD_TERMINAL_ID,
           createdAt: "2026-02-09T00:00:01.000Z",
           snapshot: {
             threadId: "thread-local-1",
             terminalId: DEFAULT_THREAD_TERMINAL_ID,
             cwd: "/tmp/project",
             status: "running",
             pid: 1234,
             history: "",
             exitCode: null,
             exitSignal: null,
             updatedAt: "2026-02-09T00:00:01.000Z",
           },
           ...overrides,
      -  };
      +  } as TerminalEvent;
       }
      
      -function makeTerminalActivityEvent(overrides: Partial<TerminalEvent> = {}): TerminalEvent {
      +function makeTerminalActivityEvent(
      +  overrides: Partial<Omit<Extract<TerminalEvent, { type: "activity" }>, "type">> = {},
      +): TerminalEvent {
         return {
           type: "activity",
           threadId: "thread-local-1",
           terminalId: DEFAULT_THREAD_TERMINAL_ID,
           createdAt: "2026-02-09T00:00:02.000Z",
           hasRunningSubprocess: true,
           ...overrides,
      -  };
      +  } as TerminalEvent;
       }

      Alternatively, a simpler fix using type assertions:

      🔧 Simpler fix with type assertions
      -function makeTerminalStartedEvent(overrides: Partial<TerminalEvent> = {}): TerminalEvent {
      -  return {
      +function makeTerminalStartedEvent(
      +  overrides: Partial<TerminalEvent> & { type?: "started" } = {},
      +): TerminalEvent {
      +  return ({
           type: "started",
           threadId: "thread-local-1",
           terminalId: DEFAULT_THREAD_TERMINAL_ID,
           createdAt: "2026-02-09T00:00:01.000Z",
           snapshot: {
             threadId: "thread-local-1",
             terminalId: DEFAULT_THREAD_TERMINAL_ID,
             cwd: "/tmp/project",
             status: "running",
             pid: 1234,
             history: "",
             exitCode: null,
             exitSignal: null,
             updatedAt: "2026-02-09T00:00:01.000Z",
           },
           ...overrides,
      -  };
      +  }) as TerminalEvent;
       }
      
      -function makeTerminalActivityEvent(overrides: Partial<TerminalEvent> = {}): TerminalEvent {
      -  return {
      +function makeTerminalActivityEvent(
      +  overrides: Partial<TerminalEvent> & { type?: "activity" } = {},
      +): TerminalEvent {
      +  return ({
           type: "activity",
           threadId: "thread-local-1",
           terminalId: DEFAULT_THREAD_TERMINAL_ID,
           createdAt: "2026-02-09T00:00:02.000Z",
           hasRunningSubprocess: true,
           ...overrides,
      -  };
      +  }) as TerminalEvent;
       }
      📝 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
      79+function makeTerminalStartedEvent(
      80+ overrides: Partial<TerminalEvent> & { type?: "started" } = {},
      81+): TerminalEvent {
      82+ return ({
      83+ type: "started",
      84+ threadId: "thread-local-1",
      85+ terminalId: DEFAULT_THREAD_TERMINAL_ID,
      86+ createdAt: "2026-02-09T00:00:01.000Z",
      87+ snapshot: {
      88+ threadId: "thread-local-1",
      89+ terminalId: DEFAULT_THREAD_TERMINAL_ID,
      90+ cwd: "/tmp/project",
      91+ status: "running",
      92+ pid: 1234,
      93+ history: "",
      94+ exitCode: null,
      95+ exitSignal: null,
      96+ updatedAt: "2026-02-09T00:00:01.000Z",
      97+ },
      98+ ...overrides,
      99+ }) as TerminalEvent;
      100+}
      101+
      102+function makeTerminalActivityEvent(
      103+ overrides: Partial<TerminalEvent> & { type?: "activity" } = {},
      104+): TerminalEvent {
      105+ return ({
      106+ type: "activity",
      107+ threadId: "thread-local-1",
      108+ terminalId: DEFAULT_THREAD_TERMINAL_ID,
      109+ createdAt: "2026-02-09T00:00:02.000Z",
      110+ hasRunningSubprocess: true,
      111+ ...overrides,
      112+ }) as TerminalEvent;
      113+}
      🧰 Tools
      🪛 GitHub Actions: CI

      [error] 80-80: TS2719: Type '{ createdAt: string; type: "started"; threadId: string; terminalId: string; snapshot: { status: "running" | "error" | "starting" | "exited"; cwd: string; threadId: string; updatedAt: string; ... 4 more ...; exitSignal: number | null; }; } | ... 5 more ... | { ...; }' is not assignable to type '{ createdAt: string; type: "started"; threadId: string; terminalId: string; snapshot: { status: "running" | "error" | "starting" | "exited"; cwd: string; threadId: string; updatedAt: string; ... 4 more ...; exitSignal: number | null; }; } | ... 5 more ... | { ...; }'. Two different types with this name exist, but they are unrelated. Type '{ createdAt: string; type: "started" | "output"; data?: string; threadId: string; terminalId: string; snapshot: { threadId: string; terminalId: string; cwd: string; status: "running"; pid: number; history: string; exitCode: null; exitSignal: null; updatedAt: string; }; }' is not assignable to type '{ createdAt: string; type: "started"; threadId: string; terminalId: string; snapshot: { status: "running" | "error" | "starting" | "exited"; cwd: string; threadId: string; updatedAt: string; ... 4 more ...; exitSignal: number | null; }; } | ... 5 more ... | { ...; }'.

      🤖 Prompt for AI Agents
      In `@apps/web/src/store.test.ts` around lines 79 - 109, The type error is caused
      because overrides: Partial<TerminalEvent> allows changing the discriminant
      "type" and yields an incompatible union; update both makeTerminalStartedEvent
      and makeTerminalActivityEvent to accept overrides: Partial<Omit<TerminalEvent,
      "type">> (i.e., exclude the "type" field from the override) so the functions
      keep their fixed discriminant ("started" or "activity") while still allowing
      other fields to be overridden; keep the return type as TerminalEvent and spread
      overrides as before.
    6. @@ -334,7 +427,8 @@
      334427 if (input.deleteHistory) {
      335428 await this.deleteAllHistoryForThread(input.threadId);
      336429 }
      430+ this.updateSubprocessPollingState();
      337431 });
      338432 }
      339433
      340434 dispose(): void {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      src/terminalManager.ts:434 Consider adding a disposed flag that's checked by runWithThreadLock or startSession. Currently, pending open operations can complete after dispose, restarting the subprocess polling timer and leaking resources.

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

      🤖 Prompt for AI
      In file apps/server/src/terminalManager.ts around line 434:
      
      Consider adding a `disposed` flag that's checked by `runWithThreadLock` or `startSession`. Currently, pending `open` operations can complete after `dispose`, restarting the subprocess polling timer and leaking resources.
    7. apps/server/src/terminalManager.ts lines 712 to 713Resolvedby juliusmarminge
    8. juliusmarminge merged this804572c

    9. juliusmarminge closed this

Sign in to join this conversation.