Skip to content

fix: regenerate TASK.md on local task updates & improve session management - #76

Merged
fum4 merged 8 commits into
masterfrom
fix/project-conversation-management-and-taskmd
Mar 17, 2026
Merged

fum4 merged 8 commits into
masterfrom
fix/project-conversation-management-and-taskmd

Conversation

@LunatiqueCoder

@LunatiqueCoder LunatiqueCoder commented Mar 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • TASK.md sync bug: Local task description/title updates via the dashboard now regenerate TASK.md in the linked worktree, so agents always see current context. Previously the PATCH /api/tasks/:id handler saved to task.json but never called regenerateTaskMd().
  • Port allocation: Desktop app now checks actual port availability (not just tracked ports) to avoid collisions with leftover server processes. Server emits __OPENKIT_PORT__ on stdout so Electron can correct the port if findAvailablePort() picks a different one.
  • Agent history: Filters out automated OpenKit prompts from session titles/previews, exposes gitBranch in history matches for better disambiguation in the restore modal, and adds debug logging for diagnosing cross-project session confusion.
  • Logging: Replaces appendFileSync debug log in server-spawner.ts with the project logger.

Test plan

  • New tasks.test.ts — verifies TASK.md regeneration on description update (with/without linked worktree, error resilience, persistence)
  • New agent-history.test.ts — covers automated prompt filtering, preview extraction, session matching
  • All 263 server tests pass
  • Manual: create local task → create worktree → update description in dashboard → verify TASK.md reflects new description

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Agent sessions now include Git branch info
    • Project label added to agent restoration UI
  • Improvements

    • Async port allocation with pending-port tracking, runtime port reconciliation, and buffered stdout/stderr parsing
    • Server readiness probing adapts to dynamic port selection
    • Centralized logging and clearer spawn/startup error handling
    • Restore flow guards against switching projects mid-request
    • Safer TASK.md regeneration when updating tasks
  • Tests

    • Extensive new tests for agent-history, task routes, detail panel, and project manager

…on management

Local task description/title changes via the dashboard were not reflected in
TASK.md because the PATCH handler never called regenerateTaskMd(). This caused
agents to read stale context. Now task updates trigger TASK.md regeneration
when a linked worktree exists, matching the existing pattern in the notes routes.

Also fixes port allocation race conditions by checking actual port availability,
improves agent history matching by filtering automated prompts and exposing
git branch info, and replaces debug file logging with the project logger.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@vercel

vercel Bot commented Mar 16, 2026 •

Copy link
Copy Markdown

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

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
openkit Skipped Skipped Mar 17, 2026 9:04pm

@coderabbitai

coderabbitai Bot commented Mar 16, 2026 •

Copy link
Copy Markdown

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

Walkthrough

Adds async port allocation with pending-port tracking and release, buffered stdout/stderr parsing for runtime port reconciliation, dynamic readiness polling via a port getter, centralized spawn logging, Claude transcript helpers and gitBranch/sourceFile metadata, TASK.md regeneration on task updates (optional HooksManager), plus related tests and UI tweaks.

Changes

Cohort / File(s) Summary
Desktop port & spawn
apps/desktop-app/src/project-manager.ts, apps/desktop-app/src/server-spawner.ts
Make port allocation async with pendingPorts tracking and releasePendingPort; buffer stdout/stderr to parse __OPENKIT_PORT__ markers and reconcile runtime port; waitForServerReady accepts a port number or getter; replace local debug prints with centralized logger; callers updated to await allocatePort.
Server port emission & routes
apps/server/src/index.ts, apps/server/src/routes/tasks.ts, apps/server/src/routes/terminal.ts
Server now emits __OPENKIT_PORT__=N to stdout on listen; registerTaskRoutes signature optionally accepts hooksManager and triggers non-fatal regenerateTaskMd for linked worktrees; terminal restore flow adds additional lookup logs.
Agent history logic & tests
apps/server/src/routes/agent-history.ts, apps/server/src/routes/agent-history.test.ts
Export ClaudeTranscriptEvent; add isOpenKitAutomatedPrompt and extractClaudeMessagePreview; include gitBranch and internal sourceFile in match construction; add verbose debug and fallback title logic; comprehensive tests added.
Task routes tests
apps/server/src/routes/tasks.test.ts
Add tests covering PATCH /api/tasks/:id behavior: persistence of description, regen TASK.md success/skip/failure scenarios, and regeneration call arguments with hooks snapshot.
Desktop tests & behavior
apps/desktop-app/src/project-manager.test.ts
Add extensive tests for port allocation (including pending-port collisions, system-occupied ports, no-ports-available), stdout port correction across chunk boundaries, startup errors, close/restore projects, and onChange events.
Web UI: Detail panel & types
apps/web-app/src/components/detail/DetailPanel.tsx, apps/web-app/src/hooks/api.ts, apps/web-app/src/components/detail/DetailPanel.test.tsx
DetailPanel tracks requestWorktreeId to guard stale restore responses; UI shows Branch: <branch> when present; AgentHistoryMatch type gains optional gitBranch; tests added for stale-response suppression and modal display/branch rendering.

Sequence Diagram(s)

sequenceDiagram
    participant Desktop as Desktop App\n(project-manager)
    participant Spawner as Server Spawner\n(server-spawner)
    participant Server as Server Process\n(apps/server)

    Desktop->>Desktop: allocatePort() (async) → probe ports, mark pending
    Desktop->>Spawner: spawn CLI with requested port
    Spawner->>Server: start process (env, args)
    activate Server
    Server->>Server: bind to actualPort
    Server->>Spawner: stdout: "__OPENKIT_PORT__=N"
    Spawner->>Spawner: waitForServerReady(getPort) polls dynamic port
    Spawner-->>Desktop: ready confirmation
    Desktop->>Desktop: update project.port, release pending port
    deactivate Server
Loading
sequenceDiagram
    participant Web as Web App\n(DetailPanel)
    participant API as Server\n(routes/terminal)
    participant FS as File System\n(agent-history)

    Web->>API: GET /api/.../restore?worktreeId=...
    activate API
    API->>FS: findClaudeHistoryMatches(cwd) (read JSONL, extract previews, gitBranch)
    FS-->>API: matches[]
    API->>API: log terminal.agent.restore.lookup (metadata)
    API-->>Web: {activeSessionId, matches, resolvedWorktreePath}
    Web->>Web: render matches (show Branch when gitBranch present)
    deactivate API
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I nibbled at pending ports in rows,
Marked whispers in stdout where the true port shows.
Branch names and sessions tucked in a neat file,
Tasks regrown, no panic—just a rabbit's mild smile.
Tiny hops, tidy fixes, wide-eyed compile.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the two main changes: TASK.md regeneration on task updates and session management improvements including port allocation and agent history filtering.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/project-conversation-management-and-taskmd
📝 Coding Plan
  • Generate coding plan for human review comments

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

Copy link
Copy Markdown
Contributor

Code Review

🔴 Major

  1. Silent catch block in tasks.ts:453-455 — The catch block after regenerateTaskMd is empty, violating the project's error handling rules (CLAUDE.md: "Silent catch {} blocks are never acceptable"). At minimum, log the error with context.
// apps/server/src/routes/tasks.ts:453
} catch {
  // Non-critical — don't fail the task update
}

Should be:

} catch (err) {
  log.warn(`Failed to regenerate TASK.md for ${task.id}`, {
    domain: "tasks",
    taskId: task.id,
    worktreeId: linkedWorktreeId,
    error: err instanceof Error ? err.message : String(err),
  });
}
  1. Port protocol message on stdout could corrupt structured output — apps/server/src/index.ts:522 writes __OPENKIT_PORT__=<port>\n to raw stdout. If anything downstream parses stdout as JSON or structured data (e.g., JSON-RPC), this unframed line could break parsing. The process.send() IPC mechanism (line 519) is the correct approach for Electron; the stdout write is redundant and risky.

🟠 Medium

  1. isPortFree timeout leaks the server handle on timeout — In apps/desktop-app/src/project-manager.ts:14-16, the timeout calls server.close() but the server might still be in a pending listen() state. If listen() succeeds after the timeout fires, the listening handler also calls server.close() and clearTimeout(timeout) on an already-fired timeout. While not catastrophic, the double-close and resolved promise are race-prone. Consider using server.close() + removing listeners + resolve(false) more defensively.

  2. allocatePort makes sequential network calls in a tight loop — apps/desktop-app/src/project-manager.ts:119 calls await isPortFree(port) for each port sequentially, with a 5-second timeout per attempt. In the worst case (many ports in use), this could hang for a very long time. Consider reducing the timeout (e.g., 500ms is plenty for a local bind check) or adding a max-attempts guard.

  3. Stdout data events may split across chunks — apps/desktop-app/src/project-manager.ts:206-219 splits stdout by \n and regex-matches __OPENKIT_PORT__. Node stream data events don't guarantee line boundaries — a line could be split across two chunks. Use a line-buffering approach or handle partial lines.

  4. tasks.test.ts:160 calls registerTaskRoutes without hooksManager — The test at line 160 omits the 4th argument, relying on the optional parameter. This is technically valid but means the getHooksSnapshot path returns undefined, and the test doesn't cover the hooks integration at all. More importantly, this means the regenerateTaskMd call in that test gets undefined for the hooks snapshot — ensure regenerateTaskMd handles that gracefully.

  5. waitForServerReady signature change is not backward-compatible — apps/desktop-app/src/server-spawner.ts:74 changes the first parameter from number to number | (() => number). Verify all callers have been updated. The union type works but adds runtime cost on every poll iteration; a breaking change to just () => number with callers wrapping their constant would be cleaner.

🟡 Minor

  1. Unused imports in test file — apps/server/src/routes/tasks.test.ts:1 imports existsSync and readdirSync from fs but neither is used in the test file.

  2. Debug logging with matches array could be verbose — apps/server/src/routes/agent-history.ts:237-245 logs all match details including truncated titles. For sessions with many matches, this could be noisy at debug level. Consider logging only the count and session IDs.

  3. Whitespace-only changes in DetailPanel.tsx — Lines 972 and 1032 add blank lines with no functional change. These are noise in the diff.

  4. resolvedWorktreePath exposed in API response — apps/server/src/routes/terminal.ts:180 adds resolvedWorktreePath to the JSON response. This leaks internal filesystem paths to the client, which is generally unnecessary for the frontend and mildly undesirable from a security standpoint.

The getHooksSnapshot helper in tasks.ts returned { config, worktreeId } instead
of the { checks, skills } shape that regenerateTaskMd expects (HooksInfo).
Matches the working pattern from notes.ts. Fixes CI typecheck failure.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions

github-actions Bot commented Mar 17, 2026 •

Copy link
Copy Markdown
Contributor

Clode Review

🟠 Medium

  1. hooksManager parameter is optional but now has a log.warn — apps/server/src/routes/tasks.ts:194: The parameter is still typed as optional (hooksManager?: HooksManager). The log.warn when absent is a good improvement, but since the only real caller (apps/server/src/index.ts:360) now passes it, making it required would be cleaner and catch regressions at compile time.

  2. Debug log unconditionally allocates .map() result — apps/server/src/routes/agent-history.ts:234-245: The sorted.map() inside the debug log block still runs on every call with matches, even when debug logging is disabled. Wrap the log.debug call and its payload construction in a guard or move the .map() inline.

🟡 Minor

  1. _sourceFile replaced but sourceFile still leaks into intermediate type — apps/server/src/routes/agent-history.ts:164,230-240: The sourceFile field is added to the intermediate map entries and used only for debug logging. The final .map() now explicitly picks fields, so it doesn't leak to the API — good. But the intermediate type & { sourceFile: string } could be a named interface for clarity.

  2. DetailPanel.test.tsx uses userEvent.setup() but imports userEvent from render — apps/web-app/src/components/detail/DetailPanel.test.tsx:3,128: The test imports userEvent from ../../test/render and calls userEvent.setup(). Verify this re-export works correctly — typically @testing-library/user-event is imported directly. If the render helper already sets up userEvent, the .setup() call may be redundant or conflicting.

  3. Dual stdout listeners comment added — apps/desktop-app/src/server-spawner.ts:74-75: The comment explaining dual listeners was added as suggested. Good.

🟢 Resolved

  1. Silent catch block in task update — Previously apps/server/src/routes/tasks.ts:459 had a bare catch {}. Now replaced with proper logging via logTaskEvent with level, status, worktreeId, and error metadata (tasks.ts:471-484).

  2. stdout parsing is fragile with buffered/split data — apps/desktop-app/src/project-manager.ts:229-248 now implements proper line buffering (stdoutBuffer/stderrBuffer), accumulating chunks and splitting on complete lines.

  3. Whitespace-only changes in DetailPanel.tsx — No longer present; changes are substantive (worktree switch race fix, git branch display, project name display).

  4. registerTaskRoutes called without hooksManager in test — apps/server/src/routes/tasks.test.ts:178 now passes createMockHooksManager() in all tests, including the "persists the updated description" case.

  5. Port scan sequential with 5-second timeout — Timeout reduced to 200ms (project-manager.ts:23), server.unref() is now called (project-manager.ts:20), and upper-bound check (port <= 65535) with error thrown if exhausted.

  6. Worktree-switch bail-out leaks isResolvingAgentRestore state — apps/web-app/src/components/detail/DetailPanel.tsx:999,1074: The bail-out now calls setIsResolvingAgentRestore((prev) => (prev === "claude" ? null : prev)) before returning, preventing the UI from getting stuck in a "resolving" state.

  7. resolvedWorktreePath still exposed in API response — apps/server/src/routes/terminal.ts:180: The resolvedWorktreePath is only in log metadata, not in the c.json() response body.

  8. Redundant process.send and process.stdout.write — The old debug() function writing to /tmp/OpenKit-debug.log has been replaced with proper log.* calls throughout server-spawner.ts. The process.stdout.write in apps/server/src/index.ts:592 is the intentional port-discovery protocol message.

  9. isPortFree timeout still 1000ms / no server.unref() — Timeout reduced to 200ms (project-manager.ts:23) and server.unref() is now called (project-manager.ts:20).

  10. Modal removed "Choose which one to resume" call-to-action — apps/web-app/src/components/detail/DetailPanel.tsx:2251: The CTA text "Choose which one to resume." is restored, and the project name badge is shown as supplementary context alongside it.

  11. Test cleanup uses afterAll instead of afterEach — apps/server/src/routes/tasks.test.ts:47-54: Cleanup now uses afterEach with a tempDirs array pattern, cleaning up after each test.

  12. _sourceFile destructuring style — apps/server/src/routes/agent-history.ts:230-240: The underscore-prefixed destructuring is replaced with an explicit field-picking .map() that constructs clean AgentHistoryMatch objects.

  13. Dual stdout listeners on server process — apps/desktop-app/src/server-spawner.ts:74-75: Comment added explaining the dual-listener design.

  14. DetailPanel.test.tsx uses fireEvent.click instead of userEvent — apps/web-app/src/components/detail/DetailPanel.test.tsx:128: Tests now use userEvent.setup() and user.click() instead of fireEvent.click.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/web-app/src/components/detail/DetailPanel.tsx (1)

967-1008: ⚠️ Potential issue | 🟠 Major

Ignore stale restore responses after the worktree changes.

Both handlers await the restore lookup and then unconditionally launch/open the modal using the captured worktree.id. If the user switches worktrees before the request resolves, the old response can reopen the restore modal or resume an agent for the previous worktree, which recreates the cross-project confusion this PR is trying to fix.

Gate the post-await path behind a request token or a ref holding the current worktree id.

Also applies to: 1027-1069

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/components/detail/DetailPanel.tsx` around lines 967 - 1008,
The async restore handlers (the IIFE that calls api.fetchRestorableAgentSessions
and the similar handler around lines 1027-1069) must ignore stale responses when
the user switches worktrees: before awaiting, capture a request token or the
current worktree.id in a ref (e.g., restoreRequestRef.current = worktree.id or
incrementing token) and after the await, verify the token/ref still matches the
current worktree id; if not, bail out without calling
setIsResolvingAgentRestore, setAgentRestoreModal, launchAgentIntent, or
handleStartNewConversation. Apply this check around the
fetchRestorableAgentSessions call and the post-await control flow so only
responses for the active worktree are applied.
apps/desktop-app/src/server-spawner.ts (1)

88-105: ⚠️ Potential issue | 🟠 Major

Log why readiness polling timed out.

This catch {} is now part of the dynamic port-correction path, but it drops the fetch error and the probed port entirely. When startup times out you'll have no way to tell whether the wrong port was used, the server never bound, or fetch itself failed. Keep the last error and emit one log.warn()/log.error() with domain, port, and timeout before returning false.

🛠️ Suggested fix
 export async function waitForServerReady(
   getPort: number | (() => number),
   timeout = 30000,
 ): Promise<boolean> {
   const start = Date.now();
+  let lastError: string | null = null;
 
   while (Date.now() - start < timeout) {
     const port = typeof getPort === "function" ? getPort() : getPort;
     try {
       const res = await fetch(`http://localhost:${port}/api/config`);
       if (res.ok) return true;
-    } catch {
-      // Server not ready yet
+    } catch (error) {
+      lastError = error instanceof Error ? error.message : String(error);
     }
     await new Promise((resolve) => setTimeout(resolve, 500));
   }
+
+  log.warn("Server readiness timed out", {
+    domain: "server-spawner",
+    port: typeof getPort === "function" ? getPort() : getPort,
+    timeout,
+    lastError,
+  });
 
   return false;
 }
As per coding guidelines, "Every catch block, every fallback branch, every error callback must do something meaningful: log through the appropriate logger (`log.error()` / `log.warn()`), surface to the user via toast, or both" and "Include actionable metadata in error logs: what operation failed, what inputs caused it, and any IDs or state needed to reproduce."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop-app/src/server-spawner.ts` around lines 88 - 105, The readiness
loop in waitForServerReady swallows fetch errors and loses the last probed port;
capture the last thrown error and the last tested port (from getPort) inside the
catch, and when the timeout elapses call log.warn() or log.error() with
contextual metadata (domain "http://localhost", the last port, and the timeout)
plus the last error message before returning false; update waitForServerReady to
declare e.g. let lastError and let lastPort, set them on each iteration/catch,
and emit the single warning/error using those variables just prior to returning
false.
🧹 Nitpick comments (2)
apps/server/src/routes/agent-history.ts (1)

6-6: Use the configured alias instead of ../logger.

This new import breaks the app/lib source rule for cross-folder references. Please switch it to the configured alias form rather than adding another parent-relative path from routes/.

As per coding guidelines, "Do not use parent-relative imports (for example ../ or ../../) in app/lib source files. Only same-folder relative imports are allowed (for example ./file). For anything outside the current folder, use configured aliases."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/agent-history.ts` at line 6, Replace the
parent-relative import of the logger in agent-history.ts (import { log } from
"../logger") with the project's configured alias import for the shared logger
module; update the import that brings in the log symbol (used in this file) to
use the alias form (the same alias other app/lib modules use for logger) so the
file no longer uses a ../ parent-relative path.
apps/server/src/routes/tasks.test.ts (1)

160-182: Consider adding temp directory cleanup.

The test correctly verifies persistence to task.json. However, temp directories created by createTempConfigDir() are never cleaned up. While not critical, this could accumulate disk usage in CI environments.

♻️ Optional: Add afterAll cleanup
+const tempDirs: string[] = [];
+
 function createTempConfigDir(): string {
   const dir = path.join(
     tmpdir(),
     `openkit-tasks-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
   );
   mkdirSync(dir, { recursive: true });
+  tempDirs.push(dir);
   return dir;
 }
+
+afterAll(() => {
+  for (const dir of tempDirs) {
+    try {
+      rmSync(dir, { recursive: true, force: true });
+    } catch {
+      // Ignore cleanup errors in tests
+    }
+  }
+});

You'd also need to add rmSync to the imports from fs.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/tasks.test.ts` around lines 160 - 182, The test
creates temporary config dirs via createTempConfigDir() but never removes them;
add an afterAll cleanup in the test file that calls rmSync on the temp
directory(s) created during the tests (or track created dirs in an array and
rmSync each), and update the imports to include rmSync from fs so the cleanup
can remove the created directory created by createTempConfigDir() after the
suite runs; ensure you reference the same temp dir variable returned by
createTempConfigDir() used in this test (and any other tests) so the correct
path is removed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop-app/src/project-manager.ts`:
- Around line 116-127: allocatePort() currently snapshots this.projects and can
race between concurrent openProject() calls, and it throws "No available port
found" outside the openProject() try path; to fix, add a pendingPorts Set on the
ProjectManager instance, change allocatePort() to reserve the chosen port in
pendingPorts before yielding (and skip ports present in pendingPorts), ensure
callers (openProject() and the restoreProjects() path that runs multiple opens)
call allocatePort() inside the startup try block (so allocation and reservation
happen inside the guarded path), and change the error flow so failures from
allocatePort() are returned as { success: false, error } from openProject()
rather than letting allocatePort() throw unhandled; also update the other call
site referenced (lines 166-167) to use the same pattern of allocating/reserving
inside the guarded startup and releasing from pendingPorts on both success and
all failure paths.
- Around line 204-221: The stdout/stderr data handlers can receive chunked
fragments so the regex for "__OPENKIT_PORT__=..." and multiline stderr messages
can be missed; fix by introducing per-stream string buffers (e.g., stdoutBuffer
and stderrBuffer) used inside the serverProcess.stdout?.on("data", ...) and
serverProcess.stderr?.on("data", ...) handlers: append incoming chunk.toString()
to the buffer, split by "\n" to process all complete lines (run the existing
portMatch logic on each complete line and call project.port assignment +
this.notifyChange() when matched), then keep the final partial fragment in the
buffer for the next event; apply the same buffering/splitting logic to the
stderr handler to preserve multiline error messages; add unit tests in
project-manager.test.ts that emit chunked data (split the "__OPENKIT_PORT__=..."
marker and multiline stderr across multiple "data" events) to assert
project.port updates and full stderr assembly.

In `@apps/server/src/routes/tasks.ts`:
- Around line 449-465: The empty catch after calling regenerateTaskMd silently
swallows failures; replace it with a catch that captures the error and logs a
warning with context (task.id and linkedWorktreeId) using the module logger
(e.g., logger.warn). Specifically, wrap the regenerateTaskMd call (which uses
resolveActiveLinkedWorktreeId, getHooksSnapshot, notesManager, configDir,
worktreesPath) in catch (err) and log a concise warning message including
task.id, linkedWorktreeId and the error object so failures are diagnosable
without failing the task update.

---

Outside diff comments:
In `@apps/desktop-app/src/server-spawner.ts`:
- Around line 88-105: The readiness loop in waitForServerReady swallows fetch
errors and loses the last probed port; capture the last thrown error and the
last tested port (from getPort) inside the catch, and when the timeout elapses
call log.warn() or log.error() with contextual metadata (domain
"http://localhost", the last port, and the timeout) plus the last error message
before returning false; update waitForServerReady to declare e.g. let lastError
and let lastPort, set them on each iteration/catch, and emit the single
warning/error using those variables just prior to returning false.

In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 967-1008: The async restore handlers (the IIFE that calls
api.fetchRestorableAgentSessions and the similar handler around lines 1027-1069)
must ignore stale responses when the user switches worktrees: before awaiting,
capture a request token or the current worktree.id in a ref (e.g.,
restoreRequestRef.current = worktree.id or incrementing token) and after the
await, verify the token/ref still matches the current worktree id; if not, bail
out without calling setIsResolvingAgentRestore, setAgentRestoreModal,
launchAgentIntent, or handleStartNewConversation. Apply this check around the
fetchRestorableAgentSessions call and the post-await control flow so only
responses for the active worktree are applied.

---

Nitpick comments:
In `@apps/server/src/routes/agent-history.ts`:
- Line 6: Replace the parent-relative import of the logger in agent-history.ts
(import { log } from "../logger") with the project's configured alias import for
the shared logger module; update the import that brings in the log symbol (used
in this file) to use the alias form (the same alias other app/lib modules use
for logger) so the file no longer uses a ../ parent-relative path.

In `@apps/server/src/routes/tasks.test.ts`:
- Around line 160-182: The test creates temporary config dirs via
createTempConfigDir() but never removes them; add an afterAll cleanup in the
test file that calls rmSync on the temp directory(s) created during the tests
(or track created dirs in an array and rmSync each), and update the imports to
include rmSync from fs so the cleanup can remove the created directory created
by createTempConfigDir() after the suite runs; ensure you reference the same
temp dir variable returned by createTempConfigDir() used in this test (and any
other tests) so the correct path is removed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 42d30f83-0978-44ad-93b6-b4c901ca3ad0

📥 Commits

Reviewing files that changed from the base of the PR and between de1881c and f80b05a.

📒 Files selected for processing (10)
  • apps/desktop-app/src/project-manager.ts
  • apps/desktop-app/src/server-spawner.ts
  • apps/server/src/index.ts
  • apps/server/src/routes/agent-history.test.ts
  • apps/server/src/routes/agent-history.ts
  • apps/server/src/routes/tasks.test.ts
  • apps/server/src/routes/tasks.ts
  • apps/server/src/routes/terminal.ts
  • apps/web-app/src/components/detail/DetailPanel.tsx
  • apps/web-app/src/hooks/api.ts

Comment thread apps/desktop-app/src/project-manager.ts Resolved
Comment on lines +204 to +221
// Listen for the server's actual port in case findAvailablePort() had to
// pick a different one (e.g. a leftover server still holds the requested port).
serverProcess.stdout?.on("data", (data: Buffer) => {
const text = data.toString();
for (const line of text.split("\n")) {
const portMatch = line.match(/^__OPENKIT_PORT__=(\d+)$/);
if (portMatch) {
const actualPort = parseInt(portMatch[1], 10);
if (actualPort !== project.port) {
log.debug(`Port corrected: requested ${project.port}, actual ${actualPort}`, {
domain: "port-allocation",
});
project.port = actualPort;
this.notifyChange();
}
}
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash

# Read the file to see the current implementation at lines 204-221
echo "=== Current code at lines 204-221 ==="
sed -n '200,225p' apps/desktop-app/src/project-manager.ts

# Also check the lines mentioned in "Also applies to: 252-254"
echo -e "\n=== Code at lines 252-254 ==="
sed -n '250,260p' apps/desktop-app/src/project-manager.ts

Repository: fum4/openkit

Length of output: 1600


🏁 Script executed:

#!/bin/bash

# Check if there's a test file for project-manager.ts
find apps/desktop-app -name "*project-manager*test*" -o -name "*project-manager*.test.ts"

# List nearby files to understand the structure
echo -e "\n=== Files in the directory ==="
ls -la apps/desktop-app/src/ | grep -E "project-manager|\.test\.ts"

Repository: fum4/openkit

Length of output: 223


🏁 Script executed:

#!/bin/bash

# Search for any use of stdout listeners in the file to see if there are other instances
echo "=== All stdout listeners in project-manager.ts ==="
rg "stdout.*on\(" apps/desktop-app/src/project-manager.ts -A 5

Repository: fum4/openkit

Length of output: 404


🏁 Script executed:

#!/bin/bash

# Check the stderr listener and surrounding context more thoroughly
echo "=== Lines 220-270 to see stderr and what's at 252-254 ==="
sed -n '220,270p' apps/desktop-app/src/project-manager.ts | cat -n

Repository: fum4/openkit

Length of output: 2230


🏁 Script executed:

#!/bin/bash

# Check for ALL data event listeners on stdout/stderr in the entire file
echo "=== All .on('data') listeners in project-manager.ts ==="
rg "\.on\(['\"]data['\"]" apps/desktop-app/src/project-manager.ts -B 2 -A 8

Repository: fum4/openkit

Length of output: 1055


Buffer stdout across chunks to avoid missing port marker if split across data events.

stdout data events are chunk-based, not line-based. If __OPENKIT_PORT__=... is split across two chunks, both fragments miss the regex and project.port never updates, causing the readiness probe to timeout even though the server started successfully.

The same buffering issue affects the stderr listener at lines 223–226, which also splits on \n without buffering and will lose multiline error messages split across chunks.

Suggested fix for stdout listener
+      let stdoutBuffer = "";
+
       // Listen for the server's actual port in case findAvailablePort() had to
       // pick a different one (e.g. a leftover server still holds the requested port).
       serverProcess.stdout?.on("data", (data: Buffer) => {
-        const text = data.toString();
-        for (const line of text.split("\n")) {
+        stdoutBuffer += data.toString();
+        const lines = stdoutBuffer.split("\n");
+        stdoutBuffer = lines.pop() ?? "";
+        for (const line of lines) {
           const portMatch = line.match(/^__OPENKIT_PORT__=(\d+)$/);
           if (portMatch) {
             const actualPort = parseInt(portMatch[1], 10);

Also apply the same buffering fix to the stderr listener (lines 223–226).

Add tests for this functionality in project-manager.test.ts per the coding guidelines.

📝 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
// Listen for the server's actual port in case findAvailablePort() had to
// pick a different one (e.g. a leftover server still holds the requested port).
serverProcess.stdout?.on("data", (data: Buffer) => {
const text = data.toString();
for (const line of text.split("\n")) {
const portMatch = line.match(/^__OPENKIT_PORT__=(\d+)$/);
if (portMatch) {
const actualPort = parseInt(portMatch[1], 10);
if (actualPort !== project.port) {
log.debug(`Port corrected: requested ${project.port}, actual ${actualPort}`, {
domain: "port-allocation",
});
project.port = actualPort;
this.notifyChange();
}
}
}
});
let stdoutBuffer = "";
// Listen for the server's actual port in case findAvailablePort() had to
// pick a different one (e.g. a leftover server still holds the requested port).
serverProcess.stdout?.on("data", (data: Buffer) => {
stdoutBuffer += data.toString();
const lines = stdoutBuffer.split("\n");
stdoutBuffer = lines.pop() ?? "";
for (const line of lines) {
const portMatch = line.match(/^__OPENKIT_PORT__=(\d+)$/);
if (portMatch) {
const actualPort = parseInt(portMatch[1], 10);
if (actualPort !== project.port) {
log.debug(`Port corrected: requested ${project.port}, actual ${actualPort}`, {
domain: "port-allocation",
});
project.port = actualPort;
this.notifyChange();
}
}
}
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop-app/src/project-manager.ts` around lines 204 - 221, The
stdout/stderr data handlers can receive chunked fragments so the regex for
"__OPENKIT_PORT__=..." and multiline stderr messages can be missed; fix by
introducing per-stream string buffers (e.g., stdoutBuffer and stderrBuffer) used
inside the serverProcess.stdout?.on("data", ...) and
serverProcess.stderr?.on("data", ...) handlers: append incoming chunk.toString()
to the buffer, split by "\n" to process all complete lines (run the existing
portMatch logic on each complete line and call project.port assignment +
this.notifyChange() when matched), then keep the final partial fragment in the
buffer for the next event; apply the same buffering/splitting logic to the
stderr handler to preserve multiline error messages; add unit tests in
project-manager.test.ts that emit chunked data (split the "__OPENKIT_PORT__=..."
marker and multiline stderr across multiple "data" events) to assert
project.port updates and full stderr assembly.

Comment thread apps/server/src/routes/tasks.ts Resolved
- prevent port allocation race in concurrent openProject() calls
  (added pendingPorts Set so parallel restoreProjects() can't collide)
- buffer stdout/stderr chunks in project-manager to avoid missing
  split port markers across data events
- log timeout context in waitForServerReady for diagnosability
- guard async restore handlers against stale worktree responses
  (prevents cross-project confusion when switching worktrees mid-request)
- log regenerateTaskMd failures instead of swallowing silently
- use @openkit/server/logger alias in agent-history route
- clean up temp directories in tasks.test.ts afterAll

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
apps/desktop-app/src/project-manager.ts (1)

11-30: Robust port availability check with timeout protection.

The isPortFree implementation correctly uses net.createServer to probe actual port availability. The 5-second timeout prevents indefinite hangs if the server never emits events.

Consider extracting the timeout as a constant for clarity:

♻️ Optional: Extract timeout constant
+const PORT_CHECK_TIMEOUT_MS = 5000;
+
 function isPortFree(port: number): Promise<boolean> {
   return new Promise((resolve) => {
     const timeout = setTimeout(() => {
       server.close();
       resolve(false);
-    }, 5000);
+    }, PORT_CHECK_TIMEOUT_MS);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop-app/src/project-manager.ts` around lines 11 - 30, The isPortFree
function currently hardcodes a 5000ms timeout inside the Promise; extract that
literal into a named constant (e.g., const PORT_CHECK_TIMEOUT = 5000) and
replace the inline 5000 with that constant to improve clarity and make the
timeout easy to adjust; keep the existing logic around server
(net.createServer), timeout, server.once("error"), server.once("listening"),
server.close(), and server.listen(port) unchanged while ensuring the constant is
declared in the same module scope above isPortFree.
apps/server/src/routes/agent-history.ts (1)

60-62: Pre-existing silent catch blocks should be addressed.

While not introduced in this PR, the empty catch blocks at lines 60-62 and 88-90 violate the coding guidelines. Consider logging a warning when directory reads or JSON parsing fails:

🛡️ Suggested improvement for readJsonLines
 function readJsonLines(filePath: string): unknown[] {
   try {
     const raw = readFileSync(filePath, "utf-8");
     return raw
       .split("\n")
       .map((line) => line.trim())
       .filter((line) => line.length > 0)
       .map((line) => JSON.parse(line));
-  } catch {
+  } catch (err) {
+    log.debug("Failed to read JSONL file", {
+      domain: "agent-history",
+      filePath,
+      error: err instanceof Error ? err.message : String(err),
+    });
     return [];
   }
 }

As per coding guidelines: "Never swallow errors silently. If you genuinely cannot handle an error, re-throw it or log it at warn/error level with context."

Also applies to: 88-90

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/agent-history.ts` around lines 60 - 62, The two empty
catch blocks in apps/server/src/routes/agent-history.ts (inside the
readJsonLines flow and the later JSON parsing block) are silently swallowing
errors; update the catch handlers in the functions (e.g., readJsonLines and the
JSON parsing loop that uses JSON.parse) to log a warning or error with context
(include the file/directory path and the caught error message) rather than doing
nothing, and only re-throw if the caller must handle the failure; use the
existing logger (or processLogger) and include enough context to identify which
file or directory failed to read/parse.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/desktop-app/src/project-manager.ts`:
- Around line 11-30: The isPortFree function currently hardcodes a 5000ms
timeout inside the Promise; extract that literal into a named constant (e.g.,
const PORT_CHECK_TIMEOUT = 5000) and replace the inline 5000 with that constant
to improve clarity and make the timeout easy to adjust; keep the existing logic
around server (net.createServer), timeout, server.once("error"),
server.once("listening"), server.close(), and server.listen(port) unchanged
while ensuring the constant is declared in the same module scope above
isPortFree.

In `@apps/server/src/routes/agent-history.ts`:
- Around line 60-62: The two empty catch blocks in
apps/server/src/routes/agent-history.ts (inside the readJsonLines flow and the
later JSON parsing block) are silently swallowing errors; update the catch
handlers in the functions (e.g., readJsonLines and the JSON parsing loop that
uses JSON.parse) to log a warning or error with context (include the
file/directory path and the caught error message) rather than doing nothing, and
only re-throw if the caller must handle the failure; use the existing logger (or
processLogger) and include enough context to identify which file or directory
failed to read/parse.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d32b5e22-b588-427b-99aa-1e59f29fe454

📥 Commits

Reviewing files that changed from the base of the PR and between f80b05a and ed32532.

📒 Files selected for processing (6)
  • apps/desktop-app/src/project-manager.ts
  • apps/desktop-app/src/server-spawner.ts
  • apps/server/src/routes/agent-history.ts
  • apps/server/src/routes/tasks.test.ts
  • apps/server/src/routes/tasks.ts
  • apps/web-app/src/components/detail/DetailPanel.tsx

- combine master's MessageCircle icon layout with PR's gitBranch display
- fix pre-existing type error in terminal.ts ("succeeded" → "success")
- remove dead process.send() IPC call not consumed by desktop app
  (stdout protocol is the actual port discovery mechanism)
- reduce isPortFree timeout from 5s to 1s
  (local bind check doesn't need 5s, was making port scan slow)
- remove resolvedWorktreePath from API response
  (leaked filesystem paths to client, not used by web-app)
- pass hooksManager in missing test case for consistency
- remove unused imports in tasks.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server/src/routes/terminal.ts`:
- Around line 159-175: Before calling findHistoricalAgentSessions in the restore
workflow, emit a start-phase ops log via logTerminalEvent with action
"terminal.agent.restore.lookup" and status "started" (include the same
contextual metadata: agent, requestedWorktreeId/worktreeId,
resolvedWorktreeId/resolved.worktreeId,
resolvedWorktreePath/resolved.worktree.path, and any available activeSessionId
from terminalManager.getSessionIdForScope). Then proceed to call
findHistoricalAgentSessions and keep the existing terminal success/failure log
after the lookup; this ensures full start→terminal traceability for the lookup
operation.

In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Line 389: restoreWorktreeIdRef can allow stale restore responses to affect the
wrong worktree and some branches are silent; update restoreWorktreeIdRef
whenever the active worktree changes (e.g., in the worktree switch handler or
effect that tracks currentWorktreeId) and, in the async restore response paths
that currently check restoreWorktreeIdRef, add a guard that compares the stored
id to the current worktree id and if they differ call log.warn(...) and show a
user toast (e.g., toast.warn(...) or toast.error(...)) before returning; also
replace any silent catch/fallback branches (mentioned around the restore
response handling and the other catch sites) to log the error with
log.error(...) and surface a user-facing toast so errors aren’t swallowed.
- Around line 981-992: Add a co-located Vitest test file for DetailPanel that
verifies the new stale-response guarding and modal disambiguation UI: write
tests that mount or render the DetailPanel and mock
api.fetchRestorableAgentSessions to resolve after worktree changes, assert that
when restoreWorktreeIdRef is updated (simulate switching worktrees) the response
is ignored (no call to setAgentRestoreModal and no modal shown) to cover the
restoreWorktreeIdRef check around fetchRestorableAgentSessions and
setIsResolvingAgentRestore, and add tests that trigger the restore modal path
and assert the modal renders project name and branch name disambiguation content
(matching the UI text inserted near Project and Branch rendering) to ensure the
disambiguation UI appears.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 58b1d483-50d9-4ed9-8117-121058cccf56

📥 Commits

Reviewing files that changed from the base of the PR and between ed32532 and d78ad16.

📒 Files selected for processing (5)
  • apps/server/src/index.ts
  • apps/server/src/routes/tasks.ts
  • apps/server/src/routes/terminal.ts
  • apps/web-app/src/components/detail/DetailPanel.tsx
  • apps/web-app/src/hooks/api.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/server/src/routes/tasks.ts
  • apps/server/src/index.ts

Comment thread apps/server/src/routes/terminal.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
apps/server/src/routes/terminal.ts (1)

159-175: ⚠️ Potential issue | 🟠 Major

Add a start-phase restore lookup event before Line 161.

You now log success/failure for restore lookup, but there is still no explicit start event before findHistoricalAgentSessions(...). Please emit a pre-lookup logTerminalEvent so this workflow has complete start → terminal traceability.

♻️ Proposed patch
     try {
       const activeSessionId = terminalManager.getSessionIdForScope(resolved.worktreeId, agent);
+      logTerminalEvent({
+        action: "terminal.agent.restore.lookup",
+        message: "Resolving agent session history",
+        status: "info",
+        worktreeId: resolved.worktreeId,
+        metadata: {
+          agent,
+          requestedWorktreeId: worktreeId,
+          resolvedWorktreePath: resolved.worktree.path,
+          activeSessionId,
+        },
+      });
       const historyMatches = findHistoricalAgentSessions(agent, resolved.worktree.path);
       logTerminalEvent({
         action: "terminal.agent.restore.lookup",
         message: "Resolved agent session history",
         status: "success",

As per coding guidelines: "Treat ops logging as mandatory for all agent/workflow operations. Always log start and terminal outcome (success/failure)...".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/terminal.ts` around lines 159 - 175, Add a pre-lookup
start event immediately before calling findHistoricalAgentSessions(...) by
emitting a logTerminalEvent with an action like
"terminal.agent.restore.lookup.start" (or similar start-phase name), status
"started", and metadata containing agent, requestedWorktreeId (worktreeId),
resolvedWorktreePath (resolved.worktree.path) and any available context such as
activeSessionId (from terminalManager.getSessionIdForScope). Place this log
right before the call to findHistoricalAgentSessions(agent,
resolved.worktree.path) so the flow has an explicit start → outcome trace for
the restore lookup.
🧹 Nitpick comments (1)
apps/desktop-app/src/project-manager.ts (1)

223-257: Buffered stdout/stderr correctly handles split chunks.

The implementation properly assembles lines across chunk boundaries, addressing the past review concern. The port marker parsing and logging with domain are well-implemented.

Minor edge case: The buffers are not flushed on process exit event. If the server's final output doesn't end with \n, that partial line is lost. For the port marker (which includes \n), this isn't an issue. For stderr diagnostics in recentServerErrors, the last partial line could be missed—though this is unlikely to affect debugging since most error output is newline-terminated.

🔧 Optional fix to flush buffers on exit
       serverProcess.on("exit", (code: number | null) => {
+        // Flush any remaining buffered output
+        if (stderrBuffer.trim()) {
+          pushServerError(stderrBuffer);
+        }
         if (project.status !== "stopped") {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop-app/src/project-manager.ts` around lines 223 - 257, The
stdoutBuffer/stderrBuffer aren't flushed when the child process exits, so add an
exit/close handler on serverProcess (use serverProcess.on("exit", ...) or
"close") that processes any remaining stdoutBuffer and stderrBuffer; for
stdoutBuffer run the same port marker detection used in the serverProcess.stdout
handler (match /^__OPENKIT_PORT__=(\d+)$/ and if found update project.port, call
this.notifyChange() and log.debug with domain "port-allocation"), and for
stderrBuffer call pushServerError for the leftover text (if non-empty, trimming
as appropriate) so the final partial stderr line isn't lost.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop-app/src/project-manager.ts`:
- Around line 11-30: Add a Vitest test file named project-manager.test.ts that
covers the new async port allocation logic: write tests for isPortFree (simulate
both "listening" and "error" paths by mocking net.createServer to call its
'listening' and 'error' callbacks and verify returned booleans), for
allocatePort (assert it returns a free port, handles failure paths, and respects
retries/timeouts by mocking isPortFree or net behavior), and for pendingPorts
state (verify pendingPorts entries are added when allocation starts and removed
on success/failure, including concurrent allocation attempts). Use Vitest async
testing patterns (await, expect.rejects/resolve), mock/stub net.createServer or
isPortFree to force fast deterministic outcomes rather than real network calls,
and clean up timers/mocks between tests so state does not leak. Ensure test
filename follows foo.test.ts pattern and asserts all non-trivial state
transitions and error handling paths.

---

Duplicate comments:
In `@apps/server/src/routes/terminal.ts`:
- Around line 159-175: Add a pre-lookup start event immediately before calling
findHistoricalAgentSessions(...) by emitting a logTerminalEvent with an action
like "terminal.agent.restore.lookup.start" (or similar start-phase name), status
"started", and metadata containing agent, requestedWorktreeId (worktreeId),
resolvedWorktreePath (resolved.worktree.path) and any available context such as
activeSessionId (from terminalManager.getSessionIdForScope). Place this log
right before the call to findHistoricalAgentSessions(agent,
resolved.worktree.path) so the flow has an explicit start → outcome trace for
the restore lookup.

---

Nitpick comments:
In `@apps/desktop-app/src/project-manager.ts`:
- Around line 223-257: The stdoutBuffer/stderrBuffer aren't flushed when the
child process exits, so add an exit/close handler on serverProcess (use
serverProcess.on("exit", ...) or "close") that processes any remaining
stdoutBuffer and stderrBuffer; for stdoutBuffer run the same port marker
detection used in the serverProcess.stdout handler (match
/^__OPENKIT_PORT__=(\d+)$/ and if found update project.port, call
this.notifyChange() and log.debug with domain "port-allocation"), and for
stderrBuffer call pushServerError for the leftover text (if non-empty, trimming
as appropriate) so the final partial stderr line isn't lost.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6200cdbd-a185-420b-b2e8-90cab9a7505c

📥 Commits

Reviewing files that changed from the base of the PR and between d78ad16 and 27fa97c.

📒 Files selected for processing (4)
  • apps/desktop-app/src/project-manager.ts
  • apps/server/src/index.ts
  • apps/server/src/routes/tasks.test.ts
  • apps/server/src/routes/terminal.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/server/src/routes/tasks.test.ts

Comment on lines +11 to +30
function isPortFree(port: number): Promise<boolean> {
return new Promise((resolve) => {
const timeout = setTimeout(() => {
server.close();
resolve(false);
}, 1000);
const server = net.createServer();
server.once("error", () => {
clearTimeout(timeout);
resolve(false);
});
server.once("listening", () => {
server.close(() => {
clearTimeout(timeout);
resolve(true);
});
});
server.listen(port);
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if project-manager tests exist and cover the new functionality
fd "project-manager" --extension test.ts --extension spec.ts
rg -l "isPortFree|allocatePort|pendingPort|__OPENKIT_PORT__" --glob "*test*" --glob "*spec*"

Repository: fum4/openkit

Length of output: 38


🏁 Script executed:

#!/bin/bash
# Locate project-manager.ts
find . -name "project-manager.ts" -type f

# Check if corresponding test file exists
find . -name "project-manager.test.ts" -type f

# List all test files in the apps/desktop-app directory
find apps/desktop-app -name "*.test.ts" -o -name "*.spec.ts" | head -20

Repository: fum4/openkit

Length of output: 135


🏁 Script executed:

#!/bin/bash
# Check dev-mode.test.ts for references to project-manager functions
cat apps/desktop-app/src/dev-mode.test.ts | head -50
rg "isPortFree|allocatePort|pendingPort" apps/desktop-app/src/dev-mode.test.ts

Repository: fum4/openkit

Length of output: 1496


Create project-manager.test.ts with test coverage for new port allocation logic.

Per coding guidelines, every code change must include corresponding tests using the foo.ts → foo.test.ts pattern with Vitest. The new isPortFree(), async allocatePort(), and pendingPorts tracking functions lack test coverage. Create project-manager.test.ts to test these non-trivial async operations, error handling paths, and state transitions.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop-app/src/project-manager.ts` around lines 11 - 30, Add a Vitest
test file named project-manager.test.ts that covers the new async port
allocation logic: write tests for isPortFree (simulate both "listening" and
"error" paths by mocking net.createServer to call its 'listening' and 'error'
callbacks and verify returned booleans), for allocatePort (assert it returns a
free port, handles failure paths, and respects retries/timeouts by mocking
isPortFree or net behavior), and for pendingPorts state (verify pendingPorts
entries are added when allocation starts and removed on success/failure,
including concurrent allocation attempts). Use Vitest async testing patterns
(await, expect.rejects/resolve), mock/stub net.createServer or isPortFree to
force fast deterministic outcomes rather than real network calls, and clean up
timers/mocks between tests so state does not leak. Ensure test filename follows
foo.test.ts pattern and asserts all non-trivial state transitions and error
handling paths.

…on management

- add stale restore response guard with useRef + useEffect to prevent
  async responses from wrong worktree leaking into current view
- add start-phase ops log event for agent restore lookup traceability
- add DetailPanel tests for stale response suppression and modal disambiguation
- add ProjectManager tests for port allocation, stdout correction, restore flow

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
apps/desktop-app/src/project-manager.test.ts (1)

297-322: Verify the captured error content in addition to status to strengthen the test.

The test confirms the project enters "error" status but doesn't assert that the stderr content is actually accessible. Since ProjectManager exposes the error message via project.error (populated from moduleResolveError), add a check that the captured stderr is present:

      const result = await resultPromise;
      // Server failed, error should include the stderr message
      expect(result.project?.status).toBe("error");
+     expect(result.project?.error).toContain("Cannot find package");

This verifies the error propagation path works end-to-end and confirms stderr content is accessible to callers.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop-app/src/project-manager.test.ts` around lines 297 - 322, The
test currently only asserts result.project?.status === "error" but doesn't
verify the captured stderr content; update the test to also assert that
ProjectManager exposed the assembled stderr via the project's error field (e.g.,
check result.project?.error or the moduleResolveError value on the returned
project) contains the full message "Cannot find package 'missing-dep'" so the
split-chunk handling is validated end-to-end (refer to ProjectManager and
project.error/moduleResolveError in the test).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/web-app/src/components/detail/DetailPanel.test.tsx`:
- Around line 146-208: The test "does not act on restore response after worktree
switch (active session)" currently resolves the first
mockFetchRestorableAgentSessions immediately, so it doesn't exercise a stale
in-flight response; change the test to return controlled promises (e.g., create
two Promise resolvers) from mockFetchRestorableAgentSessions (using
mockResolvedValueOnce or mockImplementationOnce) so the first call stays
pending, then after rerendering to worktree2 resolve both promises (first then
second) and assert defaultProps.onCodeWithClaude was only invoked for worktreeId
"wt-2" (and not for "wt-1"); keep using selectAgentFromDropdown,
rerender(<DetailPanel ... />) and the existing expectations but coordinate with
the manual promise resolvers so the stale-response path is actually tested.
- Line 1: Replace the use of fireEvent with userEvent in the DetailPanel test:
change the import to bring in userEvent from "@testing-library/user-event",
update all occurrences of fireEvent (used in tests around interactions) to the
corresponding userEvent methods (e.g., userEvent.click, userEvent.type) and,
where necessary, await userEvent calls that return promises; update any helper
names referencing fireEvent to userEvent to keep consistency with React Testing
Library best practices and the project's conventions.

---

Nitpick comments:
In `@apps/desktop-app/src/project-manager.test.ts`:
- Around line 297-322: The test currently only asserts result.project?.status
=== "error" but doesn't verify the captured stderr content; update the test to
also assert that ProjectManager exposed the assembled stderr via the project's
error field (e.g., check result.project?.error or the moduleResolveError value
on the returned project) contains the full message "Cannot find package
'missing-dep'" so the split-chunk handling is validated end-to-end (refer to
ProjectManager and project.error/moduleResolveError in the test).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f8609658-8cfc-4b10-9a89-dec0a4323f91

📥 Commits

Reviewing files that changed from the base of the PR and between 27fa97c and c6a1fee.

📒 Files selected for processing (4)
  • apps/desktop-app/src/project-manager.test.ts
  • apps/server/src/routes/terminal.ts
  • apps/web-app/src/components/detail/DetailPanel.test.tsx
  • apps/web-app/src/components/detail/DetailPanel.tsx

- reduce isPortFree timeout from 1s to 200ms and add settle-once pattern
  with server.unref() to prevent handle leaks on timeout
- restore modal CTA text "Choose which one to resume" alongside project badge
- add log.warn when hooksManager is missing in registerTaskRoutes
- change tasks.test.ts cleanup from afterAll to afterEach for robustness
- replace underscore-prefixed destructuring in agent-history with explicit field picking
- add comment in server-spawner.ts explaining dual stdout listeners
- switch DetailPanel.test.tsx from fireEvent to userEvent per project conventions
- rewrite stale-response test with deferred promises to exercise real in-flight suppression
- update test mocks: add server.unref() stub and log.get() child logger factory
@fum4
fum4 merged commit ca8a75c into master Mar 17, 2026
19 checks passed
@fum4
fum4 deleted the fix/project-conversation-management-and-taskmd branch March 17, 2026 23:50

This branch was previously deployed

1 inactive deployment
Preview — 636f24d8 Deployed Mar 17, 2026 by vercel[bot]
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