mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 12:27:28 +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>
80 lines
3.0 KiB
TypeScript
80 lines
3.0 KiB
TypeScript
/**
|
|
* The widget is a SEPARATE bundle. It must stay that way.
|
|
*
|
|
* WHY THIS EXISTS
|
|
*
|
|
* `widget/` is esbuild-bundled on its own into public/widget.js and loaded by
|
|
* strangers on other people's sites. It cannot see globals.css, Tailwind, React
|
|
* or anything under `src/` — and it must carry no third-party dependency, since
|
|
* one bundle has to mount on a static HTML page as readily as on a Next app.
|
|
*
|
|
* All of that is currently true only because whoever edits the folder remembers
|
|
* it. An `import { x } from "@/lib/..."` compiles fine under the repo's tsconfig
|
|
* paths and then either bloats the embed with half the app or fails at bundle
|
|
* time on a machine that is not the author's. Splitting main.ts into modules
|
|
* (2026-09-15) multiplied the number of files where that mistake can be made,
|
|
* so the constraint is pinned here instead of remembered.
|
|
*
|
|
* Run: npx tsx scripts/test/widget-self-contained.ts
|
|
*/
|
|
import { readdirSync, readFileSync } from "node:fs";
|
|
import { dirname, join, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
const repoRoot = resolve(here, "../..");
|
|
const widgetDir = join(repoRoot, "widget");
|
|
|
|
let pass = 0;
|
|
let fail = 0;
|
|
function ok(cond: boolean, label: string) {
|
|
if (cond) {
|
|
pass++;
|
|
console.log(` ✓ ${label}`);
|
|
} else {
|
|
fail++;
|
|
console.error(` ✗ ${label}`);
|
|
}
|
|
}
|
|
|
|
const files = readdirSync(widgetDir).filter((f) => f.endsWith(".ts"));
|
|
ok(files.includes("main.ts"), "widget/main.ts is the entry point");
|
|
|
|
/** Every `from "..."` specifier in a file, import or re-export. */
|
|
function specifiers(source: string): string[] {
|
|
return [...source.matchAll(/\bfrom\s+"([^"]+)"/g)].map((m) => m[1]);
|
|
}
|
|
|
|
for (const file of files) {
|
|
const source = readFileSync(join(widgetDir, file), "utf8");
|
|
const bad = specifiers(source).filter((spec) => !spec.startsWith("./"));
|
|
ok(
|
|
bad.length === 0,
|
|
`widget/${file} imports only its own siblings${bad.length ? ` (found: ${bad.join(", ")})` : ""}`,
|
|
);
|
|
}
|
|
|
|
// Every sibling a module imports must actually exist — a rename that misses one
|
|
// import breaks the embed on every customer site at once, not just a page here.
|
|
const known = new Set(files.map((f) => f.replace(/\.ts$/, "")));
|
|
for (const file of files) {
|
|
const source = readFileSync(join(widgetDir, file), "utf8");
|
|
const missing = specifiers(source)
|
|
.filter((spec) => spec.startsWith("./"))
|
|
.map((spec) => spec.slice(2))
|
|
.filter((name) => !known.has(name));
|
|
ok(missing.length === 0, `widget/${file} resolves every sibling import`);
|
|
}
|
|
|
|
// The one exception the architecture allows: fcw-* classes on HOST elements.
|
|
// Everything else is Shadow DOM, so a stylesheet appended to document.head that
|
|
// is not the pick highlight would leak widget styling onto a customer's page.
|
|
const theme = readFileSync(join(widgetDir, "theme.ts"), "utf8");
|
|
ok(
|
|
/\.fcw-hover/.test(theme) && /\.fcw-selected/.test(theme),
|
|
"the only document-level CSS is the fcw-* pick highlight",
|
|
);
|
|
|
|
console.log(`\n${pass} passed, ${fail} failed`);
|
|
process.exit(fail === 0 ? 0 : 1);
|