mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-03 21:17:04 +01:00
* refactor(orchestration): split the 733-line dispatch POST into named steps The POST handler in /api/orchestration/run carried every dispatch path inline: registry resolution, the cloud queue branch, the prompt-queue pop, run tracking, the queued-behind and parallel branches, and the claude / codex+gemini / openclaw executors. Reading it meant holding all of them at once. Each step is now its own named function, and POST reads as the sequence it always was. No behaviour change: same responses, same status codes, same sentinel writes in the same order, same log lines. Two genuine duplicates folded while passing: the project-state description block (claude and codex/gemini derived it identically) and the lifecycle sentinel writes. POST 733 -> 164 lines. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(inject): split injectPrompt into named dispatch steps injectPrompt was one 627-line function carrying the whole dispatch: target resolution, local and remote prompt assembly, run opening, /tmp side effects, the hosted-builder route, the executor call, and the failure and success ledgers. Each is now a named function and injectPrompt reads as the sequence. This path is autopilot-critical, so nothing moved across a boundary: same statuses, same response bodies, same event/audit rows in the same order, same log strings. injectPrompt 627 -> 163 lines (executeAndReport, the post-executor half, is 122). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(control): split the 492-line control GET into named steps The /api/control GET built the whole panel inline: project collection and dedupe, the agent-availability override, ten parallel DB slices, a 256-line per-project map callback, and the response. The card builder alone carried session persistence, run closing, runtime resolution and run serialization. Each is now named: collectControlProjects, resolveRunnerAvailability, loadControlSlices, buildProjectState (with persistSessionHandoff, maybeCloseRunFromHandoff, resolveAgentRuntime, serializeLatestRun) and resolveRunnerLastPushedAt. Same payload, same headers, same log lines, same write ordering. GET 492 -> 128 lines; the per-project builder 256 -> 133. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(widget): split the 1,329-line embed into modules widget/main.ts was one file with a 776-line mount() closure and no exports — the launcher, the element picker, the screenshot strip, the voice control, the stylesheets and the DOM helpers all lived inside it. This is the only surface strangers on other people's sites load, and it earns the same care as src/. It stays a self-contained esbuild bundle (nothing imports from src/), split into siblings: dom, theme, visitor-placement, launcher, picker, attachments, voice-control. main.ts now owns the panel, submit and boot. Same DOM, same order of construction, same copy, same listeners — verified by diffing the string literals of the old and new unbundled builds. Two pins added while the code was moving: - scripts/test/widget-self-contained.ts — every widget module imports only its siblings, every sibling import resolves, and the only document-level CSS is the fcw-* pick highlight. Proven by mutation (an "@/config/brand" import makes it fail). - widget-server-caps-mirror now reads every widget module, not just main.ts, so moving a clamp cannot silently defeat the check. main.ts 1,329 -> 528 lines; mount 776 -> 386. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(control): thin the 665-line ControlPanel into named pieces ControlPanel held the deep-link effect, the runner-presence derivation, the empty state, the Workspaces panel, the launch defaults, four modals and the toast — all inline, between the four-tier comments that explain the page's ordering. Extracted, behaviour unchanged (same DOM, same copy, same props): - useControlDeepLink — /control?focus=&switchTo= navigation handling - deriveRunnerPresence — offline / never-seen / stale, now in the presenter - latestRunSignals — the fleet-pulse outcome pairing - ControlEmptyState, WorkspacesSection, LaunchDefaultsSection, ControlNotices - ControlPanelModals — every overlay in one sibling deriveRunnerPresence is the one piece with real logic in it (the ADDITIVE rollout rule where connected===false is not yet authoritative on its own), so it is now pinned by five cases in the presenter suite — it had none. ControlPanel 665 -> 520 lines; the component function 665 -> 396 (most of which is JSX and the ordering comments that explain it). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(control): split the 412-line useControlData hook The hook did four jobs in one function: snapshot fetching + refresh triggers, the SSE patch fold, the /api/control/stream EventSource, and the five dispatch actions. - applyProjectPatches (lib/control-project-patch.ts) — the fold, now pure - useControlProjectStream — the EventSource and its reconnect - buildControlActions — inject / launch / runWithBrain / runCustomPrompt / saveAgent applyProjectPatches carries three rules a later edit could silently break (match by live tab, leave omitted fields alone, maintain liveTabs case-insensitively) and was untestable inside a useCallback. It now has six cases pinning exactly those. useControlData 412 -> 290 lines; the hook function 412 -> 180. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(shell,system): split the palette and Fleet Doctor CommandPalette (442-line component): the entry list and the filter were two useMemos nobody could test, and the NL composer's two fetch hops were inline. Both moved out — palette-entries.ts (pure) and useCommandComposer — with eight cases pinning the decisions that look arbitrary and get tidied away: projects outrank navigation, recents lead and are not repeated, free text offers Run FIRST, a pending command turns the list into a project picker, and a project with no checkout offers no agent switch. /api/system/doctor GET (328 lines): a flat run of independent probes appending to one array. Each is now a named probe returning its own checks, and GET is the list of them plus summarize(). Same checks, same order, same ids and copy. CommandPalette 442 -> 245; doctor GET 328 -> 33. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(loki): split the 450-line conversation POST into named turns The Loki chat route answered a turn with eight deterministic fast paths and a classifier path, all inline inside the SSE job — a 450-line closure whose control flow was a column of early `return send(...)`. Each fast path is now a named TurnHandler over one TurnContext, returning a message or null to pass. The classifier half splits into dispatchResolvedCommand / needsProjectReply / chatReply. The chain and its ordering are now a list you can read, and the two "add this project to the thread" patterns collapse into linkProject/linkProjects. Same replies, same meta `source` tags, same ordering, same SSE frames. POST 450 -> 63 lines; the longest piece is chatReply at 84. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * chore(lint): hold the line on function length Nothing was watching functions grow. Today's rule is a ratchet set just above the worst case that survives the split work above, so the next 700-line handler is an error on the author's machine instead of a surprise in review. Two thresholds, because the halves fail differently. Logic — routes, lib, queries, home/ — is where length hides branching, so 300. A component's length is mostly JSX depth: real, far less dangerous, so 510. Error, not warn: a warning on a repo this size is a number nobody reads. Blank lines and comments are skipped — this codebase comments heavily on purpose and a rule that punished that would push the WHY out of the code. Proven by mutation: a 324-line function under src/lib fails the rule. Also removes fnlen-all.mjs, a measurement scratch file that rode along in the previous commit. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
142 lines
5.2 KiB
TypeScript
142 lines
5.2 KiB
TypeScript
/**
|
|
* The push path and the fetch path must agree about one project.
|
|
*
|
|
* WHY THIS EXISTS
|
|
*
|
|
* /api/control/stream pushes per-project fast-state patches that are folded
|
|
* into the snapshot /api/control returned, so the panel updates without a
|
|
* refetch. That fold lived inside a useCallback in use-control-data and was
|
|
* therefore untestable, while carrying three rules a later edit can quietly
|
|
* break:
|
|
*
|
|
* 1. A patch matches by LIVE tab first, then by registry tab — a project
|
|
* running as "Loki Claude" is still the "Loki" row.
|
|
* 2. Fields the patch OMITS are left alone. The stream carries what changed;
|
|
* treating absent as empty would wipe a prompt queue nobody touched.
|
|
* 3. tabOpen maintains liveTabs case-insensitively, so active/idle
|
|
* categorisation stays live between polls.
|
|
*
|
|
* Run: npx tsx scripts/test/control-project-patch.ts
|
|
*/
|
|
import { applyProjectPatches } from "@/lib/control-project-patch";
|
|
import type { ControlData, ProjectState } from "@/lib/control-types";
|
|
import type { FastProjectState } from "@/lib/control-fast-state";
|
|
|
|
let passed = 0;
|
|
function assert(condition: boolean, message: string): void {
|
|
if (!condition) throw new Error(message);
|
|
}
|
|
function check(label: string, fn: () => void) {
|
|
fn();
|
|
passed += 1;
|
|
console.log(` ✓ ${label}`);
|
|
}
|
|
|
|
function project(overrides: Partial<ProjectState> & Pick<ProjectState, "tab">): ProjectState {
|
|
return {
|
|
id: "1",
|
|
projectId: null,
|
|
liveTab: overrides.tab,
|
|
dir: "/tmp/proj",
|
|
workspaceId: "ws",
|
|
agentPref: "claude",
|
|
modelPref: null,
|
|
builderPref: null,
|
|
session: null,
|
|
git: null,
|
|
sessionLifecycleSignals: true,
|
|
agentRunning: false,
|
|
activeAgents: [],
|
|
profile: null,
|
|
currentPrompt: null,
|
|
readyAt: null,
|
|
lockAt: null,
|
|
closingAt: null,
|
|
closedAt: null,
|
|
recentCustomPrompts: [],
|
|
recentActivity: [],
|
|
recentOutcomes: [],
|
|
liveAgentTurns: null,
|
|
promptQueue: [],
|
|
promptQueueRevision: 0,
|
|
autoContinueEnabled: true,
|
|
autoInjectModeOverride: null,
|
|
latestOrchestrationRun: null,
|
|
...overrides,
|
|
} as ProjectState;
|
|
}
|
|
|
|
function snapshot(projects: ProjectState[], liveTabs: string[] = []): ControlData {
|
|
return { projects, liveTabs } as unknown as ControlData;
|
|
}
|
|
|
|
function patch(overrides: Partial<FastProjectState> & Pick<FastProjectState, "tab">) {
|
|
return {
|
|
agentRunning: false,
|
|
activeAgents: [],
|
|
session: null,
|
|
currentPrompt: null,
|
|
readyAt: null,
|
|
lockAt: null,
|
|
closingAt: null,
|
|
closedAt: null,
|
|
tabOpen: false,
|
|
...overrides,
|
|
} as FastProjectState;
|
|
}
|
|
|
|
check("a patch keyed by the LIVE tab lands on its registry row", () => {
|
|
const prev = snapshot([project({ tab: "Loki", liveTab: "Loki Claude" })]);
|
|
const next = applyProjectPatches(prev, [patch({ tab: "Loki Claude", agentRunning: true })]);
|
|
assert(next.projects[0].agentRunning === true, "the row the live tab belongs to updated");
|
|
assert(next.projects[0].tab === "Loki", "and it is still the same registry row");
|
|
});
|
|
|
|
check("a patch for an unknown project changes nothing", () => {
|
|
const prev = snapshot([project({ tab: "Loki", agentRunning: true })]);
|
|
const next = applyProjectPatches(prev, [patch({ tab: "Elsewhere", agentRunning: false })]);
|
|
assert(next.projects[0].agentRunning === true, "the untouched row is untouched");
|
|
});
|
|
|
|
check("omitted fields survive — the stream carries changes, not state", () => {
|
|
const prev = snapshot([
|
|
project({
|
|
tab: "Loki",
|
|
promptQueue: ["ship the thing"],
|
|
promptQueueRevision: 7,
|
|
autoContinueEnabled: false,
|
|
}),
|
|
]);
|
|
const next = applyProjectPatches(prev, [patch({ tab: "Loki", agentRunning: true })]);
|
|
assert(next.projects[0].promptQueue.length === 1, "a queue nobody touched is still there");
|
|
assert(next.projects[0].promptQueueRevision === 7, "and so is its revision");
|
|
assert(next.projects[0].autoContinueEnabled === false, "and the auto-continue choice");
|
|
});
|
|
|
|
check("a present field DOES overwrite", () => {
|
|
const prev = snapshot([project({ tab: "Loki", promptQueue: ["old"] })]);
|
|
const next = applyProjectPatches(prev, [patch({ tab: "Loki", promptQueue: [] })]);
|
|
assert(next.projects[0].promptQueue.length === 0, "an explicitly empty queue is emptied");
|
|
});
|
|
|
|
check("tabOpen adds and removes liveTabs, case-insensitively", () => {
|
|
const prev = snapshot([project({ tab: "Loki" })], []);
|
|
const opened = applyProjectPatches(prev, [patch({ tab: "Loki", tabOpen: true })]);
|
|
assert(opened.liveTabs.includes("Loki"), "an opened tab joins liveTabs");
|
|
|
|
const again = applyProjectPatches(opened, [patch({ tab: "loki", tabOpen: true })]);
|
|
assert(again.liveTabs.length === 1, "a differently-cased repeat does not duplicate it");
|
|
|
|
const closed = applyProjectPatches(again, [patch({ tab: "LOKI", tabOpen: false })]);
|
|
assert(closed.liveTabs.length === 0, "and a differently-cased close still removes it");
|
|
});
|
|
|
|
check("the fold is pure — the previous snapshot is not mutated", () => {
|
|
const prev = snapshot([project({ tab: "Loki" })], []);
|
|
applyProjectPatches(prev, [patch({ tab: "Loki", agentRunning: true, tabOpen: true })]);
|
|
assert(prev.projects[0].agentRunning === false, "the old snapshot still reads false");
|
|
assert(prev.liveTabs.length === 0, "and still has no live tabs");
|
|
});
|
|
|
|
console.log(`\n${passed}/${passed} passed`);
|