Repository navigation
fix: regenerate TASK.md on local task updates & improve session management - #76
Conversation
…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]>
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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
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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
Comment |
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]>
There was a problem hiding this comment.
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 | 🟠 MajorIgnore 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-
awaitpath 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 | 🟠 MajorLog 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, orfetchitself failed. Keep the last error and emit onelog.warn()/log.error()withdomain,port, andtimeoutbefore returningfalse.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."🛠️ 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; }🤖 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 bycreateTempConfigDir()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
rmSyncto the imports fromfs.🤖 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
📒 Files selected for processing (10)
apps/desktop-app/src/project-manager.tsapps/desktop-app/src/server-spawner.tsapps/server/src/index.tsapps/server/src/routes/agent-history.test.tsapps/server/src/routes/agent-history.tsapps/server/src/routes/tasks.test.tsapps/server/src/routes/tasks.tsapps/server/src/routes/terminal.tsapps/web-app/src/components/detail/DetailPanel.tsxapps/web-app/src/hooks/api.ts
| // 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(); | ||
| } | ||
| } | ||
| } | ||
| }); |
There was a problem hiding this comment.
🧩 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.tsRepository: 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 5Repository: 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 -nRepository: 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 8Repository: 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.
| // 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.
- 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
There was a problem hiding this comment.
🧹 Nitpick comments (2)
apps/desktop-app/src/project-manager.ts (1)
11-30: Robust port availability check with timeout protection.The
isPortFreeimplementation correctly usesnet.createServerto 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
catchblocks 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
📒 Files selected for processing (6)
apps/desktop-app/src/project-manager.tsapps/desktop-app/src/server-spawner.tsapps/server/src/routes/agent-history.tsapps/server/src/routes/tasks.test.tsapps/server/src/routes/tasks.tsapps/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
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
apps/server/src/index.tsapps/server/src/routes/tasks.tsapps/server/src/routes/terminal.tsapps/web-app/src/components/detail/DetailPanel.tsxapps/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
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
apps/server/src/routes/terminal.ts (1)
159-175:⚠️ Potential issue | 🟠 MajorAdd 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-lookuplogTerminalEventso 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
exitevent. 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 inrecentServerErrors, 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
📒 Files selected for processing (4)
apps/desktop-app/src/project-manager.tsapps/server/src/index.tsapps/server/src/routes/tasks.test.tsapps/server/src/routes/terminal.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/server/src/routes/tasks.test.ts
| 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); | ||
| }); | ||
| } |
There was a problem hiding this comment.
🧩 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 -20Repository: 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.tsRepository: 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
There was a problem hiding this comment.
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. SinceProjectManagerexposes the error message viaproject.error(populated frommoduleResolveError), 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
📒 Files selected for processing (4)
apps/desktop-app/src/project-manager.test.tsapps/server/src/routes/terminal.tsapps/web-app/src/components/detail/DetailPanel.test.tsxapps/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
Summary
/api/tasks/:idhandler saved totask.jsonbut never calledregenerateTaskMd().__OPENKIT_PORT__on stdout so Electron can correct the port iffindAvailablePort()picks a different one.gitBranchin history matches for better disambiguation in the restore modal, and adds debug logging for diagnosing cross-project session confusion.appendFileSyncdebug log inserver-spawner.tswith the project logger.Test plan
tasks.test.ts— verifies TASK.md regeneration on description update (with/without linked worktree, error resilience, persistence)agent-history.test.ts— covers automated prompt filtering, preview extraction, session matching🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Improvements
Tests