Repository navigation
feat: add performance monitoring page - #80
Conversation
- real-time CPU, memory, and disk usage tracking per worktree via PerfMonitor (pidusage + du, SSE streaming, demand-driven polling) - worktree terminate action with confirmation modal and error feedback - shared InfoBanner component with per-page color theming (rose, amber, blue, brown) replacing duplicated inline banners - page titles, entrance animations, and background blobs for settings, hooks, integrations, and performance pages - CMD+P shortcut for performance page, integrated into arrow-nav cycle - conversation picker modal redesign with speech bubble icon, relative timestamps, and consistent styling - expose instanceName/instanceBranch from config API for header context - file-change SSE events for real-time config sync across hooks
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
📝 WalkthroughWalkthroughThis pull request introduces a real-time performance monitoring system for the OpenKit server and integrates a file-change event system. Key additions include a new PerfMonitor class that collects CPU/memory metrics via SSE streaming, a PerformancePage UI component, file-watching in WorktreeManager, and API routes for perf management. It also standardizes logging status from "succeeded" to "success" throughout and refactors web app panels with motion animations and dismissible banners. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Web App
participant Server as OpenKit Server
participant PerfMonitor
participant WorktreeManager as Worktree Manager
participant System as System Processes
Client->>Server: GET /api/perf/stream (SSE Subscribe)
Server->>PerfMonitor: subscribe(callback)
activate PerfMonitor
PerfMonitor->>PerfMonitor: Start polling at 2s interval
loop Poll Cycle
PerfMonitor->>WorktreeManager: getRunningProcessPids()
WorktreeManager->>System: pgrep for child processes
System-->>WorktreeManager: PIDs
PerfMonitor->>System: pidusage (CPU/memory)
System-->>PerfMonitor: Metrics
PerfMonitor->>System: du -sk (disk usage)
System-->>PerfMonitor: Disk sizes
PerfMonitor->>PerfMonitor: Build PerfSnapshot<br/>(aggregate metrics)
PerfMonitor->>PerfMonitor: Append to ring buffer
PerfMonitor->>Client: emit perf-snapshot
end
Client->>PerfMonitor: unsubscribe()
deactivate PerfMonitor
PerfMonitor->>PerfMonitor: Stop polling
sequenceDiagram
participant ExternalApp as External Tool
participant FileSystem as File System
participant WorktreeManager as Worktree Manager
participant Server as OpenKit Server
participant WebApp as Web App
participant SSE as SSE Stream
ExternalApp->>FileSystem: Modify config/.openkit/config.json
activate WorktreeManager
WorktreeManager->>FileSystem: File watcher detects change
FileSystem-->>WorktreeManager: File change event
Note over WorktreeManager: Debounce (500ms)
alt Not suppressed
WorktreeManager->>WorktreeManager: emitFileChange("config")
WorktreeManager->>Server: Notify listener
else Suppressed (e.g., we wrote it)
WorktreeManager->>WorktreeManager: Skip emission
end
deactivate WorktreeManager
alt Category="config"
Server->>Server: Reload config if needed
Server->>SSE: Enqueue config-changed event
SSE->>WebApp: Dispatch config-changed via CustomEvent
WebApp->>WebApp: useConfig refetch
else Other category (hooks, branch-rules, etc.)
Server->>SSE: Enqueue file-changed event
SSE->>WebApp: Dispatch file-changed via CustomEvent
WebApp->>WebApp: useHooks/useAgentRules refetch
end
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~70 minutes Possibly Related PRs
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 |
There was a problem hiding this comment.
Actionable comments posted: 16
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/web-app/src/hooks/useWorktrees.ts (1)
80-102:⚠️ Potential issue | 🟠 MajorReplace silent SSE catch with contextual logging.
catch {}swallows parse/dispatch failures and makes production diagnosis impossible. Usecatch (error)and log with actionable metadata (event type/payload) plus adomain(for exampleworktrees:sse).As per coding guidelines: “Silent
catch {}blocks are never acceptable.” and “Always include adomainfield in the metadata object to namespace logs by feature area.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/hooks/useWorktrees.ts` around lines 80 - 102, The SSE message handler currently swallows all errors with an empty catch; change it to catch (error) and emit a contextual error log (e.g., console.error or the app logger) including the error, the raw event payload (event.data), and the parsed message type when available, and add a domain field "worktrees:sse" to the metadata; update the eventSource.onmessage handler that calls setWorktrees, notificationRef, hookUpdateRef and window.dispatchEvent so parsing/dispatch failures are logged with these details instead of being silently ignored.
🟡 Minor comments (9)
docs/API.md-1060-1092 (1)
1060-1092:⚠️ Potential issue | 🟡 MinorDocument
diskUsagein the perf payload.This section only describes CPU/memory, but
WorktreeMetricsnow also carries per-worktree disk usage. Please add that field to the narrative/shape description and call out that it is optional/nullable bytes so API clients handle it correctly.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/API.md` around lines 1060 - 1092, Update the PerfSnapshot/WorktreeMetrics documentation to include the new optional diskUsage field: add `diskUsage` to the WorktreeMetrics shape and describe it as nullable/optional number of bytes (e.g., `number | null`) representing per-worktree disk usage so clients can handle missing values; also mention in the narrative for GET /api/perf, GET /api/perf/current, and SSE events (`perf-history` / `perf-snapshot`) that WorktreeMetrics includes this optional diskUsage alongside devServer, childProcesses, agentSessions, totalCpu, and totalMemory.apps/server/src/manager.ts-482-483 (1)
482-483:⚠️ Potential issue | 🟡 MinorUse a block body here to satisfy Biome.
This expression-bodied
forEachcallback is flagged by Biome as returning a value. Wrapping the call in braces fixes the lint error without changing behavior.As per coding guidelines "
**/*.{ts,tsx,js,jsx,mjs,cjs}: Fix any lint or format errors you encounter — whether introduced by current changes or pre-existing in the codebase.`"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server/src/manager.ts` around lines 482 - 483, The forEach callback in emitFileChange currently uses an expression-bodied arrow (this.fileChangeListeners.forEach((listener) => listener(category))) which Biome flags as returning a value; change the callback to a block-bodied arrow so it explicitly calls listener(category) inside braces (e.g., use (listener) => { listener(category); }) to satisfy the linter while preserving behavior in the emitFileChange method and referencing the fileChangeListeners iteration.apps/web-app/src/components/InfoBanner.tsx-69-75 (1)
69-75:⚠️ Potential issue | 🟡 MinorAdd an accessible name to the dismiss button.
This is an icon-only button; add
aria-label(for example, “Dismiss banner”) to ensure screen-reader usability.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/components/InfoBanner.tsx` around lines 69 - 75, The dismiss button in the InfoBanner component is icon-only and needs an accessible name; update the <button> that calls dismiss (the JSX button containing the <X /> icon) to include an aria-label (e.g., aria-label="Dismiss banner") so screen readers can announce its purpose; ensure the label is concise and the decorative <X /> remains unchanged (optionally add aria-hidden to the icon if needed).apps/web-app/src/components/InfoBanner.tsx-8-33 (1)
8-33:⚠️ Potential issue | 🟡 MinorMove banner color definitions into shared theme tokens.
This introduces a new ad-hoc color system directly in the component. Please source these variants from
theme.tsso color behavior stays centralized and consistent.As per coding guidelines: “Always use the standard shared color palette and tokens from
apps/web-app/src/theme.ts.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/components/InfoBanner.tsx` around lines 8 - 33, The banner color map (colorStyles) in InfoBanner (and the BannerColor type usage) hardcodes ad-hoc Tailwind/color strings; move these values into the shared theme tokens in theme.ts and import them into InfoBanner. Replace each hardcoded entry (teal, rose, amber, blue, brown) with references to the centralized tokens (e.g., theme.tokens.banner.teal.bg / .border / .dismiss or the equivalent token names defined in theme.ts), update the colorStyles record to use those imported tokens (or a ThemeBannerTokens type) and remove duplicated string literals so the InfoBanner component consumes the centralized theme values. Ensure imports from apps/web-app/src/theme.ts are added and tests/usage still reference BannerColor as before.docs/FRONTEND.md-70-73 (1)
70-73:⚠️ Potential issue | 🟡 MinorUpdate related view inventory sections to include Performance.
After adding this section, the earlier “six top-level views” text and
Viewunion snippet are stale. Please update those sections so the document is internally consistent.Based on learnings: “Keep ALL docs in sync at ALL TIMES… When adding/changing components, hooks, or theme tokens → update
docs/FRONTEND.md.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/FRONTEND.md` around lines 70 - 73, The docs add a new "Performance" view but the earlier "six top-level views" summary and the `View` union snippet are now stale; update the inventory and the `View` union to include the new Performance view and its pieces by adding "Performance" to the list of top-level views and adding a Performance entry to the `View` union, and also list its components/hooks (PerformancePage, SystemSummaryCard, WorktreeCard, ProcessRow, CpuBar, MemoryBar, usePerformanceMetrics) in the relevant component/hook inventories so the FRONTEND.md sections remain consistent.apps/web-app/src/components/IntegrationsPanel.tsx-1737-1741 (1)
1737-1741:⚠️ Potential issue | 🟡 MinorUse theme tokens for the new header colors.
Line 1738 (
text-blue-400) and Line 1740 (text-[#f0f2f5]) hardcode colors in a newly added UI block. Please switch these to shared theme tokens for consistency.As per coding guidelines: “Always use the standard shared color palette and tokens from
apps/web-app/src/theme.ts. Do not introduce ad-hoc lighter/darker color variants for existing control patterns.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/components/IntegrationsPanel.tsx` around lines 1737 - 1741, The new header hardcodes colors in IntegrationsPanel (the Link2 icon div uses "text-blue-400" and the h1 uses "text-[`#f0f2f5`]"); replace these with the standard shared theme tokens from the project theme (import the appropriate token names from the theme module and use them in the className or via a mapped class, e.g., replace "text-blue-400" with the theme's primary/interactive token and replace "text-[`#f0f2f5`]" with the theme's heading/text token) ensuring you reference the theme export when updating the Link2 wrapper and the h1 in IntegrationsPanel.apps/web-app/src/App.tsx-944-946 (1)
944-946:⚠️ Potential issue | 🟡 MinorPersist the new
"performance"view in the restore whitelist.
setActiveView("performance")is wired here, but the persisted-view checks at Line 531 and Line 555 still exclude"performance". After a reload or project switch, the app falls back to"workspace"instead of restoring the Performance tab.Suggested fix
if ( saved === "workspace" || saved === "agents" || saved === "activity" || saved === "hooks" || saved === "configuration" || - saved === "integrations" + saved === "integrations" || + saved === "performance" ) {Apply the same addition in both the
useStateinitializer and the restoreuseEffect.Also applies to: 3296-3299
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/App.tsx` around lines 944 - 946, The new "performance" view is being set via setActiveView("performance") but isn't included in the persisted-view whitelist used when initializing activeView and when restoring from storage; update the whitelist in the useState initializer (where activeView is initially derived from persisted/allowed views) and the restore useEffect (the block that checks persistedView or allowed views on mount/switch) to include "performance" so the Performance tab is restored after reloads or project switches; look for references to setActiveView, activeView (useState initializer) and the restore useEffect that checks persistedView/allowed views and add "performance" to those allowed values.apps/web-app/src/components/detail/DetailPanel.tsx-36-47 (1)
36-47:⚠️ Potential issue | 🟡 MinorGuard
formatRelativeTimeagainst invalid/future timestamps.If
updatedAtis malformed, this can renderNaNd ago. Clamp and validate before computing units.🛠️ Proposed fix
function formatRelativeTime(date: Date): string { - const diffMs = Date.now() - date.getTime(); + const timestamp = date.getTime(); + if (!Number.isFinite(timestamp)) return "unknown"; + const diffMs = Math.max(0, Date.now() - timestamp); const sec = Math.floor(diffMs / 1000); const min = Math.floor(sec / 60); const hr = Math.floor(min / 60); const days = Math.floor(hr / 24);🤖 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 36 - 47, The formatRelativeTime function should validate the input Date and clamp future timestamps: first check that date is a valid Date (e.g., !isNaN(date.getTime())) and if invalid return a safe fallback like an empty string or "invalid date"; then compute diffMs = Math.max(0, Date.now() - date.getTime()) to guard against future times before deriving sec/min/hr/days; update the early-return branches (e.g., "just now") accordingly so you never produce NaN-based strings; modify formatRelativeTime to include these checks.apps/server/src/terminal-manager.ts-570-576 (1)
570-576:⚠️ Potential issue | 🟡 MinorSanitize
pidbefore exposing it ingetActiveSessionInfo().The new API can currently return non-usable numeric values (e.g.,
NaN). Normalize tonullunless it is a finite positive integer.🛠️ Proposed fix
- const pid = session.pty ? ((session.pty as unknown as { pid?: number }).pid ?? null) : null; + const rawPid = session.pty ? (session.pty as unknown as { pid?: number }).pid : undefined; + const pid = + typeof rawPid === "number" && Number.isFinite(rawPid) && rawPid > 0 ? rawPid : null;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server/src/terminal-manager.ts` around lines 570 - 576, The pid extracted for each session (currently via session.pty as { pid?: number } in the getActiveSessionInfo flow) must be validated before being returned: compute the raw pid from (session.pty as unknown as { pid?: number }).pid, then normalize it to null unless Number.isFinite(rawPid) && Number.isInteger(rawPid) && rawPid > 0; assign that normalized value to the pid field in the object pushed to result so non-usable values (NaN, Infinity, negatives, non-integers) become null.
🧹 Nitpick comments (4)
apps/web-app/src/components/detail/DetailHeader.tsx (1)
502-519: LGTM — consolidation improves layout consistency.The unified condition and combined row for line stats and ports is cleaner than separate blocks. The null coalescing for
linesAdded/linesRemovedhandles undefined values safely.One minor note: the
ml-2on line 515 adds extra spacing beyondgap-3when both sections render, creating slightly inconsistent inter-item spacing. If you want uniform gaps, you could dropml-2and rely solely ongap-3, or use a visual separator element instead.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/components/detail/DetailHeader.tsx` around lines 502 - 519, The extra left margin on the ports span ("ml-2" in the JSX that renders worktree.ports) creates uneven spacing compared to the container's gap-3; remove the "ml-2" class from the <span> (or replace it with a consistent spacing approach such as relying on the parent flex gap or adding a separator element) so that the ports display uses the same gap as the linesAdded/linesRemoved block when both render; locate the JSX that references worktree.ports and adjust the className accordingly.apps/web-app/src/components/ConfigurationPanel.tsx (1)
596-600: Use shared theme tokens for the new header colors.
text-[#8a7560]andtext-[#f0f2f5]bypass the palette intheme.ts, so this header will drift from the rest of the settings surfaces. Please swap these to existing theme tokens.As per coding guidelines "Always use the standard shared color palette and tokens from apps/web-app/src/theme.ts. Do not introduce ad-hoc lighter/darker color variants for existing control patterns."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/components/ConfigurationPanel.tsx` around lines 596 - 600, Replace the hard-coded hex color utility classes on the Settings icon container and the header text—currently "text-[`#8a7560`]" on the <Settings> icon and "text-[`#f0f2f5`]" on the <h1>—with the shared theme tokens defined in theme.ts; identify the appropriate token for the muted/icon color and the primary/header text color in theme.ts and swap the inline hex classes to those token-based class names so the header follows the standard shared palette.apps/web-app/src/components/PerformancePage.tsx (1)
20-25: Avoid adding new parent-relative imports in app code.This new file introduces several
../...imports (../hooks/usePerformanceMetrics,../hooks/api,../errorToasts,../theme). The repo rule for app/lib source files is same-folder relatives only and aliases for anything above that.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/web-app/src/components/PerformancePage.tsx` around lines 20 - 25, The new PerformancePage.tsx file uses parent-relative imports for usePerformanceMetrics, stopWorktree, reportPersistentErrorToast, and theme symbols (palette, settings, text); replace these ../... imports with the repo's configured path aliases (or move/duplicate helpers into the same folder) so app files only use same-folder-relative imports; update the import statements that reference usePerformanceMetrics, stopWorktree, reportPersistentErrorToast, and the theme symbols to use the project's aliases (or local wrappers) and ensure the build resolves them correctly.apps/web-app/src/components/detail/DetailPanel.tsx (1)
2179-2179: Use theme token instead of new hardcoded icon color.This introduces another ad-hoc hex in web-app UI. Prefer
text.secondaryfor consistency.As per coding guidelines: "Always use the standard shared color palette and tokens from apps/web-app/src/theme.ts. Do not introduce ad-hoc lighter/darker color variants for existing control patterns."🎨 Proposed tweak
- icon={<MessageCircle className="w-4 h-4 text-[`#9ca3af`]" />} + icon={<MessageCircle className={`w-4 h-4 ${text.secondary}`} />}🤖 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` at line 2179, The MessageCircle icon in DetailPanel (icon prop using className "w-4 h-4 text-[`#9ca3af`]") uses a hardcoded hex color; replace that ad-hoc color with the shared theme token for secondary text (use the project's token/class for text.secondary) so the icon reads "w-4 h-4" plus the theme token instead of text-[`#9ca3af`]; update the icon usage in DetailPanel.tsx where MessageCircle is rendered to use the theme token class or style helper consistent with other components.
🤖 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/manager.ts`:
- Around line 331-332: reloadConfig() currently replaces this.portManager
without reapplying constructor-only wiring, so update reloadConfig() to preserve
and reapply the runtime hooks: when you create the new PortManager instance,
call its setDebugLogger(...) with the same logger used originally (e.g.,
this.debugLogger or whatever logger was passed to the old portManager) and call
useNativeHook(...) to restore the native-hook flag (use the previous
this.portManager's state if present, otherwise derive from the new config). In
other words, after constructing the new portManager in reloadConfig(), invoke
newPortManager.setDebugLogger(...) and newPortManager.useNativeHook(...) (or
equivalent getters on the old instance) so ops-log instrumentation and
native-hook behavior persist across config reloads.
- Around line 323-342: watchProjectFiles only registers watchers if .openkit,
CLAUDE.md or AGENTS.md exist at startup, so files/dirs created later never get
watched; fix by (a) adding a persistent watcher on the project root (or
this.configDir parent) that listens for creation events and, when it sees a new
".openkit" directory or creation of "CLAUDE.md"/"AGENTS.md", sets up the same
watcher logic (reuse classifyOpenkitFile, debouncedEmit and push created
watchers into this.fileWatchers) and triggers reloadConfig as needed, and/or (b)
ensure the /api/config/init flow calls the same setup (e.g., invoke
watchProjectFiles or the new helper that attaches watchers) after it creates
.openkit so new directories/files are immediately watched.
In `@apps/server/src/perf-monitor.ts`:
- Around line 66-72: The start() method uses setInterval to call poll() which
can overlap async executions; change to a non-overlapping loop by replacing the
setInterval pattern with a self-scheduling async cycle (or add an in-flight
guard) so poll() is awaited before scheduling the next run: add a boolean like
isPolling or refactor to an async runLoop that calls await this.poll(), then
awaits a delay(POLL_INTERVAL_MS) before repeating, continue to use intervalId or
a stop token for cancellation, and apply the same non-overlapping guard/refactor
to the corresponding polling/stop logic referenced around poll(), intervalId,
start(), and the code in the 83-106 region.
- Around line 220-223: The execFile callbacks that currently swallow errors (the
pgrep call around execFile("pgrep", ["-P", String(parentPid)], ...) and the
later execFile("du", ...) callback) should log failures instead of silently
returning empty arrays; update both callbacks to call the appropriate logger
(e.g., log.error or log.warn) with a clear message and include actionable
metadata such as the command, args, parentPid/processId, and the error and
stdout/stderr values before returning the fallback value; ensure the logging
uses the same logger used elsewhere in this module (e.g., log) and retains the
existing resolve([]) behavior after logging.
In `@apps/server/src/routes/config.ts`:
- Around line 87-90: The code uses getWorktreeBranch(gitRoot) which only handles
worktree-style .git files, causing instanceBranch to be null on normal repo
roots; replace that call so instanceBranch is obtained via a helper that
supports both repo roots and linked worktrees (e.g., getRepoBranch or
getBranchForPath) instead of getWorktreeBranch, using manager.getGitRoot() as
the input; if such a helper doesn't exist, implement one that checks for a
worktree `.git` file and falls back to reading .git/HEAD (or resolving HEAD) for
repository roots, then return that branch (or null) when assigning
instanceBranch.
In `@apps/server/src/routes/events.ts`:
- Around line 67-80: The current catch silently swallows errors from
controller.enqueue; update the catch to capture the exception (e.g., catch
(err)) and log a warning/error through the project logger before unsubscribing:
include domain (project name from manager.getProjectName()), the category value,
and the caught error in the log message so diagnostics show what failed, then
call unsubscribeFileChange(); use the project's logger (e.g.,
projectLogger.warn/error or log.warn/error) to emit the structured message.
In `@apps/server/src/routes/perf.ts`:
- Around line 15-37: Create a single shared cleanup function inside the
ReadableStream start scope (e.g., function cleanup(reason)) that calls the
subscriber unsubscribe returned by perfMonitor.subscribe, closes the controller,
and logs any cleanup reason/error with metadata { domain: "metrics" } so cleanup
is observable; replace the inline unsubscribe/close in the
c.req.raw.signal.abort listener with a call to cleanup, add a
cancel(controllerReason) handler on the ReadableStream that also calls
cleanup(controllerReason), and in the perfMonitor.subscribe enqueue() catch
block log the enqueue error with domain: "metrics" and then call cleanup so the
subscriber cannot linger.
In `@apps/web-app/src/components/ConfigurationPanel.tsx`:
- Around line 513-537: The catch blocks in both useFileChangeEvent handlers
currently swallow errors; update them to catch the error object and call
reportPersistentErrorToast with a descriptive message including the rule type
("branch rules" or "commit rules") and the active tab (branchTab or commitTab),
and also log the failure via the module logger (e.g., logger.error) including
the error and context; apply this change to the branch handler referencing
useFileChangeEvent, loadBranchTab, branchTab, api.fetchBranchRuleStatus,
setBranchOverrides and to the commit handler referencing commitLoadedTabs,
loadCommitTab, commitTab, api.fetchCommitRuleStatus, setCommitOverrides.
In `@apps/web-app/src/components/InfoBanner.tsx`:
- Around line 44-48: The try/catch around localStorage.getItem silently swallows
errors; update the catch to log the failure (use log.warn or log.error) and
include context fields: operation (e.g., "localStorage.getItem"), the storageKey
variable, and a domain string like "InfoBanner" in the metadata object so issues
are diagnosable; apply the same change to the other catch block that surrounds
the corresponding localStorage set/remove logic (the blocks referencing
storageKey in this component).
In `@apps/web-app/src/components/PerformancePage.test.tsx`:
- Around line 52-176: The test suite is missing coverage for the destructive
"terminate" flow: add a test in PerformancePage.test.tsx that renders a snapshot
with a worktree, opens the terminate confirmation modal via userEvent (query by
role/text), mocks the stopWorktree function to reject (simulate failure), clicks
the confirm button, and asserts the error toast is shown; use the existing mock
hook (mockUsePerformanceMetrics) to inject a mocked stopWorktree function that
returns a rejected promise and use React Testing Library queries
(role/label/text) and userEvent to interact with the UI and verify the modal
opens, the confirm action is invoked (stopWorktree called), and the failure
toast appears.
In `@apps/web-app/src/components/PerformancePage.tsx`:
- Around line 391-400: handleStop currently only toasts on result.success ===
false and lets thrown request errors slip past; update it to log the start,
terminal success, and terminal failure for the stopWorktree operation (include
the worktreeId in every log) and to catch exceptions from stopWorktree.
Concretely: at the top of handleStop log an "attempting to terminate" message
with worktreeId, then call stopWorktree inside try/catch; on success
(result.success true) log a success message with worktreeId, on failure
(result.success false) log the failure with result.error and worktreeId and
still call reportPersistentErrorToast, and in the catch block log the thrown
error with worktreeId and call reportPersistentErrorToast with that error. Use
the same logger used elsewhere in this component for consistency and reference
the existing symbols handleStop, stopWorktree, and reportPersistentErrorToast.
In `@apps/web-app/src/components/VerificationPanel.tsx`:
- Around line 430-487: The Worktree lifecycle Hook sections ("Worktree Created"
and "Worktree Removed" in VerificationPanel) currently allow prompts/skills;
change their HooksSection props to explicitly disallow both by setting
allowPrompts={false} and allowSkills={false} for the "worktree-created" and
"worktree-removed" HooksSection instances so only command steps can be added.
Keep other handlers intact but ensure the UI props that surface prompt/skill
flows are disabled for these two sections.
In `@apps/web-app/src/hooks/useFileChangeEvent.ts`:
- Around line 7-16: Add a co-located Vitest + React Testing Library test file
named useFileChangeEvent.test.ts that verifies useFileChangeEvent attaches and
removes the window "OpenKit:file-changed" listener, only invokes the provided
onChanged callback when the CustomEvent.detail matches the given category, and
re-registers when dependencies change; mount a simple test component that calls
useFileChangeEvent(category, onChanged), dispatch
CustomEvent("OpenKit:file-changed", { detail: category }) and with a different
detail to assert callback called vs not called, unmount to assert listener
cleanup (e.g., dispatch after unmount does not call), and update the category
prop to assert the hook re-registers (old category no longer triggers, new
category does), using spies/mocks for onChanged and checking
addEventListener/removeEventListener were called where applicable.
In `@apps/web-app/src/hooks/usePerformanceMetrics.test.ts`:
- Around line 39-45: The test suite currently overwrites globalThis.EventSource
at module load with FakeEventSource and silences any failure; move this override
into test lifecycle hooks by saving the original (const _originalEventSource =
globalThis.EventSource) in beforeAll, set globalThis.EventSource =
FakeEventSource there, and restore the original in afterAll
(globalThis.EventSource = _originalEventSource); also remove the empty catch
that hides errors and surface failures when the environment prevents assignment.
Ensure references to FakeEventSource and globalThis.EventSource are used exactly
as named so the setup/teardown wraps the suite.
In `@apps/web-app/src/hooks/usePerformanceMetrics.ts`:
- Around line 17-27: The effect in usePerformanceMetrics calls connect()
unconditionally which does new EventSource(getPerfStreamUrl(serverUrl)) even
when useServerUrlOptional() returns null; update the useEffect (and the connect
function) to bail out early if serverUrl is falsy — e.g., check if (!serverUrl)
return; before scheduling retries or creating EventSource — and also add the
same guard around the reconnect logic referenced at lines 62-68 so no SSE is
attempted until a real serverUrl exists (reference: useEffect, connect,
getPerfStreamUrl, serverUrl).
In `@apps/web-app/src/hooks/useWorktrees.ts`:
- Around line 89-92: The new SSE branches in useWorktrees.ts that handle
data.type === "config-changed" and data.type === "file-changed" dispatch
CustomEvents ("OpenKit:config-changed" with detail=data and
"OpenKit:file-changed" with detail=data.category) but lack Vitest coverage; add
tests that mount or call the SSE/message handler from useWorktrees (or the
exported function handling SSE messages) and assert window.dispatchEvent is
called with a CustomEvent having the exact type and detail payload for both
"config-changed" and "file-changed" cases. Mock or spy on window.dispatchEvent
(and restore after) and simulate incoming SSE payloads with { type:
"config-changed", ... } and { type: "file-changed", category: ... } to verify
the dispatched event names and detail values. Ensure tests use Vitest APIs
(vi.spyOn/vi.mock) and include clear test names like "dispatches
OpenKit:config-changed with full data" and "dispatches OpenKit:file-changed with
category detail".
---
Outside diff comments:
In `@apps/web-app/src/hooks/useWorktrees.ts`:
- Around line 80-102: The SSE message handler currently swallows all errors with
an empty catch; change it to catch (error) and emit a contextual error log
(e.g., console.error or the app logger) including the error, the raw event
payload (event.data), and the parsed message type when available, and add a
domain field "worktrees:sse" to the metadata; update the eventSource.onmessage
handler that calls setWorktrees, notificationRef, hookUpdateRef and
window.dispatchEvent so parsing/dispatch failures are logged with these details
instead of being silently ignored.
---
Minor comments:
In `@apps/server/src/manager.ts`:
- Around line 482-483: The forEach callback in emitFileChange currently uses an
expression-bodied arrow (this.fileChangeListeners.forEach((listener) =>
listener(category))) which Biome flags as returning a value; change the callback
to a block-bodied arrow so it explicitly calls listener(category) inside braces
(e.g., use (listener) => { listener(category); }) to satisfy the linter while
preserving behavior in the emitFileChange method and referencing the
fileChangeListeners iteration.
In `@apps/server/src/terminal-manager.ts`:
- Around line 570-576: The pid extracted for each session (currently via
session.pty as { pid?: number } in the getActiveSessionInfo flow) must be
validated before being returned: compute the raw pid from (session.pty as
unknown as { pid?: number }).pid, then normalize it to null unless
Number.isFinite(rawPid) && Number.isInteger(rawPid) && rawPid > 0; assign that
normalized value to the pid field in the object pushed to result so non-usable
values (NaN, Infinity, negatives, non-integers) become null.
In `@apps/web-app/src/App.tsx`:
- Around line 944-946: The new "performance" view is being set via
setActiveView("performance") but isn't included in the persisted-view whitelist
used when initializing activeView and when restoring from storage; update the
whitelist in the useState initializer (where activeView is initially derived
from persisted/allowed views) and the restore useEffect (the block that checks
persistedView or allowed views on mount/switch) to include "performance" so the
Performance tab is restored after reloads or project switches; look for
references to setActiveView, activeView (useState initializer) and the restore
useEffect that checks persistedView/allowed views and add "performance" to those
allowed values.
In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Around line 36-47: The formatRelativeTime function should validate the input
Date and clamp future timestamps: first check that date is a valid Date (e.g.,
!isNaN(date.getTime())) and if invalid return a safe fallback like an empty
string or "invalid date"; then compute diffMs = Math.max(0, Date.now() -
date.getTime()) to guard against future times before deriving sec/min/hr/days;
update the early-return branches (e.g., "just now") accordingly so you never
produce NaN-based strings; modify formatRelativeTime to include these checks.
In `@apps/web-app/src/components/InfoBanner.tsx`:
- Around line 69-75: The dismiss button in the InfoBanner component is icon-only
and needs an accessible name; update the <button> that calls dismiss (the JSX
button containing the <X /> icon) to include an aria-label (e.g.,
aria-label="Dismiss banner") so screen readers can announce its purpose; ensure
the label is concise and the decorative <X /> remains unchanged (optionally add
aria-hidden to the icon if needed).
- Around line 8-33: The banner color map (colorStyles) in InfoBanner (and the
BannerColor type usage) hardcodes ad-hoc Tailwind/color strings; move these
values into the shared theme tokens in theme.ts and import them into InfoBanner.
Replace each hardcoded entry (teal, rose, amber, blue, brown) with references to
the centralized tokens (e.g., theme.tokens.banner.teal.bg / .border / .dismiss
or the equivalent token names defined in theme.ts), update the colorStyles
record to use those imported tokens (or a ThemeBannerTokens type) and remove
duplicated string literals so the InfoBanner component consumes the centralized
theme values. Ensure imports from apps/web-app/src/theme.ts are added and
tests/usage still reference BannerColor as before.
In `@apps/web-app/src/components/IntegrationsPanel.tsx`:
- Around line 1737-1741: The new header hardcodes colors in IntegrationsPanel
(the Link2 icon div uses "text-blue-400" and the h1 uses "text-[`#f0f2f5`]");
replace these with the standard shared theme tokens from the project theme
(import the appropriate token names from the theme module and use them in the
className or via a mapped class, e.g., replace "text-blue-400" with the theme's
primary/interactive token and replace "text-[`#f0f2f5`]" with the theme's
heading/text token) ensuring you reference the theme export when updating the
Link2 wrapper and the h1 in IntegrationsPanel.
In `@docs/API.md`:
- Around line 1060-1092: Update the PerfSnapshot/WorktreeMetrics documentation
to include the new optional diskUsage field: add `diskUsage` to the
WorktreeMetrics shape and describe it as nullable/optional number of bytes
(e.g., `number | null`) representing per-worktree disk usage so clients can
handle missing values; also mention in the narrative for GET /api/perf, GET
/api/perf/current, and SSE events (`perf-history` / `perf-snapshot`) that
WorktreeMetrics includes this optional diskUsage alongside devServer,
childProcesses, agentSessions, totalCpu, and totalMemory.
In `@docs/FRONTEND.md`:
- Around line 70-73: The docs add a new "Performance" view but the earlier "six
top-level views" summary and the `View` union snippet are now stale; update the
inventory and the `View` union to include the new Performance view and its
pieces by adding "Performance" to the list of top-level views and adding a
Performance entry to the `View` union, and also list its components/hooks
(PerformancePage, SystemSummaryCard, WorktreeCard, ProcessRow, CpuBar,
MemoryBar, usePerformanceMetrics) in the relevant component/hook inventories so
the FRONTEND.md sections remain consistent.
---
Nitpick comments:
In `@apps/web-app/src/components/ConfigurationPanel.tsx`:
- Around line 596-600: Replace the hard-coded hex color utility classes on the
Settings icon container and the header text—currently "text-[`#8a7560`]" on the
<Settings> icon and "text-[`#f0f2f5`]" on the <h1>—with the shared theme tokens
defined in theme.ts; identify the appropriate token for the muted/icon color and
the primary/header text color in theme.ts and swap the inline hex classes to
those token-based class names so the header follows the standard shared palette.
In `@apps/web-app/src/components/detail/DetailHeader.tsx`:
- Around line 502-519: The extra left margin on the ports span ("ml-2" in the
JSX that renders worktree.ports) creates uneven spacing compared to the
container's gap-3; remove the "ml-2" class from the <span> (or replace it with a
consistent spacing approach such as relying on the parent flex gap or adding a
separator element) so that the ports display uses the same gap as the
linesAdded/linesRemoved block when both render; locate the JSX that references
worktree.ports and adjust the className accordingly.
In `@apps/web-app/src/components/detail/DetailPanel.tsx`:
- Line 2179: The MessageCircle icon in DetailPanel (icon prop using className
"w-4 h-4 text-[`#9ca3af`]") uses a hardcoded hex color; replace that ad-hoc color
with the shared theme token for secondary text (use the project's token/class
for text.secondary) so the icon reads "w-4 h-4" plus the theme token instead of
text-[`#9ca3af`]; update the icon usage in DetailPanel.tsx where MessageCircle is
rendered to use the theme token class or style helper consistent with other
components.
In `@apps/web-app/src/components/PerformancePage.tsx`:
- Around line 20-25: The new PerformancePage.tsx file uses parent-relative
imports for usePerformanceMetrics, stopWorktree, reportPersistentErrorToast, and
theme symbols (palette, settings, text); replace these ../... imports with the
repo's configured path aliases (or move/duplicate helpers into the same folder)
so app files only use same-folder-relative imports; update the import statements
that reference usePerformanceMetrics, stopWorktree, reportPersistentErrorToast,
and the theme symbols to use the project's aliases (or local wrappers) and
ensure the build resolves them correctly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 46311187-237b-4167-9173-240ff0f6dbd8
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (44)
apps/cli/package.jsonapps/server/package.jsonapps/server/src/index.tsapps/server/src/manager.tsapps/server/src/ops-log.tsapps/server/src/perf-monitor.test.tsapps/server/src/perf-monitor.tsapps/server/src/port-manager.tsapps/server/src/routes/claude-plugins.tsapps/server/src/routes/config.tsapps/server/src/routes/events.tsapps/server/src/routes/logs.tsapps/server/src/routes/perf.test.tsapps/server/src/routes/perf.tsapps/server/src/routes/tasks.tsapps/server/src/routes/terminal.tsapps/server/src/terminal-manager.tsapps/web-app/src/App.tsxapps/web-app/src/components/ConfigurationPanel.tsxapps/web-app/src/components/Header.tsxapps/web-app/src/components/InfoBanner.tsxapps/web-app/src/components/IntegrationsPanel.tsxapps/web-app/src/components/NavBar.tsxapps/web-app/src/components/PerformancePage.test.tsxapps/web-app/src/components/PerformancePage.tsxapps/web-app/src/components/ShortcutsSection.tsxapps/web-app/src/components/VerificationPanel.tsxapps/web-app/src/components/detail/DetailHeader.tsxapps/web-app/src/components/detail/DetailPanel.tsxapps/web-app/src/hooks/api.tsapps/web-app/src/hooks/useAgentRules.tsapps/web-app/src/hooks/useConfig.tsapps/web-app/src/hooks/useFileChangeEvent.tsapps/web-app/src/hooks/useHooks.tsapps/web-app/src/hooks/useLocalConfig.tsapps/web-app/src/hooks/usePerformanceMetrics.test.tsapps/web-app/src/hooks/usePerformanceMetrics.tsapps/web-app/src/hooks/useWorktrees.tsapps/web-app/src/shortcuts.tsdocs/API.mddocs/ARCHITECTURE.mddocs/FRONTEND.mdlibs/shared/src/index.tslibs/shared/src/perf-types.ts
💤 Files with no reviewable changes (1)
- apps/web-app/src/components/NavBar.tsx
| // Watch .openkit/ directory recursively (Node 19+ on macOS supports recursive) | ||
| if (existsSync(configDir)) { | ||
| try { | ||
| const watcher = watch(configDir, { recursive: true }, (_event, filename) => { | ||
| if (!filename) return; | ||
| const basename = path.basename(filename); | ||
| const category = classifyOpenkitFile(basename); | ||
| if (!category) return; | ||
| debouncedEmit(category, category === "config" ? () => this.reloadConfig() : undefined); | ||
| }); | ||
| this.fileWatchers.push(watcher); | ||
| } catch (error) { | ||
| log.warn("Failed to watch .openkit directory", { domain: "file-watch", error }); | ||
| } | ||
| } | ||
|
|
||
| // Watch CLAUDE.md and AGENTS.md in project root | ||
| for (const filename of ["CLAUDE.md", "AGENTS.md"]) { | ||
| const filePath = path.join(this.configDir, filename); | ||
| if (!existsSync(filePath)) continue; |
There was a problem hiding this comment.
These watchers miss files/directories created after startup.
watchProjectFiles() only subscribes when .openkit/, CLAUDE.md, and AGENTS.md already exist. /api/config/init creates .openkit later and only calls reloadConfig(), so external changes under that new directory — and agent-rule files created/recreated later — will not emit SSE updates until the server restarts.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/manager.ts` around lines 323 - 342, watchProjectFiles only
registers watchers if .openkit, CLAUDE.md or AGENTS.md exist at startup, so
files/dirs created later never get watched; fix by (a) adding a persistent
watcher on the project root (or this.configDir parent) that listens for creation
events and, when it sees a new ".openkit" directory or creation of
"CLAUDE.md"/"AGENTS.md", sets up the same watcher logic (reuse
classifyOpenkitFile, debouncedEmit and push created watchers into
this.fileWatchers) and triggers reloadConfig as needed, and/or (b) ensure the
/api/config/init flow calls the same setup (e.g., invoke watchProjectFiles or
the new helper that attaches watchers) after it creates .openkit so new
directories/files are immediately watched.
| debouncedEmit(category, category === "config" ? () => this.reloadConfig() : undefined); | ||
| }); |
There was a problem hiding this comment.
reloadConfig() drops the PortManager runtime wiring.
The new config file watcher now calls this.reloadConfig(), but reloadConfig() replaces this.portManager without reapplying the constructor-only setDebugLogger(...) and useNativeHook setup. After the first external config edit, port operations lose ops-log instrumentation and can drift from the persisted native-hook flag until restart.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/manager.ts` around lines 331 - 332, reloadConfig() currently
replaces this.portManager without reapplying constructor-only wiring, so update
reloadConfig() to preserve and reapply the runtime hooks: when you create the
new PortManager instance, call its setDebugLogger(...) with the same logger used
originally (e.g., this.debugLogger or whatever logger was passed to the old
portManager) and call useNativeHook(...) to restore the native-hook flag (use
the previous this.portManager's state if present, otherwise derive from the new
config). In other words, after constructing the new portManager in
reloadConfig(), invoke newPortManager.setDebugLogger(...) and
newPortManager.useNativeHook(...) (or equivalent getters on the old instance) so
ops-log instrumentation and native-hook behavior persist across config reloads.
| const gitRoot = manager.getGitRoot(); | ||
| const instanceBranch = getWorktreeBranch(gitRoot) || null; | ||
| const instanceName = path.basename(gitRoot); | ||
| return c.json({ config, projectName, hasBranchNameRule: true, instanceName, instanceBranch }); |
There was a problem hiding this comment.
instanceBranch is null for the common repo layout.
getWorktreeBranch() reads a worktree-style .git file (gitdir: ...). On the main repo root, .git is usually a directory, so this falls back to null and the new header context never gets a branch name. Please use a helper that supports both repo roots and linked worktrees here.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/routes/config.ts` around lines 87 - 90, The code uses
getWorktreeBranch(gitRoot) which only handles worktree-style .git files, causing
instanceBranch to be null on normal repo roots; replace that call so
instanceBranch is obtained via a helper that supports both repo roots and linked
worktrees (e.g., getRepoBranch or getBranchForPath) instead of
getWorktreeBranch, using manager.getGitRoot() as the input; if such a helper
doesn't exist, implement one that checks for a worktree `.git` file and falls
back to reading .git/HEAD (or resolving HEAD) for repository roots, then return
that branch (or null) when assigning instanceBranch.
| {/* Worktree Created section */} | ||
| <HooksSection | ||
| title="Worktree Created" | ||
| description="Run automatically when a worktree is created" | ||
| icon={<FolderPlus className="w-3.5 h-3.5 text-cyan-400" />} | ||
| steps={worktreeCreatedSteps} | ||
| skills={worktreeCreatedSkills} | ||
| hasItems={hasWorktreeCreatedItems} | ||
| addingStep={addingStep === "worktree-created"} | ||
| onStartAdding={() => { | ||
| setAddingPrompt(null); | ||
| setShowImportPicker(null); | ||
| setAddingStep("worktree-created"); | ||
| }} | ||
| onCancelAdding={() => { | ||
| setAddingStep(null); | ||
| setNewName(""); | ||
| setNewCommand(""); | ||
| }} | ||
| onAddStep={() => addStep("worktree-created")} | ||
| addingPrompt={addingPrompt === "worktree-created"} | ||
| onStartAddingPrompt={() => { | ||
| setAddingStep(null); | ||
| setShowImportPicker(null); | ||
| setAddingPrompt("worktree-created"); | ||
| }} | ||
| onCancelAddingPrompt={() => { | ||
| setAddingPrompt(null); | ||
| setNewPromptName(""); | ||
| setNewPrompt(""); | ||
| }} | ||
| onAddPrompt={() => addPrompt("worktree-created")} | ||
| onShowImportPicker={() => { | ||
| setAddingStep(null); | ||
| setAddingPrompt(null); | ||
| setNewName(""); | ||
| setNewCommand(""); | ||
| setShowImportPicker("worktree-created"); | ||
| }} | ||
| showImportPicker={showImportPicker === "worktree-created"} | ||
| onImportSkill={(name) => handleImportSkill(name, "worktree-created")} | ||
| onCloseImportPicker={() => setShowImportPicker(null)} | ||
| newName={newName} | ||
| setNewName={setNewName} | ||
| newCommand={newCommand} | ||
| setNewCommand={setNewCommand} | ||
| newPromptName={newPromptName} | ||
| setNewPromptName={setNewPromptName} | ||
| newPrompt={newPrompt} | ||
| setNewPrompt={setNewPrompt} | ||
| nameRef={nameRef} | ||
| updateStep={updateStep} | ||
| removeStep={removeStep} | ||
| handleToggleSkill={handleToggleSkill} | ||
| handleRemoveSkill={handleRemoveSkill} | ||
| updateSkillCondition={updateSkillCondition} | ||
| allowPrompts | ||
| /> |
There was a problem hiding this comment.
Do not offer prompts or skills for lifecycle hooks.
These two sections still expose prompt and skill flows by setting allowPrompts and leaving allowSkills at its default. That lets users save unsupported entries for worktree-created / worktree-removed, even though those triggers are supposed to allow command steps only.
Suggested fix
<HooksSection
title="Worktree Created"
@@
- allowPrompts
+ allowPrompts={false}
+ allowSkills={false}
/>
@@
<HooksSection
title="Worktree Removed"
@@
- allowPrompts
+ allowPrompts={false}
+ allowSkills={false}
/>Also applies to: 489-546
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/components/VerificationPanel.tsx` around lines 430 - 487,
The Worktree lifecycle Hook sections ("Worktree Created" and "Worktree Removed"
in VerificationPanel) currently allow prompts/skills; change their HooksSection
props to explicitly disallow both by setting allowPrompts={false} and
allowSkills={false} for the "worktree-created" and "worktree-removed"
HooksSection instances so only command steps can be added. Keep other handlers
intact but ensure the UI props that surface prompt/skill flows are disabled for
these two sections.
| export function useFileChangeEvent(category: string, onChanged: () => void): void { | ||
| useEffect(() => { | ||
| const handler = (e: Event) => { | ||
| if ((e as CustomEvent).detail === category) { | ||
| onChanged(); | ||
| } | ||
| }; | ||
| window.addEventListener("OpenKit:file-changed", handler); | ||
| return () => window.removeEventListener("OpenKit:file-changed", handler); | ||
| }, [category, onChanged]); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
fd 'useFileChangeEvent\.test\.ts$' apps/web-app/src/hooks
rg -n --glob 'apps/web-app/src/hooks/**/*.test.ts' 'useFileChangeEvent|OpenKit:file-changed'Repository: fum4/openkit
Length of output: 38
🏁 Script executed:
#!/bin/bash
# Check file status and search for any test coverage
cd apps/web-app/src/hooks
# List all files in the hooks directory to see what exists
echo "=== Files in hooks directory ==="
ls -la | grep -E '\.(ts|tsx)$'
echo ""
echo "=== Searching for any test file that might test useFileChangeEvent ==="
find . -name '*.test.ts' -o -name '*.test.tsx' | xargs grep -l 'useFileChangeEvent' 2>/dev/null || echo "No test files found referencing useFileChangeEvent"
echo ""
echo "=== Checking if useFileChangeEvent.test.ts exists ==="
test -f useFileChangeEvent.test.ts && echo "Test file EXISTS" || echo "Test file DOES NOT EXIST"Repository: fum4/openkit
Length of output: 2537
Add co-located Vitest tests for useFileChangeEvent.ts.
The hook introduces event listener attachment, category filtering, and cleanup logic, but useFileChangeEvent.test.ts is missing. Following the pattern of peer hooks in this directory (useActivityFeed, useCustomTasks, useJiraIssues, etc.), add tests covering:
- Event listener registration on mount and cleanup on unmount
- Callback invocation only when category matches
- Dependency array updates triggering re-registration
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/hooks/useFileChangeEvent.ts` around lines 7 - 16, Add a
co-located Vitest + React Testing Library test file named
useFileChangeEvent.test.ts that verifies useFileChangeEvent attaches and removes
the window "OpenKit:file-changed" listener, only invokes the provided onChanged
callback when the CustomEvent.detail matches the given category, and
re-registers when dependencies change; mount a simple test component that calls
useFileChangeEvent(category, onChanged), dispatch
CustomEvent("OpenKit:file-changed", { detail: category }) and with a different
detail to assert callback called vs not called, unmount to assert listener
cleanup (e.g., dispatch after unmount does not call), and update the category
prop to assert the hook re-registers (old category no longer triggers, new
category does), using spies/mocks for onChanged and checking
addEventListener/removeEventListener were called where applicable.
| try { | ||
| delete (globalThis as Record<string, unknown>).EventSource; | ||
| } catch { | ||
| // fall through | ||
| } | ||
| (globalThis as Record<string, unknown>).EventSource = FakeEventSource; | ||
|
|
There was a problem hiding this comment.
Restore globalThis.EventSource after this suite.
This overwrites the global at module load and never puts it back, so later tests inherit the fake EventSource. The empty catch also hides environments where the override failed. Keep the override inside test lifecycle hooks and restore the original in afterAll.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/hooks/usePerformanceMetrics.test.ts` around lines 39 - 45,
The test suite currently overwrites globalThis.EventSource at module load with
FakeEventSource and silences any failure; move this override into test lifecycle
hooks by saving the original (const _originalEventSource =
globalThis.EventSource) in beforeAll, set globalThis.EventSource =
FakeEventSource there, and restore the original in afterAll
(globalThis.EventSource = _originalEventSource); also remove the empty catch
that hides errors and surface failures when the environment prevents assignment.
Ensure references to FakeEventSource and globalThis.EventSource are used exactly
as named so the setup/teardown wraps the suite.
| useEffect(() => { | ||
| setSnapshots([]); | ||
| setIsConnected(false); | ||
| setError(null); | ||
|
|
||
| let retryTimeoutId: ReturnType<typeof setTimeout> | null = null; | ||
| let eventSource: EventSource | null = null; | ||
|
|
||
| const connect = () => { | ||
| eventSource = new EventSource(getPerfStreamUrl(serverUrl)); | ||
|
|
There was a problem hiding this comment.
Skip connection setup when no server URL is available.
This effect clears state and then still calls new EventSource(getPerfStreamUrl(serverUrl)) when useServerUrlOptional() returns null. That creates bogus SSE attempts and a reconnect loop while the app is disconnected. Bail out before connect() until a real URL exists.
Minimal fix
useEffect(() => {
setSnapshots([]);
setIsConnected(false);
setError(null);
+
+ if (serverUrl === null) {
+ return;
+ }
let retryTimeoutId: ReturnType<typeof setTimeout> | null = null;
let eventSource: EventSource | null = null;Also applies to: 62-68
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/hooks/usePerformanceMetrics.ts` around lines 17 - 27, The
effect in usePerformanceMetrics calls connect() unconditionally which does new
EventSource(getPerfStreamUrl(serverUrl)) even when useServerUrlOptional()
returns null; update the useEffect (and the connect function) to bail out early
if serverUrl is falsy — e.g., check if (!serverUrl) return; before scheduling
retries or creating EventSource — and also add the same guard around the
reconnect logic referenced at lines 62-68 so no SSE is attempted until a real
serverUrl exists (reference: useEffect, connect, getPerfStreamUrl, serverUrl).
| } else if (data.type === "config-changed") { | ||
| window.dispatchEvent(new CustomEvent("OpenKit:config-changed", { detail: data })); | ||
| } else if (data.type === "file-changed") { | ||
| window.dispatchEvent(new CustomEvent("OpenKit:file-changed", { detail: data.category })); |
There was a problem hiding this comment.
Add Vitest coverage for new config-changed and file-changed branches.
These new SSE paths change app behavior but no corresponding tests are shown for dispatching OpenKit:config-changed and OpenKit:file-changed with correct detail payloads.
As per coding guidelines: “Every code change — feature, bugfix, or refactor — must include corresponding tests… Always use Vitest for testing.”
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/hooks/useWorktrees.ts` around lines 89 - 92, The new SSE
branches in useWorktrees.ts that handle data.type === "config-changed" and
data.type === "file-changed" dispatch CustomEvents ("OpenKit:config-changed"
with detail=data and "OpenKit:file-changed" with detail=data.category) but lack
Vitest coverage; add tests that mount or call the SSE/message handler from
useWorktrees (or the exported function handling SSE messages) and assert
window.dispatchEvent is called with a CustomEvent having the exact type and
detail payload for both "config-changed" and "file-changed" cases. Mock or spy
on window.dispatchEvent (and restore after) and simulate incoming SSE payloads
with { type: "config-changed", ... } and { type: "file-changed", category: ... }
to verify the dispatched event names and detail values. Ensure tests use Vitest
APIs (vi.spyOn/vi.mock) and include clear test names like "dispatches
OpenKit:config-changed with full data" and "dispatches OpenKit:file-changed with
category detail".
- prevent overlapping poll cycles by replacing setInterval with setTimeout chaining (was stacking expensive PID/disk scans) - add process kill endpoint for reliable worktree termination (bypasses worktree manager, sends SIGKILL directly to PIDs) - show all worktrees including stopped ones for disk visibility (running worktrees sorted first, stopped ones show disk only) - dynamic severity coloring on perf page icon and banner based on actual CPU/memory consumption (green/amber/red) - expose system total memory for accurate memory bar scaling - add exponential backoff to SSE reconnect (2s→30s cap) - clear file-change debounce timers on shutdown - suppress file-change notifications for hooks config writes - fix unsafe node-pty PID access with proper IPty typing - remove instanceName/instanceBranch feature (needs rethink) - surface actual server errors in kill/stop API responses - hooks page shows title and banner during loading state
|
/package |
There was a problem hiding this comment.
Actionable comments posted: 7
♻️ Duplicate comments (5)
apps/server/src/manager.ts (2)
402-404:⚠️ Potential issue | 🟠 MajorRecreating
PortManagerinreloadConfig()drops runtime wiring.The new instance is created without reapplying
setDebugLogger(...)anduseNativeHook, so port ops logging/behavior can diverge after config reload.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server/src/manager.ts` around lines 402 - 404, In reloadConfig(), recreating this.portManager loses runtime wiring; preserve and reapply the previous debug logger and native-hook state to the new PortManager instance. Before you overwrite this.portManager, capture the existing wiring (e.g., the result of this.portManager.getDebugLogger or the debug logger reference and the native-hook flag), then after new PortManager(this.config, configPath) call, invoke the same wiring methods on the new instance (setDebugLogger(...) and useNativeHook(...) with the captured values) so logging/behavior remains consistent across config reloads.
324-353:⚠️ Potential issue | 🟠 MajorWatcher setup still misses files/directories created after startup.
watchProjectFiles()only attaches watchers when targets already exist. If.openkit,CLAUDE.md, orAGENTS.mdappears later, change events are still not subscribed until restart.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server/src/manager.ts` around lines 324 - 353, watchProjectFiles() currently only attaches watchers when targets exist, missing files/directories created later; modify it to also watch parent directories (project root and configDir's parent) for creation events and dynamically attach the specific watchers when .openkit, CLAUDE.md, or AGENTS.md appear. Concretely: add a persistent watcher on the project root (and configDir's parent if different) that listens for "rename"/"change" events, call classifyOpenkitFile and the same debouncedEmit logic when a new entry appears, create the per-file or recursive directory watcher only once (track in this.fileWatchers to avoid duplicates), and keep the same error handling and reloadConfig behavior used in the existing watchProjectFiles() code paths.apps/web-app/src/components/ConfigurationPanel.tsx (1)
514-542:⚠️ Potential issue | 🟠 MajorHandle rule-reload failures fully (toast + log + catch all async paths).
loadBranchTab(branchTab)/loadCommitTab(commitTab)are not caught, and status refresh errors only warn-log without user feedback. When external sync fails, users can be left with stale rule state silently.Proposed fix pattern
useFileChangeEvent( "branch-rules", useCallback(() => { loadedTabs.current.clear(); - loadBranchTab(branchTab); + void loadBranchTab(branchTab).catch((error) => { + log.error("Failed to reload branch rule tab", { + domain: "config", + category: "branch-rules", + activeTab: branchTab, + error, + }); + reportPersistentErrorToast(error, "Failed to reload branch rule settings", { + scope: "configuration:branch-rules", + }); + }); api .fetchBranchRuleStatus() .then((s) => setBranchOverrides(s.overrides)) .catch((error) => { - log.warn("Failed to reload branch rule status", { domain: "config", error }); + log.error("Failed to reload branch rule status", { + domain: "config", + category: "branch-rules", + activeTab: branchTab, + error, + }); + reportPersistentErrorToast(error, "Failed to reload branch rule settings", { + scope: "configuration:branch-rules", + }); }); }, [loadBranchTab, branchTab, api]), );As per coding guidelines: “Always surface user-facing errors through toast notifications…”, “Errors that surface as toasts must also be logged through the logger”, and “Include actionable metadata in error logs.”
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/components/ConfigurationPanel.tsx` around lines 514 - 542, The callbacks passed to useFileChangeEvent must catch failures from both loadBranchTab/loadCommitTab and the status fetch so users get a toast and errors are logged with actionable metadata; update the branch and commit callbacks to run loadBranchTab(branchTab) / loadCommitTab(commitTab) inside a try/catch (or await them if they return promises) and on error call the toast function (e.g., showToast or toast.error) and log.error including domain:"config", the failing action ("loadBranchTab" or "loadCommitTab"), branchTab/commitTab identifiers and the error object; likewise replace the current .catch on api.fetchBranchRuleStatus()/fetchCommitRuleStatus() to both log.error with same metadata and surface a user toast, and ensure the callback returns/awaits the async work so no promise rejections are left uncaught.apps/web-app/src/components/VerificationPanel.tsx (1)
451-508:⚠️ Potential issue | 🟠 MajorDisable prompt/skill flows for lifecycle hooks.
Worktree CreatedandWorktree Removedsections still allow prompt (and implicitly skill) flows, which permits unsupported lifecycle config entries.Proposed fix
<HooksSection title="Worktree Created" @@ - allowPrompts + allowPrompts={false} + allowSkills={false} /> @@ <HooksSection title="Worktree Removed" @@ - allowPrompts + allowPrompts={false} + allowSkills={false} />Based on learnings: “Lifecycle hooks for
worktree-createdandworktree-removedmust only support command steps, not skill references.”Also applies to: 510-567
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/components/VerificationPanel.tsx` around lines 451 - 508, The Worktree lifecycle HookSection instances still expose prompt/skill flows; restrict them to command-only by removing prompt/skill-related props for the "worktree-created" and "worktree-removed" HooksSection usages: drop allowPrompts (or set it false), remove onStartAddingPrompt, onCancelAddingPrompt, onAddPrompt, addingPrompt, newPromptName, setNewPromptName, newPrompt, setNewPrompt, onImportSkill/handleImportSkill, skills/skills props, handleToggleSkill, handleRemoveSkill, and updateSkillCondition so only step/command-related props (addingStep, onStartAdding, onCancelAdding, onAddStep, newName, setNewName, newCommand, setNewCommand, nameRef, updateStep, removeStep, onShowImportPicker, showImportPicker, onCloseImportPicker) remain for the HooksSection components handling "worktree-created" and "worktree-removed".apps/web-app/src/components/InfoBanner.tsx (1)
54-58:⚠️ Potential issue | 🟠 MajorLog localStorage failures instead of swallowing them.
Both
catchblocks suppress storage failures, so banner state issues are invisible in production. Please log with operation +storageKeycontext.Proposed fix
import { X } from "lucide-react"; import { type ReactNode, useState } from "react"; +import { log } from "../logger"; import { text } from "../theme"; @@ const [dismissed, setDismissed] = useState(() => { try { return localStorage.getItem(storageKey) === "1"; - } catch { + } catch (error) { + log.warn("Failed to read InfoBanner dismissal state", { + domain: "InfoBanner", + operation: "localStorage.getItem", + storageKey, + error, + }); return false; } }); @@ const dismiss = () => { setDismissed(true); try { localStorage.setItem(storageKey, "1"); - } catch { - // localStorage unavailable + } catch (error) { + log.warn("Failed to persist InfoBanner dismissal state", { + domain: "InfoBanner", + operation: "localStorage.setItem", + storageKey, + error, + }); } };As per coding guidelines: “Silent
catch {}blocks are never acceptable” and “Always include adomainfield in the metadata object to namespace logs by feature.”Also applies to: 65-69
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/components/InfoBanner.tsx` around lines 54 - 58, Replace the silent catch blocks around localStorage access with logged errors: when catching exceptions from localStorage.getItem, localStorage.setItem or localStorage.removeItem (reference the storageKey variable and the getItem/setItem/removeItem calls), call the application's logging facility (e.g. logger.error) including a clear operation name ("get", "set", or "remove"), the storageKey value, the caught error details, and a metadata object that contains domain: "infoBanner" to namespace the log; apply the same change to both the read block (the try around localStorage.getItem) and the write/remove block mentioned (lines 65-69).
🧹 Nitpick comments (3)
apps/web-app/src/App.tsx (2)
44-47: Consider adding tests for the new navigation path.Per coding guidelines, every code change should include corresponding tests. The Performance page integration should be covered by tests verifying:
nav-performanceshortcut triggers view switch- View state persistence includes
"performance"PerformancePagerenders whenactiveView === "performance"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/App.tsx` around lines 44 - 47, Add unit/integration tests that cover the new Performance navigation: write tests that simulate the `nav-performance` shortcut/keybinding and assert the app switches to the "performance" view (check whatever handler/function that processes shortcuts, e.g., the shortcut dispatch or onShortcut function used by Header/Nav), verify view persistence logic stores `"performance"` in the saved view state (assert the persistence API or localStorage/mocked store that your app uses), and render the top-level/App component with `activeView === "performance"` to assert `PerformancePage` is mounted and visible (check for the PerformancePage component or its unique DOM output). Target tests around the components/handlers referenced by PerformancePage, activeView, and the shortcut name `nav-performance`.
2976-2995: Motion wrapper useskey={activeView}— consider if re-mounting is intended.Using
key={activeView}causes child components to fully re-mount when switching between workspace, agents, and activity views. This enables entrance animations but resets any local state within those components. If preserving component state across tab switches is important, consider removing the key or using CSS-based transitions instead.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/App.tsx` around lines 2976 - 2995, The motion wrapper currently uses key={activeView} on the motion.div which forces full remounts of the child views (workspace/agents/activity) and resets their local state; remove the key prop from the motion.div (or move it off the persistent wrapper) so switching activeView only toggles visibility without remounting, and if you still need entrance animations, implement them via variants/animate props or a nested animated element so components like CreateForm and the workspace children keep their state across tab switches.apps/web-app/src/components/InfoBanner.tsx (1)
8-44: Use shared theme tokens for banner colors instead of ad-hoc hex variants.This shared component hardcodes multiple custom shades, which makes cross-page theming drift likely. Prefer mapping to shared theme tokens.
As per coding guidelines: “Always use the standard shared color palette and tokens from
apps/web-app/src/theme.ts. Do not introduce ad-hoc lighter/darker color variants for existing control patterns.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web-app/src/components/InfoBanner.tsx` around lines 8 - 44, colorStyles currently uses hardcoded hex/lightness variants which violates the shared-theme rule; replace each ad-hoc color entry in the colorStyles map (and any references to BannerColor) with the corresponding token names from the shared theme (import tokens from apps/web-app/src/theme.ts and map BannerColor values to theme tokens for bg, border, and dismiss classes) so the InfoBanner component uses the centralized palette instead of custom hex strings.
🤖 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/manager.ts`:
- Around line 2041-2043: The code adds "config" to
this.suppressedFileChangeCategories before calling writeFileSync(configPath,
JSON.stringify(existing, null, 2) + "\n"), so if writeFileSync throws the
suppression remains; wrap the write in a try/catch/finally (or try/finally)
around writeFileSync in the same method so that
this.suppressedFileChangeCategories.delete("config") (or .remove) is always
executed in the finally block (and rethrow the error if needed), ensuring the
"config" suppression is cleared on both success and failure.
In `@apps/server/src/routes/perf.ts`:
- Around line 32-37: In the outer catch block that currently returns c.json({
success: false, error: err instanceof Error ? err.message : "Invalid request" },
400), add an error log of err before the return; call the existing logger (e.g.,
logger.error(err) or processLogger.error(err)) if one is available in scope,
otherwise fall back to console.error(err), ensuring you still return the same
c.json response afterward.
- Around line 61-73: When enqueue() fails inside the SSE subscription callback,
call controller.close() after unsubscribe() so the ReadableStream is closed
(update the block where controller.enqueue is caught); additionally add a
cancel() handler on the ReadableStream (the stream returned from the function
that sets up the SSE) that invokes unsubscribe() and controller.close() to
ensure cleanup if the client closes the body before c.req.raw.signal aborts —
reference the existing controller.enqueue error catch, unsubscribe(),
controller.close(), and c.req.raw.signal.addEventListener("abort", ...)
locations to implement these changes.
In `@apps/server/src/routes/verification.ts`:
- Around line 264-269: The current flow calls
manager.suppressFileChangeNotification("hooks") before calling
hooksManager.saveConfig(body), which can leave suppression set if saveConfig
throws; change the flow to ensure suppression is only active during the actual
write and always cleared: either call
manager.suppressFileChangeNotification("hooks") immediately before the code path
that performs the file write (after hooksManager.saveConfig succeeds) or wrap
the save+write in a try/finally and in the finally call the corresponding
unsuppress/clear function to remove suppression. Reference
manager.suppressFileChangeNotification and hooksManager.saveConfig and ensure
the cleanup call (unsuppress/clear) is invoked unconditionally so suppression
cannot persist after an error.
In `@apps/web-app/src/App.tsx`:
- Around line 942-944: The persisted-view validation omits the "performance"
view so selection resets; update the hardcoded allowed-view checks used during
view state initialization and the restoration effect to include "performance"
(i.e., accept the string "performance" alongside existing valid values) so that
setActiveView("performance") survives refresh/project switch—locate the view
initialization block and the effect that restores savedView and add
"performance" to their allowed-values checks.
In `@apps/web-app/src/hooks/usePerformanceMetrics.test.ts`:
- Around line 41-46: The empty catch in the test setup around replacing global
EventSource must be made explicit: in the try/catch block that attempts to
delete (globalThis as Record<string, unknown>).EventSource and then assigns
FakeEventSource, replace the silent catch with either a short comment explaining
why swallowing the error is acceptable (e.g., "ignore if property is
non-configurable in this environment") or log the caught error at debug level
using the test logger; keep this change local to the test setup so the behavior
of FakeEventSource assignment remains the same in usePerformanceMetrics.test.ts.
In `@apps/web-app/src/index.css`:
- Around line 134-138: Rename the keyframe from "fadeIn" to kebab-case "fade-in"
in the global CSS (update the `@keyframes` declaration currently named fadeIn and
add an explicit from { opacity: 0 } state), then update all component references
that use that animation by changing "fadeIn" to "fade-in" (specifically in
VerificationPanel component where animation style string references fadeIn and
in PerformancePage component where animation style string references fadeIn) so
the animation name matches the new kebab-case keyframes and satisfies
Stylelint's keyframes-name-pattern.
---
Duplicate comments:
In `@apps/server/src/manager.ts`:
- Around line 402-404: In reloadConfig(), recreating this.portManager loses
runtime wiring; preserve and reapply the previous debug logger and native-hook
state to the new PortManager instance. Before you overwrite this.portManager,
capture the existing wiring (e.g., the result of this.portManager.getDebugLogger
or the debug logger reference and the native-hook flag), then after new
PortManager(this.config, configPath) call, invoke the same wiring methods on the
new instance (setDebugLogger(...) and useNativeHook(...) with the captured
values) so logging/behavior remains consistent across config reloads.
- Around line 324-353: watchProjectFiles() currently only attaches watchers when
targets exist, missing files/directories created later; modify it to also watch
parent directories (project root and configDir's parent) for creation events and
dynamically attach the specific watchers when .openkit, CLAUDE.md, or AGENTS.md
appear. Concretely: add a persistent watcher on the project root (and
configDir's parent if different) that listens for "rename"/"change" events, call
classifyOpenkitFile and the same debouncedEmit logic when a new entry appears,
create the per-file or recursive directory watcher only once (track in
this.fileWatchers to avoid duplicates), and keep the same error handling and
reloadConfig behavior used in the existing watchProjectFiles() code paths.
In `@apps/web-app/src/components/ConfigurationPanel.tsx`:
- Around line 514-542: The callbacks passed to useFileChangeEvent must catch
failures from both loadBranchTab/loadCommitTab and the status fetch so users get
a toast and errors are logged with actionable metadata; update the branch and
commit callbacks to run loadBranchTab(branchTab) / loadCommitTab(commitTab)
inside a try/catch (or await them if they return promises) and on error call the
toast function (e.g., showToast or toast.error) and log.error including
domain:"config", the failing action ("loadBranchTab" or "loadCommitTab"),
branchTab/commitTab identifiers and the error object; likewise replace the
current .catch on api.fetchBranchRuleStatus()/fetchCommitRuleStatus() to both
log.error with same metadata and surface a user toast, and ensure the callback
returns/awaits the async work so no promise rejections are left uncaught.
In `@apps/web-app/src/components/InfoBanner.tsx`:
- Around line 54-58: Replace the silent catch blocks around localStorage access
with logged errors: when catching exceptions from localStorage.getItem,
localStorage.setItem or localStorage.removeItem (reference the storageKey
variable and the getItem/setItem/removeItem calls), call the application's
logging facility (e.g. logger.error) including a clear operation name ("get",
"set", or "remove"), the storageKey value, the caught error details, and a
metadata object that contains domain: "infoBanner" to namespace the log; apply
the same change to both the read block (the try around localStorage.getItem) and
the write/remove block mentioned (lines 65-69).
In `@apps/web-app/src/components/VerificationPanel.tsx`:
- Around line 451-508: The Worktree lifecycle HookSection instances still expose
prompt/skill flows; restrict them to command-only by removing
prompt/skill-related props for the "worktree-created" and "worktree-removed"
HooksSection usages: drop allowPrompts (or set it false), remove
onStartAddingPrompt, onCancelAddingPrompt, onAddPrompt, addingPrompt,
newPromptName, setNewPromptName, newPrompt, setNewPrompt,
onImportSkill/handleImportSkill, skills/skills props, handleToggleSkill,
handleRemoveSkill, and updateSkillCondition so only step/command-related props
(addingStep, onStartAdding, onCancelAdding, onAddStep, newName, setNewName,
newCommand, setNewCommand, nameRef, updateStep, removeStep, onShowImportPicker,
showImportPicker, onCloseImportPicker) remain for the HooksSection components
handling "worktree-created" and "worktree-removed".
---
Nitpick comments:
In `@apps/web-app/src/App.tsx`:
- Around line 44-47: Add unit/integration tests that cover the new Performance
navigation: write tests that simulate the `nav-performance` shortcut/keybinding
and assert the app switches to the "performance" view (check whatever
handler/function that processes shortcuts, e.g., the shortcut dispatch or
onShortcut function used by Header/Nav), verify view persistence logic stores
`"performance"` in the saved view state (assert the persistence API or
localStorage/mocked store that your app uses), and render the top-level/App
component with `activeView === "performance"` to assert `PerformancePage` is
mounted and visible (check for the PerformancePage component or its unique DOM
output). Target tests around the components/handlers referenced by
PerformancePage, activeView, and the shortcut name `nav-performance`.
- Around line 2976-2995: The motion wrapper currently uses key={activeView} on
the motion.div which forces full remounts of the child views
(workspace/agents/activity) and resets their local state; remove the key prop
from the motion.div (or move it off the persistent wrapper) so switching
activeView only toggles visibility without remounting, and if you still need
entrance animations, implement them via variants/animate props or a nested
animated element so components like CreateForm and the workspace children keep
their state across tab switches.
In `@apps/web-app/src/components/InfoBanner.tsx`:
- Around line 8-44: colorStyles currently uses hardcoded hex/lightness variants
which violates the shared-theme rule; replace each ad-hoc color entry in the
colorStyles map (and any references to BannerColor) with the corresponding token
names from the shared theme (import tokens from apps/web-app/src/theme.ts and
map BannerColor values to theme tokens for bg, border, and dismiss classes) so
the InfoBanner component uses the centralized palette instead of custom hex
strings.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: ab6c728d-00a4-4dc4-96ee-2b84421c5540
📒 Files selected for processing (21)
.claude/skills/address-pr-review/SKILL.mdapps/server/src/manager.tsapps/server/src/perf-monitor.test.tsapps/server/src/perf-monitor.tsapps/server/src/routes/events.tsapps/server/src/routes/perf.tsapps/server/src/routes/verification.tsapps/server/src/terminal-manager.tsapps/web-app/src/App.tsxapps/web-app/src/components/ConfigurationPanel.tsxapps/web-app/src/components/Header.tsxapps/web-app/src/components/InfoBanner.tsxapps/web-app/src/components/PerformancePage.test.tsxapps/web-app/src/components/PerformancePage.tsxapps/web-app/src/components/VerificationPanel.tsxapps/web-app/src/hooks/api.tsapps/web-app/src/hooks/useConfig.tsapps/web-app/src/hooks/usePerformanceMetrics.test.tsapps/web-app/src/hooks/usePerformanceMetrics.tsapps/web-app/src/index.csslibs/shared/src/perf-types.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- apps/server/src/routes/events.ts
- apps/web-app/src/components/PerformancePage.tsx
- apps/server/src/terminal-manager.ts
- apps/web-app/src/components/Header.tsx
- apps/server/src/perf-monitor.test.ts
- apps/web-app/src/components/PerformancePage.test.tsx
| this.suppressedFileChangeCategories.add("config"); | ||
| writeFileSync(configPath, JSON.stringify(existing, null, 2) + "\n"); | ||
| } |
There was a problem hiding this comment.
Avoid leaving config file-change suppression stuck on write failure.
Suppression is set before writeFileSync. If the write throws, the suppression flag remains and can incorrectly drop a later real external config change.
Proposed fix
if (configExists || hasConfigUpdates) {
- this.suppressedFileChangeCategories.add("config");
- writeFileSync(configPath, JSON.stringify(existing, null, 2) + "\n");
+ this.suppressedFileChangeCategories.add("config");
+ try {
+ writeFileSync(configPath, JSON.stringify(existing, null, 2) + "\n");
+ } catch (error) {
+ this.suppressedFileChangeCategories.delete("config");
+ throw error;
+ }
}📝 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.
| this.suppressedFileChangeCategories.add("config"); | |
| writeFileSync(configPath, JSON.stringify(existing, null, 2) + "\n"); | |
| } | |
| this.suppressedFileChangeCategories.add("config"); | |
| try { | |
| writeFileSync(configPath, JSON.stringify(existing, null, 2) + "\n"); | |
| } catch (error) { | |
| this.suppressedFileChangeCategories.delete("config"); | |
| log.error("Failed to write config file", { | |
| domain: "config", | |
| configPath, | |
| error: error instanceof Error ? error.message : String(error), | |
| }); | |
| throw error; | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/manager.ts` around lines 2041 - 2043, The code adds "config"
to this.suppressedFileChangeCategories before calling writeFileSync(configPath,
JSON.stringify(existing, null, 2) + "\n"), so if writeFileSync throws the
suppression remains; wrap the write in a try/catch/finally (or try/finally)
around writeFileSync in the same method so that
this.suppressedFileChangeCategories.delete("config") (or .remove) is always
executed in the finally block (and rethrow the error if needed), ensuring the
"config" suppression is cleared on both success and failure.
| } catch (err) { | ||
| return c.json( | ||
| { success: false, error: err instanceof Error ? err.message : "Invalid request" }, | ||
| 400, | ||
| ); | ||
| } |
There was a problem hiding this comment.
Log the error before returning to client.
The outer catch block returns the error to the client but doesn't log it. Per coding guidelines, errors should be logged for debugging even when surfaced to users.
🔧 Proposed fix
} catch (err) {
+ log.warn("Kill request failed", { domain: "perf", error: err });
return c.json(
{ success: false, error: err instanceof Error ? err.message : "Invalid request" },
400,
);
}📝 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.
| } catch (err) { | |
| return c.json( | |
| { success: false, error: err instanceof Error ? err.message : "Invalid request" }, | |
| 400, | |
| ); | |
| } | |
| } catch (err) { | |
| log.warn("Kill request failed", { domain: "perf", error: err }); | |
| return c.json( | |
| { success: false, error: err instanceof Error ? err.message : "Invalid request" }, | |
| 400, | |
| ); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/routes/perf.ts` around lines 32 - 37, In the outer catch
block that currently returns c.json({ success: false, error: err instanceof
Error ? err.message : "Invalid request" }, 400), add an error log of err before
the return; call the existing logger (e.g., logger.error(err) or
processLogger.error(err)) if one is available in scope, otherwise fall back to
console.error(err), ensuring you still return the same c.json response
afterward.
| try { | ||
| controller.enqueue(`data: ${JSON.stringify({ type: "perf-snapshot", snapshot })}\n\n`); | ||
| } catch (error) { | ||
| log.debug("Perf SSE enqueue failed, unsubscribing", { domain: "metrics", error }); | ||
| unsubscribe(); | ||
| } | ||
| }); | ||
|
|
||
| c.req.raw.signal.addEventListener("abort", () => { | ||
| unsubscribe(); | ||
| controller.close(); | ||
| }); | ||
| }, |
There was a problem hiding this comment.
SSE cleanup is incomplete: close controller on enqueue failure and add cancel handler.
When enqueue() fails, the code unsubscribes but doesn't close the controller, leaving the stream in an inconsistent state. Additionally, there's no cancel() handler on the ReadableStream to clean up if the body is closed before the abort signal fires.
🔧 Proposed fix
const stream = new ReadableStream({
start(controller) {
+ let cleaned = false;
+ const cleanup = (reason?: string) => {
+ if (cleaned) return;
+ cleaned = true;
+ unsubscribe();
+ try {
+ controller.close();
+ } catch {
+ // controller may already be closed
+ }
+ if (reason) {
+ log.debug("Perf SSE cleanup", { domain: "metrics", reason });
+ }
+ };
+
// Always send history on connect (even if empty) to kick-start the
// stream — `@hono/node-server` may not begin piping until the first
// chunk is enqueued synchronously inside start().
const history = perfMonitor.getHistory();
controller.enqueue(
`data: ${JSON.stringify({ type: "perf-history", snapshots: history })}\n\n`,
);
// Subscribe to live updates
const unsubscribe = perfMonitor.subscribe((snapshot) => {
try {
controller.enqueue(`data: ${JSON.stringify({ type: "perf-snapshot", snapshot })}\n\n`);
} catch (error) {
log.debug("Perf SSE enqueue failed, unsubscribing", { domain: "metrics", error });
- unsubscribe();
+ cleanup("enqueue failed");
}
});
c.req.raw.signal.addEventListener("abort", () => {
- unsubscribe();
- controller.close();
+ cleanup("client abort");
});
},
+ cancel() {
+ // ReadableStream was canceled (e.g., body closed)
+ },
});🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/routes/perf.ts` around lines 61 - 73, When enqueue() fails
inside the SSE subscription callback, call controller.close() after
unsubscribe() so the ReadableStream is closed (update the block where
controller.enqueue is caught); additionally add a cancel() handler on the
ReadableStream (the stream returned from the function that sets up the SSE) that
invokes unsubscribe() and controller.close() to ensure cleanup if the client
closes the body before c.req.raw.signal aborts — reference the existing
controller.enqueue error catch, unsubscribe(), controller.close(), and
c.req.raw.signal.addEventListener("abort", ...) locations to implement these
changes.
| app.put("/api/hooks/config", async (c) => { | ||
| try { | ||
| const body = await c.req.json(); | ||
| manager.suppressFileChangeNotification("hooks"); | ||
| const config = hooksManager.saveConfig(body); | ||
| return c.json({ success: true, config }); |
There was a problem hiding this comment.
Make hooks file-change suppression failure-safe.
Suppression is set before saveConfig. If save fails before the write path, suppression can remain set and suppress the next real external hooks update.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server/src/routes/verification.ts` around lines 264 - 269, The current
flow calls manager.suppressFileChangeNotification("hooks") before calling
hooksManager.saveConfig(body), which can leave suppression set if saveConfig
throws; change the flow to ensure suppression is only active during the actual
write and always cleared: either call
manager.suppressFileChangeNotification("hooks") immediately before the code path
that performs the file write (after hooksManager.saveConfig succeeds) or wrap
the save+write in a try/finally and in the finally call the corresponding
unsuppress/clear function to remove suppression. Reference
manager.suppressFileChangeNotification and hooksManager.saveConfig and ensure
the cleanup call (unsuppress/clear) is invoked unconditionally so suppression
cannot persist after an error.
| case "nav-performance": | ||
| setActiveView("performance"); | ||
| break; |
There was a problem hiding this comment.
View persistence is broken for the "performance" view.
The view state initialization (lines 527-540) and restoration effect (lines 552-564) validate saved views against a hardcoded list that doesn't include "performance". Users navigating to the Performance page will lose their view selection on page refresh or project switch.
🐛 Proposed fix to update view validation
At line ~533, add the "performance" check:
if (
saved === "workspace" ||
saved === "agents" ||
saved === "activity" ||
saved === "hooks" ||
saved === "configuration" ||
- saved === "integrations"
+ saved === "integrations" ||
+ saved === "performance"
) {At line ~557, apply the same fix:
if (
saved === "workspace" ||
saved === "agents" ||
saved === "activity" ||
saved === "hooks" ||
saved === "configuration" ||
- saved === "integrations"
+ saved === "integrations" ||
+ saved === "performance"
) {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/App.tsx` around lines 942 - 944, The persisted-view
validation omits the "performance" view so selection resets; update the
hardcoded allowed-view checks used during view state initialization and the
restoration effect to include "performance" (i.e., accept the string
"performance" alongside existing valid values) so that
setActiveView("performance") survives refresh/project switch—locate the view
initialization block and the effect that restores savedView and add
"performance" to their allowed-values checks.
| try { | ||
| delete (globalThis as Record<string, unknown>).EventSource; | ||
| } catch { | ||
| // fall through | ||
| } | ||
| (globalThis as Record<string, unknown>).EventSource = FakeEventSource; |
There was a problem hiding this comment.
Empty catch block violates coding guidelines.
Per coding guidelines, silent catch {} blocks are never acceptable. Even if failure is expected, add a comment explaining why the error is intentionally ignored or log at debug level.
🔧 Proposed fix
try {
delete (globalThis as Record<string, unknown>).EventSource;
-} catch {
- // fall through
+} catch (error) {
+ // Some environments (e.g., jsdom) may not allow deleting EventSource.
+ // This is expected and safe to ignore since we overwrite it immediately after.
}📝 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.
| try { | |
| delete (globalThis as Record<string, unknown>).EventSource; | |
| } catch { | |
| // fall through | |
| } | |
| (globalThis as Record<string, unknown>).EventSource = FakeEventSource; | |
| try { | |
| delete (globalThis as Record<string, unknown>).EventSource; | |
| } catch (error) { | |
| // Some environments (e.g., jsdom) may not allow deleting EventSource. | |
| // This is expected and safe to ignore since we overwrite it immediately after. | |
| } | |
| (globalThis as Record<string, unknown>).EventSource = FakeEventSource; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/hooks/usePerformanceMetrics.test.ts` around lines 41 - 46,
The empty catch in the test setup around replacing global EventSource must be
made explicit: in the try/catch block that attempts to delete (globalThis as
Record<string, unknown>).EventSource and then assigns FakeEventSource, replace
the silent catch with either a short comment explaining why swallowing the error
is acceptable (e.g., "ignore if property is non-configurable in this
environment") or log the caught error at debug level using the test logger; keep
this change local to the test setup so the behavior of FakeEventSource
assignment remains the same in usePerformanceMetrics.test.ts.
| @keyframes fadeIn { | ||
| to { | ||
| opacity: 1; | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for usages of fadeIn animation name in the codebase
rg -n "fadeIn" --type css --type tsx --type ts --type jsx -g '!node_modules'Repository: fum4/openkit
Length of output: 83
🏁 Script executed:
#!/bin/bash
# Corrected search for fadeIn usage with proper rg syntax
rg -n "fadeIn" --type css --type js -g '!node_modules'Repository: fum4/openkit
Length of output: 106
🏁 Script executed:
#!/bin/bash
# Also search in all file types without type restriction
rg -n "fadeIn" -g '!node_modules' | head -30Repository: fum4/openkit
Length of output: 383
🏁 Script executed:
#!/bin/bash
# Check the actual CSS file content to verify keyframe names
cat -n apps/web-app/src/index.css | sed -n '70,150p'Repository: fum4/openkit
Length of output: 1535
Rename keyframe to kebab-case and update component references.
The existing animations in this file (border-sweep, border-sweep-fade) use kebab-case. The fadeIn keyframe breaks this consistency and violates Stylelint's keyframes-name-pattern rule.
This animation is referenced in two component files and must be updated alongside the CSS change:
apps/web-app/src/components/VerificationPanel.tsx:58apps/web-app/src/components/PerformancePage.tsx:598
Consider adding an explicit from state for clarity.
Required changes
In apps/web-app/src/index.css:
-@keyframes fadeIn {
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
to {
opacity: 1;
}
}In VerificationPanel.tsx and PerformancePage.tsx:
Update animation references from fadeIn to fade-in in the animation style strings.
🧰 Tools
🪛 Stylelint (17.4.0)
[error] 134-134: Expected keyframe name "fadeIn" to be kebab-case (keyframes-name-pattern)
(keyframes-name-pattern)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web-app/src/index.css` around lines 134 - 138, Rename the keyframe from
"fadeIn" to kebab-case "fade-in" in the global CSS (update the `@keyframes`
declaration currently named fadeIn and add an explicit from { opacity: 0 }
state), then update all component references that use that animation by changing
"fadeIn" to "fade-in" (specifically in VerificationPanel component where
animation style string references fadeIn and in PerformancePage component where
animation style string references fadeIn) so the animation name matches the new
kebab-case keyframes and satisfies Stylelint's keyframes-name-pattern.
Summary by CodeRabbit
Release Notes
New Features
Improvements
Tests