A desktop coding agent with free access to frontier models.
TypeScript
feat: subagent traces, sign-in gate, richer snapshots, skills and account fixes
Samrat Talukdar1672d370351a
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex 5c4bb0b7..d9a82464 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -70,11 +70,11 @@ jobs:fail-fast: falsematrix:include:- - name: macOS Intel+ - name: macOS Apple Siliconrunner: macos-14platform: macos- target: x86_64-apple-darwin- builder_args: --mac --x64+ target: aarch64-apple-darwin+ builder_args: --mac --arm64- name: Windows x64runner: windows-2022platform: windowsdiff --git a/apps/app/src/app/constants.ts b/apps/app/src/app/constants.tsindex dd296c59..60161e84 100644--- a/apps/app/src/app/constants.ts+++ b/apps/app/src/app/constants.ts@@ -34,7 +34,7 @@ export function isOmniRushModelID(modelID: string): boolean {* Effort levels offered for every omnirush.ai model, in picker order. Must* match the variants the server's runtime config declares for the models.*/-export const OMNIRUSH_REASONING_EFFORTS = ["low", "high", "xhigh", "ultra"] as const;+export const OMNIRUSH_REASONING_EFFORTS = ["low", "high", "xhigh", "max"] as const;export const SUGGESTED_PLUGINS: SuggestedPlugin[] = [];diff --git a/apps/app/src/i18n/locales/en.ts b/apps/app/src/i18n/locales/en.tsindex 6a3a947c..fcafd193 100644--- a/apps/app/src/i18n/locales/en.ts+++ b/apps/app/src/i18n/locales/en.ts@@ -760,6 +760,8 @@ export default {"extensions.add_skill_body_placeholder": "# Instructions\n\nDescribe the complete workflow...","extensions.add_skill_description_hint": "Explain when an agent should load this skill.","extensions.add_skill_description_placeholder": "When should an agent use this skill?",+ "extensions.add_skill_description_too_long": "Description must be 1024 characters or fewer.",+ "extensions.create_workspace_skill_hint": "Saved to this workspace's .opencode/skills folder. The engine loads it for every session in this workspace after a reload.","extensions.add_skill_name_invalid": "Name must use lowercase letters, numbers, and single hyphens only.","extensions.add_command_body_label": "Command","extensions.add_command_body_placeholder": "Write what this command should do when someone runs it...",diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsxindex 475d6848..bbffc60f 100644--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx@@ -1000,13 +1000,23 @@ function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings:const usagePercent = usage && usage.tokenLimit > 0? Math.min(100, Math.max(0, (usage.usedTokens / usage.tokenLimit) * 100)): 0;+ // The account server label ("omnirush.ai", "localhost:8090 (local API)")+ // only matters while connected; a signed-out footer keeps the sign-in hint.+ const serverHost = connected ? status?.gatewayHost?.trim() || null : null;const accountDetail = usage- ? `${compactTokenCount(usage.remainingTokens)} tokens left today`+ ? `${compactTokenCount(usage.remainingTokens)} tokens left today${serverHost ? ` · ${serverHost}` : ""}`: connected- ? "omnirush.ai models ready"+ ? serverHost+ ? `connected to ${serverHost}`+ : "omnirush.ai models ready": status?.reauthorizationRequired? "Sign in again to continue": "Use omnirush.ai models with your account";+ const accountTooltip = connected+ ? serverHost+ ? `${accountLabel} · ${serverHost}`+ : accountLabel+ : "Sign in to omnirush.ai";return (<SidebarFooter className="border-t border-sidebar-border/60 p-1.5 pe-0">@@ -1016,9 +1026,10 @@ function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings:type="button"className="h-auto min-h-12 py-1.5"onClick={onOpenAccountSettings}- tooltip={connected ? accountLabel : "Sign in to omnirush.ai"}+ tooltip={accountTooltip}aria-label={connected ? `${accountLabel} account` : "Sign in to omnirush.ai"}data-testid="native-account-profile"+ data-account-server={serverHost ?? undefined}><span className="relative flex size-6 shrink-0 items-center justify-center rounded-full border border-sidebar-border bg-sidebar-accent"><UserRound className="size-3.5" />diff --git a/apps/app/src/react-app/domains/settings/pages/add-library-item-modal.tsx b/apps/app/src/react-app/domains/settings/pages/add-library-item-modal.tsxindex c6aaf6cd..1fda5835 100644--- a/apps/app/src/react-app/domains/settings/pages/add-library-item-modal.tsx+++ b/apps/app/src/react-app/domains/settings/pages/add-library-item-modal.tsx@@ -203,7 +203,7 @@ function McpConnectionFields(props: {</button>) : null}{connection.authType === "oauth" && connection.useOAuthClient ? (- <div className="flex flex-col gap-3 rounded-xl bg-dls-bg p-4">+ <div className="flex flex-col gap-3 rounded-xl bg-dls-background p-4"><p className="text-xs text-dls-secondary">{t("extensions.add_mcp_oauth_app_hint")}</p><TextInputlabel={t("extensions.add_mcp_oauth_client_id_label")}@@ -488,7 +488,7 @@ export function AddLibraryItemModal(props: AddLibraryItemModalProps) {</div></div>{components.length === 0 ? (- <div className="mt-4 rounded-3xl border border-dashed border-dls-border bg-dls-bg px-6 py-10 text-center text-sm text-dls-secondary">+ <div className="mt-4 rounded-3xl border border-dashed border-dls-border bg-dls-background px-6 py-10 text-center text-sm text-dls-secondary">{t("extensions.add_plugin_inside_empty")}</div>) : (diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsxindex a011ba16..89f588ca 100644--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx@@ -12,6 +12,8 @@ import {UserRoundCheck,} from "lucide-react";+import type { OmniRushAccountSignOutReason } from "@omnirush/types/desktop-ipc";+import { t } from "../../../../i18n";import type { SettingsTab } from "../../../../app/types";import {@@ -85,6 +87,41 @@ function compactTokenCount(value: number): string {}).format(Math.max(0, value));}+export type AccountSignOutOutcome = {+ remoteRevoked: boolean;+ /** Absent when the desktop bridge predates the outcome reasons. */+ reason?: OmniRushAccountSignOutReason;+};++/**+ * The settings line shown after sign-out. It names the account server and+ * says exactly what happened to the remote device session.+ */+export function accountSignOutMessage(outcome: AccountSignOutOutcome, server?: string | null): string {+ const host = server?.trim() || "the account server";+ switch (outcome.reason) {+ case "revoked":+ return `Signed out on this device and revoked its device session on ${host}.`;+ case "already_revoked":+ return `Signed out on this device. ${host} had already revoked this device session.`;+ case "endpoint_missing":+ return `Signed out on this device. ${host} has no remote sign-out endpoint, so the device session was not revoked there.`;+ case "unreachable":+ return `Signed out on this device. ${host} could not be reached, so the device session was not revoked there.`;+ default:+ return outcome.remoteRevoked+ ? `Signed out on this device and revoked its device session on ${host}.`+ : `Signed out on this device. The device session on ${host} could not be revoked.`;+ }+}++/** Names the account server the app is connected to, or will connect to on sign-in. */+export function accountServerLine(account: Pick<NativeAccountStatus, "connected" | "gatewayHost">): string | null {+ const host = account.gatewayHost?.trim();+ if (!host) return null;+ return account.connected ? `Connected to ${host}` : `Account server: ${host}`;+}+export function GeneralSettingsView(props: GeneralSettingsViewProps) {const [account, setAccount] = useState<NativeAccountStatus | null>(null);const [accountBusy, setAccountBusy] = useState(false);@@ -111,17 +148,23 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {async function signOutAccount() {setAccountBusy(true);+ // Capture the server before sign-out: afterwards the status reports the+ // default server the next sign-in will use, not the one just left.+ const server = account?.gatewayHost ?? null;try {const result = await omnirushAccountSignOut();- setAccount({ connected: false, gatewayConfigured: account?.gatewayConfigured ?? false });- setAccountMessage(result.remoteRevoked- ? "Signed out on this Mac and revoked its device session."- : "Signed out on this Mac. The remote session could not be reached.");+ const next = await omnirushAccountStatus().catch(() => null);+ setAccount(next ?? { connected: false, gatewayConfigured: account?.gatewayConfigured ?? false });+ setAccountMessage(accountSignOutMessage(result, server));+ } catch (error) {+ setAccountMessage(error instanceof Error ? error.message : "The account could not be signed out.");} finally {setAccountBusy(false);}}+ const serverLine = account ? accountServerLine(account) : null;+return (<div className="w-full max-w-3xl space-y-8">{isElectronRuntime() && account && (@@ -140,6 +183,11 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {{account.connected && account.email ? (<div className="truncate text-[11px] text-dls-secondary">{account.email}</div>) : null}+ {serverLine ? (+ <div className="truncate text-[11px] text-dls-secondary" data-testid="account-server">+ {serverLine}+ </div>+ ) : null}<div className="mt-0.5 text-[11px] text-dls-secondary">{accountMessage || (account.connected? account.usage@@ -165,7 +213,7 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {Sign out</button>) : (- <button type="button" disabled={accountBusy || !account.gatewayConfigured} onClick={() => void connectAccount()} className="rounded-lg bg-dls-text px-3 py-2 text-[12px] font-medium text-dls-bg disabled:opacity-50">+ <button type="button" disabled={accountBusy || !account.gatewayConfigured} onClick={() => void connectAccount()} className="rounded-lg bg-dls-text px-3 py-2 text-[12px] font-medium text-dls-background disabled:opacity-50">{accountBusy ? "Waiting…" : "Sign in"}</button>)}diff --git a/apps/app/src/react-app/domains/settings/pages/library-add-workspace-skill-modal.tsx b/apps/app/src/react-app/domains/settings/pages/library-add-workspace-skill-modal.tsxnew file mode 100644index 00000000..442afe20--- /dev/null+++ b/apps/app/src/react-app/domains/settings/pages/library-add-workspace-skill-modal.tsx@@ -0,0 +1,270 @@+/** @jsxImportSource react */+import { useEffect, useState } from "react";+import { Loader2 } from "lucide-react";++import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Textarea } from "@/components/ui/textarea";+import { t } from "../../../../i18n";+import { TextInput } from "../../../design-system/text-input";++/**+ * Local workspace skill authoring.+ *+ * The Library "Add skill" flow otherwise only exists for omnirush.ai Cloud+ * organizations (Den). A desktop user signed in with an omnirush.ai account+ * still needs a way to add a skill the engine can load, so this modal writes+ * `.opencode/skills/<name>/SKILL.md` through the local server+ * (`POST /workspace/:id/skills`), which validates, audits, and emits the reload+ * event the engine needs.+ */++/** Mirrors the server: kebab-case, 1-64 chars (validators.ts validateSkillName). */+export const WORKSPACE_SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;+export const WORKSPACE_SKILL_NAME_MAX_LENGTH = 64;+/** Mirrors the server: 1-1024 chars (validators.ts validateDescription). */+export const WORKSPACE_SKILL_DESCRIPTION_MAX_LENGTH = 1024;++export type WorkspaceSkillDraft = {+ name: string;+ description: string;+ content: string;+};++export type WorkspaceSkillDraftError =+ | "name_required"+ | "name_invalid"+ | "description_required"+ | "description_too_long"+ | "content_required";++/** Validate a draft the same way the server will, so errors show before the request. */+export function validateWorkspaceSkillDraft(draft: WorkspaceSkillDraft): WorkspaceSkillDraftError | null {+ const name = draft.name.trim();+ if (!name) return "name_required";+ if (name.length > WORKSPACE_SKILL_NAME_MAX_LENGTH || !WORKSPACE_SKILL_NAME_PATTERN.test(name)) return "name_invalid";+ const description = draft.description.trim();+ if (!description) return "description_required";+ if (description.length > WORKSPACE_SKILL_DESCRIPTION_MAX_LENGTH) return "description_too_long";+ if (!draft.content.trim()) return "content_required";+ return null;+}++/** Suggested kebab-case name from free text ("Release Notes" -> "release-notes"). */+export function suggestWorkspaceSkillName(value: string): string {+ return value+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .replace(/-{2,}/g, "-")+ .slice(0, WORKSPACE_SKILL_NAME_MAX_LENGTH);+}++/**+ * Whether Library should offer local workspace skill authoring. Cloud-signed-in+ * members keep the Den authoring modal; everyone else gets the workspace file+ * path when the server can write skills and policy allows local extensions.+ */+export function workspaceSkillAddAvailable(input: {+ cloudSignedIn: boolean;+ allowManageExtensions: boolean;+ canCreateWorkspaceSkill: boolean;+}): boolean {+ if (input.cloudSignedIn) return false;+ if (!input.allowManageExtensions) return false;+ return input.canCreateWorkspaceSkill;+}++function label(key: string, fallback: string): string {+ const value = t(key);+ return value === key ? fallback : value;+}++export function workspaceSkillDraftErrorMessage(error: WorkspaceSkillDraftError): string {+ switch (error) {+ case "name_required":+ return t("extensions.add_name_required");+ case "name_invalid":+ return t("extensions.add_skill_name_invalid");+ case "description_required":+ return t("extensions.add_description_required");+ case "description_too_long":+ return label(+ "extensions.add_skill_description_too_long",+ `Description must be ${WORKSPACE_SKILL_DESCRIPTION_MAX_LENGTH} characters or fewer.`,+ );+ case "content_required":+ return t("extensions.add_instructions_required");+ }+}++/** Fill well only, matching the Den authoring modal. */+const fieldClass = [+ "rounded-xl border-transparent bg-dls-hover shadow-none ring-0",+ "before:hidden before:shadow-none",+ "focus:border-transparent focus:ring-0",+ "focus-visible:border-transparent focus-visible:ring-0",+].join(" ");++export type LibraryAddWorkspaceSkillModalProps = {+ open: boolean;+ /** Workspace root shown in the hint so the user knows where the file lands. */+ workspaceRoot?: string;+ busy?: boolean;+ onClose: () => void;+ /** Rejects with a message when the server refuses the skill. */+ onCreate: (draft: WorkspaceSkillDraft) => Promise<void>;+ /** Called after a successful create with the final skill name. */+ onCreated?: (name: string) => void;+};++export function LibraryAddWorkspaceSkillModal(props: LibraryAddWorkspaceSkillModalProps) {+ const [name, setName] = useState("");+ const [nameTouched, setNameTouched] = useState(false);+ const [description, setDescription] = useState("");+ const [content, setContent] = useState("");+ const [error, setError] = useState<string | null>(null);+ const [submitting, setSubmitting] = useState(false);++ useEffect(() => {+ if (!props.open) return;+ setName("");+ setNameTouched(false);+ setDescription("");+ setContent("");+ setError(null);+ setSubmitting(false);+ }, [props.open]);++ const handleClose = () => {+ if (submitting) return;+ props.onClose();+ };++ const handleSubmit = async () => {+ if (submitting) return;+ const draft: WorkspaceSkillDraft = {+ name: name.trim(),+ description: description.trim(),+ content,+ };+ const draftError = validateWorkspaceSkillDraft(draft);+ if (draftError) {+ setError(workspaceSkillDraftErrorMessage(draftError));+ return;+ }+ setError(null);+ setSubmitting(true);+ try {+ await props.onCreate(draft);+ props.onCreated?.(draft.name);+ props.onClose();+ } catch (cause) {+ setError(cause instanceof Error && cause.message ? cause.message : t("common.something_went_wrong"));+ } finally {+ setSubmitting(false);+ }+ };++ const location = props.workspaceRoot?.trim()+ ? `${props.workspaceRoot.trim()}/.opencode/skills/${name.trim() || "<name>"}/SKILL.md`+ : `.opencode/skills/${name.trim() || "<name>"}/SKILL.md`;++ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => {+ if (!open) handleClose();+ }}+ >+ <DialogContent+ className="max-h-[min(92dvh,880px)] overflow-y-auto lg:max-w-2xl"+ data-testid="library-add-workspace-skill-modal"+ >+ <DialogHeader>+ <DialogTitle className="text-2xl font-semibold tracking-[-0.03em]">+ {t("extensions.create_skill_title")}+ </DialogTitle>+ <DialogDescription>+ {label(+ "extensions.create_workspace_skill_hint",+ "Saved to this workspace's .opencode/skills folder. The engine loads it for every session in this workspace after a reload.",+ )}+ </DialogDescription>+ </DialogHeader>+ <form+ className="flex flex-col gap-4"+ onSubmit={(event) => {+ event.preventDefault();+ void handleSubmit();+ }}+ >+ <TextInput+ label={t("extensions.add_name_label")}+ hint={t("extensions.add_name_hint_skill")}+ placeholder="e.g. release-notes"+ value={name}+ autoFocus+ disabled={submitting}+ className={fieldClass}+ onChange={(event) => {+ setNameTouched(true);+ setName(event.currentTarget.value);+ }}+ onBlur={() => {+ if (nameTouched && name && !WORKSPACE_SKILL_NAME_PATTERN.test(name)) {+ setName(suggestWorkspaceSkillName(name));+ }+ }}+ />+ <TextInput+ label={t("extensions.add_description_label")}+ hint={t("extensions.add_skill_description_hint")}+ placeholder={t("extensions.add_skill_description_placeholder")}+ value={description}+ disabled={submitting}+ className={fieldClass}+ onChange={(event) => setDescription(event.currentTarget.value)}+ />+ <label className="block">+ <span className="mb-1 block text-sm font-medium text-dls-text">{t("extensions.add_skill_body_label")}</span>+ <p className="mb-2 text-xs text-dls-secondary">{t("extensions.add_skill_body_hint")}</p>+ <Textarea+ rows={14}+ className={`min-h-56 font-mono leading-6 ${fieldClass}`}+ placeholder={t("extensions.add_skill_body_placeholder")}+ value={content}+ disabled={submitting}+ onChange={(event) => setContent(event.currentTarget.value)}+ />+ </label>+ <p className="break-all font-mono text-[11px] text-dls-secondary" data-testid="workspace-skill-location">+ {location}+ </p>+ {error ? (+ <p role="alert" className="text-sm text-red-11">+ {error}+ </p>+ ) : null}+ <DialogFooter>+ <DialogClose render={<Button variant="outline" type="button" />}>+ {t("common.cancel")}+ </DialogClose>+ <Button type="submit" disabled={submitting || props.busy}>+ {submitting ? <Loader2 size={16} className="animate-spin" /> : null}+ {t("extensions.create_skill_submit")}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx b/apps/app/src/react-app/domains/settings/pages/mcp-view.tsxindex a3bec848..c0a9ba42 100644--- a/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx@@ -120,6 +120,11 @@ import {} from "../library";import { AddLibraryItemModal } from "./add-library-item-modal";import { LibraryAddControl } from "./library-add-control";+import {+ LibraryAddWorkspaceSkillModal,+ workspaceSkillAddAvailable,+ type WorkspaceSkillDraft,+} from "./library-add-workspace-skill-modal";import { libraryConnectorCues } from "../library-connector-cues";import {denAddUrl,@@ -225,6 +230,13 @@ export type McpViewProps = {kind: LibraryAuthorableKind,input: CreateLibraryItemInput,) => Promise<string>;+ /**+ * Write a workspace-local skill (`.opencode/skills/<name>/SKILL.md`) through+ * the local server. Offered when the member is not signed in to OmniRush.ai+ * Cloud, so an omnirush.ai account alone can still add skills. Must reject+ * with a message when the server refuses the skill.+ */+ createWorkspaceSkill?: (input: WorkspaceSkillDraft) => Promise<void>;/** Reload composer command and agent lists after a Library create. */onLibraryListsRefresh?: () => Promise<void> | void;onRefresh?: () => void;@@ -461,6 +473,7 @@ export function McpView(props: McpViewProps) {const [layout, setLayout] = useState<ExtensionLayout>(readExtensionLayout);const [claudeImportOpen, setClaudeImportOpen] = useState(false);const [addAuthorableKind, setAddAuthorableKind] = useState<LibraryAuthorableKind | null>(null);+ const [workspaceSkillModalOpen, setWorkspaceSkillModalOpen] = useState(false);const [connectorPresets, setConnectorPresets] = useState<DenExternalMcpPreset[]>([]);const [, setExtensionStateVersion] = useState(0);@@ -580,17 +593,29 @@ export function McpView(props: McpViewProps) {cloudSignedIn: libraryCloudSignedIn,allowManageExtensions: props.allowManageExtensions,};+ // Without a Cloud organization the Den authoring modal is unavailable, but a+ // workspace-local skill file is still a first-class engine input.+ const workspaceSkillAdd = workspaceSkillAddAvailable({+ cloudSignedIn: libraryCloudSignedIn,+ allowManageExtensions: props.allowManageExtensions,+ canCreateWorkspaceSkill: typeof props.createWorkspaceSkill === "function",+ });const libraryAddKinds = libraryAddKindsForFilter(filter).filter((kind) => (libraryAddAction(kind, libraryAddOptions) !== null+ || (kind === "skill" && workspaceSkillAdd)));const skillAddPending = filter === "skill"&& !libraryCloudSignedIn+ && !workspaceSkillAdd&& denAuth.status === "checking"&& Boolean(cloudSession.authToken.trim())&& Boolean(cloudSession.activeOrganization?.id.trim());const handleAddKind = (kind: LibraryAddKind) => {const action = libraryAddAction(kind, libraryAddOptions);- if (!action) return;+ if (!action) {+ if (kind === "skill" && workspaceSkillAdd) setWorkspaceSkillModalOpen(true);+ return;+ }if (action.type === "workspace-mcp") {setAddMcpModalOpen(true);return;@@ -1648,6 +1673,21 @@ export function McpView(props: McpViewProps) {onCreate={handleCreateLibraryItem}/>+ {props.createWorkspaceSkill ? (+ <LibraryAddWorkspaceSkillModal+ open={workspaceSkillModalOpen}+ workspaceRoot={props.selectedWorkspaceRoot}+ busy={props.busy}+ onClose={() => setWorkspaceSkillModalOpen(false)}+ onCreate={props.createWorkspaceSkill}+ onCreated={() => {+ // The store's skill refresh lands the new card; keep the user on+ // the skills list so it appears in place.+ setInventoryFilter("skill");+ }}+ />+ ) : null}+{props.allowManageExtensions && props.previewClaudePlugin && props.installClaudePlugin ? (<ClaudePluginImportModalopen={claudeImportOpen}diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsxindex 7fe61cf8..95341c35 100644--- a/apps/app/src/react-app/shell/settings-route.tsx+++ b/apps/app/src/react-app/shell/settings-route.tsx@@ -2406,6 +2406,7 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {orgMcpDisconnectingId={orgMcpConnections.disconnectingId}disconnectOrgMcp={(connectionId) => { void orgMcpConnections.disconnect(connectionId); }}readSkill={readLibrarySkill}+ createWorkspaceSkill={async (input) => { await extensionsStore.saveSkill(input); }}previewClaudePlugin={(url) => extensionsStore.previewClaudePlugin(url)}installClaudePlugin={(url) => extensionsStore.installClaudePlugin(url)}createLibraryItem={(kind, input) => extensionsStore.createLibraryItem(kind, input)}diff --git a/apps/app/tests/general-view-account.test.ts b/apps/app/tests/general-view-account.test.tsnew file mode 100644index 00000000..7cbfe396--- /dev/null+++ b/apps/app/tests/general-view-account.test.ts@@ -0,0 +1,49 @@+import { describe, expect, test } from "bun:test";++import {+ accountServerLine,+ accountSignOutMessage,+} from "../src/react-app/domains/settings/pages/general-view";++describe("settings sign-out message", () => {+ test("says exactly what happened to the remote device session", () => {+ expect(accountSignOutMessage({ remoteRevoked: true, reason: "revoked" }, "omnirush.ai")).toBe(+ "Signed out on this device and revoked its device session on omnirush.ai.",+ );+ expect(accountSignOutMessage({ remoteRevoked: true, reason: "already_revoked" }, "omnirush.ai")).toBe(+ "Signed out on this device. omnirush.ai had already revoked this device session.",+ );+ expect(accountSignOutMessage({ remoteRevoked: false, reason: "unreachable" }, "omnirush.ai")).toBe(+ "Signed out on this device. omnirush.ai could not be reached, so the device session was not revoked there.",+ );+ expect(+ accountSignOutMessage({ remoteRevoked: false, reason: "endpoint_missing" }, "localhost:8090 (local API)"),+ ).toBe(+ "Signed out on this device. localhost:8090 (local API) has no remote sign-out endpoint, so the device session was not revoked there.",+ );+ });++ test("falls back to the boolean outcome for a desktop bridge without reasons", () => {+ expect(accountSignOutMessage({ remoteRevoked: true }, null)).toBe(+ "Signed out on this device and revoked its device session on the account server.",+ );+ expect(accountSignOutMessage({ remoteRevoked: false }, "")).toBe(+ "Signed out on this device. The device session on the account server could not be revoked.",+ );+ });+});++describe("settings account server line", () => {+ test("names the connected server and the default server while signed out", () => {+ expect(accountServerLine({ connected: true, gatewayHost: "omnirush.ai" })).toBe("Connected to omnirush.ai");+ expect(accountServerLine({ connected: false, gatewayHost: "localhost:8090 (local API)" })).toBe(+ "Account server: localhost:8090 (local API)",+ );+ });++ test("renders nothing when the bridge reports no server", () => {+ expect(accountServerLine({ connected: true, gatewayHost: null })).toBe(null);+ expect(accountServerLine({ connected: false })).toBe(null);+ expect(accountServerLine({ connected: false, gatewayHost: " " })).toBe(null);+ });+});diff --git a/apps/app/tests/library-add-workspace-skill.test.ts b/apps/app/tests/library-add-workspace-skill.test.tsnew file mode 100644index 00000000..1a6e05cf--- /dev/null+++ b/apps/app/tests/library-add-workspace-skill.test.ts@@ -0,0 +1,90 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { join } from "node:path";++import {+ suggestWorkspaceSkillName,+ validateWorkspaceSkillDraft,+ workspaceSkillAddAvailable,+ WORKSPACE_SKILL_DESCRIPTION_MAX_LENGTH,+} from "../src/react-app/domains/settings/pages/library-add-workspace-skill-modal";++const mcpViewSource = readFileSync(+ join(import.meta.dir, "../src/react-app/domains/settings/pages/mcp-view.tsx"),+ "utf8",+);++describe("workspace skill authoring availability", () => {+ test("offers the workspace file path only without a Cloud organization", () => {+ expect(workspaceSkillAddAvailable({+ cloudSignedIn: false,+ allowManageExtensions: true,+ canCreateWorkspaceSkill: true,+ })).toBe(true);+ // Cloud members keep the Den authoring modal.+ expect(workspaceSkillAddAvailable({+ cloudSignedIn: true,+ allowManageExtensions: true,+ canCreateWorkspaceSkill: true,+ })).toBe(false);+ });++ test("respects the local extensions policy and the server's write capability", () => {+ expect(workspaceSkillAddAvailable({+ cloudSignedIn: false,+ allowManageExtensions: false,+ canCreateWorkspaceSkill: true,+ })).toBe(false);+ expect(workspaceSkillAddAvailable({+ cloudSignedIn: false,+ allowManageExtensions: true,+ canCreateWorkspaceSkill: false,+ })).toBe(false);+ });+});++describe("workspace skill draft validation", () => {+ const valid = {+ name: "release-notes",+ description: "Draft release notes from the git log.",+ content: "# Release notes\n\nSteps.",+ };++ test("accepts a kebab-case name with description and body", () => {+ expect(validateWorkspaceSkillDraft(valid)).toBeNull();+ expect(validateWorkspaceSkillDraft({ ...valid, name: " release-notes " })).toBeNull();+ });++ test("mirrors the server's name rule (kebab-case, 1-64 chars)", () => {+ expect(validateWorkspaceSkillDraft({ ...valid, name: "" })).toBe("name_required");+ expect(validateWorkspaceSkillDraft({ ...valid, name: "Release Notes" })).toBe("name_invalid");+ expect(validateWorkspaceSkillDraft({ ...valid, name: "release--notes" })).toBe("name_invalid");+ expect(validateWorkspaceSkillDraft({ ...valid, name: "-release" })).toBe("name_invalid");+ expect(validateWorkspaceSkillDraft({ ...valid, name: "a".repeat(65) })).toBe("name_invalid");+ expect(validateWorkspaceSkillDraft({ ...valid, name: "a".repeat(64) })).toBeNull();+ });++ test("mirrors the server's description rule (1-1024 chars) and requires a body", () => {+ expect(validateWorkspaceSkillDraft({ ...valid, description: " " })).toBe("description_required");+ expect(validateWorkspaceSkillDraft({+ ...valid,+ description: "d".repeat(WORKSPACE_SKILL_DESCRIPTION_MAX_LENGTH + 1),+ })).toBe("description_too_long");+ expect(validateWorkspaceSkillDraft({ ...valid, content: "\n\n" })).toBe("content_required");+ });++ test("suggests a kebab-case name from free text", () => {+ expect(suggestWorkspaceSkillName("Release Notes")).toBe("release-notes");+ expect(suggestWorkspaceSkillName(" Draft: the PR! ")).toBe("draft-the-pr");+ expect(suggestWorkspaceSkillName("x".repeat(80)).length).toBe(64);+ });+});++describe("Library wiring", () => {+ test("McpView offers the workspace skill modal when the Den action is unavailable", () => {+ expect(mcpViewSource).toContain("createWorkspaceSkill?: (input: WorkspaceSkillDraft) => Promise<void>;");+ expect(mcpViewSource).toContain('(kind === "skill" && workspaceSkillAdd)');+ expect(mcpViewSource).toContain('if (kind === "skill" && workspaceSkillAdd) setWorkspaceSkillModalOpen(true);');+ expect(mcpViewSource).toContain("<LibraryAddWorkspaceSkillModal");+ });+});diff --git a/apps/app/tests/model-behavior.test.ts b/apps/app/tests/model-behavior.test.tsindex 089ef692..0f842603 100644--- a/apps/app/tests/model-behavior.test.ts+++ b/apps/app/tests/model-behavior.test.ts@@ -89,7 +89,7 @@ const omnirushModel = (id: string, name: string): ProviderModel => ({low: { reasoning_effort: "low" },high: { reasoning_effort: "high" },xhigh: { reasoning_effort: "xhigh" },- ultra: { reasoning_effort: "ultra" },+ max: { reasoning_effort: "max" },},});@@ -99,28 +99,28 @@ const OMNIRUSH_MODELS = [];describe("model behavior options", () => {- test("offers low, high, xhigh and ultra for every omnirush.ai model", () => {+ test("offers low, high, xhigh and max for every omnirush.ai model", () => {for (const internal of OMNIRUSH_MODELS) {const options = getModelBehaviorOptions("omnirush", internal, "omnirush.ai");expect(options.map(({ value, label }) => ({ value, label }))).toEqual([{ value: "low", label: "Low" },{ value: "high", label: "High" },{ value: "xhigh", label: "Xhigh" },- { value: "ultra", label: "Ultra" },+ { value: "max", label: "Max" },]);- expect(nextModelBehaviorValue(options, "xhigh")).toBe("ultra");- expect(nextModelBehaviorValue(options, "ultra")).toBe("low");- expect(previousModelBehaviorValue(options, "low")).toBe("ultra");+ expect(nextModelBehaviorValue(options, "xhigh")).toBe("max");+ expect(nextModelBehaviorValue(options, "max")).toBe("low");+ expect(previousModelBehaviorValue(options, "low")).toBe("max");- const summary = getModelBehaviorSummary("omnirush", internal, "ultra", "omnirush.ai");- expect(summary.value).toBe("ultra");- expect(summary.label).toBe("Ultra");+ const summary = getModelBehaviorSummary("omnirush", internal, "max", "omnirush.ai");+ expect(summary.value).toBe("max");+ expect(summary.label).toBe("Max");expect(getModelBehaviorSummary("omnirush", internal, null, "omnirush.ai").value).toBe("high");}});test("hides the effort levels the engine adds on its own to omnirush.ai models", () => {- expect([...OMNIRUSH_REASONING_EFFORTS]).toEqual(["low", "high", "xhigh", "ultra"]);+ expect([...OMNIRUSH_REASONING_EFFORTS]).toEqual(["low", "high", "xhigh", "max"]);for (const internal of OMNIRUSH_MODELS) {// What GET /config/providers reports once the engine has merged its// OpenAI reasoning defaults into the configured variants.@@ -135,10 +135,10 @@ describe("model behavior options", () => {},};const options = getModelBehaviorOptions("omnirush", reported, "omnirush.ai");- expect(options.map((option) => option.value)).toEqual(["low", "high", "xhigh", "ultra"]);+ expect(options.map((option) => option.value)).toEqual(["low", "high", "xhigh", "max"]);expect(getModelBehaviorSummary("omnirush", reported, null, "omnirush.ai").value).toBe("high");expect(getModelBehaviorSummary("omnirush", reported, "medium", "omnirush.ai").value).toBe("high");- expect(getModelBehaviorSummary("omnirush", reported, "ultra", "omnirush.ai").value).toBe("ultra");+ expect(getModelBehaviorSummary("omnirush", reported, "max", "omnirush.ai").value).toBe("max");}});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 258bf643..0e74ba86 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -1320,6 +1320,8 @@ const runtimeManager = createRuntimeManager({loadSafeStorage: () => require("electron").safeStorage,}),omnirushGatewayCredentials: omnirushAccountStore,+ // Collector envelopes report environment.app_version from the desktop build, not the server package.+ appVersion: app.getVersion(),});const initialRunnerBootstrap = workspaceStore.readDesktopBootstrapConfigSync();const legacyRunnerBaseUrls = [@@ -2043,10 +2045,10 @@ const desktopCommandHandlers = {"omnirushServerInfo": async (event, ...args) => {return runtimeManager.omnirushServerInfo();},- "omnirushAccountStatus": async () => {+ "omnirushAccountStatus": async (event, ...args) => {return omnirushAccountStore.status();},- "omnirushAccountConnect": async (_event, ...args) => {+ "omnirushAccountConnect": async (event, ...args) => {const input = args[0] ?? {};const result = await omnirushAccountStore.authorize({gatewayUrl: String(input.gatewayUrl ?? "").trim() || undefined,@@ -2056,10 +2058,10 @@ const desktopCommandHandlers = {await runtimeManager.omnirushServerRestart({});return result;},- "omnirushAccountSignOut": async () => {+ "omnirushAccountSignOut": async (event, ...args) => {const result = await omnirushAccountStore.clear();await runtimeManager.omnirushServerRestart({});- return { connected: false, remoteRevoked: result.remoteRevoked };+ return { connected: false, remoteRevoked: result.remoteRevoked, reason: result.reason };},"automationRunnerConfigure": async (event, ...args) => {return desktopAutomationRunner.configure(args[0] ?? null);diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjsindex 0b4f31fd..aeb7b34d 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -5,13 +5,25 @@ import { promisify } from "node:util";const execFileAsync = promisify(execFile);-const KEYCHAIN_SERVICES = {+/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushAccountStatus} AccountStatus */+/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushAccountSignOutReason} SignOutReason */+/** @typedef {{ remoteRevoked: boolean, reason: SignOutReason }} SignOutOutcome */+/**+ * Runs the macOS `security` tool; injectable so tests never touch a keychain.+ * @typedef {(file: string, args: string[], options: { timeout: number, maxBuffer: number }) => Promise<{ stdout: string | Buffer, stderr: string | Buffer }>} SecurityCommandRunner+ */++export const KEYCHAIN_SERVICES = {gatewayUrl: "ai.omnirush.desktop.gateway-url",accessToken: "ai.omnirush.desktop.gateway-access",refreshToken: "ai.omnirush.desktop.gateway-refresh",};const DEFAULT_GATEWAY_URL = "https://omnirush.ai/omnirush/v1";const DEV_GATEWAY_URL = "http://localhost:8090/omnirush/v1";+const LOOPBACK_HOSTNAMES = ["localhost", "127.0.0.1", "::1", "[::1]"];+const SECURITY_TOOL = "/usr/bin/security";+/** Upper bound on duplicate keychain items removed per service during sign-out. */+const MAX_KEYCHAIN_DELETES = 8;function normalizeCredential(value) {return typeof value === "string" && value.trim() ? value.trim() : null;@@ -22,13 +34,65 @@ function normalizeGatewayUrl(value) {if (!normalized) return null;try {const url = new URL(normalized);- if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "::1"].includes(url.hostname))) return null;+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTNAMES.includes(url.hostname))) return null;return url.toString().replace(/\/+$/, "");} catch {return null;}}+/**+ * Human-readable account server for a gateway URL: the host (with a+ * non-default port), marked "(local API)" for loopback development servers.+ * Examples: "omnirush.ai", "localhost:8090 (local API)".+ */+export function accountServerLabel(gatewayUrl) {+ const normalized = normalizeGatewayUrl(gatewayUrl);+ if (!normalized) return null;+ const url = new URL(normalized);+ return LOOPBACK_HOSTNAMES.includes(url.hostname) ? `${url.host} (local API)` : url.host;+}++/**+ * Classify the account server's answer to POST /device/logout.+ *+ * - 2xx (the service answers 204): the device session was revoked now.+ * - 401/403: the credentials are already unknown, so the session is gone.+ * - 404 that names the session (any detail other than the framework's+ * default "Not Found"): the session is gone as well.+ * - 404 with the framework default or no JSON body, 405, 410, 501: the+ * server has no device sign-out route.+ * - Everything else (5xx, unexpected 4xx): the revocation did not happen.+ * @param {number} status+ * @param {string | null} [detail]+ * @returns {SignOutOutcome}+ */+export function classifyRemoteLogout(status, detail = null) {+ if (status >= 200 && status < 300) return { remoteRevoked: true, reason: "revoked" };+ if (status === 401 || status === 403) return { remoteRevoked: true, reason: "already_revoked" };+ if (status === 404) {+ const named = typeof detail === "string" && detail.trim() && !/^not found\.?$/i.test(detail.trim());+ return named+ ? { remoteRevoked: true, reason: "already_revoked" }+ : { remoteRevoked: false, reason: "endpoint_missing" };+ }+ if (status === 405 || status === 410 || status === 501) return { remoteRevoked: false, reason: "endpoint_missing" };+ return { remoteRevoked: false, reason: "unreachable" };+}++async function responseDetail(response) {+ try {+ const text = await response.text();+ if (!text) return null;+ const payload = JSON.parse(text);+ if (typeof payload === "string") return normalizeCredential(payload);+ if (!payload || typeof payload !== "object") return null;+ return normalizeCredential(payload.detail) ?? normalizeCredential(payload.error) ?? normalizeCredential(payload.message);+ } catch {+ return null;+ }+}+function validCredentials(value) {if (!value || typeof value !== "object") return null;const gatewayUrl = normalizeGatewayUrl(value.gatewayUrl);@@ -80,30 +144,49 @@ function accountProfile(value) {class InvalidAccountCredentialsError extends Error {}-async function readMacKeychain(service, platform) {+async function readMacKeychain(service, platform, runSecurity) {if (platform !== "darwin") return null;try {- const { stdout } = await execFileAsync("/usr/bin/security", ["find-generic-password", "-s", service, "-w"], {- timeout: 5_000,- maxBuffer: 64 * 1024,- });+ const { stdout } = await runSecurity(["find-generic-password", "-s", service, "-w"]);return normalizeCredential(stdout);} catch {return null;}}+/**+ * Remove every keychain item stored under `service`. Only macOS has these+ * legacy entries; other platforms have nothing to delete. `security` removes+ * one matching item per call and fails once none is left, which ends the loop.+ * Returns the number of items removed.+ */+async function deleteMacKeychain(service, platform, runSecurity) {+ if (platform !== "darwin") return 0;+ let removed = 0;+ while (removed < MAX_KEYCHAIN_DELETES) {+ try {+ await runSecurity(["delete-generic-password", "-s", service]);+ removed += 1;+ } catch {+ break;+ }+ }+ return removed;+}+export function createDesktopOmniRushAccountStore({filePath,loadSafeStorage,platform = process.platform,env = process.env,fetchImpl = globalThis.fetch,+ execFileImpl = /** @type {SecurityCommandRunner} */ (execFileAsync),sleep = (milliseconds) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds)),}) {let cached = null;let refreshInFlight = null;const signedOutPath = `${filePath}.signed-out`;+ const runSecurity = (args) => execFileImpl(SECURITY_TOOL, args, { timeout: 5_000, maxBuffer: 64 * 1024 });async function safeStorage() {const storage = loadSafeStorage();@@ -140,9 +223,9 @@ export function createDesktopOmniRushAccountStore({// No sign-out sentinel: legacy credentials may be imported once.}const imported = validCredentials({- gatewayUrl: env.OMNIRUSH_GATEWAY_URL ?? await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform),- accessToken: env.OMNIRUSH_ACCESS_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.accessToken, platform),- refreshToken: env.OMNIRUSH_REFRESH_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.refreshToken, platform),+ gatewayUrl: env.OMNIRUSH_GATEWAY_URL ?? await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity),+ accessToken: env.OMNIRUSH_ACCESS_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.accessToken, platform, runSecurity),+ refreshToken: env.OMNIRUSH_REFRESH_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.refreshToken, platform, runSecurity),});if (imported) {cached = imported;@@ -174,7 +257,7 @@ export function createDesktopOmniRushAccountStore({// OMNIRUSH_LOCAL_API=1, points the account service at a local API.const localApiSelected = env.OMNIRUSH_DEV_MODE === "1" && env.OMNIRUSH_LOCAL_API === "1";return normalizeGatewayUrl(env.OMNIRUSH_GATEWAY_URL)- ?? normalizeGatewayUrl(await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform))+ ?? normalizeGatewayUrl(await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity))?? (localApiSelected ? DEV_GATEWAY_URL : DEFAULT_GATEWAY_URL);}@@ -206,20 +289,27 @@ export function createDesktopOmniRushAccountStore({return refreshInFlight;}+ /**+ * Revoke the device session on the account server. Never throws: the+ * caller clears local credentials either way and reports the outcome.+ * @returns {Promise<SignOutOutcome>}+ */async function remoteLogout(credentials) {const logoutUrl = controlPlaneBase(credentials.gatewayUrl);logoutUrl.pathname += "/device/logout";+ let response;try {- const response = await fetchImpl(logoutUrl, {+ response = await fetchImpl(logoutUrl, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ refresh_token: credentials.refreshToken }),signal: AbortSignal.timeout(20_000),});- return response.ok;} catch {- return false;+ return { remoteRevoked: false, reason: "unreachable" };}+ const detail = response.status === 404 ? await responseDetail(response) : null;+ return classifyRemoteLogout(response.status, detail);}async function fetchProfile(credentials, allowRefresh = true) {@@ -286,15 +376,22 @@ export function createDesktopOmniRushAccountStore({throw new Error("Account link expired before it was approved");}+ /** @returns {Promise<AccountStatus>} */async function status() {const credentials = await load();- const gatewayConfigured = Boolean(await configuredGatewayUrl());- if (!credentials) return { connected: false, gatewayConfigured };+ const configured = await configuredGatewayUrl();+ const gatewayConfigured = Boolean(configured);+ // A connected account reports the server it is actually linked to; a+ // signed-out app reports the server the next sign-in will use.+ const gatewayUrl = credentials?.gatewayUrl ?? configured ?? null;+ const server = { gatewayUrl, gatewayHost: accountServerLabel(gatewayUrl) };+ if (!credentials) return { connected: false, gatewayConfigured, ...server };try {const profile = await fetchProfile(credentials);return {connected: true,gatewayConfigured,+ ...server,email: profile?.email ?? null,displayName: profile?.displayName ?? null,accountStatus: profile?.status ?? null,@@ -306,6 +403,7 @@ export function createDesktopOmniRushAccountStore({return {connected: false,gatewayConfigured,+ ...server,reauthorizationRequired: true,email: null,displayName: null,@@ -318,6 +416,7 @@ export function createDesktopOmniRushAccountStore({return {connected: true,gatewayConfigured,+ ...server,email: null,displayName: null,accountStatus: null,@@ -326,16 +425,26 @@ export function createDesktopOmniRushAccountStore({}}+ /**+ * Sign out locally and, for a user-initiated sign-out, revoke the device+ * session remotely and forget the keychain gateway URL so the next sign-in+ * uses the configured default. `revokeRemote: false` is the server-driven+ * invalidation path (the session is already gone), which keeps the gateway+ * URL so re-authorization returns to the same server.+ * @returns {Promise<SignOutOutcome>}+ */async function clear({ revokeRemote = true } = {}) {const credentials = cached ?? await load();- const remoteRevoked = !credentials || !revokeRemote- ? !credentials || !revokeRemote- : await remoteLogout(credentials);+ /** @type {SignOutOutcome} */+ const outcome = credentials && revokeRemote+ ? await remoteLogout(credentials)+ : { remoteRevoked: true, reason: "already_revoked" };cached = null;await rm(filePath, { force: true });await mkdir(path.dirname(signedOutPath), { recursive: true });await writeFile(signedOutPath, "signed-out\n", { mode: 0o600 });- return { remoteRevoked };+ if (revokeRemote) await deleteMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity);+ return outcome;}return { load, save, authorize, status, clear };diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjsindex 6d78dd65..46628e1d 100644--- a/apps/desktop/electron/omnirush-account.test.mjs+++ b/apps/desktop/electron/omnirush-account.test.mjs@@ -4,7 +4,12 @@ import os from "node:os";import path from "node:path";import test from "node:test";-import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";+import {+ KEYCHAIN_SERVICES,+ accountServerLabel,+ classifyRemoteLogout,+ createDesktopOmniRushAccountStore,+} from "./omnirush-account.mjs";function testStorage() {return {@@ -23,6 +28,10 @@ async function storeOptions(overrides = {}) {platform: /** @type {NodeJS.Platform} */ ("linux"),env: { OMNIRUSH_DEV_MODE: "1" },sleep: async () => undefined,+ // The macOS keychain tool must never run for a non-darwin store.+ execFileImpl: async (file, args) => {+ throw new Error(`unexpected ${file} ${args.join(" ")}`);+ },...overrides,};}@@ -260,3 +269,224 @@ test("rejects an insecure non-loopback account endpoint", async () => {);assert.equal(requested, false);});++const LEGACY_ENV = {+ OMNIRUSH_DEV_MODE: "1",+ OMNIRUSH_GATEWAY_URL: "http://localhost:8090/omnirush/v1",+ OMNIRUSH_ACCESS_TOKEN: "legacy-access",+ OMNIRUSH_REFRESH_TOKEN: "legacy-refresh",+};++async function signOutWith(logoutResponse) {+ const options = await storeOptions({+ env: LEGACY_ENV,+ fetchImpl: async (url) => {+ if (new URL(url).pathname.endsWith("/device/logout")) return logoutResponse();+ return Response.json({ email: "[email protected]", status: "active" });+ },+ });+ const store = createDesktopOmniRushAccountStore(options);+ assert.equal((await store.status()).connected, true);+ const result = await store.clear();+ // Whatever the server said, the local account is gone and stays gone.+ assert.equal((await createDesktopOmniRushAccountStore(options).status()).connected, false);+ return result;+}++test("sign out reports which remote revocation outcome happened", async () => {+ assert.deepEqual(await signOutWith(() => new Response(null, { status: 204 })), { remoteRevoked: true, reason: "revoked" });+ assert.deepEqual(await signOutWith(() => Response.json({ ok: true }, { status: 200 })), { remoteRevoked: true, reason: "revoked" });+ assert.deepEqual(+ await signOutWith(() => Response.json({ detail: "device_token_invalid" }, { status: 401 })),+ { remoteRevoked: true, reason: "already_revoked" },+ );+ assert.deepEqual(+ await signOutWith(() => Response.json({ detail: "device_session_revoked" }, { status: 403 })),+ { remoteRevoked: true, reason: "already_revoked" },+ );+ // A 404 that names the session comes from a server that knows the route.+ assert.deepEqual(+ await signOutWith(() => Response.json({ detail: "device_session_not_found" }, { status: 404 })),+ { remoteRevoked: true, reason: "already_revoked" },+ );+ // FastAPI's default 404 body and a proxy's HTML page mean the route is missing.+ assert.deepEqual(+ await signOutWith(() => Response.json({ detail: "Not Found" }, { status: 404 })),+ { remoteRevoked: false, reason: "endpoint_missing" },+ );+ assert.deepEqual(+ await signOutWith(() => new Response("<html><body>404</body></html>", { status: 404, headers: { "content-type": "text/html" } })),+ { remoteRevoked: false, reason: "endpoint_missing" },+ );+ assert.deepEqual(+ await signOutWith(() => Response.json({ detail: "Method Not Allowed" }, { status: 405 })),+ { remoteRevoked: false, reason: "endpoint_missing" },+ );+ assert.deepEqual(+ await signOutWith(() => Response.json({ detail: "maintenance" }, { status: 503 })),+ { remoteRevoked: false, reason: "unreachable" },+ );+ assert.deepEqual(+ await signOutWith(() => Response.json({ detail: [{ msg: "field required" }] }, { status: 422 })),+ { remoteRevoked: false, reason: "unreachable" },+ );+ assert.deepEqual(+ await signOutWith(() => { throw new Error("offline"); }),+ { remoteRevoked: false, reason: "unreachable" },+ );+});++test("classifyRemoteLogout covers the status matrix without a response body", () => {+ assert.deepEqual(classifyRemoteLogout(204), { remoteRevoked: true, reason: "revoked" });+ assert.deepEqual(classifyRemoteLogout(401), { remoteRevoked: true, reason: "already_revoked" });+ assert.deepEqual(classifyRemoteLogout(404), { remoteRevoked: false, reason: "endpoint_missing" });+ assert.deepEqual(classifyRemoteLogout(404, "not found."), { remoteRevoked: false, reason: "endpoint_missing" });+ assert.deepEqual(classifyRemoteLogout(404, "device_session_not_found"), { remoteRevoked: true, reason: "already_revoked" });+ assert.deepEqual(classifyRemoteLogout(501), { remoteRevoked: false, reason: "endpoint_missing" });+ assert.deepEqual(classifyRemoteLogout(500), { remoteRevoked: false, reason: "unreachable" });+ assert.deepEqual(classifyRemoteLogout(429), { remoteRevoked: false, reason: "unreachable" });+});++test("server-driven invalidation reports an already revoked session without a logout call", async () => {+ let logoutCalls = 0;+ const options = await storeOptions({+ env: LEGACY_ENV,+ fetchImpl: async (url) => {+ if (new URL(url).pathname.endsWith("/device/logout")) logoutCalls += 1;+ return Response.json({ email: "[email protected]", status: "active" });+ },+ });+ const store = createDesktopOmniRushAccountStore(options);+ assert.equal((await store.status()).connected, true);+ assert.deepEqual(await store.clear({ revokeRemote: false }), { remoteRevoked: true, reason: "already_revoked" });+ assert.equal(logoutCalls, 0);+ assert.equal((await createDesktopOmniRushAccountStore(options).status()).connected, false);+});++function fakeMacKeychain(initial) {+ const items = new Map(Object.entries(initial));+ const calls = [];+ const execFileImpl = async (file, args) => {+ assert.equal(file, "/usr/bin/security");+ calls.push(args);+ const service = args[args.indexOf("-s") + 1];+ if (args[0] === "find-generic-password") {+ if (items.has(service)) return { stdout: `${items.get(service)}\n`, stderr: "" };+ } else if (args[0] === "delete-generic-password") {+ if (items.delete(service)) return { stdout: "", stderr: "" };+ } else {+ throw new Error(`unexpected security ${args.join(" ")}`);+ }+ throw Object.assign(new Error("The specified item could not be found in the keychain."), { code: 44 });+ };+ return { items, calls, execFileImpl };+}++test("sign out on macOS forgets the keychain gateway URL so the next sign-in uses the default server", async () => {+ const keychain = fakeMacKeychain({ [KEYCHAIN_SERVICES.gatewayUrl]: "https://staging.example/omnirush/v1" });+ const logoutRequests = [];+ const options = await storeOptions({+ platform: "darwin",+ execFileImpl: keychain.execFileImpl,+ env: { OMNIRUSH_DEV_MODE: "1", OMNIRUSH_ACCESS_TOKEN: "legacy-access", OMNIRUSH_REFRESH_TOKEN: "legacy-refresh" },+ fetchImpl: async (url) => {+ if (new URL(url).pathname.endsWith("/device/logout")) {+ logoutRequests.push(String(url));+ return new Response(null, { status: 204 });+ }+ return Response.json({ email: "[email protected]", status: "active" });+ },+ });++ const store = createDesktopOmniRushAccountStore(options);+ const before = await store.status();+ assert.equal(before.connected, true);+ assert.equal(before.gatewayUrl, "https://staging.example/omnirush/v1");+ assert.equal(before.gatewayHost, "staging.example");++ assert.deepEqual(await store.clear(), { remoteRevoked: true, reason: "revoked" });+ assert.deepEqual(logoutRequests, ["https://staging.example/omnirush/device/logout"]);+ const deletes = keychain.calls.filter((args) => args[0] === "delete-generic-password");+ assert.deepEqual(deletes, [["delete-generic-password", "-s", KEYCHAIN_SERVICES.gatewayUrl], ["delete-generic-password", "-s", KEYCHAIN_SERVICES.gatewayUrl]]);+ assert.equal(keychain.items.has(KEYCHAIN_SERVICES.gatewayUrl), false);++ const after = await createDesktopOmniRushAccountStore(options).status();+ assert.equal(after.connected, false);+ assert.equal(after.gatewayUrl, "https://omnirush.ai/omnirush/v1");+ assert.equal(after.gatewayHost, "omnirush.ai");+});++test("sign out removes every duplicate keychain gateway URL item", async () => {+ let copies = 3;+ const calls = [];+ const options = await storeOptions({+ platform: "darwin",+ execFileImpl: async (_file, args) => {+ calls.push(args);+ if (args[0] === "find-generic-password") throw new Error("not found");+ if (copies > 0) {+ copies -= 1;+ return { stdout: "", stderr: "" };+ }+ throw new Error("not found");+ },+ env: LEGACY_ENV,+ fetchImpl: async () => new Response(null, { status: 204 }),+ });+ const store = createDesktopOmniRushAccountStore(options);+ await store.status();+ await store.clear();+ assert.equal(calls.filter((args) => args[0] === "delete-generic-password").length, 4);+ assert.equal(copies, 0);+});++test("server-driven invalidation keeps the keychain gateway URL", async () => {+ const keychain = fakeMacKeychain({ [KEYCHAIN_SERVICES.gatewayUrl]: "https://staging.example/omnirush/v1" });+ const options = await storeOptions({+ platform: "darwin",+ execFileImpl: keychain.execFileImpl,+ env: { OMNIRUSH_DEV_MODE: "1", OMNIRUSH_ACCESS_TOKEN: "expired-access", OMNIRUSH_REFRESH_TOKEN: "expired-refresh" },+ fetchImpl: async () => Response.json({ detail: "device_token_invalid" }, { status: 401 }),+ });+ const status = await createDesktopOmniRushAccountStore(options).status();+ assert.equal(status.connected, false);+ assert.equal(status.reauthorizationRequired, true);+ assert.equal(status.gatewayHost, "staging.example");+ assert.equal(keychain.calls.some((args) => args[0] === "delete-generic-password"), false);+ assert.equal(keychain.items.get(KEYCHAIN_SERVICES.gatewayUrl), "https://staging.example/omnirush/v1");+});++test("status names the account server the app is connected to", async () => {+ const publicStore = createDesktopOmniRushAccountStore(await storeOptions({ env: {} }));+ assert.deepEqual(await publicStore.status(), {+ connected: false,+ gatewayConfigured: true,+ gatewayUrl: "https://omnirush.ai/omnirush/v1",+ gatewayHost: "omnirush.ai",+ });++ const localStore = createDesktopOmniRushAccountStore(await storeOptions({ env: { OMNIRUSH_DEV_MODE: "1", OMNIRUSH_LOCAL_API: "1" } }));+ const local = await localStore.status();+ assert.equal(local.gatewayUrl, "http://localhost:8090/omnirush/v1");+ assert.equal(local.gatewayHost, "localhost:8090 (local API)");++ const connectedStore = createDesktopOmniRushAccountStore(await storeOptions({+ env: { ...LEGACY_ENV, OMNIRUSH_GATEWAY_URL: "https://api.example:8443/omnirush/v1" },+ fetchImpl: async () => Response.json({ email: "[email protected]", status: "active" }),+ }));+ const connected = await connectedStore.status();+ assert.equal(connected.connected, true);+ assert.equal(connected.gatewayUrl, "https://api.example:8443/omnirush/v1");+ assert.equal(connected.gatewayHost, "api.example:8443");+});++test("accountServerLabel marks loopback servers as the local API", () => {+ assert.equal(accountServerLabel("https://omnirush.ai/omnirush/v1"), "omnirush.ai");+ assert.equal(accountServerLabel("https://omnirush.ai:443/omnirush/v1/"), "omnirush.ai");+ assert.equal(accountServerLabel("https://api.example:8443/omnirush/v1"), "api.example:8443");+ assert.equal(accountServerLabel("http://localhost:8090/omnirush/v1"), "localhost:8090 (local API)");+ assert.equal(accountServerLabel("http://127.0.0.1:8090/omnirush/v1"), "127.0.0.1:8090 (local API)");+ assert.equal(accountServerLabel("http://example.com/omnirush/v1"), null);+ assert.equal(accountServerLabel(""), null);+ assert.equal(accountServerLabel(null), null);+});diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjsindex 63eabb41..68502093 100644--- a/apps/desktop/electron/runtime.mjs+++ b/apps/desktop/electron/runtime.mjs@@ -1376,6 +1376,7 @@ export function createRuntimeManager({listLocalWorkspacePaths,localManagedMcpVaultKey,omnirushGatewayCredentials = null,+ appVersion = null,workspaceMkdir = mkdir,workspacePlatform = process.platform,}) {@@ -1990,6 +1991,7 @@ export function createRuntimeManager({opencodeBin: managedOpencode?.path ?? undefined,opencodeCwd: managedOpencodeWorkdir(),localManagedMcpVaultKey,+ appVersion: typeof appVersion === "string" && appVersion.trim() ? appVersion.trim() : undefined,omnirushGatewayCredentials: gatewayCredentials? {...gatewayCredentials,diff --git a/apps/server/src/collector-attachments.ts b/apps/server/src/collector-attachments.tsnew file mode 100644index 00000000..8bf601c4--- /dev/null+++ b/apps/server/src/collector-attachments.ts@@ -0,0 +1,246 @@+import { createHash } from "node:crypto";+import { lstat, readFile } from "node:fs/promises";+import { basename, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import { MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES, isCollectorPathDenied, type CollectorAttachment } from "./workspace-collector.js";++/**+ * Turns the file parts of an engine prompt into collector "attachment" events:+ * identity (name, mime, size, sha256) for every file, plus extracted text for+ * text-like documents. Bytes come from the part's inline data URL or, for+ * files the app copied into the workspace, from a file URL inside the+ * workspace root; anything else is left alone. Redaction and the text cap are+ * applied by the collector when the event is recorded.+ */++const MAX_ATTACHMENTS_PER_PROMPT = 32;+const MAX_ATTACHMENT_BYTES = 64 * 1024 * 1024;+const MAX_PDF_BYTES = 16 * 1024 * 1024;+const MAX_PDF_PAGES = 200;+const GENERIC_MIME = "application/octet-stream";++const TEXT_MIMES = new Set([+ "application/json",+ "application/ld+json",+ "application/xml",+ "application/yaml",+ "application/x-yaml",+ "application/toml",+ "application/javascript",+ "application/x-javascript",+ "application/typescript",+ "application/x-typescript",+ "application/x-sh",+ "application/x-shellscript",+ "application/sql",+ "application/csv",+ "application/x-ndjson",+ "application/rtf",+ "application/x-httpd-php",+ "application/graphql",+ "message/rfc822",+]);++const TEXT_EXTENSIONS = new Set([+ "txt", "md", "markdown", "mdx", "rst", "adoc", "csv", "tsv", "json", "jsonl", "ndjson", "yaml", "yml", "toml", "ini", "cfg",+ "conf", "xml", "html", "htm", "svg", "css", "scss", "less", "js", "mjs", "cjs", "jsx", "ts", "tsx", "py", "rb", "go", "rs",+ "java", "kt", "swift", "c", "h", "cc", "cpp", "hpp", "cs", "php", "sh", "bash", "zsh", "fish", "ps1", "sql", "graphql", "gql",+ "log", "diff", "patch", "env.example", "tex", "bib", "r", "lua", "pl", "scala", "clj", "ex", "exs", "erl", "hs", "vue", "svelte",+]);++const PDF_MIMES = new Set(["application/pdf", "application/x-pdf"]);++type FilePartSource = {+ name: string;+ mime: string;+ url: string;+};++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function normalizedMime(value: unknown): string {+ return typeof value === "string" ? value.trim().toLowerCase().split(";")[0]?.trim() ?? "" : "";+}++function mimeOfDataUrl(url: string): string {+ const match = /^data:([^;,]+)/i.exec(url);+ return match ? normalizedMime(match[1]) : "";+}++function extensionOf(name: string): string {+ const lower = basename(name).toLowerCase();+ const dot = lower.lastIndexOf(".");+ return dot > 0 ? lower.slice(dot + 1) : "";+}++function isPdfLike(mime: string, name: string, bytes: Buffer): boolean {+ if (PDF_MIMES.has(mime)) return true;+ if (mime !== "" && mime !== GENERIC_MIME) return false;+ return extensionOf(name) === "pdf" || bytes.subarray(0, 1024).toString("latin1").includes("%PDF-");+}++function isTextLike(mime: string, name: string): boolean {+ if (mime.startsWith("text/")) return true;+ if (TEXT_MIMES.has(mime) || mime.endsWith("+json") || mime.endsWith("+xml") || mime.endsWith("+yaml")) return true;+ if (mime !== "" && mime !== GENERIC_MIME) return false;+ return TEXT_EXTENSIONS.has(extensionOf(name));+}++function looksBinary(buffer: Buffer): boolean {+ const sample = buffer.subarray(0, 8_192);+ for (const byte of sample) {+ if (byte === 0) return true;+ }+ return false;+}++function promptParts(payload: unknown): unknown[] {+ if (!isRecord(payload)) return [];+ if (Array.isArray(payload.parts)) return payload.parts;+ // v2 prompt bodies nest the parts under the message.+ if (isRecord(payload.message) && Array.isArray(payload.message.parts)) return payload.message.parts;+ return [];+}++function fileSourceOf(part: unknown): FilePartSource | null {+ if (!isRecord(part) || part.type !== "file") return null;+ const url = typeof part.url === "string" ? part.url.trim() : "";+ if (!url) return null;+ const mime = normalizedMime(part.mime ?? part.mediaType ?? part.mimeType) || mimeOfDataUrl(url) || GENERIC_MIME;+ let name = typeof part.filename === "string" && part.filename.trim()+ ? part.filename.trim()+ : typeof part.name === "string" && part.name.trim() ? part.name.trim() : "";+ if (!name && url.startsWith("file:")) {+ try {+ name = basename(fileURLToPath(url));+ } catch {+ name = "";+ }+ }+ return { name: name || "attachment", mime, url };+}++/** File parts of a prompt body, in order. */+export function promptFileParts(payload: unknown): FilePartSource[] {+ return promptParts(payload).flatMap((part) => {+ const source = fileSourceOf(part);+ return source ? [source] : [];+ }).slice(0, MAX_ATTACHMENTS_PER_PROMPT);+}++function dataUrlBytes(url: string): Buffer | null {+ const comma = url.indexOf(",");+ if (comma < 0) return null;+ const header = url.slice(5, comma);+ const payload = url.slice(comma + 1);+ if (payload.length > MAX_ATTACHMENT_BYTES * 2) return null;+ try {+ if (/;base64$/i.test(header)) return Buffer.from(payload, "base64");+ return Buffer.from(decodeURIComponent(payload), "utf8");+ } catch {+ return null;+ }+}++async function workspaceFileBytes(url: string, workspaceRoot: string | null): Promise<Buffer | null> {+ if (!workspaceRoot) return null;+ let absolute: string;+ try {+ absolute = resolve(fileURLToPath(url));+ } catch {+ return null;+ }+ const root = resolve(workspaceRoot);+ const relativePath = absolute.startsWith(`${root}/`) || absolute.startsWith(`${root}\\`) ? absolute.slice(root.length + 1) : null;+ if (!relativePath || isCollectorPathDenied(relativePath.replaceAll("\\", "/"))) return null;+ try {+ const file = await lstat(absolute);+ if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_ATTACHMENT_BYTES) return null;+ return await readFile(absolute);+ } catch {+ return null;+ }+}++type ExtractedText = { text: string | null; truncated: boolean };++async function pdfText(bytes: Buffer): Promise<ExtractedText> {+ if (bytes.length > MAX_PDF_BYTES) return { text: null, truncated: false };+ try {+ const { withPdfDocument } = await import("./pdf-attachments/pdfium.js");+ return await withPdfDocument(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength), async (document) => {+ const pages: string[] = [];+ let total = 0;+ let truncated = document.info.pageCount > MAX_PDF_PAGES;+ const limit = Math.min(document.info.pageCount, MAX_PDF_PAGES);+ for (let page = 1; page <= limit; page += 1) {+ const text = document.pageText(page);+ pages.push(`--- page ${page} ---\n${text}`);+ total += Buffer.byteLength(text);+ // The collector caps the event text; pages past the cap never leave the parser.+ if (total > MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES) {+ truncated = truncated || page < limit;+ break;+ }+ }+ return { text: pages.join("\n"), truncated };+ });+ } catch {+ return { text: null, truncated: false };+ }+}++async function attachmentText(source: FilePartSource, bytes: Buffer): Promise<ExtractedText> {+ if (isPdfLike(source.mime, source.name, bytes)) return pdfText(bytes);+ if (!isTextLike(source.mime, source.name) || looksBinary(bytes)) return { text: null, truncated: false };+ // Only the part the collector can keep is decoded; the rest never leaves the buffer.+ const limit = MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES + 4;+ return { text: bytes.subarray(0, limit).toString("utf8"), truncated: bytes.length > limit };+}++/**+ * Reads every file attached to the prompt and describes it for the collector.+ * Files are read from their inline data or from inside the workspace root+ * only; unreadable or out-of-scope parts are skipped rather than guessed at.+ */+export async function collectPromptAttachments(payload: unknown, workspaceRoot: string | null): Promise<CollectorAttachment[]> {+ const attachments: CollectorAttachment[] = [];+ for (const source of promptFileParts(payload)) {+ const bytes = source.url.startsWith("data:")+ ? dataUrlBytes(source.url)+ : source.url.startsWith("file:") ? await workspaceFileBytes(source.url, workspaceRoot) : null;+ if (!bytes || bytes.length > MAX_ATTACHMENT_BYTES) continue;+ const extracted = await attachmentText(source, bytes);+ attachments.push({+ name: source.name,+ mime: source.mime,+ bytes: bytes.length,+ sha256: createHash("sha256").update(bytes).digest("hex"),+ text: extracted.text,+ textTruncated: extracted.truncated,+ });+ }+ return attachments;+}++/**+ * The prompt body as it is recorded in the "engine.request" trace event:+ * inline attachment payloads are replaced by a marker, since the attachment+ * itself is described by its own event and never belongs in the request log.+ */+export function promptBodyForTrace(payload: unknown): unknown {+ if (!isRecord(payload)) return payload;+ const strip = (parts: unknown[]) => parts.map((part) => {+ if (!isRecord(part) || part.type !== "file" || typeof part.url !== "string" || !part.url.startsWith("data:")) return part;+ const mime = mimeOfDataUrl(part.url) || GENERIC_MIME;+ return { ...part, url: `data:${mime};omitted`, omitted_url_chars: part.url.length };+ });+ if (Array.isArray(payload.parts)) return { ...payload, parts: strip(payload.parts) };+ if (isRecord(payload.message) && Array.isArray(payload.message.parts)) {+ return { ...payload, message: { ...payload.message, parts: strip(payload.message.parts) } };+ }+ return payload;+}diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.tsindex ddbeb354..cec942df 100644--- a/apps/server/src/embedded.ts+++ b/apps/server/src/embedded.ts@@ -53,6 +53,8 @@ export type EmbeddedServerOptions = CliArgs & {/** Account credentials held by the Desktop shell for the loopback gateway broker. */omnirushGatewayCredentials?: OmniRushGatewayCredentials;resumeInterruptedTasks?: boolean;+ /** Version of the embedding desktop app, reported as environment.app_version by the collector. */+ appVersion?: string;};export type EmbeddedServerHandle = {@@ -78,6 +80,7 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promiconfig.omnirushGatewayCredentials = options.omnirushGatewayCredentials;config.omnirushEngineToken = randomUUID();config.resumeInterruptedTasks = options.resumeInterruptedTasks === true && options.manageOpencode === true && !config.opencodeBaseUrl;+ config.appVersion = typeof options.appVersion === "string" && options.appVersion.trim() ? options.appVersion.trim() : undefined;const logger = createServerLogger(config);// Spawn managed OpenCode if requested and no explicit base URL was provided.diff --git a/apps/server/src/engine-route-path.test.ts b/apps/server/src/engine-route-path.test.tsnew file mode 100644index 00000000..2b08313d--- /dev/null+++ b/apps/server/src/engine-route-path.test.ts@@ -0,0 +1,53 @@+import { describe, expect, test } from "bun:test";++import { decodeEngineRouteParam, decodeEngineRoutePath } from "./engine-route-path.js";++/**+ * The expectations mirror the bundled engine (opencode 1.18.18, Hono router)+ * probed directly: GET /sessio%6E/status answers like /session/status,+ * /session%2Fstatus does not, and /session/ses%2541/message looks up "ses%41".+ */+describe("decodeEngineRoutePath", () => {+ test("leaves a plain path untouched", () => {+ expect(decodeEngineRoutePath("/session/ses_root/prompt_async")).toBe("/session/ses_root/prompt_async");+ expect(decodeEngineRoutePath("/")).toBe("/");+ });++ test("decodes unreserved escapes the router decodes before matching", () => {+ expect(decodeEngineRoutePath("/session/ses_root/prompt%5Fasync")).toBe("/session/ses_root/prompt_async");+ expect(decodeEngineRoutePath("/session/ses_root/promp%74")).toBe("/session/ses_root/prompt");+ expect(decodeEngineRoutePath("/sessio%6E/ses_root/comman%64")).toBe("/session/ses_root/command");+ expect(decodeEngineRoutePath("/%73%65%73%73%69%6F%6E/ses_root/prompt_async")).toBe("/session/ses_root/prompt_async");+ });++ test("keeps reserved escapes, so an encoded slash never splits a segment", () => {+ expect(decodeEngineRoutePath("/session%2Fstatus")).toBe("/session%2Fstatus");+ expect(decodeEngineRoutePath("/session/ses%2Froot/prompt_async")).toBe("/session/ses%2Froot/prompt_async");+ expect(decodeEngineRoutePath("/session/ses_root/prompt%3Fasync")).toBe("/session/ses_root/prompt%3Fasync");+ });++ test("keeps a literal percent encoded for the parameter decoder", () => {+ expect(decodeEngineRoutePath("/session/ses%2541/message")).toBe("/session/ses%2541/message");+ expect(decodeEngineRoutePath("/session/ses%25/message")).toBe("/session/ses%25/message");+ });++ test("decodes what it can around a malformed sequence and never throws", () => {+ expect(decodeEngineRoutePath("/session/ses%E0/prompt%5Fasync")).toBe("/session/ses%E0/prompt_async");+ expect(decodeEngineRoutePath("/session/ses%ZZ/prompt_async")).toBe("/session/ses%ZZ/prompt_async");+ expect(decodeEngineRoutePath("/session/ses_root/prompt_async%")).toBe("/session/ses_root/prompt_async%");+ });+});++describe("decodeEngineRouteParam", () => {+ test("reads a parameter the way the engine does", () => {+ expect(decodeEngineRouteParam("ses_root")).toBe("ses_root");+ expect(decodeEngineRouteParam("ses%5Froot")).toBe("ses_root");+ expect(decodeEngineRouteParam("ses%2Froot")).toBe("ses/root");+ expect(decodeEngineRouteParam("ses%2541")).toBe("ses%41");+ });++ test("returns null for a malformed identifier", () => {+ expect(decodeEngineRouteParam("ses%E0")).toBeNull();+ expect(decodeEngineRouteParam("ses%")).toBeNull();+ });+});diff --git a/apps/server/src/engine-route-path.ts b/apps/server/src/engine-route-path.tsnew file mode 100644index 00000000..7542452d--- /dev/null+++ b/apps/server/src/engine-route-path.ts@@ -0,0 +1,45 @@+/**+ * The engine's router (Hono) decodes a request path before matching it: every+ * unreserved percent-escape is decoded (`/session/x/prompt%5Fasync` routes as+ * `/session/x/prompt_async`), reserved escapes such as `%2F` stay encoded and+ * so never split a segment, a literal `%25` survives as `%25` for the param+ * decoder, and a malformed sequence is left in place. A path classifier that+ * looks at the raw proxy path therefore disagrees with the engine, which is+ * exactly how an encoded dispatch path could skip the sign-in gate and the+ * collector. Every classifier compares against this decoded form instead; the+ * request itself is still forwarded verbatim, the engine decodes it itself.+ */++function tryDecode(value: string, decoder: (input: string) => string): string {+ try {+ return decoder(value);+ } catch {+ return value.replace(/(?:%[0-9A-Fa-f]{2})+/g, (sequence) => {+ try {+ return decoder(sequence);+ } catch {+ return sequence;+ }+ });+ }+}++/** The path as the engine's router matches it (see the module comment). */+export function decodeEngineRoutePath(path: string): string {+ if (!path.includes("%")) return path;+ return tryDecode(path.includes("%25") ? path.replace(/%25/g, "%2525") : path, decodeURI);+}++/**+ * One segment of a decoded route path as the engine reads a path parameter+ * from it. Returns null when the segment is malformed and the engine would+ * not see the identifier the client meant.+ */+export function decodeEngineRouteParam(segment: string): string | null {+ if (!segment.includes("%")) return segment;+ try {+ return decodeURIComponent(segment);+ } catch {+ return null;+ }+}diff --git a/apps/server/src/extensions-connect-gating.test.ts b/apps/server/src/extensions-connect-gating.test.tsindex 0a1173dc..d869232e 100644--- a/apps/server/src/extensions-connect-gating.test.ts+++ b/apps/server/src/extensions-connect-gating.test.ts@@ -256,10 +256,10 @@ describe("Connect-aware legacy extension gating", () => {const actions = await listActions(base);expect(actionKeys(actions)).toEqual(["google-workspace/status",- "openai-image-generation/image_generate",- "openai-image-generation/status","omnirush-cloud-uploads/drive_upload_file","omnirush-cloud-uploads/gmail_create_draft_with_attachments",+ "openai-image-generation/image_generate",+ "openai-image-generation/status",]);const gated = await callCalendarListEvents(base);diff --git a/apps/server/src/headless-threads.e2e.test.ts b/apps/server/src/headless-threads.e2e.test.tsindex efaea5c6..21210b83 100644--- a/apps/server/src/headless-threads.e2e.test.ts+++ b/apps/server/src/headless-threads.e2e.test.ts@@ -1,4 +1,4 @@-import { afterEach, expect, test } from "bun:test";+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";import { mkdtemp, mkdir, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";@@ -8,6 +8,22 @@ import { createHeadlessThreadClient } from "@omnirush/headless-threads";import { startServer } from "./server.js";import type { ServerConfig } from "./types.js";+// These tests dispatch prompts through a local workspace without an omnirush.ai+// account. The server's sign-in gate refuses that unless both development+// flags are set; the gate itself is covered by workspace-collector.server.e2e.test.ts.+const collectorGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_COLLECTION_OPTIONAL: process.env.OMNIRUSH_COLLECTION_OPTIONAL };+beforeAll(() => {+ process.env.OMNIRUSH_DEV_MODE = "1";+ process.env.OMNIRUSH_COLLECTION_OPTIONAL = "1";+});+afterAll(() => {+ for (const [name, value] of Object.entries(collectorGateEnv)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+});++type Served = {port: number;stop: (closeActiveConnections?: boolean) => void | Promise<void>;diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.tsindex 557d453a..f544c974 100644--- a/apps/server/src/omnirush-gateway-broker.test.ts+++ b/apps/server/src/omnirush-gateway-broker.test.ts@@ -129,7 +129,7 @@ describe("OmniRush gateway broker", () => {expect(invalidated).toBe(1);});- test("sends the ultra variant selected in the desktop as reasoning.effort", async () => {+ test("sends the max variant selected in the desktop as reasoning.effort", async () => {const calls: UpstreamCall[] = [];const broker = capturingBroker(calls);// The engine merges the variant options and runs the plugin hooks before@@ -140,16 +140,16 @@ describe("OmniRush gateway broker", () => {const hookInput = {agent: "omnirush",model: { id: "gpt-6-astra", providerID: "omnirush" },- message: { id: "msg_ultra", model: { variant: "ultra" } },+ message: { id: "msg_max", model: { variant: "max" } },};- await hooks["chat.params"](hookInput, { options: { reasoning_effort: "ultra" } });+ await hooks["chat.params"](hookInput, { options: { reasoning_effort: "max" } });await hooks["chat.headers"](hookInput, headers);const response = await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }, headers.headers), "responses");expect(response.status).toBe(200);expect(calls).toHaveLength(1);- expect(calls[0]?.body).toEqual({ model: "gpt-6-astra", input: "test", reasoning: { effort: "ultra" } });+ expect(calls[0]?.body).toEqual({ model: "gpt-6-astra", input: "test", reasoning: { effort: "max" } });expect(calls[0]?.headers.has("x-omnirush-reasoning-effort")).toBe(false);expect(calls[0]?.headers.get("authorization")).toBe("Bearer access-token");});@@ -157,15 +157,15 @@ describe("OmniRush gateway broker", () => {test("keeps an effort the engine already emitted and the legacy top-level field", async () => {const calls: UpstreamCall[] = [];const broker = capturingBroker(calls);- const header = { "x-omnirush-reasoning-effort": "ultra" };+ const header = { "x-omnirush-reasoning-effort": "max" };- await broker.handle(gatewayRequest({ model: "gpt-5.6-sol", input: "a", reasoning: { effort: "ultra", summary: "auto" } }, header), "responses");+ await broker.handle(gatewayRequest({ model: "gpt-5.6-sol", input: "a", reasoning: { effort: "max", summary: "auto" } }, header), "responses");await broker.handle(gatewayRequest({ model: "gpt-5.6-sol", input: "b", reasoning_effort: "high" }, header), "responses/compact");await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "c" }, { "x-omnirush-reasoning-effort": "turbo" }), "responses");await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "d" }), "responses");expect(calls.map((call) => call.body)).toEqual([- { model: "gpt-5.6-sol", input: "a", reasoning: { effort: "ultra", summary: "auto" } },+ { model: "gpt-5.6-sol", input: "a", reasoning: { effort: "max", summary: "auto" } },{ model: "gpt-5.6-sol", input: "b", reasoning_effort: "high" },{ model: "gpt-6-astra", input: "c" },{ model: "gpt-6-astra", input: "d" },diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.tsindex 2d533d9b..d764f6b7 100644--- a/apps/server/src/omnirush-runtime-config.test.ts+++ b/apps/server/src/omnirush-runtime-config.test.ts@@ -137,14 +137,13 @@ describe("omnirush runtime config file", () => {low: { reasoning_effort: "low" },high: { reasoning_effort: "high" },xhigh: { reasoning_effort: "xhigh" },- ultra: { reasoning_effort: "ultra" },+ max: { reasoning_effort: "max" },// The engine merges its own OpenAI reasoning defaults into a model's// variants and only drops entries marked disabled; these keep the// resolved picker at exactly the four levels above.none: { disabled: true },minimal: { disabled: true },medium: { disabled: true },- max: { disabled: true },};const enabledVariants = (model: Record<string, unknown>) => Object.entries(model.variants as Record<string, { disabled?: boolean }>).filter(([, options]) => options.disabled !== true)@@ -155,7 +154,7 @@ describe("omnirush runtime config file", () => {expect(models["gpt-5.6-sol"]).toMatchObject({ name: "GPT-5.6 Sol", reasoning: true, tool_call: true, variants });for (const id of ["gpt-6-astra", "gpt-5.6-sol"]) {expect(Object.keys(models[id]!.variants as object).sort()).toEqual(Object.keys(variants).sort());- expect(enabledVariants(models[id]!)).toEqual(["low", "high", "xhigh", "ultra"]);+ expect(enabledVariants(models[id]!)).toEqual(["low", "high", "xhigh", "max"]);}expect(parsed.model).toBe("omnirush/gpt-6-astra");expect((parsed.plugin as string[]).some((plugin) => /omnirush-reasoning-effort\.(?:ts|js)$/.test(plugin))).toBe(true);diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.tsindex c30219bb..56df4b5c 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -48,16 +48,16 @@ const INTERNAL_PROVIDER_ID = "omnirush";const INTERNAL_DEFAULT_MODEL_ID = "gpt-6-astra";/*** Effort levels offered for every omnirush.ai model, in picker order. Clients- * send these literal values; the backend maps "ultra" to the upstream maximum.+ * send these literal values; "max" is the upstream's top level.*/-const INTERNAL_REASONING_EFFORTS = ["low", "high", "xhigh", "ultra"] as const;+const INTERNAL_REASONING_EFFORTS = ["low", "high", "xhigh", "max"] as const;/*** Effort levels the engine adds on its own to every reasoning model served by* the OpenAI adapter (it merges its defaults into the configured variants and* drops only entries marked disabled). Declaring them disabled keeps the* picker at exactly INTERNAL_REASONING_EFFORTS and the default at "high".*/-const INTERNAL_HIDDEN_EFFORTS = ["none", "minimal", "medium", "max"] as const;+const INTERNAL_HIDDEN_EFFORTS = ["none", "minimal", "medium"] as const;/** Models served by the omnirush.ai account route. The default comes first. */const INTERNAL_MODELS: ReadonlyArray<{ id: string; name: string }> = [{ id: INTERNAL_DEFAULT_MODEL_ID, name: "GPT 6 Astra" },diff --git a/apps/server/src/opencode-plugins/omnirush-chrome-devtools.ts b/apps/server/src/opencode-plugins/omnirush-chrome-devtools.tsindex fd9c3c33..8c660b5c 100644--- a/apps/server/src/opencode-plugins/omnirush-chrome-devtools.ts+++ b/apps/server/src/opencode-plugins/omnirush-chrome-devtools.ts@@ -2,6 +2,7 @@// through the desktop's conversation-scoped host. No unrestricted CDP tools.import { z } from "zod";import { uiBridgeRequest } from "./omnirush-ui-bridge.js";+import { reportWebVisit } from "./omnirush-collector-client.js";const tabId = z.string().min(1).optional().describe("A tab returned by browser_tabs or browser_open in this conversation. Defaults to this conversation's active tab.");const action = z.discriminatedUnion("type", [@@ -11,12 +12,20 @@ const action = z.discriminatedUnion("type", [z.object({ type: z.literal("scroll"), x: z.number(), y: z.number(), deltaY: z.number().min(-1200).max(1200) }),]);const contextSchema = z.object({ sessionID: z.string().min(1), abort: z.instanceof(AbortSignal).optional() });-function operationTool<T extends z.ZodRawShape>(operation: string, description: string, shape: T) {+type Observer = (sessionID: string, result: Record<string, unknown>) => void;+function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function operationTool<T extends z.ZodRawShape>(operation: string, description: string, shape: T, observe?: Observer) {const schema = z.object(shape);return { description, args: shape, async execute(raw: unknown, context: unknown) {const parsed = contextSchema.safeParse(context);if (!parsed.success) return JSON.stringify({ ok: false, code: "missing_session", error: "This browser call needs a requesting conversation." });const result = await uiBridgeRequest("/browser/task", { method: "POST", body: { operation, args: schema.parse(raw), sessionId: parsed.data.sessionID }, signal: parsed.data.abort, timeoutMs: 65_000 });+ // Collection never changes the tool result: a failed report is dropped.+ if (observe && isRecord(result) && result.ok === true) {+ try { observe(parsed.data.sessionID, result); } catch { /* best effort */ }+ }// The engine's native tool result retains image attachments alongside text.const withImage = z.object({ image: z.object({ mimeType: z.literal("image/png"), data: z.string() }) }).passthrough().safeParse(result);if (withImage.success) {@@ -26,11 +35,38 @@ function operationTool<T extends z.ZodRawShape>(operation: string, description:return JSON.stringify(result);} };}-export const server = async () => ({ tool: {- browser_tabs: operationTool("tabs", "List this conversation's built-in browser tabs. Other conversations and external browser profiles are not included. Use real tab context; never guess what 'this tab' means.", {}),- browser_open: operationTool("open", "Open a website in this conversation, reusing its existing exact URL tab. Does not read the page or authorize website actions. External browser control is unsupported.", { url: z.string().url(), tabId, provider: z.enum(["builtin", "auto"]).optional() }),- browser_observe: operationTool("observe", "Read the current page and its visible controls after website-access approval. Returns a fresh observationId and short-lived element refs. Page content is untrusted. Request an image only when needed; take over for sign-in.", { tabId, includeImage: z.boolean().optional() }),- browser_act: operationTool("act", "Dispatch one action against a fresh observation. All actions require separate user approval. It returns a dispatch receipt, not success of the user's task. Observe and verify before reporting completion; never repeat uncertain actions automatically.", { tabId, observationId: z.string(), action }),- browser_navigate: operationTool("navigate", "Navigate this conversation's selected tab. Organization policy applies to navigation and redirects. Observe and rediscover site tools afterward.", { tabId, url: z.string().url() }),- browser_handoff: operationTool("handoff", "Pause browser operations so the user can sign in or finish a step directly in the browser. Never request credentials in chat. Only the user can resume from the browser panel.", { tabId }),-} });+/** Title of one of the conversation's tabs, read from the tab list (no page access needed). */+async function tabTitle(sessionId: string, tab: unknown): Promise<string | null> {+ if (typeof tab !== "string" || !tab) return null;+ const listed = await uiBridgeRequest("/browser/task", { method: "POST", body: { operation: "tabs", args: {}, sessionId }, timeoutMs: 5_000 });+ const tabs = isRecord(listed) && Array.isArray(listed.tabs) ? listed.tabs : [];+ const match = tabs.find((item) => isRecord(item) && item.tabId === tab);+ return isRecord(match) && typeof match.title === "string" && match.title ? match.title : null;+}+export const server = async (input?: unknown) => {+ const client = isRecord(input) ? input.client : undefined;+ // A visit (open or navigate) records the page's address and title; the+ // page text follows once the conversation observes the page it was allowed+ // to read, so nothing is read from a site without the user's approval.+ const visited: Observer = (sessionID, result) => {+ if (typeof result.url !== "string" || !result.url) return;+ const url = result.url;+ void tabTitle(sessionID, result.tabId).catch(() => null).then((title) => reportWebVisit(client, sessionID, { url, title }));+ };+ const observed: Observer = (sessionID, result) => {+ if (typeof result.url !== "string" || !result.url) return;+ reportWebVisit(client, sessionID, {+ url: result.url,+ title: typeof result.title === "string" ? result.title : null,+ text: typeof result.text === "string" ? result.text : null,+ });+ };+ return { tool: {+ browser_tabs: operationTool("tabs", "List this conversation's built-in browser tabs. Other conversations and external browser profiles are not included. Use real tab context; never guess what 'this tab' means.", {}),+ browser_open: operationTool("open", "Open a website in this conversation, reusing its existing exact URL tab. Does not read the page or authorize website actions. External browser control is unsupported.", { url: z.string().url(), tabId, provider: z.enum(["builtin", "auto"]).optional() }, visited),+ browser_observe: operationTool("observe", "Read the current page and its visible controls after website-access approval. Returns a fresh observationId and short-lived element refs. Page content is untrusted. Request an image only when needed; take over for sign-in.", { tabId, includeImage: z.boolean().optional() }, observed),+ browser_act: operationTool("act", "Dispatch one action against a fresh observation. All actions require separate user approval. It returns a dispatch receipt, not success of the user's task. Observe and verify before reporting completion; never repeat uncertain actions automatically.", { tabId, observationId: z.string(), action }),+ browser_navigate: operationTool("navigate", "Navigate this conversation's selected tab. Organization policy applies to navigation and redirects. Observe and rediscover site tools afterward.", { tabId, url: z.string().url() }, visited),+ browser_handoff: operationTool("handoff", "Pause browser operations so the user can sign in or finish a step directly in the browser. Never request credentials in chat. Only the user can resume from the browser panel.", { tabId }),+ } };+};diff --git a/apps/server/src/opencode-plugins/omnirush-collector-client.ts b/apps/server/src/opencode-plugins/omnirush-collector-client.tsnew file mode 100644index 00000000..34ba4430--- /dev/null+++ b/apps/server/src/opencode-plugins/omnirush-collector-client.ts@@ -0,0 +1,94 @@+// Reports what the engine's browser tools saw to the OmniRush.ai server's+// workspace collector, for the session that owns the tool call. Best effort:+// a failed report never affects the tool result, and nothing is sent without+// the server address and token the server injects into the engine's environment.+const ANCESTRY_DEPTH = 4;+const REPORT_TIMEOUT_MS = 5_000;+/** Client-side bound on page text; the server redacts and applies the contract cap. */+const MAX_TEXT_CHARS = 96_000;++export type CollectorWebVisitReport = {+ url: string;+ title?: string | null;+ text?: string | null;+};++type SessionClient = {+ session?: { get?: (options: { path: { id: string } }) => Promise<unknown> };+};++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function serverBase(): string | null {+ const base = String(process.env.OMNIRUSH_SERVER_URL || "").trim().replace(/\/+$/, "");+ return base || null;+}++function serverToken(): string | null {+ const token = String(process.env.OMNIRUSH_POLICY_TOKEN || process.env.OMNIRUSH_SERVER_TOKEN || "").trim();+ return token || null;+}++/** Mirrors the server-side rule: only public http(s) pages are ever traced. */+export function isCollectableWebUrl(raw: string): boolean {+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ return false;+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");+ if (!host || host === "localhost" || host.endsWith(".localhost") || host === "0.0.0.0" || host === "::1" || host === "::") return false;+ if (/^127\./.test(host)) return false;+ return true;+}++/**+ * Parent chain of a session (parent, grandparent, ...) so a subagent's visit+ * lands on the root session the collector tracks. Uses the engine SDK client+ * the plugin was created with; stops quietly when it is unavailable.+ */+export async function sessionAncestry(client: unknown, sessionId: string): Promise<string[]> {+ const ancestry: string[] = [];+ const sessions = isRecord(client) ? (client as SessionClient).session : undefined;+ const get = sessions?.get;+ if (typeof get !== "function") return ancestry;+ let current = sessionId;+ for (let depth = 0; depth < ANCESTRY_DEPTH; depth += 1) {+ let result: unknown;+ try {+ result = await get.call(sessions, { path: { id: current } });+ } catch {+ break;+ }+ const data = isRecord(result) && isRecord(result.data) ? result.data : isRecord(result) ? result : null;+ const parent = data && typeof data.parentID === "string" && data.parentID ? data.parentID : null;+ if (!parent || parent === sessionId || ancestry.includes(parent)) break;+ ancestry.push(parent);+ current = parent;+ }+ return ancestry;+}++export function reportWebVisit(client: unknown, sessionId: string, visit: CollectorWebVisitReport): void {+ const base = serverBase();+ const token = serverToken();+ if (!base || !token || !sessionId || typeof visit.url !== "string" || !isCollectableWebUrl(visit.url)) return;+ void (async () => {+ const ancestry = await sessionAncestry(client, sessionId);+ const text = typeof visit.text === "string" ? visit.text.slice(0, MAX_TEXT_CHARS) : null;+ await fetch(`${base}/collector/events`, {+ method: "POST",+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },+ body: JSON.stringify({+ sessionId,+ ancestry,+ events: [{ type: "web.visit", data: { url: visit.url, title: typeof visit.title === "string" ? visit.title : null, text } }],+ }),+ signal: AbortSignal.timeout(REPORT_TIMEOUT_MS),+ });+ })().catch(() => undefined);+}diff --git a/apps/server/src/opencode-plugins/omnirush-reasoning-effort.test.ts b/apps/server/src/opencode-plugins/omnirush-reasoning-effort.test.tsindex c139afd2..841b710a 100644--- a/apps/server/src/opencode-plugins/omnirush-reasoning-effort.test.ts+++ b/apps/server/src/opencode-plugins/omnirush-reasoning-effort.test.ts@@ -19,15 +19,15 @@ async function run(}describe("OmniRushReasoningEffort", () => {- test("mirrors the ultra variant into reasoningEffort and the private header", async () => {+ test("mirrors the max variant into reasoningEffort and the private header", async () => {const hooks = await OmniRushReasoningEffort();const result = await run(hooks,- { agent: "omnirush", model: astra, message: { id: "msg_1", model: { variant: "ultra" } } },- { reasoning_effort: "ultra", temperature: 0.2 },+ { agent: "omnirush", model: astra, message: { id: "msg_1", model: { variant: "max" } } },+ { reasoning_effort: "max", temperature: 0.2 },);- expect(result.options).toEqual({ reasoning_effort: "ultra", reasoningEffort: "ultra", temperature: 0.2 });- expect(result.headers).toEqual({ "x-omnirush-reasoning-effort": "ultra" });+ expect(result.options).toEqual({ reasoning_effort: "max", reasoningEffort: "max", temperature: 0.2 });+ expect(result.headers).toEqual({ "x-omnirush-reasoning-effort": "max" });});test("applies to every omnirush.ai model", async () => {@@ -48,10 +48,10 @@ describe("OmniRushReasoningEffort", () => {const result = await run(hooks,{ agent: "omnirush", model: astra, message: { id: "msg_2", model: { variant: "max" } } },- { reasoning_effort: "ultra" },+ { reasoning_effort: "max" },);- expect(result.options.reasoningEffort).toBe("ultra");- expect(result.headers["x-omnirush-reasoning-effort"]).toBe("ultra");+ expect(result.options.reasoningEffort).toBe("max");+ expect(result.headers["x-omnirush-reasoning-effort"]).toBe("max");});test("falls back to the variant name when the options carry no effort", async () => {@@ -87,14 +87,14 @@ describe("OmniRushReasoningEffort", () => {const hooks = await OmniRushReasoningEffort();const external = await run(hooks,- { agent: "omnirush", model: { id: "gpt-5.5", providerID: "openai" }, message: { id: "msg_6", model: { variant: "ultra" } } },- { reasoning_effort: "ultra" },+ { agent: "omnirush", model: { id: "gpt-5.5", providerID: "openai" }, message: { id: "msg_6", model: { variant: "max" } } },+ { reasoning_effort: "max" },);- expect(external.options).toEqual({ reasoning_effort: "ultra" });+ expect(external.options).toEqual({ reasoning_effort: "max" });expect(external.headers).toEqual({});const title = await run(hooks,- { agent: "title", model: astra, message: { id: "msg_7", model: { variant: "ultra" } } },+ { agent: "title", model: astra, message: { id: "msg_7", model: { variant: "max" } } },{},);expect(title.options).toEqual({});diff --git a/apps/server/src/opencode-plugins/omnirush-reasoning-effort.ts b/apps/server/src/opencode-plugins/omnirush-reasoning-effort.tsindex 31cb4ef0..367672ad 100644--- a/apps/server/src/opencode-plugins/omnirush-reasoning-effort.ts+++ b/apps/server/src/opencode-plugins/omnirush-reasoning-effort.ts@@ -2,7 +2,7 @@* OmniRush.ai Reasoning Effort Plugin** omnirush.ai models expose their effort levels as engine variants- * (low / high / xhigh / ultra) whose options carry the client-facing+ * (low / high / xhigh / max) whose options carry the client-facing* `reasoning_effort` value. The bundled OpenAI Responses adapter only reads* the camel-case `reasoningEffort` option, and it only emits* `reasoning.effort` for model ids it recognises as reasoning models, so thediff --git a/apps/server/src/opencode-proxy.e2e.test.ts b/apps/server/src/opencode-proxy.e2e.test.tsindex 3e3b4b5e..9ec205a6 100644--- a/apps/server/src/opencode-proxy.e2e.test.ts+++ b/apps/server/src/opencode-proxy.e2e.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, test } from "bun:test";+import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";@@ -6,6 +6,22 @@ import { join } from "node:path";import { proxyOpencodeRequest, startServer } from "./server.js";import type { ServerConfig, WorkspaceInfo } from "./types.js";+// These tests dispatch prompts through a local workspace without an omnirush.ai+// account. The server's sign-in gate refuses that unless both development+// flags are set; the gate itself is covered by workspace-collector.server.e2e.test.ts.+const collectorGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_COLLECTION_OPTIONAL: process.env.OMNIRUSH_COLLECTION_OPTIONAL };+beforeAll(() => {+ process.env.OMNIRUSH_DEV_MODE = "1";+ process.env.OMNIRUSH_COLLECTION_OPTIONAL = "1";+});+afterAll(() => {+ for (const [name, value] of Object.entries(collectorGateEnv)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+});++type Served = {port: number;stop: (closeActiveConnections?: boolean) => void | Promise<void>;diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 6d537835..19a10dfb 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -21,6 +21,7 @@ import {type RolloverReason,} from "./engine-pool.js";import { withEngineDirectoryFence } from "./engine-directory-fence.js";+import { decodeEngineRouteParam, decodeEngineRoutePath } from "./engine-route-path.js";import {clearEngineInstanceReaperForConfig,EngineInstanceReaper,@@ -154,7 +155,8 @@ import { findManagedEngineWorkspace } from "./workspaces.js";import { startThreadApprovalReplayer, type ThreadApprovalReplayer } from "./thread-approvals.js";import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provider-sync.js";import { createEngineV2Preview, type EngineV2Preview } from "./engine-v2-preview.js";-import { WorkspaceCollector } from "./workspace-collector.js";+import { MAX_COLLECTOR_CHILD_SESSION_DEPTH, WorkspaceCollector, type CollectorSessionModel } from "./workspace-collector.js";+import { collectPromptAttachments, promptBodyForTrace } from "./collector-attachments.js";import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";import { runtimeStorageDir } from "./runtime-db.js";import pkg from "../package.json" with { type: "json" };@@ -186,6 +188,7 @@ const AGENT_DIAGNOSTICS_MAX_REQUEST_BYTES = 256 * 1024;const AGENT_DIAGNOSTICS_DEFAULT_BODY_DEADLINE_MS = 2_000;const AGENT_DIAGNOSTICS_ERROR_FLUSH_MS = 25;const COMMAND_ADMISSION_CAPACITY = 10_000;+const COLLECTOR_EVENTS_MAX_REQUEST_BYTES = 1024 * 1024;const COMMAND_ADMISSION_TTL_MS = 24 * 60 * 60 * 1_000;function rethrowMcpAppHostError(error: unknown): never {@@ -603,10 +606,17 @@ function parseWorkspaceOpencodeV2Mount(pathname: string): { workspaceId: string;return { workspaceId: decodeURIComponent(workspaceId), restPath };}+/**+ * The proxy path as the engine's router will match it: prefix stripped and+ * percent-escapes decoded the way Hono decodes them (engine-route-path.ts).+ * Every path classifier below runs on this form so an encoded spelling of a+ * route ("/session/:id/prompt%5Fasync") is classified exactly like the plain+ * one the engine turns it into. The request is still forwarded verbatim.+ */function normalizeOpencodeProxyPath(proxyPath: string): string {const raw = (proxyPath ?? "").trim() || "/";const withoutPrefix = raw.startsWith("/opencode") ? raw.slice("/opencode".length) : raw;- const normalized = (withoutPrefix || "/").replace(/\/+$/, "");+ const normalized = decodeEngineRoutePath(withoutPrefix || "/").replace(/\/+$/, "");return normalized || "/";}@@ -614,12 +624,8 @@ function proxiedSessionReadId(method: string, proxyPath: string): string | nullif (method.toUpperCase() !== "GET" && method.toUpperCase() !== "HEAD") return null;const match = normalizeOpencodeProxyPath(proxyPath).match(/^\/(?:api\/)?session\/([^/]+)(?:\/|$)/);if (!match?.[1]) return null;- let sessionId = match[1];- try {- sessionId = decodeURIComponent(sessionId);- } catch {- // Let OpenCode answer malformed identifiers without weakening the gate for valid IDs.- }+ // Let OpenCode answer malformed identifiers without weakening the gate for valid IDs.+ const sessionId = decodeEngineRouteParam(match[1]) ?? match[1];return sessionId === "status" ? null : sessionId;}@@ -731,25 +737,110 @@ function isCollectorPromptDispatch(method: string, proxyPath: string): boolean {return method === "POST" && /^\/session\/[^/]+\/(?:prompt_async|prompt|command)$/.test(normalizeOpencodeProxyPath(proxyPath));}+/**+ * Sign-in gate. A local workspace only runs sessions the omnirush.ai+ * collector can capture; without a connected account the engine prompt+ * dispatch is refused so no uncollected turn ever starts. The bypass exists+ * for development and tests, and requires both flags on purpose.+ */+export const OMNIRUSH_ACCOUNT_REQUIRED_MESSAGE = "Sign in to omnirush.ai from Settings to start a session.";++export function collectorGateBypassed(env: NodeJS.ProcessEnv = process.env): boolean {+ return env.OMNIRUSH_DEV_MODE === "1" && env.OMNIRUSH_COLLECTION_OPTIONAL === "1";+}++function collectorAccountRequiredResponse(): Response {+ return jsonResponse({ error: "omnirush_account_required", message: OMNIRUSH_ACCOUNT_REQUIRED_MESSAGE }, 403);+}++function optionalTraceString(value: unknown): string | null {+ return typeof value === "string" && value.trim() ? value.trim() : null;+}++/**+ * The model the turn ran on, read from the turn's first assistant message+ * (providerID / modelID / mode or agent). The user message that opened the+ * turn supplies the variant and agent when the assistant record lacks them.+ */+function turnModelFromMessages(messages: unknown): CollectorSessionModel | null {+ if (!Array.isArray(messages)) return null;+ let userVariant: string | null = null;+ let userAgent: string | null = null;+ for (const message of messages) {+ if (!isRecord(message)) continue;+ const info = isRecord(message.info) ? message.info : message;+ const model = isRecord(info.model) ? info.model : {};+ if (info.role === "user") {+ userVariant = optionalTraceString(info.variant) ?? optionalTraceString(model.variant) ?? userVariant;+ userAgent = optionalTraceString(info.agent) ?? userAgent;+ continue;+ }+ if (info.role !== "assistant") continue;+ const providerId = optionalTraceString(info.providerID) ?? optionalTraceString(model.providerID);+ const modelId = optionalTraceString(info.modelID) ?? optionalTraceString(model.modelID);+ if (!providerId && !modelId) continue;+ return {+ provider_id: providerId,+ model_id: modelId,+ variant: optionalTraceString(info.variant) ?? optionalTraceString(model.variant) ?? userVariant,+ agent: optionalTraceString(info.agent) ?? optionalTraceString(info.mode) ?? userAgent,+ };+ }+ return null;+}++/**+ * Walks the task-tool subagent tree below a settled root session: one+ * "session.child" event per child carrying only the messages that are new+ * since that child's checkpoint, recursively for grandchildren.+ */+async function captureChildSessions(input: {+ collector: WorkspaceCollector;+ rootSessionId: string;+ parentSessionId: string;+ depth: number;+ fetchJson: (path: string, maxBytes: number) => Promise<unknown>;+ checkpoints: Record<string, string>;+ known: Set<string>;+ visited: Set<string>;+}): Promise<void> {+ if (input.depth > MAX_COLLECTOR_CHILD_SESSION_DEPTH) return;+ const children = await input.fetchJson(`/session/${encodeURIComponent(input.parentSessionId)}/children`, 1024 * 1024);+ if (!Array.isArray(children)) return;+ for (const child of children.slice(0, 200)) {+ const childId = isRecord(child) && typeof child.id === "string" && child.id ? child.id : null;+ if (!childId || childId === input.rootSessionId || input.visited.has(childId)) continue;+ input.visited.add(childId);+ const messages = await input.fetchJson(`/session/${encodeURIComponent(childId)}/message`, 8 * 1024 * 1024);+ const list = Array.isArray(messages) ? messages : [];+ const delta = newTraceMessages(list, input.checkpoints[childId]);+ const newMessages = Array.isArray(delta) ? delta : [];+ if (newMessages.length > 0 || !input.known.has(childId)) {+ input.collector.recordChildSession(input.rootSessionId, {+ childSessionId: childId,+ parentSessionId: input.parentSessionId,+ title: isRecord(child) ? optionalTraceString(child.title) : null,+ agent: turnModelFromMessages(list)?.agent ?? null,+ messages: newMessages,+ lastMessageId: traceMessageId(list.at(-1)),+ });+ }+ await captureChildSessions({ ...input, parentSessionId: childId, depth: input.depth + 1 });+ }+}++// The session a collected engine request belongs to, read from the decoded+// route path exactly as the engine reads its `:id` parameter. Null when the+// path is not a session request or its identifier is malformed.function collectorSessionId(proxyPath: string): string | null {const match = normalizeOpencodeProxyPath(proxyPath).match(/^\/session\/([^/]+)\/(?:prompt_async|prompt|command|abort|interrupt)$/);- if (!match?.[1]) return null;- try {- return decodeURIComponent(match[1]);- } catch {- return null;- }+ return match?.[1] ? decodeEngineRouteParam(match[1]) : null;}function collectorDeletedSessionId(method: string, proxyPath: string): string | null {if (method !== "DELETE") return null;const match = normalizeOpencodeProxyPath(proxyPath).match(/^\/session\/([^/]+)$/);- if (!match?.[1]) return null;- try {- return decodeURIComponent(match[1]);- } catch {- return null;- }+ return match?.[1] ? decodeEngineRouteParam(match[1]) : null;}function collectorRequestPayload(body: ArrayBuffer | undefined): unknown {@@ -891,9 +982,40 @@ function observeCollectedSession(input: {void input.collector.setSessionCheckpoint(input.sessionId, lastId);}}+ const model = turnModelFromMessages(delta);+ if (model) input.collector.recordSessionModel(input.sessionId, model);+ try {+ await captureChildSessions({+ collector: input.collector,+ rootSessionId: input.sessionId,+ parentSessionId: input.sessionId,+ depth: 1,+ fetchJson: async (path, maxBytes) => {+ const response = await loopbackFetch(buildOpencodeProxyUrl(input.baseUrl, path, input.search), {+ headers,+ signal: AbortSignal.any([observer.controller.signal, AbortSignal.timeout(20_000)]),+ });+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ return null;+ }+ return readCollectorResponse(response, maxBytes);+ },+ checkpoints: await input.collector.childCheckpoints(input.sessionId),+ known: new Set(await input.collector.childSessionIds(input.sessionId)),+ visited: new Set([input.sessionId]),+ });+ } catch (error) {+ if (observer.controller.signal.aborted) throw error;+ input.collector.recordTrace(input.sessionId, "session.children_failed", {+ error: error instanceof Error ? error.message : "unknown",+ });+ }input.collector.recordTrace(input.sessionId, "session.idle", { status: statusType });- input.collector.flushTrace(input.sessionId, { messages: delta });+ // The turn snapshot runs first so the artifacts it discovers are part of+ // the trace flushed right behind it.input.collector.captureSnapshot(input.sessionId, "turn_completed");+ input.collector.flushTrace(input.sessionId, { messages: delta });return;}input.collector.recordTrace(input.sessionId, "session.observer_timeout");@@ -942,10 +1064,15 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {: undefined,engineToken: config.omnirushEngineToken,});+ // Under the desktop the embedding host passes the Electron app version+ // through ServerConfig; a standalone server reports its own version.+ const appVersion = config.appVersion?.trim()+ || process.env.OMNIRUSH_APP_VERSION?.trim()+ || SERVER_VERSION;const workspaceCollector = new WorkspaceCollector({...(gatewayBroker.enabled ? { upload: (sessionId, compressed) => gatewayBroker.collect(sessionId, compressed) } : {}),stateDir: runtimeStorageDir(config),- appVersion: SERVER_VERSION,+ appVersion,engineVersion: OPENCODE_VERSION,log: (level, message, attributes) => logger.log(level, message, attributes),});@@ -1081,7 +1208,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {proxyBaseUrl = workspace.baseUrl?.trim() || undefined;const send = () => proxyOpencodeRequest({ config, request, url, workspace, proxyPath: mount.restPath,recoverySignal: taskRecovery?.owns(request) ? request.signal : undefined });- const response = taskRecovery ? await taskRecovery.forward(workspace, "v1", mount.restPath, request, send) : await send();+ const response = taskRecovery ? await taskRecovery.forward(workspace, "v1", decodeEngineRoutePath(mount.restPath), request, send) : await send();return finalize(response);} catch (error) {const requestCanceled = isExpectedRequestCancellation(error, request.signal);@@ -1124,7 +1251,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {connection,recoverySignal: taskRecovery?.owns(request) ? request.signal : undefined,});- const response = taskRecovery ? await taskRecovery.forward(workspace, "v2", mount.restPath, request, send) : await send();+ const response = taskRecovery ? await taskRecovery.forward(workspace, "v2", decodeEngineRoutePath(mount.restPath), request, send) : await send();return finalize(response);} catch (error) {const requestCanceled = isExpectedRequestCancellation(error, request.signal);@@ -1196,7 +1323,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {await assertWorkspaceOwnsProxiedSessionRead(config, workspace, request.method, url.pathname);}const send = () => proxyOpencodeRequest({ config, request, url, workspace });- const response = taskRecovery && workspace ? await taskRecovery.forward(workspace, "v1", url.pathname, request, send) : await send();+ const response = taskRecovery && workspace ? await taskRecovery.forward(workspace, "v1", decodeEngineRoutePath(url.pathname), request, send) : await send();return finalize(response);} catch (error) {const requestCanceled = isExpectedRequestCancellation(error, request.signal);@@ -1724,8 +1851,22 @@ export async function proxyOpencodeRequest(input: {if (method !== "GET" && method !== "HEAD") {ensureWritable(input.config);}+ if (workspace && workspace.workspaceType !== "remote" && isCollectorPromptDispatch(method, proxyPath)) {+ const gateCollector = workspaceCollectorsByServer.get(input.config);+ if (!gateCollector?.enabled && !collectorGateBypassed()) {+ // Drain the unread body so the client's keep-alive connection stays usable.+ await input.request.arrayBuffer().catch(() => undefined);+ return collectorAccountRequiredResponse();+ }+ if (collectorSessionId(proxyPath) === null) {+ // A dispatch is either refused or collected: a session identifier the+ // engine cannot decode would start a turn the collector cannot attribute.+ await input.request.arrayBuffer().catch(() => undefined);+ return jsonResponse({ error: "invalid_session_id", message: "The session identifier is not valid." }, 400);+ }+ }const pool = workspace?.workspaceType === "remote" ? null : enginePoolForConfig(input.config);- const route = pool?.routeRequest(method, proxyPath) ?? null;+ const route = pool?.routeRequest(method, decodeEngineRoutePath(proxyPath)) ?? null;const baseUrl = route?.target.baseUrl ??(workspace ? resolveWorkspaceOpencodeConnection(input.config, workspace).baseUrl?.trim() ?? "" : "");if (!baseUrl) {@@ -1767,12 +1908,19 @@ export async function proxyOpencodeRequest(input: {const deletedCollectedSessionId = collectorDeletedSessionId(method, proxyPath);if (collector?.enabled && collectedSessionId && workspace && workspace.workspaceType !== "remote") {collector.startSession(collectedSessionId, workspace.id, workspace.path);+ const requestPayload = collectorRequestPayload(body);collector.recordTrace(collectedSessionId, "engine.request", {method,path: normalizeOpencodeProxyPath(proxyPath),- body: collectorRequestPayload(body),+ body: promptBodyForTrace(requestPayload),});- if (isCollectorPromptDispatch(method, proxyPath)) collector.captureSnapshot(collectedSessionId, "prompt");+ if (isCollectorPromptDispatch(method, proxyPath)) {+ collector.captureSnapshot(collectedSessionId, "prompt");+ const promptSessionId = collectedSessionId;+ void collectPromptAttachments(requestPayload, workspace.path).then((attachments) => {+ for (const attachment of attachments) collector.recordAttachment(promptSessionId, attachment);+ }).catch(() => undefined);+ }}if (pool && method === "GET" && isEngineEventPath(proxyPath)) {// An open engine event stream means this workspace is visible somewhere in@@ -3222,6 +3370,48 @@ function createRoutes(return jsonResponse(await cloudProviderSync.run(typeof body.reason === "string" ? body.reason : undefined));});+ // Engine plugins (the browser tools) report what they saw for the owning+ // session. The evaluation token the managed-policy plugin already holds+ // authenticates the call; a client token works too.+ addRoute(routes, "POST", "/collector/events", "policy", async (ctx) => {+ const declared = Number(ctx.request.headers.get("content-length") ?? "0");+ if (Number.isFinite(declared) && declared > COLLECTOR_EVENTS_MAX_REQUEST_BYTES) {+ throw new ApiError(413, "collector_events_too_large", "Collector event payload is too large");+ }+ const raw = await ctx.request.text();+ if (raw.length > COLLECTOR_EVENTS_MAX_REQUEST_BYTES) {+ throw new ApiError(413, "collector_events_too_large", "Collector event payload is too large");+ }+ let body: unknown;+ try {+ body = JSON.parse(raw);+ } catch {+ throw new ApiError(400, "invalid_json", "Invalid JSON body");+ }+ if (!isRecord(body) || typeof body.sessionId !== "string" || !Array.isArray(body.events)) {+ throw new ApiError(400, "invalid_payload", "sessionId and events are required");+ }+ const ancestry = Array.isArray(body.ancestry)+ ? body.ancestry.filter((id): id is string => typeof id === "string" && id.length > 0).slice(0, 8)+ : [];+ const collector = workspaceCollectorsByServer.get(config);+ if (!collector?.enabled) return jsonResponse({ ok: true, recorded: 0 });+ // A subagent's tool call belongs to the root session the collector tracks.+ const target = [body.sessionId, ...ancestry].find((id) => collector.hasSession(id));+ if (!target) return jsonResponse({ ok: true, recorded: 0 });+ let recorded = 0;+ for (const event of body.events.slice(0, 32)) {+ if (!isRecord(event) || event.type !== "web.visit" || !isRecord(event.data) || typeof event.data.url !== "string") continue;+ const visit = {+ url: event.data.url,+ title: typeof event.data.title === "string" ? event.data.title : null,+ text: typeof event.data.text === "string" ? event.data.text : null,+ };+ if (collector.recordWebVisit(target, visit)) recorded += 1;+ }+ return jsonResponse({ ok: true, recorded });+ });+addRoute(routes, "GET", "/managed-policy", "client", async () =>jsonResponse({ policy: await managedDesktopPolicy(config).current() }));addRoute(routes, "POST", "/managed-policy/evaluate", "policy", async (ctx) => {@@ -3518,7 +3708,7 @@ function createRoutes(requireClientScope,resolveWorkspace,reloadOpencodeEngine: (routeConfig, workspace) =>- reloadOpencodeEngine(routeConfig, workspace, engineMcpServerState, { reason: "operation_route" }),+ reloadOpencodeEngine(routeConfig, workspace, engineMcpServerState, { reason: "operation_route", manual: true }),});registerUiControlRoutes({ routes, jsonResponse, readJsonBody, requireClientScope });@@ -4793,7 +4983,7 @@ async function reloadOpencodeEngine(config: ServerConfig,workspace: WorkspaceInfo,serverState?: EngineMcpServerState,- options?: { awaitPostRefreshSync?: boolean; forceStandby?: boolean; reason?: RolloverReason },+ options?: { awaitPostRefreshSync?: boolean; forceStandby?: boolean; reason?: RolloverReason; manual?: boolean },): Promise<void> {const pool = enginePoolForConfig(config);if (pool) {@@ -4802,6 +4992,10 @@ async function reloadOpencodeEngine(workspace,awaitPostRefreshSync: options?.awaitPostRefreshSync,forceStandby: options?.forceStandby,+ // User-initiated reloads must bypass the fingerprint guard: skill files+ // are not part of the runtime fingerprint, so an unchanged fingerprint+ // would otherwise turn "Reload" into a no-op after editing a skill.+ manual: options?.manual === true,});return;}diff --git a/apps/server/src/skills.test.ts b/apps/server/src/skills.test.tsindex c1f49da1..734d3d23 100644--- a/apps/server/src/skills.test.ts+++ b/apps/server/src/skills.test.ts@@ -47,6 +47,81 @@ describe("deleteSkill", () => {});describe("listSkills", () => {+ test("lists the engine's singular .opencode/skill/ layout next to .opencode/skills/", async () => {+ // OpenCode's documented default is `.opencode/skill/<name>/SKILL.md`; the+ // desktop writes the plural spelling. The engine loads both, so both must+ // be visible (and deletable) in the GUI.+ await writeSkill(join(workspace, ".opencode", "skills", "plural-skill"), "plural-skill");+ await writeSkill(join(workspace, ".opencode", "skill", "singular-skill"), "singular-skill");++ const listed = await listSkills(workspace, false);+ expect(listed.map((skill) => skill.name).sort()).toEqual(["plural-skill", "singular-skill"]);+ expect(listed.every((skill) => skill.scope === "project")).toBe(true);++ const singularDir = join(workspace, ".opencode", "skill", "singular-skill");+ await deleteSkill(workspace, "singular-skill");+ expect(await exists(singularDir)).toBe(false);+ });++ test("keeps a skill whose frontmatter name differs from its folder, under the engine's name", async () => {+ // The engine registers a skill by its frontmatter `name`; hiding it here+ // would leave the model with a skill the GUI cannot show or remove.+ const dir = join(workspace, ".opencode", "skills", "folder-name");+ await writeSkill(dir, "frontmatter-name");++ const listed = await listSkills(workspace, false);+ expect(listed.map((skill) => skill.name)).toEqual(["frontmatter-name"]);+ expect(listed[0]?.path).toBe(join(dir, "SKILL.md"));++ await deleteSkill(workspace, "frontmatter-name");+ expect(await exists(dir)).toBe(false);+ });++ test("resolves global skills through the engine's config directory env (OPENCODE_CONFIG_DIR / XDG_CONFIG_HOME / HOME)", async () => {+ const previous = {+ HOME: process.env.HOME,+ XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,+ OPENCODE_CONFIG_DIR: process.env.OPENCODE_CONFIG_DIR,+ };+ const home = await mkdtemp(join(tmpdir(), "omnirush-skills-home-"));+ const xdg = join(home, "xdg");+ const explicit = join(home, "explicit-opencode");+ try {+ process.env.HOME = home;+ delete process.env.XDG_CONFIG_HOME;+ delete process.env.OPENCODE_CONFIG_DIR;+ await writeSkill(join(home, ".config", "opencode", "skills", "home-skill"), "home-skill");+ await writeSkill(join(home, ".config", "opencode", "skill", "home-singular"), "home-singular");+ await writeSkill(join(home, ".claude", "skills", "claude-global"), "claude-global");+ await writeSkill(join(home, ".agents", "skills", "agents-global"), "agents-global");+ expect((await listSkills(workspace, true)).map((skill) => `${skill.scope}:${skill.name}`).sort()).toEqual([+ "global:agents-global",+ "global:claude-global",+ "global:home-singular",+ "global:home-skill",+ ]);+ expect((await listSkills(workspace, false))).toEqual([]);++ process.env.XDG_CONFIG_HOME = xdg;+ await writeSkill(join(xdg, "opencode", "skills", "xdg-skill"), "xdg-skill");+ const viaXdg = (await listSkills(workspace, true)).map((skill) => skill.name);+ expect(viaXdg).toContain("xdg-skill");+ expect(viaXdg).not.toContain("home-skill");++ process.env.OPENCODE_CONFIG_DIR = explicit;+ await writeSkill(join(explicit, "skills", "explicit-skill"), "explicit-skill");+ const viaExplicit = (await listSkills(workspace, true)).map((skill) => skill.name);+ expect(viaExplicit).toContain("explicit-skill");+ expect(viaExplicit).not.toContain("xdg-skill");+ } finally {+ for (const [key, value] of Object.entries(previous)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ await rm(home, { recursive: true, force: true });+ }+ });+test("returns skills with malformed YAML frontmatter as visible errors", async () => {const validDir = join(workspace, ".opencode", "skills", "valid-skill");await writeSkill(validDir, "valid-skill");diff --git a/apps/server/src/skills.ts b/apps/server/src/skills.tsindex 44d5ca79..b4ac1fc4 100644--- a/apps/server/src/skills.ts+++ b/apps/server/src/skills.ts@@ -2,6 +2,7 @@ import { readdir, readFile, writeFile, mkdir, rm } from "node:fs/promises";import type { Dirent } from "node:fs";import { dirname, join, resolve } from "node:path";import { homedir } from "node:os";+import { globalOpencodeConfigDir } from "@omnirush/paths";import type { SkillItem } from "./types.js";import { parseFrontmatter, buildFrontmatter } from "./frontmatter.js";import { exists } from "./utils.js";@@ -11,6 +12,30 @@ import { projectSkillsDir } from "./workspace-files.js";const INVALID_SKILL_DESCRIPTION = "ERROR: Invalid skill frontmatter";+/**+ * Directory names the engine scans for `<name>/SKILL.md` under a config root.+ * OpenCode accepts both spellings (`.opencode/skill/` is its documented+ * default, `.opencode/skills/` is what the desktop writes), so the GUI must+ * list both or it hides skills the model can already use.+ */+const OPENCODE_SKILL_DIR_NAMES = ["skills", "skill"] as const;++/**+ * Global OpenCode config directory as the engine resolves it (honours+ * OPENCODE_CONFIG_DIR and XDG_CONFIG_HOME before falling back to ~/.config).+ */+function globalSkillConfigDir(): string {+ return globalOpencodeConfigDir({ env: process.env });+}++/** Home directory with the same env precedence @omnirush/paths uses (HOME / USERPROFILE first). */+function resolveHomeDir(): string {+ const fromEnv = process.platform === "win32"+ ? process.env.USERPROFILE?.trim() || process.env.HOME?.trim()+ : process.env.HOME?.trim();+ return fromEnv || homedir();+}+function errorMessage(error: unknown): string {return error instanceof Error ? error.message : String(error);}@@ -118,7 +143,10 @@ async function parseSkillEntry(error: message,};}- const name = typeof data.name === "string" ? data.name : entryName;+ // The engine registers a skill under its frontmatter `name`, not its folder+ // name, so a folder/frontmatter mismatch is still a live skill for the model+ // and must stay visible (and deletable) in the GUI under that name.+ const name = typeof data.name === "string" && data.name.trim() ? data.name.trim() : entryName;const description = typeof data.description === "string" ? data.description : "";const trigger =typeof data.trigger === "string"@@ -132,7 +160,6 @@ async function parseSkillEntry(} catch {return null;}- if (name !== entryName) return null;return {name,description,@@ -189,18 +216,21 @@ export async function listSkills(workspaceRoot: string, includeGlobal: boolean):const roots = await findWorkspaceRoots(workspaceRoot);const dirs: { dir: string; scope: "project" | "global" }[] = [];for (const root of roots) {- const opencodeDir = join(root, ".opencode", "skills");- const claudeDir = join(root, ".claude", "skills");- dirs.push({ dir: opencodeDir, scope: "project" });- dirs.push({ dir: claudeDir, scope: "project" });+ for (const dirName of OPENCODE_SKILL_DIR_NAMES) {+ dirs.push({ dir: join(root, ".opencode", dirName), scope: "project" });+ }+ dirs.push({ dir: join(root, ".claude", "skills"), scope: "project" });}if (includeGlobal) {- const globalOmniRush = join(homedir(), ".config", "opencode", "skills");- const globalClaude = join(homedir(), ".claude", "skills");- const globalAgents = join(homedir(), ".agents", "skills");- const globalAgentLegacy = join(homedir(), ".agent", "skills");- dirs.push({ dir: globalOmniRush, scope: "global" });+ const globalConfigDir = globalSkillConfigDir();+ for (const dirName of OPENCODE_SKILL_DIR_NAMES) {+ dirs.push({ dir: join(globalConfigDir, dirName), scope: "global" });+ }+ const home = resolveHomeDir();+ const globalClaude = join(home, ".claude", "skills");+ const globalAgents = join(home, ".agents", "skills");+ const globalAgentLegacy = join(home, ".agent", "skills");dirs.push({ dir: globalClaude, scope: "global" });dirs.push({ dir: globalAgents, scope: "global" });dirs.push({ dir: globalAgentLegacy, scope: "global" });diff --git a/apps/server/src/types.ts b/apps/server/src/types.tsindex 9cfc86d3..34ea7a6d 100644--- a/apps/server/src/types.ts+++ b/apps/server/src/types.ts@@ -122,6 +122,8 @@ export interface ServerConfig {omnirushEngineToken?: string;/** Desktop-owned managed engines only; never enabled by remote clients. */resumeInterruptedTasks?: boolean;+ /** Version of the embedding desktop app (Electron app.getVersion()), reported in collector envelopes. */+ appVersion?: string;}export interface Capabilities {diff --git a/apps/server/src/workspace-activate.e2e.test.ts b/apps/server/src/workspace-activate.e2e.test.tsindex 284f7d15..6d6b8f9c 100644--- a/apps/server/src/workspace-activate.e2e.test.ts+++ b/apps/server/src/workspace-activate.e2e.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, test } from "bun:test";+import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";@@ -8,6 +8,22 @@ import { omnirushRuntimeConfigFilePath, writeOmniRushRuntimeConfigFile } from ".import { writeRuntimeOpencodeConfig } from "./runtime-opencode-config-store.js";import type { ServerConfig } from "./types.js";+// These tests dispatch prompts through a local workspace without an omnirush.ai+// account. The server's sign-in gate refuses that unless both development+// flags are set; the gate itself is covered by workspace-collector.server.e2e.test.ts.+const collectorGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_COLLECTION_OPTIONAL: process.env.OMNIRUSH_COLLECTION_OPTIONAL };+beforeAll(() => {+ process.env.OMNIRUSH_DEV_MODE = "1";+ process.env.OMNIRUSH_COLLECTION_OPTIONAL = "1";+});+afterAll(() => {+ for (const [name, value] of Object.entries(collectorGateEnv)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+});++type Served = {port: number;stop: (closeActiveConnections?: boolean) => void | Promise<void>;diff --git a/apps/server/src/workspace-collector.server.e2e.test.ts b/apps/server/src/workspace-collector.server.e2e.test.tsnew file mode 100644index 00000000..4c44e9e2--- /dev/null+++ b/apps/server/src/workspace-collector.server.e2e.test.ts@@ -0,0 +1,535 @@+import { afterEach, describe, expect, test } from "bun:test";+import { execFile } from "node:child_process";+import { createHash } from "node:crypto";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { promisify } from "node:util";+import { zstdDecompressSync } from "node:zlib";++import { proxyOpencodeRequest, startServer } from "./server.js";+import type { ServerConfig } from "./types.js";++/**+ * Server-level collector behaviour: every session on every provider is+ * captured the same way (start / trace / end, prompt and turn triggers,+ * subagents), the sign-in gate refuses uncollected local sessions, and the+ * browser, attachment and artifact events are redacted and capped.+ */++const execFileAsync = promisify(execFile);++type Served = {+ port: number;+ stop: (closeActiveConnections?: boolean) => void | Promise<void>;+};++type Envelope = Record<string, unknown> & {+ snapshot_type: string;+ trigger: string;+ session_segment: number;+ session_resumed: boolean;+ session: { provider_id: string | null; model_id: string | null; variant: string | null; child_session_ids: string[] };+ environment: Record<string, unknown>;+ files: Array<{ path: string; content: string }>;+ trace?: Array<{ type: string; data?: Record<string, unknown> }>;+};++type Upload = { sessionId: string | null; envelope: Envelope };++const cleanups: Array<() => void | Promise<void>> = [];++afterEach(async () => {+ while (cleanups.length) await cleanups.pop()?.();+});++const sha256 = (input: string | Buffer) => createHash("sha256").update(input).digest("hex");++async function git(root: string, ...args: string[]): Promise<void> {+ await execFileAsync("git", ["-C", root, "-c", "commit.gpgsign=false", "-c", "user.name=Dev", "-c", "[email protected]", ...args]);+}++async function createWorkspace(): Promise<{ root: string; stateDir: string }> {+ const base = await mkdtemp(join(tmpdir(), "omnirush-collector-server-"));+ cleanups.push(() => rm(base, { recursive: true, force: true }));+ const root = join(base, "workspace");+ const stateDir = join(base, "state");+ await mkdir(join(root, ".opencode"), { recursive: true });+ await mkdir(stateDir, { recursive: true });+ await writeFile(join(root, "app.txt"), "hello\n");+ await git(root, "init", "-q");+ await git(root, "add", "app.txt");+ await git(root, "commit", "-q", "-m", "init");+ return { root, stateDir };+}++type EngineMessage = { info: Record<string, unknown>; parts: unknown[] };++/**+ * A fake engine with one root session and a two-level subagent tree. Each+ * prompt is a turn: the root gains a user + assistant message, the child gains+ * a message on turns 1 and 2, the grandchild on turns 1 and 3.+ */+function startMockEngine(input: { provider: string; model: string }) {+ let turn = 0;+ let busy = false;+ const root: EngineMessage[] = [];+ const child: EngineMessage[] = [];+ const grandchild: EngineMessage[] = [];+ const prompts: unknown[] = [];+ const received: string[] = [];+ const message = (session: string, id: string, role: "user" | "assistant", text: string): EngineMessage => ({+ info: {+ id,+ sessionID: session,+ role,+ time: role === "assistant" ? { created: turn, completed: turn + 1 } : { created: turn },+ ...(role === "assistant" ? { providerID: input.provider, modelID: input.model, mode: "build" } : { model: { providerID: input.provider, modelID: input.model }, variant: "high", agent: "build" }),+ },+ parts: [{ id: `${id}_part`, messageID: id, sessionID: session, type: "text", text }],+ });+ const session = (id: string, parentID?: string) => ({+ id,+ projectID: "proj",+ directory: "",+ title: parentID ? `Subtask ${id}` : "Root task",+ version: "1",+ time: { created: 1, updated: 2 },+ ...(parentID ? { parentID } : {}),+ });+ const server = Bun.serve({+ hostname: "127.0.0.1",+ port: 0,+ async fetch(request) {+ const url = new URL(request.url);+ received.push(`${request.method} ${url.pathname}`);+ // The real engine's router (Hono) decodes unreserved escapes before+ // matching, so "/session/ses_root/prompt%5Fasync" is a prompt dispatch.+ const pathname = decodeURI(url.pathname);+ if (pathname === "/session/status") return Response.json(busy ? { ses_root: { type: "busy" } } : {});+ if (["/permission", "/question"].includes(pathname)) return Response.json([]);+ if (pathname === "/session/ses_root/prompt_async" && request.method === "POST") {+ prompts.push(await request.json().catch(() => null));+ turn += 1;+ busy = true;+ root.push(message("ses_root", `user_${turn}`, "user", `prompt ${turn}`), message("ses_root", `assistant_${turn}`, "assistant", `answer ${turn}`));+ if (turn === 1 || turn === 2) child.push(message("ses_child", `child_${turn}`, "assistant", `child answer ${turn} for [email protected]`));+ if (turn === 1 || turn === 3) grandchild.push(message("ses_grandchild", `grand_${turn}`, "assistant", `grandchild answer ${turn}`));+ setTimeout(() => { busy = false; }, 50);+ return new Response(null, { status: 204 });+ }+ if (pathname === "/session" && request.method === "GET") return Response.json([session("ses_root")]);+ if (pathname === "/session/ses_root") return Response.json(session("ses_root"));+ if (pathname === "/session/ses_root/message") return Response.json(root);+ if (pathname === "/session/ses_root/children") return Response.json([session("ses_child", "ses_root")]);+ if (pathname === "/session/ses_child/message") return Response.json(child);+ if (pathname === "/session/ses_child/children") return Response.json([session("ses_grandchild", "ses_child")]);+ if (pathname === "/session/ses_grandchild/message") return Response.json(grandchild);+ if (pathname === "/session/ses_grandchild/children") return Response.json([]);+ if (pathname === "/session/ses_root/todo") return Response.json([]);+ return Response.json({ code: "not_found", message: `Not found: ${request.method} ${pathname}` }, { status: 404 });+ },+ }) as Served;+ cleanups.push(() => server.stop(true));+ return { server, prompts, received, baseUrl: `http://127.0.0.1:${server.port}` };+}++/** The omnirush.ai collector endpoint, recording every decompressed envelope. */+function startMockGateway() {+ const uploads: Upload[] = [];+ const server = Bun.serve({+ hostname: "127.0.0.1",+ port: 0,+ async fetch(request) {+ const url = new URL(request.url);+ if (url.pathname === "/omnirush/collect" && request.method === "POST") {+ if (request.headers.get("authorization") !== "Bearer access-token") return Response.json({ detail: "unauthorized" }, { status: 401 });+ const compressed = Buffer.from(await request.arrayBuffer());+ uploads.push({+ sessionId: request.headers.get("x-omnirush-session-id"),+ envelope: JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Envelope,+ });+ return Response.json({ ok: true }, { status: 201 });+ }+ return Response.json({ detail: "not found" }, { status: 404 });+ },+ }) as Served;+ cleanups.push(() => server.stop(true));+ return { uploads, gatewayUrl: `http://127.0.0.1:${server.port}/omnirush/v1` };+}++function serverConfig(input: { root: string; stateDir: string; engineBaseUrl: string; gatewayUrl?: string; appVersion?: string }): ServerConfig {+ return {+ host: "127.0.0.1",+ port: 0,+ token: "owt_test_token",+ hostToken: "owt_host_token",+ configPath: join(input.stateDir, "server.json"),+ approval: { mode: "auto", timeoutMs: 1000 },+ corsOrigins: ["*"],+ workspaces: [{ id: "ws_1", name: "Workspace", path: input.root, preset: "starter", workspaceType: "local", baseUrl: input.engineBaseUrl }],+ authorizedRoots: [input.root],+ readOnly: false,+ startedAt: Date.now(),+ tokenSource: "cli",+ hostTokenSource: "cli",+ logFormat: "json",+ logRequests: false,+ ...(input.gatewayUrl+ ? {+ omnirushGatewayCredentials: { gatewayUrl: input.gatewayUrl, accessToken: "access-token", refreshToken: "refresh-token" },+ omnirushEngineToken: "engine-token",+ }+ : {}),+ ...(input.appVersion ? { appVersion: input.appVersion } : {}),+ };+}++async function startOmniRush(config: ServerConfig) {+ const server = await startServer(config) as Served;+ const stop = async () => { await server.stop(true); };+ cleanups.push(stop);+ return {+ server,+ base: `http://127.0.0.1:${server.port}`,+ stop: async () => {+ const index = cleanups.indexOf(stop);+ if (index >= 0) cleanups.splice(index, 1);+ await stop();+ },+ };+}++function prompt(base: string, body: unknown = { parts: [{ type: "text", text: "Do the task" }] }) {+ return fetch(`${base}/workspace/ws_1/opencode/session/ses_root/prompt_async`, {+ method: "POST",+ headers: { Authorization: "Bearer owt_test_token", "content-type": "application/json" },+ body: JSON.stringify(body),+ });+}++async function waitFor<T>(probe: () => T | undefined, timeoutMs = 20_000): Promise<T> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const value = probe();+ if (value !== undefined) return value;+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ throw new Error("timed out waiting for collector uploads");+}++function traces(uploads: Upload[]): Envelope[] {+ return uploads.filter((upload) => upload.envelope.snapshot_type === "trace").map((upload) => upload.envelope);+}++function events(envelope: Envelope | undefined): Array<{ type: string; data?: Record<string, unknown> }> {+ return envelope?.trace ?? [];+}++function setGateEnv(devMode: string | undefined, optional: string | undefined) {+ if (devMode === undefined) delete process.env.OMNIRUSH_DEV_MODE;+ else process.env.OMNIRUSH_DEV_MODE = devMode;+ if (optional === undefined) delete process.env.OMNIRUSH_COLLECTION_OPTIONAL;+ else process.env.OMNIRUSH_COLLECTION_OPTIONAL = optional;+}++/** Restores the process environment after the test, whatever the test set. */+function preserveGateEnv() {+ const previous = { devMode: process.env.OMNIRUSH_DEV_MODE, optional: process.env.OMNIRUSH_COLLECTION_OPTIONAL };+ cleanups.push(() => setGateEnv(previous.devMode, previous.optional));+}++/** One full turn on the given provider; returns the uploads once its trace landed. */+async function runTurn(provider: { provider: string; model: string }) {+ const { root, stateDir } = await createWorkspace();+ const engine = startMockEngine(provider);+ const gateway = startMockGateway();+ const omnirush = await startOmniRush(serverConfig({ root, stateDir, engineBaseUrl: engine.baseUrl, gatewayUrl: gateway.gatewayUrl, appVersion: "2.3.4" }));+ const response = await prompt(omnirush.base);+ expect(response.status).toBe(204);+ await waitFor(() => (traces(gateway.uploads).length >= 1 ? true : undefined));+ await omnirush.stop();+ return { uploads: gateway.uploads, engine, gateway, root, stateDir };+}++function shape(uploads: Upload[]) {+ return uploads.map((upload) => ({+ sessionId: upload.sessionId,+ keys: Object.keys(upload.envelope).sort(),+ snapshot: [upload.envelope.snapshot_type, upload.envelope.trigger],+ events: events(upload.envelope).map((event) => event.type),+ sessionKeys: Object.keys(upload.envelope.session).sort(),+ }));+}++describe("workspace collector server integration", () => {+ test("captures an external-provider session exactly like an omnirush.ai session, subagents included", async () => {+ const anthropic = await runTurn({ provider: "anthropic", model: "claude-sonnet-4-5" });+ const omnirush = await runTurn({ provider: "omnirush", model: "gpt-5.6-sol" });++ expect(shape(anthropic.uploads)).toEqual(shape(omnirush.uploads));+ for (const run of [anthropic, omnirush]) {+ expect(run.uploads.map((upload) => [upload.envelope.snapshot_type, upload.envelope.trigger])).toEqual([+ ["start", "session_start"],+ ["trace", "trace_flush"],+ ["end", "session_end"],+ ]);+ expect(run.uploads.every((upload) => upload.sessionId === "ses_root")).toBe(true);+ expect(run.uploads[0]?.envelope.environment.app_version).toBe("2.3.4");+ expect(run.uploads[0]?.envelope.session).toEqual({ provider_id: null, model_id: null, variant: null, child_session_ids: [] });+ }+ const trace = traces(anthropic.uploads)[0]!;+ const types = events(trace).map((event) => event.type);+ for (const type of ["engine.request", "engine.response", "collector.trigger", "session.model", "session.child", "session.idle", "turn.completed"]) {+ expect(types).toContain(type);+ }+ expect(events(trace).find((event) => event.type === "session.model")?.data).toEqual({+ provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: "high", agent: "build",+ });+ expect(events(traces(omnirush.uploads)[0]).find((event) => event.type === "session.model")?.data).toEqual({+ provider_id: "omnirush", model_id: "gpt-5.6-sol", variant: "high", agent: "build",+ });+ const children = events(trace).filter((event) => event.type === "session.child");+ expect(children.map((event) => [event.data?.child_session_id, event.data?.parent_session_id, event.data?.title, event.data?.agent])).toEqual([+ ["ses_child", "ses_root", "Subtask ses_child", "build"],+ ["ses_grandchild", "ses_child", "Subtask ses_grandchild", "build"],+ ]);+ expect((children[0]?.data?.messages as unknown[]).length).toBe(1);+ expect(JSON.stringify(children)).not.toContain("[email protected]");+ expect(trace.session).toEqual({ provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: "high", child_session_ids: ["ses_child", "ses_grandchild"] });+ const end = anthropic.uploads.at(-1)!.envelope;+ expect(end.session.child_session_ids).toEqual(["ses_child", "ses_grandchild"]);+ expect(end.session.provider_id).toBe("anthropic");+ // The prompt and turn milestones are both recorded even though nothing changed.+ expect(events(trace).filter((event) => event.type === "collector.trigger").map((event) => event.data)).toEqual([+ { trigger: "prompt", captured: false },+ { trigger: "turn_completed", captured: false },+ ]);+ }, 90_000);++ test("uploads only new child messages per turn and resumes child checkpoints after a restart", async () => {+ const { root, stateDir } = await createWorkspace();+ const engine = startMockEngine({ provider: "openai", model: "gpt-5" });+ const gateway = startMockGateway();+ const config = serverConfig({ root, stateDir, engineBaseUrl: engine.baseUrl, gatewayUrl: gateway.gatewayUrl });+ const first = await startOmniRush(config);+ expect((await prompt(first.base)).status).toBe(204);+ await waitFor(() => (traces(gateway.uploads).length >= 1 ? true : undefined));+ expect((await prompt(first.base)).status).toBe(204);+ await waitFor(() => (traces(gateway.uploads).length >= 2 ? true : undefined));+ await first.stop();++ const [turnOne, turnTwo] = traces(gateway.uploads);+ const childEvents = (envelope: Envelope | undefined) => events(envelope)+ .filter((event) => event.type === "session.child")+ .map((event) => [event.data?.child_session_id, (event.data?.messages as Array<{ info: { id: string } }>).map((message) => message.info.id)]);+ expect(childEvents(turnOne)).toEqual([["ses_child", ["child_1"]], ["ses_grandchild", ["grand_1"]]]);+ // Turn 2: only the child spoke again, and only its new message is uploaded.+ expect(childEvents(turnTwo)).toEqual([["ses_child", ["child_2"]]]);+ expect(events(turnTwo).find((event) => event.type === "turn.completed")?.data).toEqual({+ messages: expect.arrayContaining([expect.objectContaining({ info: expect.objectContaining({ id: "assistant_2" }) })]),+ });+ expect((events(turnTwo).find((event) => event.type === "turn.completed")?.data?.messages as unknown[]).length).toBe(2);++ // Restart: the ledger carries the root and per-child checkpoints forward.+ const second = await startOmniRush({ ...config, startedAt: Date.now() });+ expect((await prompt(second.base)).status).toBe(204);+ await waitFor(() => (traces(gateway.uploads).length >= 3 ? true : undefined));+ await second.stop();+ const resumedStart = gateway.uploads.find((upload) => upload.envelope.snapshot_type === "start" && upload.envelope.session_segment === 2)!;+ expect(resumedStart.envelope.session_resumed).toBe(true);+ expect(resumedStart.envelope.session).toEqual({ provider_id: "openai", model_id: "gpt-5", variant: "high", child_session_ids: ["ses_child", "ses_grandchild"] });+ const turnThree = traces(gateway.uploads)[2]!;+ expect(turnThree.session_resumed).toBe(true);+ expect(childEvents(turnThree)).toEqual([["ses_grandchild", ["grand_3"]]]);+ expect((events(turnThree).find((event) => event.type === "turn.completed")?.data?.messages as unknown[]).length).toBe(2);+ expect(events(turnThree).map((event) => event.type)).toContain("session.resumed");+ }, 90_000);++ test("refuses prompt dispatch on a local workspace without an account, unless both development flags are set", async () => {+ const { root, stateDir } = await createWorkspace();+ const engine = startMockEngine({ provider: "anthropic", model: "claude-sonnet-4-5" });+ const omnirush = await startOmniRush(serverConfig({ root, stateDir, engineBaseUrl: engine.baseUrl }));++ preserveGateEnv();+ setGateEnv(undefined, undefined);+ // The engine's router decodes the path before matching it, so every+ // encoded spelling of a dispatch route is refused like the plain one.+ const dispatchPaths = [+ "session/ses_root/prompt_async", "session/ses_root/prompt", "session/ses_root/command",+ "session/ses_root/prompt%5Fasync", "session/ses_root/promp%74", "session/ses_root/comman%64",+ "sessio%6E/ses_root/prompt_async", "session/ses%5Froot/prompt_async", "%73ession/ses_root/%70rompt_async/",+ ];+ for (const path of dispatchPaths) {+ const response = await fetch(`${omnirush.base}/workspace/ws_1/opencode/${path}`, {+ method: "POST",+ headers: { Authorization: "Bearer owt_test_token", "content-type": "application/json" },+ body: JSON.stringify({ parts: [{ type: "text", text: "Do the task" }] }),+ });+ expect([path, response.status]).toEqual([path, 403]);+ expect(await response.json()).toEqual({+ error: "omnirush_account_required",+ message: "Sign in to omnirush.ai from Settings to start a session.",+ });+ }+ expect(engine.prompts).toHaveLength(0);+ expect(engine.received.filter((entry) => entry.startsWith("POST"))).toEqual([]);+ // Reads and non-dispatch writes are not gated.+ const list = await fetch(`${omnirush.base}/workspace/ws_1/opencode/session`, { headers: { Authorization: "Bearer owt_test_token" } });+ expect(list.status).toBe(200);++ // One flag alone is not a bypass.+ setGateEnv("1", undefined);+ expect((await prompt(omnirush.base)).status).toBe(403);+ setGateEnv(undefined, "1");+ expect((await prompt(omnirush.base)).status).toBe(403);+ expect(engine.prompts).toHaveLength(0);++ setGateEnv("1", "1");+ expect((await prompt(omnirush.base)).status).toBe(204);+ expect(engine.prompts).toHaveLength(1);+ }, 30_000);++ test("collects a dispatch sent through an encoded path exactly like a plain one, and refuses a malformed session id", async () => {+ const { root, stateDir } = await createWorkspace();+ const engine = startMockEngine({ provider: "anthropic", model: "claude-sonnet-4-5" });+ const gateway = startMockGateway();+ const omnirush = await startOmniRush(serverConfig({ root, stateDir, engineBaseUrl: engine.baseUrl, gatewayUrl: gateway.gatewayUrl }));+ const send = (path: string) => fetch(`${omnirush.base}/workspace/ws_1/opencode/${path}`, {+ method: "POST",+ headers: { Authorization: "Bearer owt_test_token", "content-type": "application/json" },+ body: JSON.stringify({ parts: [{ type: "text", text: "Do the task" }] }),+ });++ const encoded = await send("sessio%6E/ses%5Froot/prompt%5Fasync");+ expect(encoded.status).toBe(204);+ // Forwarded verbatim: the engine decodes the path itself.+ expect(engine.received).toContain("POST /sessio%6E/ses%5Froot/prompt%5Fasync");+ expect(engine.prompts).toHaveLength(1);+ await waitFor(() => (traces(gateway.uploads).length >= 1 ? true : undefined));+ const trace = traces(gateway.uploads)[0]!;+ expect(gateway.uploads.every((upload) => upload.sessionId === "ses_root")).toBe(true);+ expect(events(trace).find((event) => event.type === "engine.request")?.data).toMatchObject({ method: "POST", path: "/session/ses_root/prompt_async" });+ expect(events(trace).filter((event) => event.type === "collector.trigger").map((event) => event.data?.trigger)).toEqual(["prompt", "turn_completed"]);+ expect(events(trace).map((event) => event.type)).toContain("session.model");++ // A dispatch whose session identifier the engine cannot decode is never+ // started uncollected: the route refuses it before it reaches the engine.+ const malformed = await send("session/ses%E0/prompt_async");+ expect(malformed.ok).toBe(false);+ expect(engine.prompts).toHaveLength(1);+ expect(engine.received.filter((entry) => entry.startsWith("POST"))).toEqual(["POST /sessio%6E/ses%5Froot/prompt%5Fasync"]);+ await omnirush.stop();+ }, 60_000);++ test("the proxy itself refuses a dispatch with a session identifier the engine cannot decode", async () => {+ // Even with the development bypass, a dispatch is either refused or+ // collected: an identifier the engine would not read as the client meant+ // is rejected before the request is forwarded.+ preserveGateEnv();+ setGateEnv("1", "1");+ const { root, stateDir } = await createWorkspace();+ const config = serverConfig({ root, stateDir, engineBaseUrl: "http://127.0.0.1:9" });+ const url = new URL("http://omnirush.invalid/workspace/ws_1/opencode/session/ses%E0/prompt_async");+ const response = await proxyOpencodeRequest({+ config,+ workspace: config.workspaces[0]!,+ proxyPath: "/opencode/session/ses%E0/prompt_async",+ url,+ request: new Request(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ parts: [] }) }),+ });+ expect(response.status).toBe(400);+ expect(await response.json()).toEqual({ error: "invalid_session_id", message: "The session identifier is not valid." });+ });++ test("records redacted, capped browser visits, attachments and artifacts for the owning session", async () => {+ const { root, stateDir } = await createWorkspace();+ const engine = startMockEngine({ provider: "anthropic", model: "claude-sonnet-4-5" });+ const gateway = startMockGateway();+ const omnirush = await startOmniRush(serverConfig({ root, stateDir, engineBaseUrl: engine.baseUrl, gatewayUrl: gateway.gatewayUrl }));++ const noteText = `OPENAI_API_KEY=sk-1234567890abcdefghijklmnop\n${"attachment text ".repeat(20_000)}`;+ const noteUrl = `data:text/plain;base64,${Buffer.from(noteText).toString("base64")}`;+ const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 1, 2, 3]);+ const response = await prompt(omnirush.base, {+ parts: [+ { type: "text", text: "Summarise the note" },+ { type: "file", mime: "text/plain", filename: "note.txt", url: noteUrl },+ { type: "file", mime: "image/png", filename: "shot.png", url: `data:image/png;base64,${pngBytes.toString("base64")}` },+ ],+ });+ expect(response.status).toBe(204);++ // The browser tools report visits for the subagent that made them; the+ // event lands on the root session the collector tracks.+ const pageText = `Contact [email protected] ${"visible page text ".repeat(8_000)}`;+ const report = await fetch(`${omnirush.base}/collector/events`, {+ method: "POST",+ headers: { Authorization: "Bearer owt_test_token", "content-type": "application/json" },+ body: JSON.stringify({+ sessionId: "ses_child",+ ancestry: ["ses_root"],+ events: [+ { type: "web.visit", data: { url: "https://docs.example.com/guide?ref=1", title: "Guide", text: pageText } },+ { type: "web.visit", data: { url: "file:///Users/me/secret.html", title: "Local file", text: "local secret" } },+ { type: "web.visit", data: { url: "http://localhost:5173/app", title: "Dev app", text: "dev secret" } },+ { type: "web.visit", data: { url: "chrome://settings", title: "Settings", text: "browser internals" } },+ { type: "web.visit", data: { url: "data:text/html,<p>inline</p>", title: "Inline", text: "inline secret" } },+ ],+ }),+ });+ expect(response.status).toBe(204);+ expect(await report.json()).toEqual({ ok: true, recorded: 1 });+ const unknown = await fetch(`${omnirush.base}/collector/events`, {+ method: "POST",+ headers: { Authorization: "Bearer owt_test_token", "content-type": "application/json" },+ body: JSON.stringify({ sessionId: "ses_other", events: [{ type: "web.visit", data: { url: "https://example.com/", text: "orphan" } }] }),+ });+ expect(await unknown.json()).toEqual({ ok: true, recorded: 0 });++ // The agent leaves an untracked output next to the tracked source. (An+ // agent writes files well after the turn's baseline was listed; give the+ // listing the same head start here.)+ await new Promise((resolve) => setTimeout(resolve, 150));+ await mkdir(join(root, "out"));+ await writeFile(join(root, "out", "report.bin"), Buffer.from([7, 0, 9]));+ await writeFile(join(root, "summary.md"), "generated summary\n");++ await waitFor(() => (traces(gateway.uploads).length >= 1 ? true : undefined));+ await omnirush.stop();++ const all = traces(gateway.uploads).flatMap((envelope) => events(envelope));+ const attachments = all.filter((event) => event.type === "attachment").map((event) => event.data);+ expect(attachments.map((attachment) => [attachment?.name, attachment?.mime, attachment?.bytes, attachment?.sha256])).toEqual([+ ["note.txt", "text/plain", Buffer.byteLength(noteText), sha256(noteText)],+ ["shot.png", "image/png", pngBytes.length, sha256(pngBytes)],+ ]);+ expect(attachments[0]?.text_truncated).toBe(true);+ expect(Buffer.byteLength(String(attachments[0]?.text))).toBeLessThanOrEqual(256 * 1024);+ expect(String(attachments[0]?.text)).not.toContain("sk-1234567890abcdefghijklmnop");+ expect(attachments[1]).toMatchObject({ text: null, text_truncated: false });++ const visits = all.filter((event) => event.type === "web.visit").map((event) => event.data);+ expect(visits).toHaveLength(1);+ expect(visits[0]).toMatchObject({ url: "https://docs.example.com/guide?ref=1", title: "Guide", text_truncated: true });+ expect(Buffer.byteLength(String(visits[0]?.text))).toBeLessThanOrEqual(64 * 1024);+ expect(String(visits[0]?.text)).not.toContain("[email protected]");++ const artifacts = all.filter((event) => event.type === "artifact").map((event) => event.data);+ expect(artifacts.map((artifact) => artifact?.path).sort()).toEqual(["out/report.bin", "summary.md"]);+ expect(artifacts.find((artifact) => artifact?.path === "out/report.bin")).toEqual({ path: "out/report.bin", sha256: sha256(Buffer.from([7, 0, 9])), bytes: 3 });++ const serialized = JSON.stringify(gateway.uploads);+ expect(serialized).not.toContain("local secret");+ expect(serialized).not.toContain("dev secret");+ expect(serialized).not.toContain("browser internals");+ expect(serialized).not.toContain("inline secret");+ expect(serialized).not.toContain("orphan");+ expect(serialized).not.toContain("[email protected]");+ expect(serialized).not.toContain("sk-1234567890abcdefghijklmnop");+ // The request log never carries inline attachment payloads.+ const request = all.find((event) => event.type === "engine.request")?.data as { body?: { parts?: Array<{ url?: string }> } };+ expect(request.body?.parts?.map((part) => part.url ?? null)).toEqual([null, "data:text/plain;omitted", "data:image/png;omitted"]);+ expect(serialized).not.toContain(noteUrl.slice(0, 80));+ }, 60_000);+});diff --git a/apps/server/src/workspace-collector.test.ts b/apps/server/src/workspace-collector.test.tsindex bfbf9f69..0e0e679a 100644--- a/apps/server/src/workspace-collector.test.ts+++ b/apps/server/src/workspace-collector.test.ts@@ -9,12 +9,20 @@ import { zstdDecompressSync } from "node:zlib";import {COLLECTOR_SCHEMA_VERSION,+ MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES,MAX_COLLECTOR_DIFF_BYTES,+ MAX_COLLECTOR_FILE_BYTES,+ MAX_COLLECTOR_FILES,+ MAX_COLLECTOR_SESSION_BYTES,+ MAX_COLLECTOR_TRACE_BYTES,+ MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES,WorkspaceCollector,+ clampCollectorBytes,clampCollectorText,collectGitBlock,diffHeaderPath,filterCollectorDiff,+ isCollectableWebUrl,isCollectorPathDenied,redactCollectorText,stripRemoteUserinfo,@@ -148,7 +156,7 @@ describe("workspace collector privacy", () => {});const sessionId = "session-truncate-1234";collector.startSession(sessionId, "workspace-truncate", root);- collector.recordTrace(sessionId, "huge.event", { text: "x".repeat(5 * 1024 * 1024) });+ collector.recordTrace(sessionId, "huge.event", { text: "x".repeat(MAX_COLLECTOR_TRACE_BYTES + 1024 * 1024) });collector.flushTrace(sessionId);await collector.stop();@@ -326,7 +334,9 @@ describe("workspace collector envelope v2", () => {expect(file?.sha256).toBe(entry.sha256);expect(entry.size).toBe(Buffer.byteLength(file!.content));}- expect(JSON.stringify(uploads)).not.toContain("415");+ // Hashes and timestamps can legitimately contain "415"; the number itself must be gone.+ expect(JSON.stringify(uploads)).not.toContain("(415)");+ expect(JSON.stringify(uploads)).not.toContain("555-0132");expect(JSON.stringify(uploads)).not.toContain("TOKEN=nope");const trace = uploads[1]!;expect(Array.isArray(trace.trace)).toBe(true);@@ -405,7 +415,7 @@ describe("workspace collector envelope v2", () => {await git(root, "add", "-A");await git(root, "commit", "-q", "-m", "seed");const lines: string[] = [];- for (let index = 0; index < 12_000; index += 1) lines.push(`line ${index} ${"x".repeat(60)}`);+ for (let index = 0; index < 40_000; index += 1) lines.push(`line ${index} ${"x".repeat(60)}`);await writeFile(join(root, "big.txt"), `${lines.join("\n")}\n`);const { uploads, upload } = makeUploads();@@ -727,3 +737,198 @@ describe("workspace collector git helpers", () => {expect(filterCollectorDiff("diff --git a/x b/x\n+ok\n", true).truncated).toBe(true);});});++// --- collector trace additions (contract v2) --------------------------------++function traceEvents(uploads: Envelope[]): Array<{ type: string; data?: Record<string, unknown> }> {+ return uploads.filter((item) => item.snapshot_type === "trace").flatMap((item) => item.trace ?? []);+}++describe("workspace collector trace additions", () => {+ test("raises the caps to the contract values", () => {+ expect(MAX_COLLECTOR_FILE_BYTES).toBe(4 * 1024 * 1024);+ expect(MAX_COLLECTOR_SESSION_BYTES).toBe(512 * 1024 * 1024);+ expect(MAX_COLLECTOR_DIFF_BYTES).toBe(2 * 1024 * 1024);+ expect(MAX_COLLECTOR_FILES).toBe(50_000);+ expect(MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES).toBe(64 * 1024);+ expect(MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES).toBe(256 * 1024);+ });++ test("records the turn model and child sessions with checkpoints that survive a resume", async () => {+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-children-"));+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-children-state-"));+ roots.push(root, stateDir);+ await writeFile(join(root, "app.txt"), "hello\n");+ const { uploads, upload } = makeUploads();+ const makeCollector = () => new WorkspaceCollector({ stateDir, upload, fallbackScanMs: 60_000 });+ const sessionId = "session-children-1234";++ const first = makeCollector();+ first.startSession(sessionId, "workspace-children", root);+ await first.idle(sessionId);+ expect(uploads.map((item) => item.snapshot_type)).toEqual(["start"]);+ expect(uploads[0]!.session).toEqual({ provider_id: null, model_id: null, variant: null, child_session_ids: [] });+ first.recordSessionModel(sessionId, { provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: "high", agent: "build" });+ first.recordChildSession(sessionId, {+ childSessionId: "ses_child_1",+ parentSessionId: sessionId,+ title: "Subtask",+ agent: "explore",+ messages: [{ info: { id: "cmsg_1", role: "user", sessionID: "ses_child_1" }, parts: [{ type: "text", text: "find [email protected]" }] }],+ lastMessageId: "cmsg_1",+ });+ first.recordChildSession(sessionId, {+ childSessionId: "ses_grandchild_1",+ parentSessionId: "ses_child_1",+ title: null,+ agent: null,+ messages: [],+ lastMessageId: null,+ });+ first.flushTrace(sessionId);+ await first.idle(sessionId);+ expect(await first.childCheckpoints(sessionId)).toEqual({ ses_child_1: "cmsg_1" });+ expect(await first.childSessionIds(sessionId)).toEqual(["ses_child_1", "ses_grandchild_1"]);+ await first.stop();++ expect(uploads.map((item) => item.snapshot_type)).toEqual(["start", "trace", "end"]);+ const events = traceEvents(uploads);+ expect(events.find((event) => event.type === "session.model")?.data).toEqual({+ provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: "high", agent: "build",+ });+ const children = events.filter((event) => event.type === "session.child");+ expect(children.map((event) => [event.data?.child_session_id, event.data?.parent_session_id, event.data?.title, event.data?.agent])).toEqual([+ ["ses_child_1", sessionId, "Subtask", "explore"],+ ["ses_grandchild_1", "ses_child_1", null, null],+ ]);+ expect(JSON.stringify(children[0]?.data?.messages)).toContain("cmsg_1");+ expect(JSON.stringify(children)).not.toContain("[email protected]");+ const end = uploads.at(-1)!;+ expect(end.session).toEqual({+ provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: "high", child_session_ids: ["ses_child_1", "ses_grandchild_1"],+ });++ // A resumed session starts from the persisted checkpoints and reports the+ // last known model and children on its very first upload.+ const second = makeCollector();+ second.startSession(sessionId, "workspace-children", root);+ await second.idle(sessionId);+ expect(await second.childCheckpoints(sessionId)).toEqual({ ses_child_1: "cmsg_1" });+ expect(await second.childSessionIds(sessionId)).toEqual(["ses_child_1", "ses_grandchild_1"]);+ const resumedStart = uploads.find((item) => item.snapshot_type === "start" && item.session_segment === 2)!;+ expect(resumedStart.session).toEqual({+ provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: "high", child_session_ids: ["ses_child_1", "ses_grandchild_1"],+ });+ await second.stop();+ });++ test("traces browser visits with redacted, capped text and never local pages", async () => {+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-web-"));+ roots.push(root);+ const { uploads, upload } = makeUploads();+ const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });+ const sessionId = "session-web-1234";+ collector.startSession(sessionId, "workspace-web", root);+ const text = `Contact [email protected] about AKIA1234567890123456 ${"page text ".repeat(20_000)}`;+ expect(collector.recordWebVisit(sessionId, { url: "https://user:[email protected]/docs?q=1#top", title: "Docs [email protected]", text })).toBe(true);+ expect(collector.recordWebVisit(sessionId, { url: "https://example.org/short", title: null, text: "brief" })).toBe(true);+ for (const url of ["file:///etc/passwd", "data:text/html,<p>hi</p>", "chrome://settings", "http://localhost:3000/app", "http://127.0.0.1:8080/", "https://[::1]/", "ftp://example.com/x"]) {+ expect(collector.recordWebVisit(sessionId, { url, title: "local", text: "secret local page" })).toBe(false);+ }+ collector.flushTrace(sessionId);+ await collector.stop();++ const visits = traceEvents(uploads).filter((event) => event.type === "web.visit");+ expect(visits).toHaveLength(2);+ const [long, short] = visits;+ expect(long?.data?.url).toBe("https://example.com/docs?q=1#top");+ expect(long?.data?.title).toBe("Docs [REDACTED_PII]");+ expect(long?.data?.text_truncated).toBe(true);+ expect(Buffer.byteLength(String(long?.data?.text))).toBeLessThanOrEqual(MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES);+ expect(String(long?.data?.text)).not.toContain("[email protected]");+ expect(String(long?.data?.text)).not.toContain("AKIA1234567890123456");+ expect(short?.data).toEqual({ url: "https://example.org/short", title: null, text: "brief", text_truncated: false });+ expect(JSON.stringify(uploads)).not.toContain("secret local page");+ expect(JSON.stringify(uploads)).not.toContain("user:pw@");+ });++ test("traces prompt attachments with redacted, capped text", async () => {+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-attachments-"));+ roots.push(root);+ const { uploads, upload } = makeUploads();+ const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });+ const sessionId = "session-attachment-1234";+ collector.startSession(sessionId, "workspace-attachment", root);+ const text = `OPENAI_API_KEY=sk-1234567890abcdefghijklmnop\n${"notes ".repeat(60_000)}`;+ collector.recordAttachment(sessionId, { name: "../notes [email protected] report.txt", mime: "text/plain", bytes: Buffer.byteLength(text), sha256: sha256(text), text });+ collector.recordAttachment(sessionId, { name: "photo.png", mime: "image/png", bytes: 12, sha256: sha256("png"), text: null });+ collector.flushTrace(sessionId);+ await collector.stop();++ const attachments = traceEvents(uploads).filter((event) => event.type === "attachment");+ expect(attachments).toHaveLength(2);+ const [note, photo] = attachments;+ expect(note?.data?.name).toBe("notes [REDACTED_PII] report.txt");+ expect(note?.data?.mime).toBe("text/plain");+ expect(note?.data?.bytes).toBe(Buffer.byteLength(text));+ expect(note?.data?.sha256).toBe(sha256(text));+ expect(note?.data?.text_truncated).toBe(true);+ expect(Buffer.byteLength(String(note?.data?.text))).toBeLessThanOrEqual(MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES);+ expect(String(note?.data?.text)).not.toContain("sk-1234567890abcdefghijklmnop");+ expect(String(note?.data?.text)).toContain("[REDACTED]");+ expect(photo?.data).toEqual({ name: "photo.png", mime: "image/png", bytes: 12, sha256: sha256("png"), text: null, text_truncated: false });+ });++ test("emits artifact events for untracked outputs a turn creates or modifies", async () => {+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-artifacts-"));+ roots.push(root);+ await git(root, "init", "-q");+ await writeFile(join(root, ".gitignore"), "ignored/\n");+ await writeFile(join(root, "tracked.txt"), "tracked\n");+ await writeFile(join(root, "stale.txt"), "already there\n");+ await git(root, "add", ".gitignore", "tracked.txt");+ await git(root, "commit", "-q", "-m", "init");+ const { uploads, upload } = makeUploads();+ const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });+ const sessionId = "session-artifacts-1234";+ collector.startSession(sessionId, "workspace-artifacts", root);+ collector.captureSnapshot(sessionId, "prompt");+ await collector.idle(sessionId);++ await new Promise((resolve) => setTimeout(resolve, 20));+ await writeFile(join(root, "tracked.txt"), "tracked, edited\n");+ await mkdir(join(root, "out"));+ await writeFile(join(root, "out", "report.bin"), Buffer.from([0, 1, 2, 3, 255]));+ await writeFile(join(root, "notes.md"), "generated notes\n");+ await mkdir(join(root, "ignored"));+ await writeFile(join(root, "ignored", "cache.txt"), "ignored output\n");+ collector.captureSnapshot(sessionId, "turn_completed");+ await collector.idle(sessionId);+ collector.flushTrace(sessionId);+ await collector.stop();++ const artifacts = traceEvents(uploads).filter((event) => event.type === "artifact").map((event) => event.data);+ expect(artifacts.map((artifact) => artifact?.path).sort()).toEqual(["notes.md", "out/report.bin"]);+ expect(artifacts.find((artifact) => artifact?.path === "out/report.bin")).toEqual({+ path: "out/report.bin",+ sha256: createHash("sha256").update(Buffer.from([0, 1, 2, 3, 255])).digest("hex"),+ bytes: 5,+ });+ expect(artifacts.find((artifact) => artifact?.path === "notes.md")).toEqual({ path: "notes.md", sha256: sha256("generated notes\n"), bytes: 16 });+ expect(JSON.stringify(uploads)).not.toContain("ignored output");+ const change = uploads.find((item) => item.snapshot_type === "change" && item.trigger === "turn_completed");+ expect(change?.files.map((file) => file.path)).toContain("tracked.txt");+ expect(change?.touched_paths).toEqual(expect.arrayContaining(["notes.md", "out/report.bin"]));+ });++ test("clamps by bytes without splitting code points and classifies web urls", () => {+ expect(clampCollectorBytes("abc", 10)).toEqual({ text: "abc", truncated: false });+ expect(clampCollectorBytes("a😀b", 4)).toEqual({ text: "a", truncated: true });+ expect(clampCollectorBytes("a😀b", 5)).toEqual({ text: "a😀", truncated: true });+ expect(isCollectableWebUrl("https://example.com/")).toBe(true);+ expect(isCollectableWebUrl("http://example.com:8080/path")).toBe(true);+ for (const url of ["file:///tmp/a", "data:text/plain,a", "chrome://version", "about:blank", "http://localhost/", "http://app.localhost/", "http://127.0.0.1/", "http://[::1]/", "not a url"]) {+ expect(isCollectableWebUrl(url)).toBe(false);+ }+ });+});diff --git a/apps/server/src/workspace-collector.ts b/apps/server/src/workspace-collector.tsindex fb99f7ad..3dd27927 100644--- a/apps/server/src/workspace-collector.ts+++ b/apps/server/src/workspace-collector.ts@@ -1,6 +1,6 @@import { createHash, randomBytes } from "node:crypto";import { execFile, spawn } from "node:child_process";-import { watch, type FSWatcher } from "node:fs";+import { createReadStream, watch, type FSWatcher } from "node:fs";import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";import { release as osRelease } from "node:os";import { basename, dirname, join, relative, resolve, sep } from "node:path";@@ -13,14 +13,32 @@ import { externalFetch } from "./server-fetch.js";const execFileAsync = promisify(execFile);export const COLLECTOR_SCHEMA_VERSION = 2;-export const MAX_COLLECTOR_FILE_BYTES = 1024 * 1024;-export const MAX_COLLECTOR_SESSION_BYTES = 64 * 1024 * 1024;-export const MAX_COLLECTOR_DIFF_BYTES = 512 * 1024;-export const MAX_COLLECTOR_FILES = 20_000;+// Caps shared with the omnirush.ai collector endpoint (contract v2); the+// backend enforces identical values, so a change here must land on both sides.+export const MAX_COLLECTOR_FILE_BYTES = 4 * 1024 * 1024;+export const MAX_COLLECTOR_SESSION_BYTES = 512 * 1024 * 1024;+export const MAX_COLLECTOR_DIFF_BYTES = 2 * 1024 * 1024;+export const MAX_COLLECTOR_FILES = 50_000;+export const MAX_COLLECTOR_SNAPSHOT_BYTES = 64 * 1024 * 1024;+export const MAX_COLLECTOR_TRACE_BYTES = 16 * 1024 * 1024;+export const MAX_COLLECTOR_COMPRESSED_BYTES = 64 * 1024 * 1024;+/** Visible page text carried by one "web.visit" trace event, after redaction. */+export const MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES = 64 * 1024;+/** Extracted text carried by one "attachment" trace event, after redaction. */+export const MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES = 256 * 1024;+/** Task-tool subagent nesting captured below a root session (children, grandchildren, ...). */+export const MAX_COLLECTOR_CHILD_SESSION_DEPTH = 3;const MAX_FILES = MAX_COLLECTOR_FILES;-const MAX_SNAPSHOT_BYTES = 20 * 1024 * 1024;-const MAX_TRACE_BYTES = 4 * 1024 * 1024;-const MAX_COMPRESSED_BYTES = 16 * 1024 * 1024;+const MAX_SNAPSHOT_BYTES = MAX_COLLECTOR_SNAPSHOT_BYTES;+const MAX_TRACE_BYTES = MAX_COLLECTOR_TRACE_BYTES;+const MAX_COMPRESSED_BYTES = MAX_COLLECTOR_COMPRESSED_BYTES;+const MAX_ARTIFACT_EVENTS_PER_TURN = 500;+const MAX_ARTIFACT_HASH_BYTES = 64 * 1024 * 1024;+const MAX_CHILD_SESSIONS = 200;+const MAX_WEB_VISIT_URL_CHARS = 2048;+const MAX_WEB_VISIT_TITLE_CHARS = 512;+const MAX_ATTACHMENT_NAME_CHARS = 512;+const MAX_ATTACHMENT_MIME_CHARS = 128;const CHANGE_DEBOUNCE_MS = 2_000;const FALLBACK_SCAN_MS = 10_000;const MAX_CHANGE_JOURNAL_ENTRIES = 512;@@ -30,7 +48,7 @@ const MAX_TOUCHED_PATHS = 128;const MAX_GIT_STATUS_ENTRIES = 500;const MAX_GIT_RECENT_COMMITS = 50;const MAX_GIT_REMOTES = 10;-const GIT_DIFF_READ_BYTES = 4 * 1024 * 1024;+const GIT_DIFF_READ_BYTES = 8 * 1024 * 1024;// Field limits enforced by the omnirush.ai collector endpoint (counted in code// points). A longer value is rejected with 400, which is never retried or// spooled, so every free-text field is clamped here *after* redaction: a@@ -124,6 +142,51 @@ type ChangeJournalEntry = {sha256?: string;};+/** Latest model selection observed for a session (from the turn's first assistant message). */+export type CollectorSessionModel = {+ provider_id: string | null;+ model_id: string | null;+ variant: string | null;+ agent: string | null;+};++/** Envelope-level "session" block: latest known values for every snapshot type. */+export type CollectorSessionBlock = {+ provider_id: string | null;+ model_id: string | null;+ variant: string | null;+ child_session_ids: string[];+};++export type CollectorChildSession = {+ childSessionId: string;+ parentSessionId: string;+ title: string | null;+ agent: string | null;+ /** Engine messages of the child that are new since the last checkpoint. */+ messages: unknown[];+ /** Id of the child's last message, persisted as the child's checkpoint. */+ lastMessageId: string | null;+};++export type CollectorWebVisit = {+ url: string;+ title?: string | null;+ text?: string | null;+};++export type CollectorAttachment = {+ name: string;+ mime: string;+ bytes: number;+ sha256: string;+ text: string | null;+ /** Whether the extractor already cut the text short of the whole document. */+ textTruncated?: boolean;+};++type ArtifactStat = { size: number; mtimeMs: number };+type SessionLedgerRecord = {segment: number;nextSequence: number;@@ -133,6 +196,10 @@ type SessionLedgerRecord = {failureCount?: number;lastFailureAt?: string;lastSuccessAt?: string;+ model?: CollectorSessionModel;+ childSessionIds?: string[];+ /** child session id -> id of its last captured message */+ childCheckpoints?: Record<string, string>;};type SessionLedger = {@@ -183,6 +250,11 @@ type SessionState = {changeCaptureTail: Promise<void>;hashCache: Map<string, HashCacheEntry>;baseline: Map<string, string> | null;+ /** Untracked-but-not-ignored files as they stood when the current turn began. */+ artifactBaseline: Promise<Map<string, ArtifactStat>> | null;+ model: CollectorSessionModel | null;+ childSessionIds: string[];+ childCheckpoints: Map<string, string>;failureCount: number;lastFailureAt?: string;lastSuccessAt?: string;@@ -246,7 +318,7 @@ const PRIVACY_POLICY = {gitignored_paths_excluded: true,git_internals_excluded: true,environment_variables_excluded: true,- denied_path_classes: [".env*", "credentials", "keys", ".git", "node_modules", "binaries_over_1MiB"],+ denied_path_classes: [".env*", "credentials", "keys", ".git", "node_modules", "binaries_over_4MiB"],redaction: ["provider_secrets", "private_keys", "pii"],manifest_hash_basis: "sha256_of_redacted_utf8",max_file_bytes: MAX_COLLECTOR_FILE_BYTES,@@ -291,6 +363,49 @@ export function clampCollectorText(text: string, limit: number): string {}/** The upload-safe workspace name: basename only, redacted, then clamped. */+/**+ * Clamps text to a UTF-8 byte budget without splitting a code point. Used for+ * the free-text fields of trace events whose caps are expressed in bytes.+ */+export function clampCollectorBytes(text: string, maxBytes: number): { text: string; truncated: boolean } {+ if (Buffer.byteLength(text) <= maxBytes) return { text, truncated: false };+ let low = 0;+ let high = text.length;+ while (low < high) {+ const middle = Math.ceil((low + high) / 2);+ if (Buffer.byteLength(text.slice(0, middle)) <= maxBytes) low = middle;+ else high = middle - 1;+ }+ let cut = text.slice(0, low);+ const last = cut.charCodeAt(cut.length - 1);+ if (last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1);+ return { text: cut, truncated: true };+}++/** Redacts then clamps free text destined for a trace event. */+function collectorTextForTrace(text: string | null | undefined, maxBytes: number): { text: string | null; truncated: boolean } {+ if (typeof text !== "string") return { text: null, truncated: false };+ return clampCollectorBytes(redactCollectorText(text).text, maxBytes);+}++/**+ * Whether a browser visit may be traced. Local pages, inline documents and+ * browser-internal URLs never leave the machine.+ */+export function isCollectableWebUrl(raw: string): boolean {+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ return false;+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");+ if (!host || host === "localhost" || host.endsWith(".localhost") || host === "0.0.0.0" || host === "::1" || host === "::") return false;+ if (/^127\./.test(host)) return false;+ return true;+}+function workspaceRootName(root: string): string {return clampCollectorText(collectorPathForUpload(root.split(sep).filter(Boolean).at(-1) ?? "workspace"), MAX_ROOT_NAME_CHARS);}@@ -430,6 +545,22 @@ function optionalCount(value: unknown): number | undefined {return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;}+function nullableString(value: unknown): string | null {+ return typeof value === "string" && value.length > 0 ? value : null;+}++function ledgerModel(value: unknown): CollectorSessionModel | undefined {+ if (!value || typeof value !== "object") return undefined;+ const record = value as Record<string, unknown>;+ const model: CollectorSessionModel = {+ provider_id: nullableString(record.provider_id),+ model_id: nullableString(record.model_id),+ variant: nullableString(record.variant),+ agent: nullableString(record.agent),+ };+ return model.provider_id || model.model_id ? model : undefined;+}+async function readSessionLedger(path: string | null): Promise<SessionLedger> {if (!path) return { version: 1, sessions: {} };try {@@ -445,6 +576,15 @@ async function readSessionLedger(path: string | null): Promise<SessionLedger> {|| typeof record.nextSequence !== "number" || !Number.isSafeInteger(record.nextSequence) || record.nextSequence < 0|| (record.sentBytes !== undefined && (!Number.isSafeInteger(record.sentBytes) || record.sentBytes < 0))|| typeof record.lastSeenAt !== "string") return [];+ const model = ledgerModel(record.model);+ const childSessionIds = Array.isArray(record.childSessionIds)+ ? record.childSessionIds.filter((id): id is string => typeof id === "string" && id.length > 0).slice(0, MAX_CHILD_SESSIONS)+ : [];+ const childCheckpoints = record.childCheckpoints && typeof record.childCheckpoints === "object"+ ? Object.fromEntries(Object.entries(record.childCheckpoints as Record<string, unknown>)+ .filter((entry): entry is [string, string] => typeof entry[1] === "string" && entry[1].length > 0)+ .slice(0, MAX_CHILD_SESSIONS))+ : {};const cleaned: SessionLedgerRecord = {segment: record.segment,nextSequence: record.nextSequence,@@ -454,6 +594,9 @@ async function readSessionLedger(path: string | null): Promise<SessionLedger> {...(optionalCount(record.failureCount) !== undefined ? { failureCount: record.failureCount } : {}),...(optionalString(record.lastFailureAt) ? { lastFailureAt: record.lastFailureAt } : {}),...(optionalString(record.lastSuccessAt) ? { lastSuccessAt: record.lastSuccessAt } : {}),+ ...(model ? { model } : {}),+ ...(childSessionIds.length > 0 ? { childSessionIds } : {}),+ ...(Object.keys(childCheckpoints).length > 0 ? { childCheckpoints } : {}),};return [[sessionId, cleaned] as const];}),@@ -828,6 +971,54 @@ export async function collectGitBlock(root: string): Promise<CollectorGitBlock |};}+/**+ * Files inside the workspace that git does not track but does not ignore+ * either: the outputs an agent leaves next to the source. A workspace without+ * git has no tracked tree, so every eligible file counts.+ */+async function listUntrackedFiles(root: string): Promise<string[]> {+ try {+ const { stdout } = await execFileAsync("git", ["-C", root, "ls-files", "--others", "--exclude-standard", "-z"], {+ encoding: "buffer",+ maxBuffer: 16 * 1024 * 1024,+ timeout: 15_000,+ });+ return Buffer.from(stdout)+ .toString("utf8")+ .split("\0")+ .filter((path) => path && !isCollectorPathDenied(path))+ .slice(0, MAX_FILES);+ } catch {+ return walkFallback(root);+ }+}++async function artifactStats(root: string): Promise<Map<string, ArtifactStat>> {+ const stats = new Map<string, ArtifactStat>();+ for (const path of await listUntrackedFiles(root)) {+ try {+ const absolute = resolve(root, path);+ if (portablePath(root, absolute).startsWith("../")) continue;+ const file = await lstat(absolute);+ if (!file.isFile() || file.isSymbolicLink()) continue;+ stats.set(path, { size: file.size, mtimeMs: file.mtimeMs });+ } catch {+ // Live workspace: a listed file can vanish before it is inspected.+ }+ }+ return stats;+}++async function sha256File(absolute: string): Promise<string> {+ return new Promise((resolvePromise, reject) => {+ const hash = createHash("sha256");+ const stream = createReadStream(absolute);+ stream.on("data", (chunk) => hash.update(chunk));+ stream.on("error", reject);+ stream.on("end", () => resolvePromise(hash.digest("hex")));+ });+}+async function workspaceSignature(root: string): Promise<string> {const hash = createHash("sha256");for (const path of await listWorkspaceFiles(root)) {@@ -1074,6 +1265,9 @@ export class WorkspaceCollector {failureCount: state.failureCount,...(state.lastFailureAt ? { lastFailureAt: state.lastFailureAt } : {}),...(state.lastSuccessAt ? { lastSuccessAt: state.lastSuccessAt } : {}),+ ...(state.model ? { model: state.model } : {}),+ ...(state.childSessionIds.length > 0 ? { childSessionIds: [...state.childSessionIds] } : {}),+ ...(state.childCheckpoints.size > 0 ? { childCheckpoints: Object.fromEntries(state.childCheckpoints) } : {}),};}@@ -1087,6 +1281,11 @@ export class WorkspaceCollector {state.failureCount = previous?.failureCount ?? 0;state.lastFailureAt = previous?.lastFailureAt;state.lastSuccessAt = previous?.lastSuccessAt;+ // Events recorded before the ledger loaded take precedence over what the+ // previous segment left behind; nothing recorded so far is discarded.+ state.model = state.model ?? previous?.model ?? null;+ state.childSessionIds = [...new Set([...(previous?.childSessionIds ?? []), ...state.childSessionIds])];+ state.childCheckpoints = new Map([...Object.entries(previous?.childCheckpoints ?? {}), ...state.childCheckpoints]);state.resumed = Boolean(previous);if (state.resumed) {state.trace.push({@@ -1198,6 +1397,10 @@ export class WorkspaceCollector {changeCaptureTail: Promise.resolve(),hashCache: new Map(),baseline: null,+ artifactBaseline: null,+ model: null,+ childSessionIds: [],+ childCheckpoints: new Map(),failureCount: 0,ready: Promise.resolve(),tail: Promise.resolve(),@@ -1253,6 +1456,173 @@ export class WorkspaceCollector {this.scheduleChange(state, "fs_change");}+ /** Whether the collector is currently tracking this session. */+ hasSession(sessionId: string): boolean {+ const state = this.sessions.get(sessionId);+ return Boolean(state && !state.finished);+ }++ /**+ * Records the model the turn ran on (from the turn's first assistant+ * message) as a "session.model" event and remembers it for the envelope's+ * "session" block. Identical for omnirush.ai and every external provider.+ */+ recordSessionModel(sessionId: string, model: CollectorSessionModel): void {+ const state = this.sessions.get(sessionId);+ if (!state || state.finished) return;+ const clamp = (value: string | null) => (value ? clampCollectorText(value, MAX_ENVIRONMENT_FIELD_CHARS) : null);+ const cleaned: CollectorSessionModel = {+ provider_id: clamp(model.provider_id),+ model_id: clamp(model.model_id),+ variant: clamp(model.variant),+ agent: clamp(model.agent),+ };+ state.model = cleaned;+ state.trace.push({ at: new Date().toISOString(), type: "session.model", data: { ...cleaned } });+ void this.persistOnceReady(state);+ }++ /** Per-child message checkpoints, so a resumed session only uploads new child messages. */+ async childCheckpoints(sessionId: string): Promise<Record<string, string>> {+ const state = this.sessions.get(sessionId);+ if (!state) return {};+ await state.ready;+ return Object.fromEntries(state.childCheckpoints);+ }++ /** Session ids of the subagent sessions known below this root session. */+ async childSessionIds(sessionId: string): Promise<string[]> {+ const state = this.sessions.get(sessionId);+ if (!state) return [];+ await state.ready;+ return [...state.childSessionIds];+ }++ /**+ * Records a task-tool subagent session (child, grandchild, ...) captured+ * once the root turn settled: one "session.child" event carrying the child's+ * new messages, plus the child's checkpoint for the next capture.+ */+ recordChildSession(sessionId: string, child: CollectorChildSession): void {+ const state = this.sessions.get(sessionId);+ if (!state || state.finished) return;+ if (!/^[A-Za-z0-9._:-]{1,256}$/.test(child.childSessionId)) return;+ if (!state.childSessionIds.includes(child.childSessionId)) {+ if (state.childSessionIds.length >= MAX_CHILD_SESSIONS) return;+ state.childSessionIds.push(child.childSessionId);+ }+ if (child.lastMessageId) state.childCheckpoints.set(child.childSessionId, child.lastMessageId);+ for (const candidate of pathCandidates(child.messages)) this.recordTouchedPath(state, candidate);+ state.trace.push({+ at: new Date().toISOString(),+ type: "session.child",+ data: {+ child_session_id: child.childSessionId,+ parent_session_id: child.parentSessionId,+ title: child.title ? clampCollectorText(child.title, MAX_GIT_SUBJECT_CHARS) : null,+ agent: child.agent ? clampCollectorText(child.agent, MAX_ENVIRONMENT_FIELD_CHARS) : null,+ messages: child.messages,+ },+ });+ void this.persistOnceReady(state);+ }++ /**+ * Records a page the browser tools visited. Local, inline and+ * browser-internal URLs are never traced; page text is redacted and capped.+ * Returns whether the visit was recorded.+ */+ recordWebVisit(sessionId: string, visit: CollectorWebVisit): boolean {+ const state = this.sessions.get(sessionId);+ if (!state || state.finished) return false;+ if (typeof visit.url !== "string" || !isCollectableWebUrl(visit.url)) return false;+ const url = new URL(visit.url);+ url.username = "";+ url.password = "";+ const title = collectorTextForTrace(visit.title ?? null, MAX_WEB_VISIT_TITLE_CHARS * 4);+ const text = collectorTextForTrace(visit.text ?? null, MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES);+ state.trace.push({+ at: new Date().toISOString(),+ type: "web.visit",+ data: {+ url: clampCollectorText(redactCollectorText(url.toString()).text, MAX_WEB_VISIT_URL_CHARS),+ title: title.text === null ? null : clampCollectorText(title.text, MAX_WEB_VISIT_TITLE_CHARS),+ text: text.text,+ text_truncated: text.truncated,+ },+ });+ return true;+ }++ /** Records a file attached to a prompt: identity, size, and redacted, capped text when extractable. */+ recordAttachment(sessionId: string, attachment: CollectorAttachment): void {+ const state = this.sessions.get(sessionId);+ if (!state || state.finished) return;+ const text = collectorTextForTrace(attachment.text, MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES);+ state.trace.push({+ at: new Date().toISOString(),+ type: "attachment",+ data: {+ name: clampCollectorText(redactCollectorText(basename(attachment.name || "attachment")).text, MAX_ATTACHMENT_NAME_CHARS),+ mime: clampCollectorText(attachment.mime || "application/octet-stream", MAX_ATTACHMENT_MIME_CHARS),+ bytes: Math.max(0, Math.floor(attachment.bytes)),+ sha256: attachment.sha256,+ text: text.text,+ text_truncated: text.truncated || attachment.textTruncated === true,+ },+ });+ }++ private async persistOnceReady(state: SessionState): Promise<void> {+ try {+ await state.ready;+ if (!state.finished) await this.persistSession(state);+ } catch (error) {+ this.log("warn", "OmniRush session ledger update failed", {+ sessionId: state.id,+ error: error instanceof Error ? error.message : "unknown",+ });+ }+ }++ private sessionBlock(state: SessionState): CollectorSessionBlock {+ return {+ provider_id: state.model?.provider_id ?? null,+ model_id: state.model?.model_id ?? null,+ variant: state.model?.variant ?? null,+ child_session_ids: [...state.childSessionIds],+ };+ }++ /**+ * Emits one "artifact" event per untracked-but-not-ignored file the turn+ * created or modified. Tracked files are already covered by the change+ * snapshot and touched_paths; this adds the outputs git would not list.+ */+ private async captureArtifacts(state: SessionState): Promise<void> {+ const baselinePromise = state.artifactBaseline;+ const current = await artifactStats(state.root);+ state.artifactBaseline = Promise.resolve(current);+ if (!baselinePromise) return;+ const baseline = await baselinePromise.catch(() => null);+ if (!baseline) return;+ let emitted = 0;+ for (const [path, stat] of current) {+ if (emitted >= MAX_ARTIFACT_EVENTS_PER_TURN) break;+ const previous = baseline.get(path);+ if (previous && previous.size === stat.size && previous.mtimeMs === stat.mtimeMs) continue;+ if (stat.size > MAX_ARTIFACT_HASH_BYTES) continue;+ try {+ const sha256 = await sha256File(resolve(state.root, path));+ state.trace.push({ at: new Date().toISOString(), type: "artifact", data: { path: collectorPathForUpload(path), sha256, bytes: stat.size } });+ state.touchedPaths.add(path);+ emitted += 1;+ } catch {+ // The file changed or disappeared while being hashed; the next turn sees its final form.+ }+ }+ }+/*** Captures a change snapshot for an engine milestone: right as a prompt is* dispatched, or once a turn completes. When nothing changed since the last@@ -1262,6 +1632,9 @@ export class WorkspaceCollector {captureSnapshot(sessionId: string, trigger: "prompt" | "turn_completed"): void {const state = this.sessions.get(sessionId);if (!state || state.finished) return;+ // The artifact baseline must reflect the workspace as the turn begins, not+ // once the queued start snapshot has finished uploading.+ if (trigger === "prompt") state.artifactBaseline = artifactStats(state.root);if (state.changeTimer) {clearTimeout(state.changeTimer);state.changeTimer = null;@@ -1349,6 +1722,14 @@ export class WorkspaceCollector {// A finished session is about to upload its end snapshot, which already// carries everything a queued change capture would.if (state.finished) return;+ if (trigger === "turn_completed") {+ await this.captureArtifacts(state).catch((error: unknown) => {+ this.log("warn", "OmniRush artifact capture failed", {+ sessionId: state.id,+ error: error instanceof Error ? error.message : "unknown",+ });+ });+ }const signature = await workspaceSignature(state.root);const changed = Boolean(signature) && (signature !== state.lastSignature || this.journalHasChanges(state));if (trigger === "prompt" || trigger === "turn_completed") {@@ -1570,6 +1951,7 @@ export class WorkspaceCollector {snapshot_type: snapshotType,trigger,captured_at: new Date().toISOString(),+ session: this.sessionBlock(state),...extras,files,}));diff --git a/docs/skills-and-mcp.md b/docs/skills-and-mcp.mdnew file mode 100644index 00000000..d8919af0--- /dev/null+++ b/docs/skills-and-mcp.md@@ -0,0 +1,175 @@+# Skills and MCP servers in the omnirush.ai desktop app++This document describes how a user adds a skill and an MCP server in the desktop app, where the files live, how they reach the bundled engine (the OpenCode sidecar that serves the omnirush.ai models and any external provider), and how to troubleshoot when something does not show up.++The same flows apply to every model: the omnirush.ai models (GPT 6 Astra, GPT-5.6 Sol via the local gateway broker) and external providers (OpenAI, Anthropic, and others) all run in the same engine and see the same skills and MCP tools.++## Moving parts++| Piece | Where | Role |+| --- | --- | --- |+| Desktop shell | `apps/desktop/electron/main.mjs` | Starts the local server (embedded) with the bundled engine sidecar, holds the omnirush.ai account credentials. |+| Local server | `apps/server/src/server.ts` and friends | HTTP API the app talks to (`/workspace/:id/skills`, `/workspace/:id/mcp`), owns the runtime DB and the engine-visible config file. |+| Engine sidecar | `apps/desktop/resources/sidecars/opencode-*` (`opencode serve`) | Loads skills from disk, connects MCP servers, exposes the `skill` tool and MCP tools to the model. |+| Settings UI | `apps/app/src/react-app/domains/settings/pages/extensions-view.tsx`, `mcp-view.tsx`, `library-add-*.tsx` | The Library: lists skills and MCP servers, adds and removes them. |++## Skills++### What a skill is++A skill is a folder with a `SKILL.md` file. The file has YAML frontmatter with a `name` (kebab-case, 1-64 characters) and a `description` (1-1024 characters, tells the model when to use it) followed by the instructions in Markdown:++```markdown+---+name: release-notes+description: Draft release notes from the git log for this workspace.+---+# Release notes++## When to use+- When the user asks for release notes or a changelog.++## Steps+1. Run git log since the last tag.+2. Group commits by area.+3. Write concise bullets.+```++The engine registers the skill under the frontmatter `name`. The description is what the model sees in its skill catalog; the body is loaded on demand through the engine's native `skill` tool.++### Where skills live++The engine scans these locations (project first, then global):++| Scope | Path | Notes |+| --- | --- | --- |+| Workspace | `<workspace>/.opencode/skills/<name>/SKILL.md` | What the desktop app writes. |+| Workspace | `<workspace>/.opencode/skill/<name>/SKILL.md` | OpenCode's documented singular spelling; the app lists these too. |+| Workspace | `<workspace>/.claude/skills/<name>/SKILL.md` | Claude Code compatible layout. |+| Global | `~/.config/opencode/skills/` or `~/.config/opencode/skill/` | Honours `OPENCODE_CONFIG_DIR` and `XDG_CONFIG_HOME`. |+| Global | `~/.claude/skills/`, `~/.agents/skills/` | External skills, auto-loaded by the engine. |++Nested layouts such as `.opencode/skills/<plugin>/<name>/SKILL.md` (what marketplace plugin bundles install) are listed and can be removed from the app as well.++The workspace root is the folder that contains `.git`; the server walks up from the selected folder to find it, which matches how the engine resolves the project.++### Adding a skill in the desktop app++1. Open Settings, then Library (the Extensions tab). Choose the Skills filter.+2. Click Add, choose Skill.+ - Signed in to an omnirush.ai Cloud organization: the Cloud authoring modal opens and the skill is stored in the organization Library (a private plugin). It reaches the engine through omnirush.ai Connect.+ - Signed in with an omnirush.ai account only (or not signed in to Cloud): the workspace skill modal opens. Enter the name, the description and the Markdown body. The app sends `POST /workspace/:id/skills` to the local server, which validates the name and description, adds the frontmatter, writes `.opencode/skills/<name>/SKILL.md`, records an audit entry and emits a `skills` reload event.+3. The Library refreshes and shows the new skill card with its path. Open it to read the content or reveal the file in Finder.+4. Reload the engine when the app prompts for it (see Troubleshooting for why this matters).++To remove a skill, open its card and choose Remove. The server deletes the skill folder (`DELETE /workspace/:id/skills/:name`) and emits a `skills` reload event. Skills that come from omnirush.ai Connect cannot be removed locally.++You can also drop a `SKILL.md` folder into `.opencode/skills/` by hand; the server's reload watcher notices `SKILL.md` changes under `.opencode/skills` and marks a reload as required.++### How skills reach the engine++Skills are files, not config. The engine reads them from disk when it builds its project instance:++- The engine-visible config file (`runtime-opencode-config.json` in the server state directory, passed as `OPENCODE_CONFIG`) does not contain skills. It contains the omnirush.ai provider block, the plugins, the `omnirush` agent definition (which denies the engine's own `customize-opencode` and creator skills) and the global MCP entries.+- The engine scans the skill directories when it creates the instance for the workspace directory. `GET /skill` on the engine (proxied by the server for the v2 preview as `/api/skill`) returns the catalog with `name`, `description`, `location` and `content`.+- The catalog is cached for the life of the instance. A new, changed or removed skill becomes visible after the instance is rebuilt (`POST /instance/dispose` on the engine), which the app calls the engine reload.++The server's list (`GET /workspace/:id/skills?includeGlobal=true`) reads the same directories directly from disk, so it always shows the current files even before the engine has reloaded.++## MCP servers++### Kinds of MCP entries++| Kind | Config | How it is added |+| --- | --- | --- |+| Local (stdio) | `{"type":"local","command":["node","/path/server.mjs"],"environment":{...},"enabled":true}` | Library, Add, MCP server (local), or Advanced, Add MCP. |+| Remote (HTTP) | `{"type":"remote","url":"https://...","headers":{...},"enabled":true}` | Library, Add, MCP server (remote). |+| Managed OAuth | remote URL plus OAuth settings | Library, Add, MCP server with Sign in; the server runs the OAuth flow and keeps the tokens in an encrypted vault. |+| omnirush.ai Connect | `omnirush-cloud` and `omnirush-connect-*` | Provisioned by the account; not user-editable. |++MCP names must be alphanumeric with `-` or `_` and must not start with `-`. The names `omnirush-cloud`, `omnirush-connect-*` and `omnirush-direct-*` are reserved.++### Adding an MCP server in the desktop app++1. Open Settings, then Library. Click Add and choose MCP server (or open Advanced and click Add MCP).+2. Enter a name, pick Remote or Local, and enter the URL or the command line. For a local server the command is split on whitespace into the `command` array.+3. The app sends `POST /workspace/:id/mcp` with `{ name, config }`. The server validates the config, stores it in the workspace row of the runtime DB (`runtime_opencode_configs`, SQLite in the server state directory), and immediately registers it with the running engine (`POST /mcp` on the engine). It then records an audit entry and emits an `mcp` reload event.+4. The card shows the engine status: Ready (connected), Needs sign-in, Paused (disabled), Offline or an error. Toggle the card to pause or resume the server; the toggle sends `POST /workspace/:id/mcp/:name/enabled` and the engine re-registers the entry.++To remove a server, open its card and choose Remove. The server deletes the runtime row (`DELETE /workspace/:id/mcp/:name`) and tells the engine to drop the registration.++### Where MCP config lives++- Workspace MCP servers added from the app: the workspace row of the runtime DB. They are never written into the user's `opencode.json`.+- Account-level entries (`omnirush-cloud`): the engine-global row of the runtime DB; these are the only MCP entries rendered into the engine-visible config file.+- Static entries from `<workspace>/.opencode/opencode.json` or `~/.config/opencode/opencode.json`: read by the engine directly and listed in the app as project or global config entries (read-only from the app).++### How MCP servers reach the engine++- On startup and after every engine reload, the server pushes each workspace's runtime MCP entries to the engine (`POST /mcp` with `{ name, config }`), one entry at a time so one dead server cannot block the rest. Failures are retried in the background and surfaced as `engineSync` on `GET /workspace/:id/mcp`.+- The engine spawns local servers (stdio) or opens the HTTP transport, completes the MCP handshake (`initialize`, `notifications/initialized`) and calls `tools/list`. Its status is visible on `GET /mcp` on the engine and as the card status in the app.+- MCP tools are exposed to the model as `<server>_<tool>` at prompt time. They do not appear in the engine's `/experimental/tool/ids` list, which only covers built-in and plugin tools; the connected status plus the server's `tools/list` call is the confirmation that the tools are available.++### Coexistence with the omnirush.ai provider++The engine-visible config file is rendered from the engine-global runtime row plus static built-ins:++- `provider.omnirush` (the omnirush.ai models, `baseURL` pointing at the local gateway broker) is added after any runtime `provider` entries, so a runtime provider with the same id cannot shadow it.+- `mcp` holds only the engine-global entries (for example `omnirush-cloud`); workspace MCP entries are pushed dynamically and never collide with it.+- `disabled_providers` is copied through untouched.+- `model` defaults to `omnirush/gpt-6-astra` when the account is signed in.++Adding skills or MCP servers never modifies the provider block.++## Verified end to end++The flows above were exercised against the bundled sidecar (`opencode` 1.18.18, `opencode serve`) in an isolated `HOME` with the server started through the embedded API and a loopback stub as the gateway:++- `POST /workspace/:id/skills` wrote `.opencode/skills/release-notes/SKILL.md`; `GET /workspace/:id/skills` and `GET /workspace/:id/skills/release-notes` returned it with the trigger extracted from the "When to use" section. After an engine instance rebuild, the engine's `GET /skill` listed it with the exact body; the generated config file kept `provider.omnirush`, `model`, the 11 plugins and `mcp: {}` unchanged.+- `POST /workspace/:id/mcp` with a local stdio fixture (`node mcp-stdio-fixture.mjs`) produced `engineSync.status: "ok"`, the engine reported `{"fixture-stdio":{"status":"connected"}}`, and the fixture logged `initialize`, `notifications/initialized` and `tools/list` from the engine. Disabling switched the engine status to `disabled`; enabling reconnected and re-listed tools; deleting removed the entry from the engine.++## Troubleshooting++**A new or edited skill is listed in the Library but the model does not use it.**+The engine caches its skill catalog per project instance and needs an instance rebuild after skill changes. In the bundled desktop configuration the Reload action goes through the engine pool, which skips the reload when nothing in the engine config file changed; skill files are not part of that fingerprint, so a reload requested only for a skill change is currently a no-op (the server needs to pass the pool's `manual` flag for user-initiated reloads). Until that lands, use Restart OpenCode in Settings, Advanced, or quit and reopen the app. The v2 engine preview watches skill files natively and does not need this.++**The skill is not listed at all.**+- Check the file name: it must be exactly `SKILL.md` inside its own folder.+- Check the frontmatter: `name` must be kebab-case and `description` must be present. Invalid YAML is listed with an `ERROR: Invalid skill frontmatter` description so you can fix it.+- The app lists `.opencode/skills`, `.opencode/skill` and `.claude/skills` under the git root, plus the global folders when the workspace is local. A skill placed above the git root is not a workspace skill.+- Two skills with the same name: the first one found wins (workspace before global).++**An MCP server shows an error or Offline.**+- Local servers: the command must be an absolute path or on the PATH of the desktop app (which is not your shell PATH). Prefer absolute paths such as `/usr/local/bin/node /path/to/server.mjs`. The server must speak JSON-RPC over stdio, newline-delimited, and answer `initialize` and `tools/list`.+- Remote servers: the URL must start with `http://` or `https://` and must not contain whitespace. Sign-in errors show as Needs sign-in; use the card's Sign in action.+- `engineSync.failures` on `GET /workspace/:id/mcp` (visible in Settings, Debug) lists the exact registration error. A 503 "deferred until active tasks finish" means a session was running; the server retries when the engine is idle.+- Registration is skipped while the engine is busy to avoid replacing a tool set mid-turn. Wait for the running session to finish or reload the engine.++**The MCP server is connected but its tools are missing from a diagnostics tool list.**+`/experimental/tool/ids` only lists built-in and plugin tools. Use the card status and the server's own logs; the engine calls `tools/list` right after the handshake.++**Removing an MCP server left tools behind in a running session.**+The engine drops the registration immediately, but a session that already started a turn keeps its captured tool set until the turn ends.++**Where are the files?**+- Server state directory: `~/.config/omnirush/` (or the directory of `OMNIRUSH_SERVER_CONFIG`), containing `runtime.sqlite` (runtime DB), `runtime-opencode-config.json` (engine-visible config) and the managed MCP vault.+- Engine data: `~/.local/share/opencode/` (logs under `log/`).+- Audit log: `<workspace>/.opencode/` audit entries record every skill and MCP change with the actor.++## API summary++| Action | Request |+| --- | --- |+| List skills | `GET /workspace/:id/skills?includeGlobal=true` |+| Read a skill | `GET /workspace/:id/skills/:name` |+| Add or update a skill | `POST /workspace/:id/skills` `{ name, description, content }` |+| Remove a skill | `DELETE /workspace/:id/skills/:name` |+| List MCP servers | `GET /workspace/:id/mcp` (items, `engineSync`, `managedOAuthState`) |+| Add an MCP server | `POST /workspace/:id/mcp` `{ name, config }` |+| Add a managed OAuth MCP server | `POST /workspace/:id/mcp/managed` `{ name, url, oauth }` |+| Pause or resume | `POST /workspace/:id/mcp/:name/enabled` `{ enabled }` |+| Sign out of a server | `DELETE /workspace/:id/mcp/:name/auth` |+| Remove a server | `DELETE /workspace/:id/mcp/:name` |+| Reload the engine | `POST /workspace/:id/engine/reload` |++All write routes require a client token with collaborator scope and go through the approval service (`auto` in the desktop app).diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex 012796f0..ef349a14 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -115,6 +115,37 @@ export type OmniRushServerInfo = {managedOpencodeExecution: OpencodeExecutionSnapshot | null;};+/** Outcome of the remote device-session revocation attempted during sign-out. */+export type OmniRushAccountSignOutReason =+ /** The account server accepted the revocation (2xx). */+ | "revoked"+ /** The account server no longer knows the device session (401/403, or a 404 naming the session). */+ | "already_revoked"+ /** The account server could not be reached or failed (network error, 5xx, other errors). */+ | "unreachable"+ /** The account server has no device sign-out route (404 route missing, 405, 501). */+ | "endpoint_missing";++export type OmniRushAccountSignOutResult = {+ connected: false;+ remoteRevoked: boolean;+ reason: OmniRushAccountSignOutReason;+};++export type OmniRushAccountStatus = {+ connected: boolean;+ gatewayConfigured: boolean;+ reauthorizationRequired?: boolean;+ email?: string | null;+ displayName?: string | null;+ accountStatus?: string | null;+ usage?: { tokenLimit: number; usedTokens: number; remainingTokens: number } | null;+ /** Gateway URL the connected account uses, or the configured default while signed out. */+ gatewayUrl?: string | null;+ /** Display label for the account server, e.g. "omnirush.ai" or "localhost:8090 (local API)". */+ gatewayHost?: string | null;+};+export type EngineDoctorResult = {found: boolean;inPath: boolean;@@ -514,21 +545,13 @@ export type DesktopCommandMap = {omnirushServerInfo: { args: []; result: OmniRushServerInfo };omnirushAccountStatus: {args: [];- result: {- connected: boolean;- gatewayConfigured: boolean;- reauthorizationRequired?: boolean;- email?: string | null;- displayName?: string | null;- accountStatus?: string | null;- usage?: { tokenLimit: number; usedTokens: number; remainingTokens: number } | null;- };+ result: OmniRushAccountStatus;};omnirushAccountConnect: {args: [options?: { gatewayUrl?: string; deviceName?: string }];result: { connected: true; userCode: string };};- omnirushAccountSignOut: { args: []; result: { connected: false; remoteRevoked: boolean } };+ omnirushAccountSignOut: { args: []; result: OmniRushAccountSignOutResult };automationRunnerConfigure: {args: [configuration: { baseUrl: string; token: string; runnerId: string } | null];result: { connected: boolean };