Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
refactor: remove unused code paths
Leo57ff984e0fe4
diff --git a/apps/desktop/src/preview/PickLabelPosition.ts b/apps/desktop/src/preview/PickLabelPosition.tsdeleted file mode 100644index cf7f3c811..000000000--- a/apps/desktop/src/preview/PickLabelPosition.ts+++ /dev/null@@ -1,46 +0,0 @@-/**- * Pure clamp/flip math for the floating label that follows the cursor while- * the user is picking an element in the in-app browser. Lives in its own- * electron-free module so the geometry can be unit-tested without spinning- * up an Electron preload context (`PickPreload.ts` itself imports- * `electron` and `react-grab/primitives`, which can't load under vitest).- *- * - Horizontally pins the label to `targetLeft`, clamped into- * `[VIEWPORT_MARGIN, viewportWidth - labelWidth - VIEWPORT_MARGIN]`.- * - Vertically prefers above the target. If the label would overflow the- * top, flips below; if THAT also overflows the bottom, pins to the- * bottom margin (better to overlap the highlight than disappear).- */--/** Distance in CSS pixels between the highlight and the floating label. */-export const LABEL_GAP = 4;-/** Minimum padding the label keeps from any viewport edge. */-export const VIEWPORT_MARGIN = 4;--export function computeLabelPosition(input: {- targetLeft: number;- targetTop: number;- targetBottom: number;- labelWidth: number;- labelHeight: number;- viewportWidth: number;- viewportHeight: number;-}): { x: number; y: number } {- const { targetLeft, targetTop, targetBottom, labelWidth, labelHeight } = input;- const { viewportWidth, viewportHeight } = input;-- let x = targetLeft;- const maxX = viewportWidth - labelWidth - VIEWPORT_MARGIN;- if (x > maxX) x = maxX;- if (x < VIEWPORT_MARGIN) x = VIEWPORT_MARGIN;-- let y = targetTop - labelHeight - LABEL_GAP;- if (y < VIEWPORT_MARGIN) {- y = targetBottom + LABEL_GAP;- if (y + labelHeight > viewportHeight - VIEWPORT_MARGIN) {- y = Math.max(VIEWPORT_MARGIN, viewportHeight - labelHeight - VIEWPORT_MARGIN);- }- }-- return { x, y };-}diff --git a/apps/marketing/src/lib/installPrompts.test.ts b/apps/marketing/src/lib/installPrompts.test.tsindex 56f8d5d2a..9ec9d4a85 100644--- a/apps/marketing/src/lib/installPrompts.test.ts+++ b/apps/marketing/src/lib/installPrompts.test.ts@@ -1,21 +1,8 @@import { describe, expect, it } from "vite-plus/test";-import {- VERIFIED_INSTALL_SUCCESS,- verifiedInstallSuccess,- windowsInstallPrompt,-} from "./installPrompts";+import { windowsInstallPrompt } from "./installPrompts";describe("Windows install prompt", () => {- it("reports success only after every verification passes", () => {- expect(verifiedInstallSuccess({ checksum: true, install: true, launch: true })).toBe(- VERIFIED_INSTALL_SUCCESS,- );- expect(verifiedInstallSuccess({ checksum: false, install: true, launch: true })).toBeNull();- expect(verifiedInstallSuccess({ checksum: true, install: false, launch: true })).toBeNull();- expect(verifiedInstallSuccess({ checksum: true, install: true, launch: false })).toBeNull();- });-it("pins the official source and preserves Windows security controls", () => {expect(windowsInstallPrompt).toContain("opencoredev/akeru-bot");expect(windowsInstallPrompt).toContain("SHA256SUMS");diff --git a/apps/marketing/src/lib/installPrompts.ts b/apps/marketing/src/lib/installPrompts.tsindex b733f6b3e..468722e65 100644--- a/apps/marketing/src/lib/installPrompts.ts+++ b/apps/marketing/src/lib/installPrompts.ts@@ -1,11 +1,3 @@export const VERIFIED_INSTALL_SUCCESS = "You can open the app now with no issues.";export const windowsInstallPrompt = `Install the latest stable Windows release of Akeru Bot from opencoredev/akeru-bot. Use PowerShell and stop on every failed check. Detect the native Windows architecture first. Continue only for AMD64 as x64. Refuse ARM64, x86, and every other architecture because the official release supports Windows x64 only. Fetch the latest stable release only from https://api.github.com/repos/opencoredev/akeru-bot/releases/latest and require a stable vX.Y.Z tag. Download its exact Akeru-Bot-<version>-x64.exe asset and SHA256SUMS. Require both download URLs to start with https://github.com/opencoredev/akeru-bot/releases/download/. Find one SHA256SUMS entry whose filename exactly matches the installer. Stop if the entry is missing, duplicated, malformed, or if Get-FileHash -Algorithm SHA256 does not match it. Only after the hash matches, run Unblock-File on that installer. Do not disable or change SmartScreen, antivirus software, or any system-wide security setting. Run the installer and ask me only for a native Windows administrator confirmation if Windows requires one. Launch Akeru Bot, then verify its running process has an Akeru Bot window or that its executable is the installed Akeru Bot executable. Do not claim success after only starting the installer or process. Say exactly "${VERIFIED_INSTALL_SUCCESS}" only after checksum verification, completed installation, launch, and process or window verification all succeed.`;--export function verifiedInstallSuccess(input: {- checksum: boolean;- install: boolean;- launch: boolean;-}): string | null {- return input.checksum && input.install && input.launch ? VERIFIED_INSTALL_SUCCESS : null;-}diff --git a/apps/mobile/src/components/GlassSafeAreaView.tsx b/apps/mobile/src/components/GlassSafeAreaView.tsxdeleted file mode 100644index 8f91d6103..000000000--- a/apps/mobile/src/components/GlassSafeAreaView.tsx+++ /dev/null@@ -1,52 +0,0 @@-import type { ReactNode } from "react";-import { View, type StyleProp, type ViewStyle } from "react-native";-import { useSafeAreaInsets } from "react-native-safe-area-context";-import { useThemeColor } from "../lib/useThemeColor";--import { GlassSurface } from "./GlassSurface";--export interface GlassSafeAreaViewProps {- readonly leftSlot?: ReactNode;- readonly centerSlot?: ReactNode;- readonly rightSlot?: ReactNode;- readonly style?: StyleProp<ViewStyle>;-}--export function GlassSafeAreaView({- leftSlot,- centerSlot,- rightSlot,- style,-}: GlassSafeAreaViewProps) {- const insets = useSafeAreaInsets();- const headerColor = useThemeColor("--color-header");- const headerBorderColor = useThemeColor("--color-header-border");- const glassTint = useThemeColor("--color-glass-tint");- const headerPaddingTop = insets.top + 16;- const surfaceStyle = {- borderRadius: 0,- backgroundColor: headerColor,- borderBottomWidth: 1,- borderBottomColor: headerBorderColor,- } as const;-- return (- <View style={[surfaceStyle, style]}>- <GlassSurface- chrome="none"- glassEffectStyle="regular"- tintColor={glassTint}- style={{ borderRadius: 0, backgroundColor: "transparent" }}- >- <View- className="flex-row items-center gap-2.5 px-5 pb-4"- style={{ paddingTop: headerPaddingTop }}- >- <View className="items-start justify-center">{leftSlot}</View>- <View className="flex-1 items-center justify-center overflow-hidden">{centerSlot}</View>- <View className="items-end justify-center">{rightSlot}</View>- </View>- </GlassSurface>- </View>- );-}diff --git a/apps/server/src/orchestration/Errors.ts b/apps/server/src/orchestration/Errors.tsindex 7abd56770..631bbea3f 100644--- a/apps/server/src/orchestration/Errors.ts+++ b/apps/server/src/orchestration/Errors.ts@@ -107,13 +107,6 @@ export type OrchestrationEngineError =| OrchestrationCommandJsonParseError| OrchestrationCommandDecodeError;-export function toOrchestrationCommandDecodeError(error: Schema.SchemaError) {- return new OrchestrationCommandDecodeError({- issue: SchemaIssue.makeFormatterDefault()(error.issue),- cause: error,- });-}-export function toProjectorDecodeError(eventType: string) {return (error: Schema.SchemaError): OrchestrationProjectorDecodeError =>new OrchestrationProjectorDecodeError({@@ -122,19 +115,3 @@ export function toProjectorDecodeError(eventType: string) {cause: error,});}--export function toOrchestrationJsonParseError(cause: unknown) {- return new OrchestrationCommandJsonParseError({- detail: `Failed to parse orchestration command JSON`,- cause,- });-}--export function toListenerCallbackError(listener: "read-model" | "domain-event") {- return (cause: unknown): OrchestrationListenerCallbackError =>- new OrchestrationListenerCallbackError({- listener,- detail: `Failed to invoke orchestration ${listener} listener`,- cause,- });-}diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.tsindex 8bd9620c5..b3f1313df 100644--- a/apps/server/src/orchestration/commandInvariants.ts+++ b/apps/server/src/orchestration/commandInvariants.ts@@ -460,19 +460,3 @@ export function requireThreadAbsent(input: {),);}--export function requireNonNegativeInteger(input: {- readonly commandType: OrchestrationCommand["type"];- readonly field: string;- readonly value: number;-}): Effect.Effect<void, OrchestrationCommandInvariantError> {- if (Number.isInteger(input.value) && input.value >= 0) {- return Effect.void;- }- return Effect.fail(- invariantError(- input.commandType,- `${input.field} must be an integer greater than or equal to 0.`,- ),- );-}diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.tsindex 23075bd9a..253a954d2 100644--- a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts+++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts@@ -195,7 +195,3 @@ export const ProviderSessionDirectoryLive = Layer.effect(ProviderSessionDirectory,makeProviderSessionDirectory,);--export function makeProviderSessionDirectoryLive() {- return Layer.effect(ProviderSessionDirectory, makeProviderSessionDirectory);-}diff --git a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts b/apps/server/src/provider/acp/AcpAdapterSupport.test.tsindex 0aebe0ca6..ded1a275e 100644--- a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts+++ b/apps/server/src/provider/acp/AcpAdapterSupport.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vite-plus/test";import * as EffectAcpErrors from "effect-acp/errors";-import { ProviderDriverKind } from "@t3tools/contracts";+import { ProviderDriverKind, ThreadId } from "@t3tools/contracts";import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts";@@ -11,18 +11,50 @@ describe("AcpAdapterSupport", () => {expect(acpPermissionOutcome("decline")).toBe("reject-once");});- it("maps ACP request errors to provider adapter request errors", () => {+ it.each([+ new EffectAcpErrors.AcpRequestError({+ code: -32602,+ errorMessage: "Invalid params",+ }),+ new EffectAcpErrors.AcpTransportError({ cause: "connection closed" }),+ new EffectAcpErrors.AcpSpawnError({ command: "agent", cause: "not found" }),+ new EffectAcpErrors.AcpProtocolParseError({+ operation: "decode-wire-message",+ cause: "invalid JSON",+ }),+ new EffectAcpErrors.AcpInputStreamEndedError({}),+ ])("maps $_tag to a request error and preserves its cause", (cause) => {const error = mapAcpToAdapterError(ProviderDriverKind.make("cursor"),- "thread-1" as never,+ ThreadId.make("thread-1"),"session/prompt",- new EffectAcpErrors.AcpRequestError({- code: -32602,- errorMessage: "Invalid params",- }),+ cause,);- expect(error._tag).toBe("ProviderAdapterRequestError");- expect(error.message).toContain("Invalid params");+ expect(error).toMatchObject({+ _tag: "ProviderAdapterRequestError",+ provider: "cursor",+ method: "session/prompt",+ detail: cause.message,+ });+ expect(error.cause).toBe(cause);+ expect(error.message).toContain(cause.message);+ });++ it("maps an exited ACP process to a closed session instead of a request error", () => {+ const cause = new EffectAcpErrors.AcpProcessExitedError({ code: 1 });+ const error = mapAcpToAdapterError(+ ProviderDriverKind.make("cursor"),+ ThreadId.make("thread-1"),+ "session/prompt",+ cause,+ );++ expect(error).toMatchObject({+ _tag: "ProviderAdapterSessionClosedError",+ provider: "cursor",+ threadId: "thread-1",+ });+ expect(error.cause).toBe(cause);});});diff --git a/apps/server/src/provider/acp/AcpAdapterSupport.ts b/apps/server/src/provider/acp/AcpAdapterSupport.tsindex cde110e6d..f082f5197 100644--- a/apps/server/src/provider/acp/AcpAdapterSupport.ts+++ b/apps/server/src/provider/acp/AcpAdapterSupport.ts@@ -12,7 +12,6 @@ import {type ProviderAdapterError,} from "../Errors.ts";const isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);-const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);export function mapAcpToAdapterError(provider: ProviderDriverKind,@@ -27,14 +26,6 @@ export function mapAcpToAdapterError(cause: error,});}- if (isAcpRequestError(error)) {- return new ProviderAdapterRequestError({- provider,- method,- detail: error.message,- cause: error,- });- }return new ProviderAdapterRequestError({provider,method,diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.tsindex adbe110d9..0ec788af7 100644--- a/apps/server/src/provider/providerSnapshot.ts+++ b/apps/server/src/provider/providerSnapshot.ts@@ -97,20 +97,6 @@ export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Commanreturn result;}).pipe(Effect.scoped);-export function detailFromResult(- result: CommandResult & { readonly timedOut?: boolean },-): string | undefined {- if (result.timedOut) return "Timed out while running command.";- const stderr = nonEmptyTrimmed(result.stderr);- if (stderr) return stderr;- const stdout = nonEmptyTrimmed(result.stdout);- if (stdout) return stdout;- if (result.code !== 0) {- return `Command exited with code ${result.code}.`;- }- return undefined;-}-export function extractAuthBoolean(value: unknown): boolean | undefined {if (globalThis.Array.isArray(value)) {for (const entry of value) {diff --git a/apps/web/src/components/AgentsPanel.tsx b/apps/web/src/components/AgentsPanel.tsxdeleted file mode 100644index d46bbd752..000000000--- a/apps/web/src/components/AgentsPanel.tsx+++ /dev/null@@ -1,583 +0,0 @@-/**- * Agents right-panel surface: the fleet view over the native subagent fold,- * and the ONLY place the roster renders (the chat carries one CTA row per- * spawn batch).- *- * Visualization rules (from live-test feedback):- * - Spawn order is stable. Activity and completion update rows in place.- * - Agent rows reserve three fixed lines for identity, activity, and metrics;- * changing data must never change their height.- * - Workflow expansion is presentation state. A live run stays expanded when- * it settles; older collapsed runs can still be opened at run granularity.- * - Static status dots, DOM-write elapsed timers, plain token counters.- */-import { useAtomValue } from "@effect/atom-react";-import type {- AgentPanelModel,- AgentPanelWorkflowGroup,- RuntimeSubagent,-} from "@t3tools/client-runtime/state/subagentRuntime";-import {- formatSubagentModelLabel,- formatSubagentTokenCount,-} from "@t3tools/client-runtime/state/subagentRuntime";-import type { EnvironmentId, ThreadId } from "@t3tools/contracts";-import { Bot, Braces, Check, ChevronDown, ChevronRight, X } from "lucide-react";-import { useEffect, useRef, useState } from "react";--import { cn } from "~/lib/utils";-import { orchestrationEnvironment } from "~/state/orchestration";-import { ScrollArea } from "~/components/ui/scroll-area";-import { Button } from "~/components/ui/button";--/**- * In-flight states all present as Working (one steady state, per the- * monitoring-pill design: detail belongs in the activity sub-line, and a- * stalled/waiting/queued subagent is still the fleet doing its job, not a- * user problem). Only settled states differentiate.- */-const STATUS_VISUALS: Record<RuntimeSubagent["status"], { dotClass: string; label: string }> = {- pending: { dotClass: "bg-info", label: "Working" },- running: { dotClass: "bg-info", label: "Working" },- waiting: { dotClass: "bg-info", label: "Working" },- // Idle reads as settled (muted, not sky): a resting Codex child looks done- // unless resumed — live-test: sky idle dots read as stuck in-progress.- idle: { dotClass: "bg-muted-foreground/50", label: "Idle · resumable" },- completed: { dotClass: "bg-success", label: "Completed" },- failed: { dotClass: "bg-destructive", label: "Failed" },- cancelled: { dotClass: "bg-muted-foreground/60", label: "Stopped" },- interrupted: { dotClass: "bg-muted-foreground/60", label: "Stopped" },-};--function StatusDot({ status }: { status: RuntimeSubagent["status"] }) {- return (- <span- aria-hidden- className={cn("size-1.5 shrink-0 rounded-full", STATUS_VISUALS[status].dotClass)}- />- );-}--function formatElapsedSeconds(totalSeconds: number): string {- const seconds = Math.max(0, Math.floor(totalSeconds));- const minutes = Math.floor(seconds / 60);- if (minutes === 0) {- return `${seconds}s`;- }- const hours = Math.floor(minutes / 60);- if (hours === 0) {- return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;- }- return `${hours}h ${String(minutes % 60).padStart(2, "0")}m`;-}--function elapsedBetween(startedAt: string, endIso: string | null): string {- const start = Date.parse(startedAt);- const end = endIso ? Date.parse(endIso) : Date.now();- if (Number.isNaN(start) || Number.isNaN(end)) {- return "";- }- return formatElapsedSeconds((end - start) / 1000);-}--/**- * Elapsed time for the current activation. Live agents self-tick via DOM- * writes (zero React commits per tick); settled agents freeze at completedAt.- */-function AgentElapsed({ agent }: { agent: RuntimeSubagent }) {- const textRef = useRef<HTMLSpanElement>(null);- const live = agent.status === "running" || agent.status === "waiting";- const startedAt = agent.startedAt;-- useEffect(() => {- if (!live || !startedAt) {- return;- }- const update = () => {- if (textRef.current) {- textRef.current.textContent = elapsedBetween(startedAt, null);- }- };- update();- const id = setInterval(update, 1000);- return () => clearInterval(id);- }, [live, startedAt]);-- if (!startedAt) {- return null;- }- return (- <span ref={textRef} className="tabular-nums">- {elapsedBetween(startedAt, live ? null : agent.completedAt)}- </span>- );-}--/**- * Status-dependent activity line. Live rows lead with what is happening now;- * settled rows lead with the outcome. Errors are the only inline previews on- * failed rows because they explain a red row at a glance.- */-function agentActivityText(agent: RuntimeSubagent): string | null {- const live =- agent.status === "running" || agent.status === "pending" || agent.status === "waiting";- if (live) {- return (- agent.progress ??- (agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??- agent.result ??- agent.error- );- }- return (- agent.error ??- agent.result ??- agent.progress ??- (agent.lastToolName ? `▸ ${agent.lastToolName}` : null)- );-}--/** Flat, non-interactive agent status line. No unfold. */-function AgentRow({ agent }: { agent: RuntimeSubagent }) {- const visuals = STATUS_VISUALS[agent.status];- const activity = agentActivityText(agent);- const modelLabel = formatSubagentModelLabel(agent.model, agent.effort);- const role =- agent.role?.trim().toLocaleLowerCase() === agent.title.trim().toLocaleLowerCase()- ? null- : agent.role;- const metadata = [- modelLabel,- agent.usage ? `${formatSubagentTokenCount(agent.usage.totalTokens)} tok` : "— tok",- agent.usage?.toolUses !== undefined ? `${agent.usage.toolUses} tools` : null,- agent.activationCount > 1 ? `run ${agent.activationCount}` : null,- ].filter((value): value is string => value !== null);-- return (- <div className="grid h-[3.875rem] grid-cols-[0.375rem_minmax(0,1fr)_auto] grid-rows-[1.25rem_1.125rem_1rem] items-center gap-x-2 rounded-md px-1.5 py-1">- <span className="col-start-1 row-start-1 flex items-center">- <StatusDot status={agent.status} />- </span>- <span className="col-start-2 row-start-1 flex min-w-0 items-baseline gap-2">- <span className="min-w-0 truncate text-sm font-medium">{agent.title}</span>- {role ? (- <span className="max-w-28 shrink-0 truncate rounded-sm border border-border/60 px-1 font-mono text-[.65rem] text-muted-foreground">- {role}- </span>- ) : null}- </span>- <span className="col-start-3 row-start-1 min-w-14 text-right font-mono text-[.7rem] text-muted-foreground/80">- <span className="inline-flex items-center gap-1">- <AgentElapsed agent={agent} />- {agent.status === "completed" ? (- <Check aria-hidden className="size-3 text-success" />- ) : null}- </span>- </span>- <span- className={cn(- "col-start-2 col-end-4 row-start-2 block truncate text-xs",- agent.status === "failed" ? "text-destructive-foreground" : "text-muted-foreground",- )}- >- {activity ?? visuals.label}- </span>- <span className="col-start-2 col-end-4 row-start-3 truncate font-mono text-[.7rem] tabular-nums text-muted-foreground/70">- {metadata.join(" · ")}- </span>- <span className="sr-only">{visuals.label}</span>- </div>- );-}--function workflowIsLive(group: AgentPanelWorkflowGroup): boolean {- const status = group.workflow.status;- return (- status !== "completed" &&- status !== "failed" &&- status !== "cancelled" &&- status !== "interrupted"- );-}--function workflowMembers(group: AgentPanelWorkflowGroup): ReadonlyArray<RuntimeSubagent> {- return [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];-}--/**- * Phase rail: the run's shape at a glance. One segment per phase in order,- * separated by chevrons; each segment shows title + one dot per member.- * The whole arc (done → live → pending) is visible without scrolling the- * member list.- */-function PhaseRail({ group }: { group: AgentPanelWorkflowGroup }) {- if (group.phases.length === 0) {- return null;- }- return (- <div className="flex flex-wrap items-center gap-x-1 gap-y-1 px-1.5 pb-1 pt-1.5">- {group.phases.map((phase, index) => (- <div key={phase.index} className="flex items-center gap-1">- {index > 0 ? (- <ChevronRight aria-hidden className="size-3 text-muted-foreground/40" />- ) : null}- <div- className={cn(- "flex items-center gap-1 rounded-sm border px-1.5 py-0.5",- phase.state === "running"- ? "border-info/40"- : phase.state === "done"- ? "border-success/30"- : "border-border/50",- )}- >- <span- className={cn(- "font-mono text-[.65rem]",- phase.state === "running"- ? "text-info-foreground"- : phase.state === "done"- ? "text-success-foreground"- : "text-muted-foreground/70",- )}- >- {phase.state === "done" ? "✓ " : ""}- {phase.title}- </span>- <span className="flex items-center gap-0.5">- {phase.members.length === 0 ? (- <span className="font-mono text-[.6rem] text-muted-foreground/50">–</span>- ) : (- phase.members.map((member) => <StatusDot key={member.id} status={member.status} />)- )}- </span>- </div>- </div>- ))}- </div>- );-}--/**- * Read-only workflow script viewer, fetched through the contained- * getWorkflowScript RPC (never a raw filesystem read from the client).- */-function WorkflowScriptView({- environmentId,- threadId,- scriptPath,- onClose,-}: {- environmentId: EnvironmentId;- threadId: ThreadId;- scriptPath: string;- onClose: () => void;-}) {- const result = useAtomValue(- orchestrationEnvironment.workflowScript({ environmentId, input: { threadId, scriptPath } }),- );- return (- <div className="mx-1.5 mb-1 rounded-md border border-border/60 bg-background/60">- <div className="flex items-center gap-2 border-b border-border/50 px-2 py-1">- <Braces aria-hidden className="size-3 text-muted-foreground" />- <span className="truncate font-mono text-[.65rem] text-muted-foreground">- {scriptPath.split("/").at(-1)}- </span>- <Button- size="icon-micro"- variant="ghost-muted"- onClick={onClose}- aria-label="Close script"- className="ml-auto"- >- <X aria-hidden className="size-3" />- </Button>- </div>- <div className="max-h-72 overflow-auto p-2">- {result._tag === "Success" ? (- <pre className="whitespace-pre-wrap break-words font-mono text-[.7rem] leading-relaxed text-foreground/90">- {result.value.contents}- {result.value.truncated ? "\n… (truncated)" : ""}- </pre>- ) : result._tag === "Failure" ? (- <p className="text-xs text-destructive-foreground">Could not load the script.</p>- ) : (- <p className="text-xs text-muted-foreground">Loading…</p>- )}- </div>- </div>- );-}--/**- * Collapsible phase section. A phase opens when it becomes active, then keeps- * that shape as it settles so completion never yanks rows out from under the- * user. Manual toggles stick until a later activation begins.- */-function PhaseSection({- phase,- defaultOpen = false,-}: {- phase: AgentPanelWorkflowGroup["phases"][number];- defaultOpen?: boolean;-}) {- const [open, setOpen] = useState(defaultOpen || phase.state === "running");- const previousState = useRef(phase.state);-- useEffect(() => {- if (previousState.current !== "running" && phase.state === "running") {- setOpen(true);- }- previousState.current = phase.state;- }, [phase.state]);-- return (- <div>- <button- type="button"- onClick={() => setOpen((value) => !value)}- aria-expanded={open}- className={cn(- "mt-2 flex w-full items-center gap-1.5 rounded-sm px-1.5 text-left text-[.65rem] font-medium uppercase tracking-wider hover:bg-accent/40",- phase.state === "done"- ? "text-success-foreground"- : phase.state === "running"- ? "text-info-foreground"- : "text-muted-foreground/70",- )}- >- {open ? (- <ChevronDown aria-hidden className="size-3 shrink-0" />- ) : (- <ChevronRight aria-hidden className="size-3 shrink-0" />- )}- {phase.state === "done" ? <Check aria-hidden className="size-3" /> : null}- <span>{phase.title}</span>- <span className="font-normal normal-case text-muted-foreground/70">- {phase.state === "pending" && phase.members.length === 0- ? "pending"- : phase.state === "done"- ? `${phase.settledCount} done`- : `${phase.activeCount} active · ${phase.settledCount} done`}- </span>- {!open && phase.members.length > 0 ? (- <span className="ml-auto flex items-center gap-0.5">- {phase.members.map((member) => (- <StatusDot key={member.id} status={member.status} />- ))}- </span>- ) : null}- </button>- {open ? phase.members.map((member) => <AgentRow key={member.id} agent={member} />) : null}- </div>- );-}--/** Expanded workflow: phase rail + full phase tree. */-function ExpandedWorkflowSection({- group,- environmentId,- threadId,- onCollapse,-}: {- group: AgentPanelWorkflowGroup;- environmentId: EnvironmentId | null;- threadId: ThreadId | null;- onCollapse: () => void;-}) {- const [scriptOpen, setScriptOpen] = useState(false);- const members = workflowMembers(group);- const settled = members.filter(- (member) =>- member.status === "completed" ||- member.status === "failed" ||- member.status === "cancelled" ||- member.status === "interrupted",- ).length;- const scriptPath = group.workflow.runHandles?.scriptPath;- const canShowScript = scriptPath !== undefined && environmentId !== null && threadId !== null;- return (- <section className="rounded-lg border border-border/50 bg-card/30 p-1.5">- <div className="flex items-center gap-2 px-1.5 pt-0.5 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">- <StatusDot status={group.workflow.status} />- <span className="min-w-0 truncate">- {group.workflow.workflowName ?? group.workflow.title}- </span>- {canShowScript ? (- <button- type="button"- onClick={() => setScriptOpen((value) => !value)}- className={cn(- "rounded-sm border border-border/60 px-1 font-mono normal-case hover:text-foreground",- scriptOpen && "text-foreground",- )}- aria-expanded={scriptOpen}- >- {"{}"} script- </button>- ) : null}- <span className="ml-auto font-mono normal-case text-muted-foreground/80">- {settled}/{members.length} settled- </span>- <Button- size="icon-micro"- variant="ghost-muted"- onClick={onCollapse}- aria-label="Collapse workflow"- >- <ChevronDown aria-hidden className="size-3" />- </Button>- </div>- <PhaseRail group={group} />- {scriptOpen && canShowScript ? (- <WorkflowScriptView- environmentId={environmentId}- threadId={threadId}- scriptPath={scriptPath}- onClose={() => setScriptOpen(false)}- />- ) : null}- {group.phases.map((phase) => (- <PhaseSection key={phase.index} phase={phase} defaultOpen={!workflowIsLive(group)} />- ))}- {group.unphasedMembers.map((member) => (- <AgentRow key={member.id} agent={member} />- ))}- {group.phases.length === 0 && group.unphasedMembers.length === 0 ? (- <AgentRow agent={group.workflow} />- ) : null}- </section>- );-}--/**- * Collapsed workflow: one summary line. The parent owns expansion so a live- * workflow keeps its shape when it settles.- */-function CollapsedWorkflowSection({- group,- onExpand,-}: {- group: AgentPanelWorkflowGroup;- onExpand: () => void;-}) {- const members = workflowMembers(group);- const failed = members.filter((member) => member.status === "failed").length;- // Coordinator usage may already aggregate members (panel-footer rule):- // count it only when there are no member rows to sum.- const totalTokens = members.reduce(- (sum, member) => sum + (member.usage?.totalTokens ?? 0),- members.length === 0 ? (group.workflow.usage?.totalTokens ?? 0) : 0,- );- const elapsed =- group.workflow.startedAt && group.workflow.completedAt- ? elapsedBetween(group.workflow.startedAt, group.workflow.completedAt)- : null;- return (- <section>- <button- type="button"- onClick={onExpand}- className="flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left hover:bg-accent/40"- aria-expanded={false}- >- <StatusDot status={failed > 0 ? "failed" : group.workflow.status} />- <span className="truncate text-sm">- {group.workflow.workflowName ?? group.workflow.title}- </span>- <span className="ml-auto flex items-center gap-1.5 font-mono text-[.7rem] text-muted-foreground/80">- {failed > 0 ? <span className="text-destructive-foreground">{failed} failed</span> : null}- <span>{members.length} work items</span>- <span className="tabular-nums">· {formatSubagentTokenCount(totalTokens)} tok</span>- {elapsed ? <span className="tabular-nums">· {elapsed}</span> : null}- <ChevronRight aria-hidden className="size-3" />- </span>- </button>- </section>- );-}--/** A workflow's open state is presentation state, not a status derivative. */-function WorkflowSection({- group,- environmentId,- threadId,-}: {- group: AgentPanelWorkflowGroup;- environmentId: EnvironmentId | null;- threadId: ThreadId | null;-}) {- const [open, setOpen] = useState(() => workflowIsLive(group));- return open ? (- <ExpandedWorkflowSection- group={group}- environmentId={environmentId}- threadId={threadId}- onCollapse={() => setOpen(false)}- />- ) : (- <CollapsedWorkflowSection group={group} onExpand={() => setOpen(true)} />- );-}--export function AgentsPanel({- model,- environmentId = null,- threadId = null,-}: {- model: AgentPanelModel;- environmentId?: EnvironmentId | null;- threadId?: ThreadId | null;-}) {- if (!model.hasAgents) {- return (- <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">- <Bot aria-hidden className="size-6 text-muted-foreground/60" />- <p className="text-sm font-medium">No bot work yet</p>- <p className="max-w-56 text-xs text-muted-foreground">- When this chat delegates bot work or runs a workflow, it appears here with live status,- activity, and token usage.- </p>- </div>- );- }-- return (- <div className="flex h-full min-h-0 flex-col">- <ScrollArea className="min-h-0 flex-1">- <div className="flex flex-col gap-2 p-2">- {model.workflows.map((group) => (- <WorkflowSection- key={group.workflow.id}- group={group}- environmentId={environmentId}- threadId={threadId}- />- ))}- {model.directAgents.length > 0 ? (- <section>- <div className="px-1.5 pt-1 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">- Direct bot work- </div>- {model.directAgents.map((agent) => (- <AgentRow key={agent.id} agent={agent} />- ))}- </section>- ) : null}- </div>- </ScrollArea>- <footer className="flex items-center justify-between border-t border-border/60 px-3 py-1.5 font-mono text-[.7rem] text-muted-foreground">- <span className="flex items-center gap-2">- {model.runningCount + model.waitingCount > 0 ? (- <span className="text-info-foreground">- ● {model.runningCount + model.waitingCount} working- </span>- ) : null}- {model.idleCount > 0 ? <span>{model.idleCount} idle</span> : null}- {model.settledCount > 0 ? <span>{model.settledCount} settled</span> : null}- </span>- <span className="tabular-nums">Σ {formatSubagentTokenCount(model.totalTokens)} tok</span>- </footer>- </div>- );-}diff --git a/apps/web/src/components/RightPanelSheet.tsx b/apps/web/src/components/RightPanelSheet.tsxdeleted file mode 100644index ebc4aa0a6..000000000--- a/apps/web/src/components/RightPanelSheet.tsx+++ /dev/null@@ -1,30 +0,0 @@-import { type ReactNode } from "react";--import { RIGHT_PANEL_SHEET_CLASS_NAME } from "../rightPanelLayout";-import { Sheet, SheetPopup } from "./ui/sheet";--export function RightPanelSheet(props: {- children: ReactNode;- open: boolean;- onClose: () => void;-}) {- return (- <Sheet- open={props.open}- onOpenChange={(open) => {- if (!open) {- props.onClose();- }- }}- >- <SheetPopup- side="right"- showCloseButton={false}- keepMounted- className={RIGHT_PANEL_SHEET_CLASS_NAME}- >- {props.children}- </SheetPopup>- </Sheet>- );-}diff --git a/apps/web/src/components/ThreadCommandSubtitle.tsx b/apps/web/src/components/ThreadCommandSubtitle.tsxindex d866004e7..d52642ec1 100644--- a/apps/web/src/components/ThreadCommandSubtitle.tsx+++ b/apps/web/src/components/ThreadCommandSubtitle.tsx@@ -1,112 +1,5 @@-import type { EnvironmentId, ProviderDriverKind } from "@t3tools/contracts";-import { FolderGit2Icon, FolderIcon, GitBranchIcon } from "lucide-react";-import { ProjectFavicon } from "./ProjectFavicon";-import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon";-import { cn } from "~/lib/utils";--/**- * Flip this while reviewing command-palette thread subtitles.- * - favicon-workspace-harness: favicon + Folder/FolderGit2 + branch + harness (default)- * - favicon-workspace: same without harness- * - favicon-branch-harness: GitBranch for local, FolderGit2 for worktrees, + harness- */-export type ThreadCommandSubtitleVariant =- | "favicon-workspace-harness"- | "favicon-workspace"- | "favicon-branch-harness";--export const THREAD_COMMAND_SUBTITLE_VARIANT: ThreadCommandSubtitleVariant =- "favicon-workspace-harness";-export const COMMAND_PALETTE_META_ICON_CLASS = "size-3 shrink-0 text-muted-foreground/70";export function CommandPaletteMetaDot() {return <span className="shrink-0 text-muted-foreground/50">·</span>;}--function WorkspaceIcon(props: { variant: ThreadCommandSubtitleVariant; isWorktree: boolean }) {- if (props.isWorktree) {- return <FolderGit2Icon className={COMMAND_PALETTE_META_ICON_CLASS} aria-hidden />;- }- if (props.variant === "favicon-branch-harness") {- return <GitBranchIcon className={COMMAND_PALETTE_META_ICON_CLASS} aria-hidden />;- }- return <FolderIcon className={COMMAND_PALETTE_META_ICON_CLASS} aria-hidden />;-}--export function ThreadCommandSubtitle(props: {- environmentId: EnvironmentId;- projectCwd: string | null;- projectFaviconPath?: string | null;- projectTitle: string | null;- branch: string | null;- worktreePath: string | null;- isCurrent: boolean;- driverKind?: ProviderDriverKind | null;- providerDisplayName?: string | null;- variant?: ThreadCommandSubtitleVariant;- className?: string;-}) {- const variant = props.variant ?? THREAD_COMMAND_SUBTITLE_VARIANT;- const isWorktree = props.worktreePath != null && props.worktreePath.trim().length > 0;- const showHarness =- variant !== "favicon-workspace" && props.driverKind != null && props.providerDisplayName;-- const projectLabel = props.projectTitle?.trim() || null;- const branchLabel = props.branch?.trim() || null;-- if (!projectLabel && !branchLabel && !props.isCurrent && !showHarness) {- return null;- }-- return (- <span- className={cn(- "inline-flex min-w-0 max-w-full items-center gap-1 text-xs text-muted-foreground/70",- props.className,- )}- >- {projectLabel ? (- <span className="inline-flex min-w-0 items-center gap-1">- {props.projectCwd ? (- <ProjectFavicon- environmentId={props.environmentId}- cwd={props.projectCwd}- faviconPath={props.projectFaviconPath}- className="size-3 shrink-0"- />- ) : null}- <span className="min-w-0 truncate">{projectLabel}</span>- </span>- ) : null}-- {branchLabel ? (- <>- {projectLabel ? <CommandPaletteMetaDot /> : null}- <span className="inline-flex min-w-0 items-center gap-1">- <WorkspaceIcon variant={variant} isWorktree={isWorktree} />- <span className="min-w-0 truncate">{branchLabel}</span>- </span>- </>- ) : null}-- {showHarness && props.driverKind ? (- <>- {projectLabel || branchLabel ? <CommandPaletteMetaDot /> : null}- <ProviderInstanceIcon- driverKind={props.driverKind}- displayName={props.providerDisplayName ?? props.driverKind}- iconClassName="size-3 shrink-0 opacity-70"- />- </>- ) : null}-- {props.isCurrent ? (- <>- {projectLabel || branchLabel || showHarness ? <CommandPaletteMetaDot /> : null}- <span className="shrink-0">Current chat</span>- </>- ) : null}- </span>- );-}diff --git a/apps/web/src/historyBootstrap.ts b/apps/web/src/historyBootstrap.tsdeleted file mode 100644index 2130bde80..000000000--- a/apps/web/src/historyBootstrap.ts+++ /dev/null@@ -1,139 +0,0 @@-import type { ChatMessage } from "./types";--export interface BootstrapInputResult {- text: string;- includedCount: number;- omittedCount: number;- truncated: boolean;-}--const BOOTSTRAP_PREAMBLE =- "Continue this conversation using the transcript context below. The final section is the latest user request to answer now.";-const TRANSCRIPT_HEADER = "Transcript context:";-const LATEST_PROMPT_HEADER = "Latest user request (answer this now):";-const OMITTED_SUMMARY = (count: number) =>- `[${count} earlier message(s) omitted to stay within input limits.]`;--function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {- return message.role === "assistant" ? "ASSISTANT" : "USER";-}--function attachmentSummary(message: ChatMessage): string | null {- const attachments = message.attachments ?? [];- const count = attachments.length;- if (count === 0) {- return null;- }-- const names = attachments.slice(0, 3).map((attachment) => attachment.name);- const namesSummary = names.join(", ");- const extraCount = count - names.length;- const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";- return `[Attached file${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;-}--function buildMessageBlock(message: ChatMessage): string {- const text = message.text;- const attachments = attachmentSummary(message);-- if (text && attachments) {- return `${messageRoleLabel(message)}:\n${text}\n${attachments}`;- }- if (text) {- return `${messageRoleLabel(message)}:\n${text}`;- }- if (attachments) {- return `${messageRoleLabel(message)}:\n${attachments}`;- }- return `${messageRoleLabel(message)}:\n(empty message)`;-}--function finalizeWithPrompt(- transcriptBody: string,- latestPrompt: string,- maxChars: number,-): string | null {- const text = `${BOOTSTRAP_PREAMBLE}\n\n${TRANSCRIPT_HEADER}\n${transcriptBody}\n\n${LATEST_PROMPT_HEADER}\n${latestPrompt}`;- return text.length <= maxChars ? text : null;-}--export function buildBootstrapInput(- previousMessages: ChatMessage[],- latestPrompt: string,- maxChars: number,-): BootstrapInputResult {- const budget = Number.isFinite(maxChars) ? Math.max(1, Math.floor(maxChars)) : 1;- const promptOnly = latestPrompt.length <= budget ? latestPrompt : latestPrompt.slice(0, budget);-- if (previousMessages.length === 0) {- return {- text: promptOnly,- includedCount: 0,- omittedCount: 0,- truncated: promptOnly.length !== latestPrompt.length,- };- }-- const newestFirstBlocks: string[] = [];- for (let index = previousMessages.length - 1; index >= 0; index -= 1) {- const message = previousMessages[index];- if (!message) continue;- newestFirstBlocks.push(buildMessageBlock(message));- }-- if (newestFirstBlocks.length === 0) {- return {- text: promptOnly,- includedCount: 0,- omittedCount: previousMessages.length,- truncated: true,- };- }-- // Include a contiguous suffix from newest to oldest, then reverse to chronological.- let includedNewestFirst: string[] = [];- for (const block of newestFirstBlocks) {- const nextNewestFirst = [...includedNewestFirst, block];- const nextChronological = nextNewestFirst.toReversed();- const omittedCount = newestFirstBlocks.length - nextChronological.length;- const transcriptBody =- omittedCount > 0- ? `${OMITTED_SUMMARY(omittedCount)}\n\n${nextChronological.join("\n\n")}`- : nextChronological.join("\n\n");- if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {- break;- }- includedNewestFirst = nextNewestFirst;- }-- let includedChronological = includedNewestFirst.toReversed();- while (true) {- const omittedCount = newestFirstBlocks.length - includedChronological.length;- const transcriptBody =- omittedCount > 0- ? includedChronological.length > 0- ? `${OMITTED_SUMMARY(omittedCount)}\n\n${includedChronological.join("\n\n")}`- : OMITTED_SUMMARY(omittedCount)- : includedChronological.join("\n\n");- const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);- if (finalized) {- return {- text: finalized,- includedCount: includedChronological.length,- omittedCount,- truncated: omittedCount > 0 || latestPrompt.length !== promptOnly.length,- };- }-- if (includedChronological.length === 0) {- return {- text: promptOnly,- includedCount: 0,- omittedCount: previousMessages.length,- truncated: true,- };- }-- includedChronological = includedChronological.slice(1);- }-}diff --git a/apps/web/src/orchestrationEventEffects.ts b/apps/web/src/orchestrationEventEffects.tsdeleted file mode 100644index 34e33ace8..000000000--- a/apps/web/src/orchestrationEventEffects.ts+++ /dev/null@@ -1,94 +0,0 @@-import type { OrchestrationEvent, ThreadId } from "@t3tools/contracts";--export interface OrchestrationBatchEffects {- promoteDraftThreadIds: ThreadId[];- clearDeletedThreadIds: ThreadId[];- removeTerminalUiStateThreadIds: ThreadId[];- needsProviderInvalidation: boolean;-}--export function deriveOrchestrationBatchEffects(- events: readonly OrchestrationEvent[],-): OrchestrationBatchEffects {- const threadLifecycleEffects = new Map<- ThreadId,- {- clearPromotedDraft: boolean;- clearDeletedThread: boolean;- removeTerminalUiState: boolean;- }- >();- let needsProviderInvalidation = false;-- for (const event of events) {- switch (event.type) {- case "thread.turn-diff-completed":- case "thread.reverted": {- needsProviderInvalidation = true;- break;- }-- case "thread.created": {- threadLifecycleEffects.set(event.payload.threadId, {- clearPromotedDraft: true,- clearDeletedThread: false,- removeTerminalUiState: false,- });- break;- }-- case "thread.deleted": {- threadLifecycleEffects.set(event.payload.threadId, {- clearPromotedDraft: false,- clearDeletedThread: true,- removeTerminalUiState: true,- });- break;- }-- case "thread.archived": {- threadLifecycleEffects.set(event.payload.threadId, {- clearPromotedDraft: false,- clearDeletedThread: false,- removeTerminalUiState: true,- });- break;- }-- case "thread.unarchived": {- threadLifecycleEffects.set(event.payload.threadId, {- clearPromotedDraft: false,- clearDeletedThread: false,- removeTerminalUiState: false,- });- break;- }-- default: {- break;- }- }- }-- const promoteDraftThreadIds: ThreadId[] = [];- const clearDeletedThreadIds: ThreadId[] = [];- const removeTerminalUiStateThreadIds: ThreadId[] = [];- for (const [threadId, effect] of threadLifecycleEffects) {- if (effect.clearPromotedDraft) {- promoteDraftThreadIds.push(threadId);- }- if (effect.clearDeletedThread) {- clearDeletedThreadIds.push(threadId);- }- if (effect.removeTerminalUiState) {- removeTerminalUiStateThreadIds.push(threadId);- }- }-- return {- promoteDraftThreadIds,- clearDeletedThreadIds,- removeTerminalUiStateThreadIds,- needsProviderInvalidation,- };-}diff --git a/apps/web/src/orchestrationRecovery.ts b/apps/web/src/orchestrationRecovery.tsdeleted file mode 100644index c9ccf3a39..000000000--- a/apps/web/src/orchestrationRecovery.ts+++ /dev/null@@ -1,211 +0,0 @@-export type OrchestrationRecoveryReason =- | "bootstrap"- | "sequence-gap"- | "resubscribe"- | "replay-failed";--export interface OrchestrationRecoveryPhase {- kind: "snapshot" | "replay";- reason: OrchestrationRecoveryReason;-}--export interface OrchestrationRecoveryState {- latestSequence: number;- highestObservedSequence: number;- bootstrapped: boolean;- pendingReplay: boolean;- inFlight: OrchestrationRecoveryPhase | null;-}--export interface ReplayRecoveryCompletion {- replayMadeProgress: boolean;- shouldReplay: boolean;-}--export interface ReplayRetryTracker {- attempts: number;- latestSequence: number;- highestObservedSequence: number;-}--export interface ReplayRetryDecision {- shouldRetry: boolean;- delayMs: number;- tracker: ReplayRetryTracker | null;-}--type SequencedEvent = Readonly<{ sequence: number }>;--export function deriveReplayRetryDecision(input: {- previousTracker: ReplayRetryTracker | null;- completion: ReplayRecoveryCompletion;- recoveryState: Pick<OrchestrationRecoveryState, "latestSequence" | "highestObservedSequence">;- baseDelayMs: number;- maxNoProgressRetries: number;-}): ReplayRetryDecision {- if (!input.completion.shouldReplay) {- return {- shouldRetry: false,- delayMs: 0,- tracker: null,- };- }-- if (input.completion.replayMadeProgress) {- return {- shouldRetry: true,- delayMs: 0,- tracker: null,- };- }-- const previousTracker = input.previousTracker;- const sameFrontier =- previousTracker !== null &&- previousTracker.latestSequence === input.recoveryState.latestSequence &&- previousTracker.highestObservedSequence === input.recoveryState.highestObservedSequence;-- const attempts = sameFrontier && previousTracker !== null ? previousTracker.attempts + 1 : 1;- if (attempts > input.maxNoProgressRetries) {- return {- shouldRetry: false,- delayMs: 0,- tracker: null,- };- }-- return {- shouldRetry: true,- delayMs: input.baseDelayMs * 2 ** (attempts - 1),- tracker: {- attempts,- latestSequence: input.recoveryState.latestSequence,- highestObservedSequence: input.recoveryState.highestObservedSequence,- },- };-}--export function createOrchestrationRecoveryCoordinator() {- let state: OrchestrationRecoveryState = {- latestSequence: 0,- highestObservedSequence: 0,- bootstrapped: false,- pendingReplay: false,- inFlight: null,- };- let replayStartSequence: number | null = null;-- const snapshotState = (): OrchestrationRecoveryState => ({- ...state,- ...(state.inFlight ? { inFlight: { ...state.inFlight } } : {}),- });-- const observeSequence = (sequence: number) => {- state.highestObservedSequence = Math.max(state.highestObservedSequence, sequence);- };-- const resolveReplayNeedAfterRecovery = () => {- const pendingReplayBeforeReset = state.pendingReplay;- const observedAhead = state.highestObservedSequence > state.latestSequence;- const shouldReplay = pendingReplayBeforeReset || observedAhead;- state.pendingReplay = false;- return {- shouldReplay,- pendingReplayBeforeReset,- observedAhead,- };- };-- return {- getState(): OrchestrationRecoveryState {- return snapshotState();- },-- classifyDomainEvent(sequence: number): "ignore" | "defer" | "recover" | "apply" {- observeSequence(sequence);- if (sequence <= state.latestSequence) {- return "ignore";- }- if (!state.bootstrapped || state.inFlight) {- state.pendingReplay = true;- return "defer";- }- if (sequence !== state.latestSequence + 1) {- state.pendingReplay = true;- return "recover";- }- return "apply";- },-- markEventBatchApplied<T extends SequencedEvent>(events: ReadonlyArray<T>): ReadonlyArray<T> {- const nextEvents = events- .filter((event) => event.sequence > state.latestSequence)- .toSorted((left, right) => left.sequence - right.sequence);- if (nextEvents.length === 0) {- return [];- }-- state.latestSequence = nextEvents.at(-1)?.sequence ?? state.latestSequence;- state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);- return nextEvents;- },-- beginSnapshotRecovery(reason: OrchestrationRecoveryReason): boolean {- if (state.inFlight?.kind === "snapshot") {- state.pendingReplay = true;- return false;- }- if (state.inFlight?.kind === "replay") {- state.pendingReplay = true;- return false;- }- state.inFlight = { kind: "snapshot", reason };- return true;- },-- completeSnapshotRecovery(snapshotSequence: number): boolean {- state.latestSequence = Math.max(state.latestSequence, snapshotSequence);- state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);- state.bootstrapped = true;- state.inFlight = null;- return resolveReplayNeedAfterRecovery().shouldReplay;- },-- failSnapshotRecovery(): void {- state.inFlight = null;- },-- beginReplayRecovery(reason: OrchestrationRecoveryReason): boolean {- if (!state.bootstrapped || state.inFlight?.kind === "snapshot") {- state.pendingReplay = true;- return false;- }- if (state.inFlight?.kind === "replay") {- state.pendingReplay = true;- return false;- }- state.pendingReplay = false;- replayStartSequence = state.latestSequence;- state.inFlight = { kind: "replay", reason };- return true;- },-- completeReplayRecovery(): ReplayRecoveryCompletion {- const replayMadeProgress =- replayStartSequence !== null && state.latestSequence > replayStartSequence;- replayStartSequence = null;- state.inFlight = null;- const replayResolution = resolveReplayNeedAfterRecovery();- return {- replayMadeProgress,- shouldReplay: replayResolution.shouldReplay,- };- },-- failReplayRecovery(): void {- replayStartSequence = null;- state.bootstrapped = false;- state.inFlight = null;- },- };-}diff --git a/packages/client-runtime/src/rpc/index.ts b/packages/client-runtime/src/rpc/index.tsindex b7d385519..76608388f 100644--- a/packages/client-runtime/src/rpc/index.ts+++ b/packages/client-runtime/src/rpc/index.ts@@ -1,5 +1,4 @@export * from "./client.ts";export * from "./http.ts";export * from "./protocol.ts";-export * from "./portability.ts";export { type RpcSession, RpcSessionFactory } from "./session.ts";diff --git a/packages/client-runtime/src/rpc/portability.ts b/packages/client-runtime/src/rpc/portability.tsdeleted file mode 100644index ad3d12192..000000000--- a/packages/client-runtime/src/rpc/portability.ts+++ /dev/null@@ -1,26 +0,0 @@-import {- WS_METHODS,- type PortabilityImportPreview,- type PortabilityProjectFolderMap,-} from "@t3tools/contracts";--import { request } from "./client.ts";--export const exportPortabilityArchive = () => request(WS_METHODS.portabilityExport, {});--export const previewPortabilityArchive = (- contents: string,- projectFolders: PortabilityProjectFolderMap = {},-) => request(WS_METHODS.portabilityPreviewImport, { contents, projectFolders });--export const applyPortabilityArchive = (- contents: string,- preview: Pick<PortabilityImportPreview, "snapshotSequence" | "stateChecksum">,- projectFolders: PortabilityProjectFolderMap = {},-) =>- request(WS_METHODS.portabilityApplyImport, {- contents,- projectFolders,- expectedSnapshotSequence: preview.snapshotSequence,- expectedStateChecksum: preview.stateChecksum,- });diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.tsindex baa84a4e1..b55e00dfa 100644--- a/packages/shared/src/serverSettings.test.ts+++ b/packages/shared/src/serverSettings.test.ts@@ -401,6 +401,7 @@ describe("serverSettings helpers", () => {overrides: {},},automaticGitFetchInterval: Duration.seconds(5),+ providerHealthRefreshInterval: Duration.seconds(10),backgroundActivityProfile: "performance",});@@ -411,6 +412,7 @@ describe("serverSettings helpers", () => {});expect(next.backgroundActivityProfile).toBe("battery-saver");expect(Duration.toMillis(next.automaticGitFetchInterval)).toBe(0);+ expect(Duration.toMillis(next.providerHealthRefreshInterval)).toBe(15 * 60_000);});it("reconciles custom background activity back to a preset when overrides match the preset", () => {diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.tsindex 256b00083..01dd8caeb 100644--- a/packages/shared/src/serverSettings.ts+++ b/packages/shared/src/serverSettings.ts@@ -98,12 +98,6 @@ export function parsePersistedServerObservabilitySettings(return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };}-function shouldReplaceTextGenerationModelSelection(- patch: ServerSettingsPatch["textGenerationModelSelection"] | undefined,-): boolean {- return Boolean(patch && (patch.instanceId !== undefined || patch.model !== undefined));-}-function mergeModelSelectionOptionsById(input: {current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;@@ -194,8 +188,6 @@ export function applyServerSettingsPatch(...(patch.sourceControlWriterModelSelection !== undefined? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }: {}),- ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),- ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),};const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(nextWithReplacementsBase.backgroundActivity,@@ -216,12 +208,13 @@ export function applyServerSettingsPatch(const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;const model = selectionPatch.model ?? current.textGenerationModelSelection.model;- const options = shouldReplaceTextGenerationModelSelection(selectionPatch)- ? selectionPatch.options- : mergeModelSelectionOptionsById({- current: current.textGenerationModelSelection.options,- patch: selectionPatch.options,- });+ const options =+ selectionPatch.instanceId !== undefined || selectionPatch.model !== undefined+ ? selectionPatch.options+ : mergeModelSelectionOptionsById({+ current: current.textGenerationModelSelection.options,+ patch: selectionPatch.options,+ });return {...nextWithReplacements,diff --git a/packages/ssh/src/command.test.ts b/packages/ssh/src/command.test.tsindex c8aac8241..803597393 100644--- a/packages/ssh/src/command.test.ts+++ b/packages/ssh/src/command.test.ts@@ -119,16 +119,20 @@ describe("ssh command", () => {}),);- it.effect("reads the last non-empty ssh output line", () =>- Effect.sync(() => {- assert.equal(- getLastNonEmptyOutputLine(- ["Welcome to the host", "", '{"credential":"pairing-token"}', ""].join("\n"),- ),- '{"credential":"pairing-token"}',- );- }),- );+ it.each([+ ["", null],+ [" \t\r\n\n ", null],+ [" ready ", "ready"],+ ["Welcome\n\n ready \n \t\n", "ready"],+ ["Welcome\r\n\r\n\tready \r\n \t\r\n", "ready"],+ ["first\rsecond", "first\rsecond"],+ [+ ["Welcome to the host", "", '{"credential":"pairing-token"}', ""].join("\n"),+ '{"credential":"pairing-token"}',+ ],+ ] as const)("reads the last non-empty ssh output line from %j", (stdout, expected) => {+ assert.equal(getLastNonEmptyOutputLine(stdout), expected);+ });it.effect("includes stdout in non-zero command failures when stderr is empty", () => {const spawner = ChildProcessSpawner.make(() =>diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.tsindex 09c3004c4..7e6325534 100644--- a/packages/ssh/src/command.ts+++ b/packages/ssh/src/command.ts@@ -113,13 +113,8 @@ export function baseSshArgs(}export function getLastNonEmptyOutputLine(stdout: string): string | null {- return (- stdout- .trim()- .split(/\r?\n/u)- .map((entry) => entry.trim())- .findLast((entry) => entry.length > 0) ?? null- );+ const trimmed = stdout.trim();+ return trimmed.slice(trimmed.lastIndexOf("\n") + 1).trim() || null;}export const collectProcessOutput = <E>(diff --git a/plugins/lifecycle-matrix.test.ts b/plugins/lifecycle-matrix.test.tsindex d649ff5ea..420186466 100644--- a/plugins/lifecycle-matrix.test.ts+++ b/plugins/lifecycle-matrix.test.ts@@ -22,9 +22,6 @@ describe("milestone 13 plugin lifecycle matrix", () => {expect(directory.map((plugin) => plugin.id).toSorted()).toEqual(EXPECTED_IDS);expect(installable.map((plugin) => plugin.id)).toEqual(INSTALLABLE_IDS);- expect(installable.map((plugin) => `builtin-${plugin.id}`)).toEqual(- INSTALLABLE_IDS.map((id) => `builtin-${id}`),- );expect(directory.filter((plugin) => plugin.featuredRank !== undefined)@@ -49,7 +46,6 @@ describe("milestone 13 plugin lifecycle matrix", () => {pending.filter((plugin) => plugin.catalogStatus === "verification-pending"),).toHaveLength(32);for (const plugin of pending) {- expect(["approval-pending", "verification-pending"]).toContain(plugin.catalogStatus);expect(plugin.connection).toMatchObject({type: plugin.catalogStatus,blocker: expect.stringMatching(/\S/),diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.tsindex 17b074de2..73a1c3dbd 100644--- a/scripts/build-desktop-artifact.ts+++ b/scripts/build-desktop-artifact.ts@@ -30,7 +30,6 @@ import {findInlinedExternalPackages,selectCliPackagedRuntimeDependencies,} from "./lib/cli-external-packages.ts";-import { loadRepoEnv } from "./lib/public-config.ts";import { stageReleaseLegalFiles } from "./lib/release-legal.ts";import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";@@ -52,7 +51,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";const LINUX_ICON_SIZES = [16, 22, 24, 32, 48, 64, 128, 256, 512] as const;const DESKTOP_APP_ID = "dev.leodoes.akeru";-const APPLE_TEAM_ID_PATTERN = /^[A-Z0-9]{10}$/u;const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);@@ -189,15 +187,6 @@ function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Typreturn undefined;}-const getDefaultArch = Effect.fn("getDefaultArch")(function* (platform: typeof BuildPlatform.Type) {- const config = PLATFORM_CONFIG[platform];- if (!config) {- return "x64";- }-- return yield* getDefaultBuildArch(platform, config);-});-export class UnsupportedHostBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedHostBuildPlatformError>()("UnsupportedHostBuildPlatformError",{@@ -1056,7 +1045,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (}const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);- const defaultArch = yield* getDefaultArch(platform);+ const defaultArch = yield* getDefaultBuildArch(PLATFORM_CONFIG[platform].archChoices);const arch = mergeOptions(input.arch, env.arch, defaultArch);const supportedArchitectures = PLATFORM_CONFIG[platform].archChoices;if (!supportedArchitectures.includes(arch)) {diff --git a/scripts/lib/build-target-arch.test.ts b/scripts/lib/build-target-arch.test.tsindex 5da970475..018584fc0 100644--- a/scripts/lib/build-target-arch.test.ts+++ b/scripts/lib/build-target-arch.test.ts@@ -6,21 +6,16 @@ import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hoimport { getDefaultBuildArch } from "./build-target-arch.ts";-const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<string, string> =>- Object.fromEntries(- Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined),- );-const withHostRuntime = (platform: NodeJS.Platform,arch: NodeJS.Architecture,- env: Readonly<Record<string, string | undefined>> = {},+ env: Record<string, string> = {},) =>Effect.provide(Layer.mergeAll(Layer.succeed(HostProcessPlatform, platform),Layer.succeed(HostProcessArchitecture, arch),- ConfigProvider.layer(ConfigProvider.fromEnv({ env: compactEnv(env) })),+ ConfigProvider.layer(ConfigProvider.fromEnv({ env })),),);@@ -30,7 +25,7 @@ describe("build-target-arch", () => {// This mirrors the packaging script's default-path behavior: the current// process is x64, but the machine itself is ARM64, so the default build// target should be win-arm64 rather than win-x64.- const arch = yield* getDefaultBuildArch("win", { archChoices: ["x64", "arm64"] }).pipe(+ const arch = yield* getDefaultBuildArch(["x64", "arm64"]).pipe(withHostRuntime("win32", "x64", {PROCESSOR_ARCHITECTURE: "AMD64", // The currently running Node process is x64.PROCESSOR_ARCHITEW6432: "ARM64", // The process is x64, but the actual Windows host is ARM64.@@ -41,9 +36,37 @@ describe("build-target-arch", () => {}),);- it.effect("does not apply Windows host env heuristics for non-Windows targets", () =>+ it.effect("uses x64 when Windows architecture variables are absent", () =>+ Effect.gen(function* () {+ const arch = yield* getDefaultBuildArch(["arm64", "x64"]).pipe(+ withHostRuntime("win32", "x64"),+ );++ assert.equal(arch, "x64");+ }),+ );++ it.effect("uses the first supported architecture when the host is unsupported", () =>+ Effect.gen(function* () {+ const arch = yield* getDefaultBuildArch(["arm64", "universal"]).pipe(+ withHostRuntime("darwin", "x64"),+ );++ assert.equal(arch, "arm64");+ }),+ );++ it.effect("uses x64 when no architectures are configured", () =>+ Effect.gen(function* () {+ const arch = yield* getDefaultBuildArch([]).pipe(withHostRuntime("darwin", "arm64"));++ assert.equal(arch, "x64");+ }),+ );++ it.effect("does not apply Windows host env heuristics on non-Windows hosts", () =>Effect.gen(function* () {- const arch = yield* getDefaultBuildArch("linux", { archChoices: ["x64", "arm64"] }).pipe(+ const arch = yield* getDefaultBuildArch(["x64", "arm64"]).pipe(withHostRuntime("linux", "x64", {PROCESSOR_ARCHITECTURE: "AMD64",PROCESSOR_ARCHITEW6432: "ARM64",diff --git a/scripts/lib/build-target-arch.ts b/scripts/lib/build-target-arch.tsindex eb804b226..b5c452e61 100644--- a/scripts/lib/build-target-arch.ts+++ b/scripts/lib/build-target-arch.ts@@ -4,11 +4,6 @@ import * as Effect from "effect/Effect";import * as Option from "effect/Option";export type BuildArch = "arm64" | "x64" | "universal";-export type BuildPlatform = "mac" | "linux" | "win";--interface PlatformConfig {- readonly archChoices: ReadonlyArray<BuildArch>;-}const WindowsProcessorArchitectureConfig = Config.all({processorArchitecture: Config.string("PROCESSOR_ARCHITECTURE").pipe(Config.option),@@ -23,9 +18,6 @@ function normalizeWindowsArch(value: string | undefined): BuildArch | undefinedreturn undefined;}-const optionToUndefined = <A>(value: Option.Option<A>): A | undefined =>- Option.getOrUndefined(value);-const resolveHostProcessArch = Effect.fn("resolveHostProcessArch")(function* () {const platform = yield* HostProcessPlatform;const processArch = yield* HostProcessArchitecture;@@ -37,8 +29,8 @@ const resolveHostProcessArch = Effect.fn("resolveHostProcessArch")(function* ()// still reports ARM64 via the processor environment variables.const env = yield* WindowsProcessorArchitectureConfig;return (- normalizeWindowsArch(optionToUndefined(env.processorArchitectureW6432)) ??- normalizeWindowsArch(optionToUndefined(env.processorArchitecture)) ??+ normalizeWindowsArch(Option.getOrUndefined(env.processorArchitectureW6432)) ??+ normalizeWindowsArch(Option.getOrUndefined(env.processorArchitecture)) ??"x64");}@@ -46,13 +38,12 @@ const resolveHostProcessArch = Effect.fn("resolveHostProcessArch")(function* ()});export const getDefaultBuildArch = Effect.fn("getDefaultBuildArch")(function* (- platform: BuildPlatform,- platformConfig: PlatformConfig,+ archChoices: ReadonlyArray<BuildArch>,) {const hostArch = yield* resolveHostProcessArch();- if (hostArch && platformConfig.archChoices.includes(hostArch)) {+ if (hostArch && archChoices.includes(hostArch)) {return hostArch;}- return platformConfig.archChoices[0] ?? "x64";+ return archChoices[0] ?? "x64";});diff --git a/scripts/plugin-contribution-policy.test.ts b/scripts/plugin-contribution-policy.test.tsindex 20d617f35..47f1a362c 100644--- a/scripts/plugin-contribution-policy.test.ts+++ b/scripts/plugin-contribution-policy.test.ts@@ -134,39 +134,6 @@ describe("plugin contribution policy", () => {expect(labelsForPath(pathLabels, "apps/server/src/mcp/McpHttpServer.ts")).toEqual([]);});- it("documents the admission and safety rules", () => {- const contributorRules = text("plugins/AGENTS.md");- const publicRules = text("plugins/README.md");-- for (const requirement of [- "curated directory",- "not a complete MCP registry",- "does not guarantee acceptance",- "Custom MCP",- "experimental apps, wrappers, duplicates, and narrow utilities",- "PostgreSQL, SQLite, Redis, Docker, Playwright, time, fetch, filesystem, and generic memory",- "actively use the product",- "user or maintainer requested",- "real Akeru Bot job",- "official or trusted MCP server",- "current setup and reference documentation",- "approval-pending",- "accountable publisher",- "logo",- "add, connect, use, disable, re-enable, and remove",- "export a provider token or secret",- "send, pay, delete, production, secrets, publishing, signatures, refunds, and account-wide",- ]) {- expect(contributorRules).toContain(requirement);- }-- expect(publicRules).toContain("This is a curated directory, not a complete MCP registry");- expect(publicRules).toContain("experimental apps, wrappers, duplicates, and narrow utilities");- expect(text(".github/ISSUE_TEMPLATE/plugin_proposal.yml")).toContain(- "experimental apps, wrappers, duplicates, and narrow utilities",- );- });-it("runs catalog validation and contribution policy tests in CI", () => {const ci = yaml(".github/workflows/ci.yml") as {jobs: Record<string, { steps?: Array<{ run?: string }> }>;