refactor: package code organization wave 11 - #2333
Conversation
…ow-definitions Behavior-preserving package organization after wave 9 (#2274): - types/agents.ts: agent permissions, entity, ratings, reflections, heartbeat runs - app/api: missions, messaging, plugins-and-skills, todo, insights, system-panel - rename remaining-ops-8 → task-store/workflow-definitions.ts Ratchet types.ts and legacy.ts line-count ceilings downward.
- Import MissionWithHierarchy locally for createMissionFromInterview - Import message contract types in messaging.ts - Import dedupe for fetchPluginUiSlots - Import todo create/update input types in todo.ts
export type re-exports from missions.ts do not create local bindings; milestone/slice interview apply/skip handlers need the imports for typecheck.
Dashboard app typecheck failed with TS2307 on html2canvas under bundler resolution on CI. Ship an ambient module under app/types so capture-screenshot typechecks without relying on package typings resolution.
Behavior-preserving package organization after wave 10: - app/api/event-source.ts (resilient SSE reconnect) - app/api/chat, projects, agents, workflows, scheduling, ai-text, ai-sessions, research - rename remaining-ops-6 → task-store/branch-and-pr-entities.ts Ratchet legacy.ts line-count ceiling downward (~8921 → ~5670).
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThe PR extracts dashboard API clients into dedicated modules, adds typed agents, AI sessions, chat, research, project, scheduling, and workflow APIs, preserves legacy imports through re-exports, updates core task-store wiring, supports nullable mission auto-merge values, and forwards subtask priorities during task creation. ChangesCore store module rewiring
Dashboard AI and streaming clients
Dashboard domain API clients
Dashboard project, workflow, and scheduling clients
Legacy compatibility and supporting declarations
Mission and subtask contract updates
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant connectSubtaskStream
participant createResilientEventSource
participant SubtaskSSEEndpoint
Client->>connectSubtaskStream: Start breakdown stream
connectSubtaskStream->>createResilientEventSource: Register event handlers
createResilientEventSource->>SubtaskSSEEndpoint: Open authenticated SSE connection
SubtaskSSEEndpoint-->>createResilientEventSource: Send thinking, subtasks, error, complete
createResilientEventSource-->>connectSubtaskStream: Dispatch parsed events
connectSubtaskStream-->>Client: Forward updates and connection state
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Greptile SummaryWave 11 of the dashboard API code-organization effort, continuing the peel of ~3,250 lines from
Confidence Score: 5/5Safe to merge — this is a behavior-preserving extraction with stable public re-exports and no logic changes in the core paths. All peeled modules are straight extractions from legacy.ts with matching re-exports, the store rename is mechanical, and the two feature additions (subtask priority, mission autoMerge null) are narrowly scoped and correctly validated. Typechecks and eslint are reported green in the test plan. No files require special attention beyond the minor FNXC docstring correction in branch-and-pr-entities.ts. Important Files Changed
Flowchart%%{init: {'theme': 'neutral'}}%%
flowchart TD
A["app/api.ts\n(public barrel)"] --> L["legacy.ts\n(re-export shim)"]
L --> ES["event-source.ts\nResilientEventSource / SSE"]
L --> AG["agents.ts\nAgent CRUD / soul / memory"]
L --> AIS["ai-sessions.ts\nAI sessions + startKeepAlive"]
L --> AIT["ai-text.ts\nrefine / translate / subtasks"]
L --> CH["chat.ts\nChat sessions / rooms / stream"]
L --> PR["projects.ts\nMulti-project management"]
L --> WF["workflows.ts\nWorkflow definitions"]
L --> SC["scheduling.ts\nAutomations + routines"]
L --> RE["research.ts\nResearch + evals"]
AIT -->|"imports startKeepAlive"| AIS
AIT -->|"imports createResilientEventSource"| ES
CH -->|"imports StreamConnectionState"| ES
subgraph core["@fusion/core"]
RO6["remaining-ops-6.ts\n(old name)"] -->|"renamed to"| BAP["branch-and-pr-entities.ts\nBranchGroup / PrEntity / PrThread"]
end
S["store.ts"] -->|"imports"| BAP
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
A["app/api.ts\n(public barrel)"] --> L["legacy.ts\n(re-export shim)"]
L --> ES["event-source.ts\nResilientEventSource / SSE"]
L --> AG["agents.ts\nAgent CRUD / soul / memory"]
L --> AIS["ai-sessions.ts\nAI sessions + startKeepAlive"]
L --> AIT["ai-text.ts\nrefine / translate / subtasks"]
L --> CH["chat.ts\nChat sessions / rooms / stream"]
L --> PR["projects.ts\nMulti-project management"]
L --> WF["workflows.ts\nWorkflow definitions"]
L --> SC["scheduling.ts\nAutomations + routines"]
L --> RE["research.ts\nResearch + evals"]
AIT -->|"imports startKeepAlive"| AIS
AIT -->|"imports createResilientEventSource"| ES
CH -->|"imports StreamConnectionState"| ES
subgraph core["@fusion/core"]
RO6["remaining-ops-6.ts\n(old name)"] -->|"renamed to"| BAP["branch-and-pr-entities.ts\nBranchGroup / PrEntity / PrThread"]
end
S["store.ts"] -->|"imports"| BAP
Reviews (4): Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." | Re-trigger Greptile |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (4)
packages/dashboard/app/api/workflows.ts (1)
13-18: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRepeated inline
import("@fusion/core").Xtype references.Since
export type { ... } from "@fusion/core"doesn't create a local binding, the file falls back to inlineimport("@fusion/core").WorkflowDefinition/TraitFlags/etc. dozens of times. Adding a companionimport type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionUpdate, WorkflowIr, TraitFlags, TraitHookDescriptors, TraitConfigSchema, ResolvedWorkflowOptionalStep, WorkflowStepTemplate } from "@fusion/core";would let the rest of the file reference these directly, improving readability without changing behavior.Also applies to: 21-21, 34-36, 59-71
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/dashboard/app/api/workflows.ts` around lines 13 - 18, The file’s type-only re-exports do not create local bindings, causing repeated inline import type references. Add a companion type-only import from `@fusion/core` for WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionUpdate, WorkflowIr, TraitFlags, TraitHookDescriptors, TraitConfigSchema, ResolvedWorkflowOptionalStep, and WorkflowStepTemplate, then replace the corresponding inline references throughout the workflow API definitions with the imported names while preserving the existing exports.packages/dashboard/app/api/ai-sessions.ts (1)
122-166: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicates
api()'s error-parsing logic instead of reusing it.This block reimplements the HTML/JSON detection and
ApiRequestErrorconstruction that already exists inclient.ts'sapi()(see context snippet 3), only to special-case a 404 as success. Any future fix to that shared parsing logic (e.g. error-preview truncation, content-type checks) now has to be kept in sync in two places.Consider adding a narrow option to
api()(e.g.okStatuses) so DELETE-with-404-as-success can reuse the shared implementation instead of duplicating it.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/dashboard/app/api/ai-sessions.ts` around lines 122 - 166, Update deleteAiSession to reuse the shared api() error-parsing path instead of locally handling content types, JSON parsing, and ApiRequestError construction. Add a narrow okStatuses option to api() in client.ts, pass the 404 status from deleteAiSession while retaining DELETE behavior, and remove the duplicated parsing block.packages/dashboard/app/api/chat.ts (1)
568-628: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: extract the shared SSE parser.
dispatchEventandprocessLinesare duplicated almost verbatim betweenstreamChatResponse(568-727) andattachChatStream(791-922). Consider extracting a shared SSE line-parser/dispatcher to avoid the two copies drifting (e.g., the connection-close handling already differs). Not blocking.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/dashboard/app/api/chat.ts` around lines 568 - 628, The SSE event parsing and dispatch logic is duplicated between streamChatResponse’s dispatchEvent/processLines flow and attachChatStream. Extract the shared line-parser/dispatcher into a reusable helper, then have both flows use it while preserving their existing connection-close behavior and handler callbacks.packages/dashboard/app/api/scheduling.ts (1)
64-66: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winEncode automation/routine IDs in path segments for consistency and safety.
Every other API satellite (
agents.ts,messaging.ts,insights.ts,plugins-and-skills.ts) wraps path IDs inencodeURIComponent, but the automations/routines paths here interpolate${id}directly. This diverges from the established pattern and would produce malformed/misrouted URLs if an id ever contains reserved characters.Affected sites:
fetchAutomation(65),updateAutomation(78),deleteAutomation(85),runAutomation(91),toggleAutomation(97),reorderAutomationSteps(103),fetchRoutine(136),updateRoutine(149),deleteRoutine(156),runRoutine(162),triggerRoutineWebhook(205), and thestreamRoutineRunbase URL (168).♻️ Example for one site
- return api<ScheduledTask>(withSchedulingScope(`/automations/${id}`, options)); + return api<ScheduledTask>(withSchedulingScope(`/automations/${encodeURIComponent(id)}`, options));🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/dashboard/app/api/scheduling.ts` around lines 64 - 66, Encode every automation and routine ID before interpolating it into a URL path. Update fetchAutomation, updateAutomation, deleteAutomation, runAutomation, toggleAutomation, reorderAutomationSteps, fetchRoutine, updateRoutine, deleteRoutine, runRoutine, triggerRoutineWebhook, and the streamRoutineRun base URL to use encodeURIComponent for their path-segment IDs, preserving the existing request behavior otherwise.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/dashboard/app/api/ai-sessions.ts`:
- Around line 77-93: Update fetchAiSessions and fetchAiSession to use the
module’s shared api() helper instead of raw fetch(), preserving their existing
request parameters and response data mapping while allowing authentication,
server, and parsing failures to propagate consistently with archiveAiSession and
pingSession. If soft empty/null fallback behavior is intentionally required,
document that contract explicitly at both functions.
In `@packages/dashboard/app/api/ai-text.ts`:
- Around line 331-367: Update createTasksFromBreakdown so each mapped subtask
includes its priority in the POST body. Forward SubtaskItem.priority alongside
title, description, size, and dependsOn, preserving the existing task creation
payload behavior.
In `@packages/dashboard/app/api/missions.ts`:
- Around line 38-58: Add autoMerge?: boolean | null to the Mission interface
alongside autopilotEnabled, so the Mission return type exposes the field
accepted by createMission. Then simplify updateMission’s parameter type by
removing the ad-hoc “& { autoMerge?: boolean | null }” intersection and rely on
Partial<Mission>.
---
Nitpick comments:
In `@packages/dashboard/app/api/ai-sessions.ts`:
- Around line 122-166: Update deleteAiSession to reuse the shared api()
error-parsing path instead of locally handling content types, JSON parsing, and
ApiRequestError construction. Add a narrow okStatuses option to api() in
client.ts, pass the 404 status from deleteAiSession while retaining DELETE
behavior, and remove the duplicated parsing block.
In `@packages/dashboard/app/api/chat.ts`:
- Around line 568-628: The SSE event parsing and dispatch logic is duplicated
between streamChatResponse’s dispatchEvent/processLines flow and
attachChatStream. Extract the shared line-parser/dispatcher into a reusable
helper, then have both flows use it while preserving their existing
connection-close behavior and handler callbacks.
In `@packages/dashboard/app/api/scheduling.ts`:
- Around line 64-66: Encode every automation and routine ID before interpolating
it into a URL path. Update fetchAutomation, updateAutomation, deleteAutomation,
runAutomation, toggleAutomation, reorderAutomationSteps, fetchRoutine,
updateRoutine, deleteRoutine, runRoutine, triggerRoutineWebhook, and the
streamRoutineRun base URL to use encodeURIComponent for their path-segment IDs,
preserving the existing request behavior otherwise.
In `@packages/dashboard/app/api/workflows.ts`:
- Around line 13-18: The file’s type-only re-exports do not create local
bindings, causing repeated inline import type references. Add a companion
type-only import from `@fusion/core` for WorkflowDefinition,
WorkflowDefinitionInput, WorkflowDefinitionUpdate, WorkflowIr, TraitFlags,
TraitHookDescriptors, TraitConfigSchema, ResolvedWorkflowOptionalStep, and
WorkflowStepTemplate, then replace the corresponding inline references
throughout the workflow API definitions with the imported names while preserving
the existing exports.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: d65bf41b-9a2e-45a4-a111-6827afcbd47b
📒 Files selected for processing (28)
packages/core/src/__tests__/executor-tool-failure-retry-claim.test.tspackages/core/src/__tests__/postgres/workflow-settings-project-identity.pg.test.tspackages/core/src/store.tspackages/core/src/task-store/branch-and-pr-entities.tspackages/core/src/task-store/remaining-ops-1.tspackages/core/src/task-store/remaining-ops-2.tspackages/core/src/task-store/remaining-ops-5.tspackages/core/src/task-store/workflow-definitions.tspackages/core/src/types.tspackages/core/src/types/agents.tspackages/dashboard/app/api/agents.tspackages/dashboard/app/api/ai-sessions.tspackages/dashboard/app/api/ai-text.tspackages/dashboard/app/api/chat.tspackages/dashboard/app/api/event-source.tspackages/dashboard/app/api/insights.tspackages/dashboard/app/api/legacy.tspackages/dashboard/app/api/messaging.tspackages/dashboard/app/api/missions.tspackages/dashboard/app/api/plugins-and-skills.tspackages/dashboard/app/api/projects.tspackages/dashboard/app/api/research.tspackages/dashboard/app/api/scheduling.tspackages/dashboard/app/api/system-panel.tspackages/dashboard/app/api/todo.tspackages/dashboard/app/api/workflows.tspackages/dashboard/app/types/html2canvas.d.tsscripts/line-count-baseline.json
- Drop orphaned withRepoPath JSDoc; re-export AgentLogEntry from agents.ts - Document intentional soft-fail for fetchAiSessions / fetchAiSession - Forward subtask priority on createTasksFromBreakdown + server create-tasks - Add autoMerge to Mission interface; simplify updateMission signature
- Re-export SubtaskItem/PlanningSubtaskDraft from legacy ai-text peel - Allow autoMerge null on mission-types + MissionManager override helper
Resolve legacy.ts peel re-export conflicts by keeping wave11 structure, preserve Mission.autoMerge on missions.ts, and refresh line-count baseline.
## Summary Behavior-preserving package code organization (wave 12), continuing after wave 11 (#2333). - **Dashboard client API peels** from `app/api/legacy.ts` into focused modules with stable re-exports: - `git.ts` — remotes, PR management, terminal sessions, git management (`withRepoPath` preserved) - `workspace-files.ts` — file browser + workspace file ops - `provider-status.ts` — auth/CLI and runtime provider status - `github-import.ts` / `gitlab-import.ts` — issue/PR import clients - `run-audit.ts` — run-audit, timeline, org tree, task review - `task-diff.ts` — task diffs and commit associations - `agent-import-generation.ts` — agent import catalog + generation - **Core types peels** from `types.ts`: - `types/run-audit.ts` - `types/planner-intervention.ts` - **Domain rename**: `task-store/remaining-ops-5.ts` → `task-store/task-id-integrity.ts` (call sites updated) - **Line-count ratchet**: `legacy.ts` ceiling ~5665 → ~3339; baseline refreshed No intentional behavior changes; public import paths via `app/api` / `@fusion/core` remain stable. ## Test plan - [x] `@fusion/core` typecheck - [x] Dashboard `tsconfig.app` typecheck (wave12-related errors cleared; pre-existing playwright/plugin env noise unchanged vs main) - [x] ESLint on peeled API modules - [x] `pnpm check:line-count` (baseline updated) - [ ] CI: Lint / Typecheck / Build / Gate <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added dashboard client support for Git remotes/PR workflows, GitHub/GitLab importing, terminals (HTTP/SSE) and PTY sessions, workspace file browsing/editing/search, and task diff viewing with file/ZIP download helpers. - Added new dashboard APIs for planning/onboarding streaming, mission interview flows, provider/auth status, dev server sessions, run-audit/timelines & task review, agent import/generation, and AI title summarization. - Added backup and settings export/import helpers, plus model discovery/usage reporting and task steering actions. - **Refactor** - Modularized dashboard API clients into focused modules while preserving the existing integration style. - **Tests** - Updated a backend-mode SQLite guidance regression test to exercise the intended implementations. - **Chores** - Refreshed internal line-count baselines. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Summary
Wave 11 of package code organization (continues #2328 / wave 10), after syncing main into the wave10 stack.
Peels
app/api/event-source.tsEventSourcereconnect + pagehide cleanupapp/api/chat.tsapp/api/projects.tsapp/api/agents.tsapp/api/workflows.tsapp/api/scheduling.tsapp/api/ai-text.tsapp/api/ai-sessions.tsstartKeepAliveapp/api/research.tstask-store/branch-and-pr-entities.tsremaining-ops-6Public paths stay stable via
legacy.tsre-exports (app/api.ts→legacy).LOC
legacy.ts~8921 → ~5670Shims
legacy.ts→ peels above (delete-when: dashboard imports domain modules)remaining-ops-6→branch-and-pr-entities(rename complete)Test plan
app/api/*clean)plugin-setup-apitestsSummary by CodeRabbit
New Features
Enhancements