Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

17.8 KB
Raw Blame
import {
  readComposerModule,
  readComposerSource,
  readMainModule,
  readStoreModule,
  readStoreSource,
  readTranscriptModule,
  readTranscriptSource,
} from "./helpers/source-contracts.mjs";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { loadStyles } from "./helpers/styles.mjs";

const composerSource = await readComposerSource();
const composerToolbarSource = await readComposerModule("ComposerToolbar.tsx");
const composerModelPickerSource = await readComposerModule("ComposerModelPicker.tsx");
const composerPermissionPickerSource = await readComposerModule("ComposerPermissionPicker.tsx");
const scheduledModelPickerSource = await readFile(
  new URL("../src/features/scheduled/ScheduledModelPicker.tsx", import.meta.url),
  "utf8",
);
const transcriptSource = await readTranscriptSource();
const transcriptSharedSource = await readTranscriptModule("shared.tsx");
const transcriptToolRowSource = await readTranscriptModule("ToolRow.tsx");
const transcriptDisclosureSource = await readTranscriptModule("disclosure.tsx");
const transcriptActivityGroupSource = await readTranscriptModule("ActivityGroup.tsx");
const appSource = await readFile(
  new URL("../src/components/ChatSurface.tsx", import.meta.url),
  "utf8",
);
const launchErrorSource = await readFile(
  new URL("../src/lib/chat-launch-error.ts", import.meta.url),
  "utf8",
);
const providerCatalogSource = await readMainModule("runtime/provider-catalog.ts");
const sessionIpcSource = await readMainModule("ipc/session-ipc.ts");
const sessionLaunchSource = await readMainModule("runtime/session-launch.ts");
const storeSource = await readStoreSource();
const sessionCoordinationSource = await readStoreModule("runtime/session-coordination.ts");
const modelMenuSource = await readFile(
  new URL(
    "../src/features/chat/composer/hooks/useComposerModelMenu.ts",
    import.meta.url,
  ),
  "utf8",
);
// Agent/Plan mode and model selection are owned by the Composer; the
// conversation top bar only hosts the project crumb, task title, and window
// actions.
const topbarSource = await readFile(
  new URL("../src/components/ConversationTopbar.tsx", import.meta.url),
  "utf8",
);
// Provider thinking config lives in the provider settings components, not the
// settings page shell.
const settingsSource = (
  await Promise.all(
    [
      "../src/components/settings/ModelConfigPage.tsx",
      "../src/components/settings/ProviderSetupDialog.tsx",
      // The picker both credential kinds render owns the thinking chips (D270).
      "../src/components/settings/ModelSelectionPanes.tsx",
      "../src/components/settings/ModelAdvancedSettings.tsx",
      "../src/components/settings/VendorAccountDialog.tsx",
      "../src/components/settings/useProviderModels.ts",
    ].map((path) => readFile(new URL(path, import.meta.url), "utf8")),
  )
).join("\n");
const stylesSource = await loadStyles();

test("composer exposes the runtime thinking level order and provider filtering", () => {
  for (const level of ["off", "minimal", "low", "medium", "high", "xhigh", "max", "omit"]) {
    assert.match(composerSource, new RegExp(`"${level}"`));
  }
  assert.match(composerSource, /supportedThinkingLevels/);
  assert.match(composerSource, /supportsReasoning/);
  assert.match(composerSource, /thinkingLevelForProvider/);
  assert.match(composerSource, /thinkingLevel:\s*level/);
  // The level is a drag on the slider: no reasoning list submenu to render.
  assert.doesNotMatch(composerSource, /composer-thinking-list/);
  assert.doesNotMatch(stylesSource, /\.composer-thinking-levels/);
  assert.doesNotMatch(stylesSource, /\.composer-thinking-level\b/);
  assert.match(
    stylesSource,
    /\.composer-model-thinking-menu\s*\{[\s\S]*?width:\s*min\(320px,\s*calc\(100vw - 24px\)\);/
  );
  assert.match(composerSource, /availableThinkingLevels/);
  assert.match(composerSource, /thinkingMenuLevels/);
});

test("thinking levels use their canonical English values without i18n", () => {
  assert.match(composerSource, /const thinkingLabel = thinkingLevel;/);
  // The slider's ticks print the canonical level values themselves.
  assert.match(composerSource, /onClick=\{\(\) => select\(stop\)\}>\{candidate\}<\/button>/);
  assert.doesNotMatch(composerSource, /THINKING_LEVEL_(LABELS|I18N_KEYS)/);
  assert.doesNotMatch(composerSource, /chat\.effort(?:Off|Minimal|Low|Mid|High|Xhigh|Max)/);
  assert.doesNotMatch(transcriptSource, /thinkingLevel\./);
  assert.doesNotMatch(settingsSource, /thinkingLevel\./);
});

test("Composer owns the mode and model controls", () => {
  const leftToolbar = composerToolbarSource.slice(
    composerToolbarSource.indexOf('<div className="composer-left">'),
    composerToolbarSource.indexOf('<div className="composer-right">'),
  );
  const modeControl = leftToolbar.indexOf("<ComposerModePicker");
  const permissionControl = leftToolbar.indexOf("<ComposerPermissionPicker");
  const rightToolbar = composerToolbarSource.slice(
    composerToolbarSource.indexOf('<div className="composer-right">'),
  );

  assert.ok(modeControl >= 0, "the left toolbar owns the mode trigger");
  assert.ok(permissionControl > modeControl, "approval follows the mode trigger");
  // The task draft has no session, so its picker must not claim one: with
  // `activeSessionId` unset the menu resolves the selected model's binding
  // default thinking level instead of pinning the draft to its current value.
  assert.match(scheduledModelPickerSource, /activeSessionId: null/);
  assert.doesNotMatch(scheduledModelPickerSource, /useId\(/);
  assert.match(scheduledModelPickerSource, /composerModelDisplayName\(provider, value\.modelId \?\? ""\)/);
  assert.doesNotMatch(
    scheduledModelPickerSource,
    /composerModelDisplayName\(provider, value\.modelId \?\? "", selected\.displayName\)/,
  );
  assert.doesNotMatch(leftToolbar, /composer-thinking|thinking-chip/);
  assert.doesNotMatch(topbarSource, /ModelSelect|model-chip/);
  assert.doesNotMatch(topbarSource, /ct-mode|ct-mode-btn|configureActiveSession/);
  assert.doesNotMatch(stylesSource, /\.conversation-topbar \.ct-mode/);
  assert.match(composerModelPickerSource, /composer-model-thinking-chip/);
  assert.match(composerModelPickerSource, /composer-model-thinking-menu/);
  assert.match(composerModelPickerSource, /<ComposerModelList/);
  assert.doesNotMatch(composerModelPickerSource, /composer-menu-back/);
});

test("conversation topbar keeps the crumb and title free of a running indicator", () => {
  // The left lane is a project crumb plus the task title; neither may grow a
  // running status, and the title still owns width-based clipping.
  assert.match(topbarSource, /IconFolder/);
  assert.match(topbarSource, /className="ct-project"/);
  assert.doesNotMatch(topbarSource, /IconChevronRight/);
  assert.doesNotMatch(topbarSource, /className="ct-title-chevron"/);
  assert.match(topbarSource, /className="ct-title"/);
  assert.doesNotMatch(topbarSource, /TOPBAR_TITLE_MAX_LENGTH|truncateTopbarTitle/);
  assert.doesNotMatch(topbarSource, /runningSessions|const isRunning|ct-running|role="status"/);
  assert.match(stylesSource, /\.conversation-topbar \.ct-title-wrap[\s\S]*?align-items: center/);
  assert.match(
    stylesSource,
    /\.conversation-topbar \.ct-title[\s\S]*?overflow:\s*hidden[\s\S]*?text-overflow:\s*ellipsis[\s\S]*?white-space:\s*nowrap/,
  );
  assert.match(
    stylesSource,
    /\.conversation-topbar \.ct-title[\s\S]*?font-size: var\(--text-sm-plus\)/,
  );
  assert.doesNotMatch(stylesSource, /\.conversation-topbar \.ct-running(?:-dot)?\b/);
});

test("model menus do not expose desktop-owned reasoning overrides", () => {
  assert.doesNotMatch(composerSource, /canEnableThinkingOverride/);
  assert.doesNotMatch(composerSource, /chat\.thinkingEnable/);
  assert.doesNotMatch(composerSource, /supportsReasoning:\s*true/);
});

test("switching to a provider without reasoning resets the session level", () => {
  assert.match(
    composerSource,
    /if\s*\(!provider\?\.supportsReasoning\)\s*return\s*"off"/,
  );
  // Composer owns both the reasoning-level guard and its session write.
  assert.match(
    composerSource,
    /const thinkingLevel = thinkingLevelForProvider\(\s*thinkingProvider,\s*configuredThinkingLevel,\s*\)/,
  );
  assert.match(composerSource, /thinkingLevel:\s*level/);
});

test("draft Composer thinking follows the exact model selected in its menu", () => {
  assert.match(
    composerSource,
    /const providerModels = useAppStore\(\(s\) => s\.providerModels\)/,
  );
  assert.match(composerSource, /thinkingProviderForModel\(/);
  assert.match(composerSource, /const binding = provider\.models\.find/);
  assert.match(composerSource, /THINKING_LEVELS\.filter/);
  assert.match(composerSource, /binding\.thinkingLevels\.includes/);
  assert.match(
    composerSource,
    /const selectedModelCatalog = provider \? providerModels\[provider\.id\]/,
  );
  assert.match(composerSource, /const catalogThinkingProvider = thinkingProviderForModel\(/);
  assert.match(composerSource, /resolveComposerThinkingProvider\(\{/);
  assert.match(
    composerSource,
    /const nextModelProvider = thinkingProviderForModel\([\s\S]*?providerModels\[candidate\.id\]/,
  );
  assert.match(
    composerSource,
    /const selectedSameModel =\s*activeSessionId &&\s*candidate\.id === provider\?\.id &&\s*sameComposerModelId\(modelId \?\? "", nextModelId\);/,
  );
  assert.match(
    composerSource,
    /const nextThinkingLevel = selectedSameModel\s*\?\s*thinkingLevelForProvider\(nextModelProvider, thinkingLevel\)[\s\S]*?initialThinkingLevelForBinding\([\s\S]*?initialThinkingLevelForUnmatchedModel\(/,
  );
  assert.match(composerSource, /const selectedBinding = provider\?\.models\.find/);
  assert.match(
    composerSource,
    /const draftThinkingLevel = selectedModelInfo\?\.catalogSource === "models\.dev"\s*\?\s*initialThinkingLevelForBinding\(/,
  );
  assert.match(composerSource, /initialThinkingLevelForUnmatchedModel\(/);
  assert.match(modelMenuSource, /initialThinkingLevelForUnmatchedModel\(/);
  assert.match(sessionCoordinationSource, /initialThinkingLevelForUnmatchedModel\(/);
  assert.match(modelMenuSource, /nextModel\?\.catalogSource === "models\.dev"/);
  assert.match(sessionCoordinationSource, /catalogModel\?\.catalogSource === "models\.dev"/);
  assert.doesNotMatch(composerSource, /highestSupportedThinkingLevel/);
});

test("new sessions default to the selected model binding's thinking level", () => {
  const materializeSource =
    sessionCoordinationSource.match(
      /async function persistSessionAndSelect[\s\S]*?\n  }\n\n  async function materializeDraftSession/,
    )?.[0] ?? "";
  assert.ok(
    materializeSource.length > 0,
    "materializeDraftSession implementation not found",
  );
  assert.match(materializeSource, /initialThinkingLevelForBinding\(/);
  assert.match(materializeSource, /inheritedBinding/);
  assert.match(
    materializeSource,
    /thinkingLevel:[\s\S]*?defaultThinkingLevel/,
  );
  assert.doesNotMatch(materializeSource, /highestSupportedThinkingLevel\(/);
});

test("main resolves reasoning from each session's exact selected model", () => {
  assert.match(providerCatalogSource, /const enrichSession/);
  assert.match(providerCatalogSource, /const resolveSessionCapabilityTarget/);
  assert.match(providerCatalogSource, /defaults\?\.defaultProviderId/);
  assert.match(sessionIpcSource, /result\.sessions\.map\(\(session\) =>/);
  assert.match(sessionIpcSource, /enrichSession\(session, providers, defaults\)/);
  assert.match(providerCatalogSource, /catalogModelConfigFor\(modelsDevCatalog/);
  // models.dev records stamp reasoning capability per exact model id.
  assert.match(providerCatalogSource, /capabilitiesFromModelConfig\(modelConfig\)/);
  assert.match(providerCatalogSource, /supportsReasoning/);
  assert.doesNotMatch(providerCatalogSource, /resolvePiModelConfig/);
});

test("transcript keeps assistant thinking in a separate disclosure", () => {
  assert.match(transcriptSource, /tool-row thinking/);
  assert.match(transcriptSource, /className="tool-row-header"/);
  assert.match(transcriptSource, /aria-expanded=\{open\}/);
  assert.match(transcriptSharedSource, /\{open \? \(\s*<div className="tool-row-body"/);
  assert.match(transcriptSource, /IconSparkles/);
  assert.match(transcriptSource, /messageThinking as thinkingText/);
  assert.match(transcriptSource, /thinking-prose[\s\S]*?Markdown source=\{text\}/);
  assert.match(transcriptSource, /CopyButton text=\{content\}/);
  assert.match(transcriptSource, /messageThinking as thinkingText/);
  assert.match(transcriptSource, /onlyThinking = useMemo\(\(\) => items\.every/);
  assert.match(stylesSource, /\.thinking-prose/);
});

test("expanded assistant activity rails collapse their disclosures", () => {
  assert.match(
    transcriptSharedSource,
    /function DisclosureCollapseRail\([\s\S]*?className="disclosure-collapse-rail"[\s\S]*?ariaLabel=\{label\}[\s\S]*?tooltip=\{label\}[\s\S]*?onClick=\{onCollapse\}/,
  );
  assert.match(
    transcriptToolRowSource,
    /className="tool-row-body"[\s\S]*?<DisclosureCollapseRail[\s\S]*?onCollapse=\{collapseRow\}/,
  );
  assert.match(
    transcriptActivityGroupSource,
    /className="tool-activity-body"[\s\S]*?<DisclosureCollapseRail[\s\S]*?onCollapse=\{collapseDisclosure\}/,
  );
  assert.match(
    stylesSource,
    /\.disclosure-collapse-rail\s*\{[\s\S]*?position:\s*absolute;[\s\S]*?width:\s*16px;[\s\S]*?cursor:\s*pointer;/,
  );
  assert.match(stylesSource, /\.disclosure-collapse-rail:focus-visible\s*\{/);
});

test("tool and search rows stay collapsed while reasoning follows its own switch", () => {
  assert.match(transcriptDisclosureSource, /export function useAutomaticDisclosure\(/);
  assert.match(transcriptDisclosureSource, /revealRequest\?: number/);
  assert.match(transcriptDisclosureSource, /const currentOpen = useRef\(open\)/);
  assert.match(transcriptDisclosureSource, /const setManualOpen = useCallback/);
  assert.match(
    transcriptSource,
    /const automaticallyOpen = activityGroupStartsOpen\(\{\s*groupActive: live \|\| runningOperation,\s*collapseSettled: collapseSettledGroups,\s*\}\);/,
  );
  assert.match(
    transcriptSource,
    /<ThinkingRow[\s\S]*?\n\s*autoOpen=\{thinkingRowStartsOpen\(/,
  );
  // The leaf default stays with thinking only; a tool, hosted-search or plan
  // row waits for an explicit user action in either mode.
  assert.doesNotMatch(transcriptSource, /autoOpenLatest/);
  assert.doesNotMatch(transcriptSource, /<ToolRow[^>]*\sautoOpen/);
  assert.match(transcriptToolRowSource, /const disclosure = useAutomaticDisclosure\(\s*false,\s*revealRequest,\s*disclosureKey\("tool", message\.id\),\s*\);/);
  assert.match(transcriptSource, /onClick=\{toggleDisclosure\}/);
  assert.match(transcriptSource, /onCollapse=\{collapseDisclosure\}/);
  assert.match(transcriptSource, /onUserInteraction=\{claimDisclosure\}/);
  assert.doesNotMatch(transcriptActivityGroupSource, /const tail =|tool-activity-preview/);
});

test("activity headers omit the redundant status capsule", () => {
  assert.doesNotMatch(
    transcriptSource,
    /activityItemStatus|currentStatus|tool-activity-current/,
  );
  assert.match(transcriptSource, /aria-live="polite"/);
  assert.match(transcriptSource, /waitingForModel/);
  assert.match(transcriptSource, /retryingModel/);
  assert.match(transcriptSource, /waitingForSubagents/);
  assert.doesNotMatch(stylesSource, /\.tool-activity-current/);
  assert.match(stylesSource, /\.run-activity-indicator\[data-phase="waiting-model"\]/);
  assert.match(stylesSource, /\.run-activity-indicator\[data-phase="retrying"\]/);
  assert.match(stylesSource, /\.run-activity-indicator\[data-phase="waiting-subagents"\]/);
});

test("thinking-only assistant streams open the transcript surface", () => {
  assert.match(launchErrorSource, /typeof message\.thinking === "string"/);
  assert.match(launchErrorSource, /hasContent \|\| hasThinking/);
  assert.match(appSource, /messageHasTranscriptContent\(message\)/);
});

test("provider settings persist model-local limits and thinking configuration", () => {
  assert.match(settingsSource, /useProviderModels/);
  assert.match(settingsSource, /bindingFromModelInfo/);
  assert.match(settingsSource, /levelChoices\.map/);
  assert.match(settingsSource, /supportedThinkingLevels/);
  assert.match(settingsSource, /contextWindow/);
  assert.match(settingsSource, /maxTokens/);
  assert.match(settingsSource, /defaultThinkingLevel/);
  assert.match(settingsSource, /models/);
});

test("main forwards the complete models.dev model record to the sidecar", () => {
  // catalogModelConfigFor returns modelConfigFromModelsDev for a resolved record.
  assert.match(sessionLaunchSource, /catalogModelConfigFor/);
  assert.doesNotMatch(sessionLaunchSource, /resolvePiModelConfig/);
  assert.match(sessionLaunchSource, /\.\.\.\(modelConfig \? \{ modelConfig \} : \{\}\)/);
  assert.doesNotMatch(sessionLaunchSource, /modelCompat/);
});

test("settings offers the canonical thinking levels for explicit overrides", () => {
  // Published levels still seed known-model bindings, but the catalog is not a
  // gate: proxies and newly released models need the same opt-in controls.
  assert.match(settingsSource, /publishedThinkingLevels/);
  assert.match(settingsSource, /THINKING_LEVELS/);
  assert.match(
    settingsSource,
    /publishedLevelsById[\s\S]*?publishedThinkingLevels\(row\.info\)/,
  );
  assert.match(settingsSource, /settings\.thinkingManualOverrideHint/);
  assert.match(settingsSource, /const levelChoices = THINKING_LEVELS/);
  // Explicit selections, including levels absent from the catalog, survive
  // save and are resolved by the runtime for the configured endpoint.
  assert.doesNotMatch(
    settingsSource,
    /binding\.thinkingLevels\.filter\(\(level\) => choices\.includes\(level\)\)/,
  );
  assert.match(settingsSource, /models: persisted/);
  // A row the catalog does not describe stays out of the published map, while
  // its editable choices remain the canonical ladder.
  assert.match(settingsSource, /if \(!row\.info\) continue;/);
  assert.match(settingsSource, /const publishedLevels =/);
});