Skip to content

Cli Fixes#330

Merged
arul28 merged 3 commits into
mainfrom
ade/cli-fixes-87ec38d0
May 22, 2026
Merged

Cli Fixes#330
arul28 merged 3 commits into
mainfrom
ade/cli-fixes-87ec38d0

Conversation

@arul28
Copy link
Copy Markdown
Owner

@arul28 arul28 commented May 21, 2026

Summary

Describe the change.

What Changed

Key files and behaviors.

Validation

How you tested.

Risks

Anything to watch.

ADE   Open in ADE  ·  ade/cli-fixes-87ec38d0 branch  ·  PR #330

Summary by CodeRabbit

  • New Features

    • Added support for configurable startup delay when launching terminal sessions, allowing commands to execute after a specified interval.
  • Tests

    • Added test coverage for delayed startup command execution behavior.
    • Added test coverage for optimistic terminal session reconciliation and lifecycle cleanup.

Review Change Stack

Greptile Summary

This PR completes the fix for the startupTimer handle not being stored on the PTY entry: the handle is now persisted on entry.startupTimer, cleared in both closeEntry and dispose, and self-nulled inside the callback — exactly matching the existing aiTitleTimer pattern. A new test covers the dispose-during-delay scenario, and docs are updated to reflect the delay clamping, unref, and Work-CLI use case.

  • ptyService.ts: PtyEntry gains a startupTimer field; both closeEntry (natural exit) and dispose (explicit kill) now clear the timer before the async pty.kill() completes, preventing stale closures from firing after PTY teardown.
  • ptyService.test.ts: New test creates a PTY with a 180 ms startup delay, disposes it immediately, advances fake timers to 180 ms, and asserts pty.write was never called — directly validating the fix.
  • AgentChatPane.tsx: Module-level constant renamed from WORK_CLI_STARTUP_DELAY_MS to workCliStartupDelayMs (camelCase); no behavioral change.

Confidence Score: 5/5

Safe to merge — the timer lifecycle is now correctly managed across both natural-exit and explicit-dispose paths, with a test validating the fixed race condition.

The change is targeted and well-scoped: the timer handle is stored, cleared in every teardown path, and the callback guards with an entry.disposed check as belt-and-suspenders. The new test directly exercises the previously broken case. No behavioral regressions are expected.

No files require special attention.

Important Files Changed

Filename Overview
apps/desktop/src/main/services/pty/ptyService.ts Stores startupTimer on PtyEntry, clears it in both closeEntry and dispose, and self-nulls in the callback — fully matching the aiTitleTimer pattern.
apps/desktop/src/main/services/pty/ptyService.test.ts Adds a test verifying that dispose during the startup-delay window prevents the startup command write; correctly uses fake timers and advances by exactly the delay.
apps/desktop/src/renderer/components/chat/AgentChatPane.tsx Renames WORK_CLI_STARTUP_DELAY_MS to workCliStartupDelayMs (camelCase); no functional change, value remains 180.
docs/features/terminals-and-sessions/pty-and-processes.md Expands the create-flow description with accurate detail about startupDelayMs clamping, unref, timer cancellation, and the renderer Work-CLI use case.
docs/features/terminals-and-sessions/ui-surfaces.md Documents the optimistic ptyId merge race fix and adds startupDelayMs to the launchPtySession helper signature description.
docs/features/chat/README.md Updates AgentChatPane description to mention workCliStartupDelayMs and the intentional direct-argv skip for Work CLI launches.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant ptyService
    participant entry as PtyEntry
    participant timer as setTimeout
    participant pty as node-pty

    Caller->>ptyService: "create({ startupCommand, startupDelayMs: 180 })"
    ptyService->>entry: "init (startupTimer = null)"
    ptyService->>timer: setTimeout(writeStartupCommand, 180)
    ptyService->>entry: "entry.startupTimer = handle"
    ptyService-->>Caller: "{ ptyId, sessionId }"

    alt dispose() called before timer fires
        Caller->>ptyService: "dispose({ ptyId, sessionId })"
        ptyService->>entry: "entry.disposed = true"
        ptyService->>timer: clearTimeout(entry.startupTimer)
        ptyService->>entry: "entry.startupTimer = null"
        ptyService->>pty: pty.kill()
        Note over timer: timer cancelled — write never happens
    else timer fires normally
        timer->>ptyService: writeStartupCommand()
        ptyService->>entry: "entry.startupTimer = null"
        ptyService->>entry: check entry.disposed (false)
        ptyService->>pty: pty.write(command)
    end
Loading

Reviews (4): Last reviewed commit: "ship: iteration 2 - address coderabbit n..." | Re-trigger Greptile

@vercel
Copy link
Copy Markdown

vercel Bot commented May 21, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
ade Ignored Ignored Preview May 21, 2026 11:59pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 21, 2026

📝 Walkthrough

Walkthrough

This PR adds configurable startup delay for PTY terminal sessions with lifecycle safeguards, propagates the delay parameter through renderer callbacks, and improves optimistic session reconciliation when persisted rows are refreshed from the server.

Changes

Startup delay and session optimization

Layer / File(s) Summary
PTY startup delay contract and core implementation
apps/desktop/src/shared/types/sessions.ts, apps/desktop/src/main/services/pty/ptyService.ts
PtyCreateArgs gains optional startupDelayMs field. PtyEntry state extended with startupTimer field initialized to null. Validation helper normalizeStartupCommandDelayMs() clamps delay to [0, MAX_STARTUP_COMMAND_DELAY_MS]. Startup command write path schedules via setTimeout with unref() when delay > 0, or executes immediately; timer is cleared on PTY close and disposal to prevent writes after teardown.
PTY service startup delay tests
apps/desktop/src/main/services/pty/ptyService.test.ts
Two new test cases verify delayed writes are postponed until startupDelayMs elapses (using fake timers) and that pending delayed writes are canceled on service.dispose() before the timer fires.
Renderer callback type propagation and wiring
apps/desktop/src/renderer/components/chat/AgentChatPane.tsx, apps/desktop/src/renderer/components/terminals/WorkStartSurface.tsx, apps/desktop/src/renderer/components/terminals/WorkViewArea.tsx, apps/desktop/src/renderer/components/terminals/useWorkSessions.ts
Callback argument types for onLaunchCliSession and onLaunchPtySession extended with optional startupDelayMs?: number. AgentChatPane introduces WORK_CLI_STARTUP_DELAY_MS constant (180ms) and passes it via the callback; CLI launch payload no longer includes command/args fields. useWorkSessions.launchPtySession() forwards startupDelayMs to window.ade.pty.create() when provided.
Optimistic session reconciliation
apps/desktop/src/renderer/components/terminals/useWorkSessions.ts
New mergePendingOptimisticSession() helper determines whether pending optimistic sessions should merge into persisted "running" rows (by matching ptyId and filling missing toolType/runtimeState). refresh() now uses a rowIndexById map for fetched rows, expires optimistic entries by TTL, merges into existing persisted rows using the helper, and appends remaining valid pending sessions while keeping the index synchronized.
Integration test updates
apps/desktop/src/renderer/components/terminals/useWorkSessions.test.ts, apps/desktop/src/renderer/components/chat/AgentChatPane.submit.test.tsx
New test case verifies launchPtySession preserves optimistic ptyId when refresh returns stale row with null ptyId. Persistent identity view clear test updated with new transcript text fixture. Tracked CLI session launch test updated to expect startupDelayMs: 180, tracked: true, and asserts command/args are undefined.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • arul28/ADE#199: Both PRs modify apps/desktop/src/main/services/pty/ptyService.ts's startup-command handling: this PR delays/cleans up the startupCommand write via startupTimer, while PR #199 backfills missing resume targets and updates the resume-derived startupCommand before startup.

Suggested labels

desktop

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Cli Fixes' is vague and generic, using non-descriptive phrasing that does not convey meaningful information about the specific changes in the changeset. Consider a more descriptive title that captures the main change, such as 'Add startup delay configuration for CLI sessions' or 'Support delayed startup commands in PTY with optimistic session merging'.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ade/cli-fixes-87ec38d0

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.

@arul28
Copy link
Copy Markdown
Owner Author

arul28 commented May 21, 2026

@copilot review but do not make fixes

@capy-ai
Copy link
Copy Markdown

capy-ai Bot commented May 21, 2026

Capy auto-review is paused for this organization because the monthly auto-review limit has been reached. Increase the limit or turn it off in billing settings to resume automatic reviews.

@arul28
Copy link
Copy Markdown
Owner Author

arul28 commented May 21, 2026

@copilot review but do not make fixes

Copy link
Copy Markdown
Contributor

@cursor cursor Bot left a comment

Choose a reason for hiding this comment

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

PR Review

Scope: 12 file(s), +219 / −30
Verdict: Looks good

This PR fixes Work-tab CLI launch races: it defers typing startupCommand into the shell (180 ms, clamped in main), routes Work chat launches through the shell + startupCommand path instead of direct argv, and merges optimistic PTY ids into persisted session rows when a refresh lands before ptyId is backfilled. The changes are focused, tested, and align with the terminals docs.


Notes

  • Optimistic merge (mergePendingOptimisticSession in useWorkSessions.ts) correctly targets the race where listSessions returns a running row with a null/mismatched ptyId while the live create result is already known; keepPending until ids match is the right follow-up behavior.
  • Startup delay is bounded in main (normalizeStartupCommandDelayMs, max 1000 ms), guarded on dispose before write, and covered by a fake-timer test in ptyService.test.ts.
  • Work CLI path intentionally drops command / args so launches always go through shell + delayed startupCommand, which matches the documented fix for half-rendered scrollback and shell-shim resolution; other launchPtySession callers can still pass command / args and omit startupDelayMs.
  • Not verified in this run: full desktop test suite or manual Work-tab launch on macOS; review is based on diff + targeted file reads.
Open in Web View Automation 

Sent by Cursor Automation: BUGBOT in Versic

Comment thread apps/desktop/src/main/services/pty/ptyService.ts
Copy link
Copy Markdown
Contributor

Copilot AI commented May 21, 2026

@copilot review but do not make fixes

Reviewed commit 0f28f6c without making fixes. I didn’t find any blocking correctness issues in the submitted changes. Validation note: targeted tests for the touched files passed except one environment-sensitive assertion in ptyService.test.ts (TERM expected xterm-256color vs observed xterm-color in this runner).

@arul28
Copy link
Copy Markdown
Owner Author

arul28 commented May 21, 2026

@copilot review but do not make fixes

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
apps/desktop/src/renderer/components/chat/AgentChatPane.tsx (1)

155-155: ⚡ Quick win

Rename this constant to camelCase for guideline compliance.

Line 155 introduces a new constant using SCREAMING_SNAKE_CASE; this file should use camelCase variable names per project rule.

♻️ Proposed rename
-const WORK_CLI_STARTUP_DELAY_MS = 180;
+const workCliStartupDelayMs = 180;
-          startupDelayMs: WORK_CLI_STARTUP_DELAY_MS,
+          startupDelayMs: workCliStartupDelayMs,

As per coding guidelines, **/*.{ts,tsx,js,jsx}: Use camelCase for variable names in TypeScript/JavaScript files.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/renderer/components/chat/AgentChatPane.tsx` at line 155,
Rename the constant WORK_CLI_STARTUP_DELAY_MS to camelCase (e.g.,
workCliStartupDelayMs) throughout AgentChatPane.tsx: update its declaration and
every usage site (references in functions, JSX, hooks) so identifiers match, and
run a quick type-check to ensure no remaining references to the old name remain;
keep the numeric value (180) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@apps/desktop/src/renderer/components/chat/AgentChatPane.tsx`:
- Line 155: Rename the constant WORK_CLI_STARTUP_DELAY_MS to camelCase (e.g.,
workCliStartupDelayMs) throughout AgentChatPane.tsx: update its declaration and
every usage site (references in functions, JSX, hooks) so identifiers match, and
run a quick type-check to ensure no remaining references to the old name remain;
keep the numeric value (180) unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5db3842e-a524-4455-9787-ac312e62b760

📥 Commits

Reviewing files that changed from the base of the PR and between 03a9163 and 56b4f4d.

⛔ Files ignored due to path filters (3)
  • docs/features/chat/README.md is excluded by !docs/**
  • docs/features/terminals-and-sessions/pty-and-processes.md is excluded by !docs/**
  • docs/features/terminals-and-sessions/ui-surfaces.md is excluded by !docs/**
📒 Files selected for processing (9)
  • apps/desktop/src/main/services/pty/ptyService.test.ts
  • apps/desktop/src/main/services/pty/ptyService.ts
  • apps/desktop/src/renderer/components/chat/AgentChatPane.submit.test.tsx
  • apps/desktop/src/renderer/components/chat/AgentChatPane.tsx
  • apps/desktop/src/renderer/components/terminals/WorkStartSurface.tsx
  • apps/desktop/src/renderer/components/terminals/WorkViewArea.tsx
  • apps/desktop/src/renderer/components/terminals/useWorkSessions.test.ts
  • apps/desktop/src/renderer/components/terminals/useWorkSessions.ts
  • apps/desktop/src/shared/types/sessions.ts

@arul28
Copy link
Copy Markdown
Owner Author

arul28 commented May 21, 2026

@copilot review but do not make fixes

@arul28 arul28 force-pushed the ade/cli-fixes-87ec38d0 branch from e226b29 to d127917 Compare May 21, 2026 23:59
@arul28
Copy link
Copy Markdown
Owner Author

arul28 commented May 21, 2026

@copilot review but do not make fixes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants