diff --git a/server/src/hephaestus/http/context.py b/server/src/hephaestus/http/context.py index edf03776..a98dc2a4 100644 --- a/server/src/hephaestus/http/context.py +++ b/server/src/hephaestus/http/context.py @@ -178,7 +178,12 @@ class ContextEnvelope: @property def is_empty(self) -> bool: - """§7A.3: "an empty or absent envelope is not an error".""" + """§7A.3: "an empty or absent envelope is not an error". + + ``view`` names a reference once the operator adds it (issue #13). + Navigation tabs alone are still the blank canvas; a camera token + that the operator explicitly sent is not. + """ return ( self.part is None and self.artifact_ref is None @@ -186,6 +191,7 @@ def is_empty(self) -> bool: and not self.hidden_labels and self.section_plane is None and self.focus is None + and self.view is None ) diff --git a/server/src/hephaestus/http/providers.py b/server/src/hephaestus/http/providers.py index c7176b59..9607fa1a 100644 --- a/server/src/hephaestus/http/providers.py +++ b/server/src/hephaestus/http/providers.py @@ -794,10 +794,18 @@ def provider_specs_of(file: ProvidersFile) -> list[dict[str, Any]]: """The declared specs, normalized for display. **No credential material.**""" rows: list[dict[str, Any]] = [] for spec in file.providers: - models = [ - {"id": str(model.get("id", "")), "name": str(model.get("name", model.get("id", "")))} - for model in _dicts(spec.get("models")) - ] + models: list[dict[str, Any]] = [] + for model in _dicts(spec.get("models")): + entry: dict[str, Any] = { + "id": str(model.get("id", "")), + "name": str(model.get("name", model.get("id", ""))), + } + # Projected only when the spec declared it. Absence is the named + # "this model has no thinking levels" — the composer maps effort + # from this field and must not invent one. + if model.get("reasoning") is True: + entry["reasoning"] = True + models.append(entry) row: dict[str, Any] = { "id": str(spec.get("id", "")), "kind": str(spec.get("kind", "")), diff --git a/server/tests/test_context_envelope.py b/server/tests/test_context_envelope.py index 763f7e64..303eeb3a 100644 --- a/server/tests/test_context_envelope.py +++ b/server/tests/test_context_envelope.py @@ -196,6 +196,21 @@ def test_the_blank_canvas_composes_nothing(app: Workspace) -> None: assert body["sources"] == [] +def test_an_explicit_view_is_composed_rather_than_collapsed(app: Workspace) -> None: + """Issue #13: Add current view must change what the agent is told. + + Tabs alone remain the blank canvas. A ``view`` the operator sent is a + reference: ``_say_viewport`` already knew the line; collapsing on + ``is_empty`` made the composer's disclosure say the agent would hear + nothing. + """ + response = app.post("/context/preview", json={"context": {"view": "iso"}}) + assert response.status_code == 200, response.text + body = cast("dict[str, Any]", response.json()) + assert "camera view: iso" in body["block"] + assert body["truncated"] is False + + def test_composition_is_deterministic_in_the_envelope_and_the_project(app: Workspace) -> None: """§7A.3: "deterministic in ``(references, project state)``". diff --git a/server/tests/test_http_providers.py b/server/tests/test_http_providers.py index 571f428b..618b7ff7 100644 --- a/server/tests/test_http_providers.py +++ b/server/tests/test_http_providers.py @@ -111,6 +111,38 @@ def test_a_serve_with_no_providers_json_still_reads_and_writes_one(ws: Workspace assert _config_path(ws).exists() +def test_get_providers_projects_model_ids_and_reasoning_without_house_names( + ws: Workspace, +) -> None: + """The composer maps model + effort from this document (issue #13). + + Identifiers are the spec's own ``models[].id``. ``reasoning`` is projected + only when the spec declared it — absence is the named "no thinking + levels", not a defaulted house effort scale. + """ + with_reasoning = { + **_FAKE_SPEC, + "models": [ + { + "id": "heph-fake-model", + "name": "Heph Fake", + "contextWindow": 128000, + "maxTokens": 4096, + "reasoning": True, + } + ], + } + written = _write_specs(ws, [with_reasoning]) + assert written.status_code == 200, written.text + models = ws.get("/providers").json()["providers"][0]["models"] + assert models == [{"id": "heph-fake-model", "name": "Heph Fake", "reasoning": True}] + + _write_specs(ws, [_FAKE_SPEC]) + plain = ws.get("/providers").json()["providers"][0]["models"] + assert plain == [{"id": "heph-fake-model", "name": "Heph Fake"}] + assert "reasoning" not in plain[0] + + def test_the_written_file_is_0600_created_private(ws: Workspace) -> None: """§23.2: ``write_private``, created private, never ``chmod``'ed after. diff --git a/web/e2e/composer.spec.ts b/web/e2e/composer.spec.ts index 1479db31..2232a798 100644 --- a/web/e2e/composer.spec.ts +++ b/web/e2e/composer.spec.ts @@ -107,6 +107,12 @@ test.describe("§7A.12 case 1 — the blank canvas reaches the workspace", () => await expect(composer).toHaveAttribute("data-composer-state", "idle"); await expect(composer).toHaveAttribute("data-disabled-reason", "null"); await expect(composer).toHaveAttribute("data-profile", "orchestrator"); + // Issue #13: model id is the provider's own, never a house name. + await expect(composer.locator("[data-composer-model]")).toHaveAttribute( + "data-composer-model", + "heph-fake-model", + ); + await expect(composer.locator("[data-context-add-view]")).toHaveCount(1); await composer .locator("[data-composer-input]") @@ -157,9 +163,26 @@ test.describe("§7A.12 case 2 — the context envelope", () => { await expect(partChip).toHaveAttribute("data-context-value", PART); await expect(composer.locator("[data-context-chips] [data-source]")).toHaveCount(0); + // Issue #13: a selected part projects the two §6.4 DFM controls, not a + // Plan toggle. The fixture starts `[dfm] auto_run = false`. + await expect(composer.locator("[data-composer-dfm]")).toHaveCount(1); + await expect(composer.locator("[data-dfm-auto-run]")).toHaveAttribute("data-dfm-auto-run", "false"); + await expect(composer.locator("[data-dfm-auto-run-toggle]")).toHaveCount(1); + await expect(composer.locator("[data-dfm-run]")).toHaveCount(1); + // Every member is opt-out (§7A.3). await partChip.locator('[data-context-drop="part"]').click(); await expect(partChip).toHaveAttribute("data-context-dropped", ""); + + // Issue #13: Add current view un-drops the view and opens the advisory + // preview. The server must compose the camera token — a disclosure that + // said the agent would be told nothing would be the client/server + // emptiness predicates disagreeing. + await composer.locator("[data-context-add-view]").click(); + const viewChip = composer.locator('[data-context-key="view"]'); + await expect(viewChip).not.toHaveAttribute("data-context-dropped", ""); + await expect(composer.locator("[data-context-preview]")).toBeVisible(); + await expect(composer.locator("[data-context-block]")).toContainText("camera view:"); }); test("the disclosure renders the server's block, and says it is advisory", async ({ page }) => { @@ -290,6 +313,10 @@ test.describe("§7A.12 case 6 — no agent runtime", () => { const path = await composer.locator("[data-attach-path]").getAttribute("data-attach-path"); expect(path).toMatch(/providers\.json$/); + // Named absence: do not render a model picker that reads as a signed-in agent. + await expect(composer.locator("[data-composer-model]")).toHaveCount(0); + await expect(composer.locator("[data-context-add-view]")).toHaveCount(1); + // The serve still answers every read route: `agent_unavailable` is about // sessions, not about the project. const project = await fetch(`${baseUrl}/api/v1/project`, { diff --git a/web/src/api/dfm.ts b/web/src/api/dfm.ts new file mode 100644 index 00000000..36ed17fc --- /dev/null +++ b/web/src/api/dfm.ts @@ -0,0 +1,49 @@ +// Copyright 2026 The Hephaestus Authors +// SPDX-License-Identifier: Apache-2.0 +// +// The two DFM writes INTERFACE.md §6.4 keeps apart. +// +// `[dfm] auto_run` is a *project setting*, not a per-message flag, so the +// workspace exposes (a) a **Run DFM** action → `POST /parts/{part}/dfm` and +// (b) a project-settings toggle → `POST /project/config/dfm`. Collapsing them +// into one composer switch would imply a tool argument that does not exist. +// Both routes require an `Idempotency-Key`; the caller owns *when*. + +import { apiJson } from "./client"; +import type { DfmDocument, DfmRun } from "./types"; + +export interface DfmAutoRunDocument { + readonly status: "ok"; + readonly auto_run: boolean; +} + +async function keyedPost(path: string, body: unknown, key: string): Promise { + return apiJson(path, { + method: "POST", + headers: { "Content-Type": "application/json", "Idempotency-Key": key }, + body: JSON.stringify(body), + }); +} + +/** `POST /project/config/dfm` — the `[dfm] auto_run` project-config write. */ +export function writeDfmAutoRun(autoRun: boolean, key: string): Promise { + return keyedPost("/project/config/dfm", { auto_run: autoRun }, key); +} + +/** + * `POST /parts/{part}/dfm` — `run_dfm`, keyed (§2.3). + * + * The body is empty by default: process and pack come from the part's own + * declarations. A caller that has a process from the last run may pass it + * through; this function does not invent one. + */ +export function runDfm( + part: string, + key: string, + body: Readonly> = {}, +): Promise { + return keyedPost(`/parts/${encodeURIComponent(part)}/dfm`, body, key); +} + +/** Re-export the read document so a call site can name one module. */ +export type { DfmDocument }; diff --git a/web/src/api/providers.ts b/web/src/api/providers.ts index 9f632ed2..0060cb29 100644 --- a/web/src/api/providers.ts +++ b/web/src/api/providers.ts @@ -74,6 +74,12 @@ export type DiscoveryKind = (typeof DISCOVERY_KINDS)[number]; export interface ProviderModel { readonly id: string; readonly name: string; + /** + * Present only when the spec declared `reasoning: true`. Absence is the + * named "this model has no thinking levels" — the composer does not invent + * an effort picker for it. + */ + readonly reasoning?: boolean; } /** diff --git a/web/src/components/stream/Composer.module.css b/web/src/components/stream/Composer.module.css index d025d155..3c30f518 100644 --- a/web/src/components/stream/Composer.module.css +++ b/web/src/components/stream/Composer.module.css @@ -25,6 +25,22 @@ flex: 0 0 auto; } +/* ---- session chrome (issue #13) ------------------------------------ */ + +.chrome { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2); +} + +.dfm { + display: inline-flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-1); +} + /* ---- the context chip row (§7A.3) ---------------------------------- */ .chips { diff --git a/web/src/components/stream/Composer.tsx b/web/src/components/stream/Composer.tsx index 44805d2d..e752310c 100644 --- a/web/src/components/stream/Composer.tsx +++ b/web/src/components/stream/Composer.tsx @@ -47,10 +47,23 @@ // surface: a state that exists for a reason reads as designed; the same state // with its content missing reads as a bug. Silence is what produced a product // review finding that the workspace has no way to talk to an agent. +// +// **6. Session chrome stays a thin client** (issue #13). Model + effort are +// a *projection* of `GET /providers` using the provider's own model ids — +// never house names, and never a picker. §7A.3's prompt body is `{text, +// context?}`; inventing a Select that does not write would be hosted-chat +// chrome over a field the route does not admit. There is no Plan mode in the +// engine; `[dfm] auto_run` / `run_dfm` is the equivalent and stays two +// controls (§6.4). Add current view is an explicit opt-in that opens +// `POST /context/preview`. No runtime / no `providers.json` keeps the named +// `agent_unavailable` absence. import { useCallback, useEffect, useMemo, useSyncExternalStore, useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { WorkspaceError } from "../../api/client"; +import { writeDfmAutoRun, runDfm } from "../../api/dfm"; +import { uuid7 } from "../../api/idempotency"; +import { keys, useDfm, useProviders } from "../../api/queries"; import { refreshAfterTurn } from "../../api/refresh"; import { attachAgent, type AttachProjection, isAttachCause } from "../../api/attach"; import { @@ -64,8 +77,15 @@ import { copy } from "../../copy"; import { Button, Chip, EmptyState, TextInput } from "../../system"; import { useWorkspaceState } from "../../state/react"; import { labelsForPart, visibilityStore } from "../../state/visibility"; +import { + defaultModel, + modelsFrom, + showDfmChrome, + showModelChrome, +} from "../../stream/composerChrome"; import { chipsFor, envelopeFor, type ContextChip } from "../../stream/composerContext"; import type { ContextMember } from "../../api/sessions"; +import { Fact } from "../Fact"; import styles from "./Composer.module.css"; /** §7A.10's closed `data-composer-state` vocabulary. */ @@ -130,6 +150,7 @@ export function Composer(props: ComposerProps): React.JSX.Element { const [text, setText] = useState(""); const [post, setPost] = useState({ phase: "idle" }); const [dropped, setDropped] = useState>(() => new Set()); + const [added, setAdded] = useState>(() => new Set()); const [disclosed, setDisclosed] = useState(false); const [preview, setPreview] = useState(null); const [previewError, setPreviewError] = useState(null); @@ -138,10 +159,80 @@ export function Composer(props: ComposerProps): React.JSX.Element { const [attachError, setAttachError] = useState(null); const chips = useMemo(() => chipsFor(state, hiddenLabels), [state, hiddenLabels]); const envelope = useMemo( - () => envelopeFor(state, hiddenLabels, dropped), - [state, hiddenLabels, dropped], + () => envelopeFor(state, hiddenLabels, dropped, added), + [state, hiddenLabels, dropped, added], ); + // -- session chrome (issue #13) ---------------------------------------- + // + // Model + effort are a projection of `GET /providers`. They render only + // when a runtime is attached *and* that document named at least one model; + // a picker over an empty set — or a Select that wrote nothing — would read + // as a signed-in agent that is not there. The first declared model id is + // the identifier; effort stays the named `off` because the prompt route + // has no such member. DFM is the engine equivalent of a Plan/DFM chip: + // `[dfm] auto_run` and `run_dfm`, two controls, because collapsing them + // would imply a tool argument that does not exist (§6.4). There is no + // Plan mode to toggle. + const providers = useProviders(); + const models = useMemo(() => modelsFrom(providers.data), [providers.data]); + const modelChrome = showModelChrome(agentUnavailable, models); + const selectedModel = defaultModel(models); + + const dfm = useDfm(state.part); + const [dfmBusy, setDfmBusy] = useState<"auto_run" | "run" | null>(null); + const [dfmError, setDfmError] = useState(null); + + const toggleAutoRun = useCallback(() => { + if (dfm.data === undefined || dfmBusy !== null) return; + setDfmBusy("auto_run"); + setDfmError(null); + void writeDfmAutoRun(!dfm.data.auto_run, uuid7()) + .then(() => { + if (state.part !== null) { + void client.invalidateQueries({ queryKey: keys.dfm(state.part) }); + } + }) + .catch((cause: unknown) => { + setDfmError(cause instanceof WorkspaceError ? cause.message : copy.composer.dfmWriting); + }) + .finally(() => { + setDfmBusy(null); + }); + }, [client, dfm.data, dfmBusy, state.part]); + + const runDfmNow = useCallback(() => { + if (state.part === null || dfmBusy !== null) return; + setDfmBusy("run"); + setDfmError(null); + void runDfm(state.part, uuid7()) + .then(() => { + refreshAfterTurn(client, state.part); + }) + .catch((cause: unknown) => { + setDfmError(cause instanceof WorkspaceError ? cause.message : copy.composer.dfmRunning); + }) + .finally(() => { + setDfmBusy(null); + }); + }, [client, dfmBusy, state.part]); + + const addCurrentView = useCallback(() => { + setDropped((previous) => { + const next = new Set(previous); + next.delete("view"); + if (state.selection !== null) next.delete("selection"); + return next; + }); + setAdded((previous) => { + const next = new Set(previous); + next.add("view"); + if (state.selection !== null) next.add("selection"); + return next; + }); + setDisclosed(true); + }, [state.selection]); + // -- the two closed vocabularies (§7A.10) ------------------------------- // // Ordered most-specific first, and every branch is a fact the SERVER stated: @@ -357,6 +448,75 @@ export function Composer(props: ComposerProps): React.JSX.Element { ) : null} + {/* Session chrome: model + effort projected from GET /providers (not + a picker — §7A.3's prompt body has no such field), DFM as the + engine equivalent of a Plan/DFM chip, and Add current view. + Existing `data-*` selectors on the form and the chip row are + unchanged. */} +
+ {modelChrome && selectedModel !== null ? ( + <> + + + {selectedModel.id} + + + + {copy.composer.effortOff} + + + ) : null} + + {showDfmChrome(agentUnavailable, state.part, dfm.data !== undefined) === "chip" && + dfm.data !== undefined ? ( +
+ + + {dfm.data.auto_run ? copy.dfm.autoRunOn : copy.dfm.autoRunOff} + + + + +
+ ) : showDfmChrome(agentUnavailable, state.part, dfm.data !== undefined) === "absent" ? ( + + {copy.composer.dfmNoPart} + + ) : null} + + +
+ {dfmError !== null ? ( +

+ {dfmError} +

+ ) : null} + {/* §7A.3's chip row: the references this turn carries, every one removable. The chips render §4.5 state — navigation, not fact — so none goes through `` and none carries a `data-source` (§7A.10). */} diff --git a/web/src/copy.ts b/web/src/copy.ts index 3f6dd160..05ad6024 100644 --- a/web/src/copy.ts +++ b/web/src/copy.ts @@ -1014,6 +1014,28 @@ export const copy = { discloseEmpty: "Nothing. The agent is told only what you type.", discloseFailed: "The preview could not be composed.", + /** + * Session chrome (issue #13). Model and effort identifiers come from + * `GET /providers` — the text is the provider's own model id, not a + * house name. Effort is not a prompt field (§7A.3), so the chrome + * projects `off` rather than offering a picker. DFM is the engine + * equivalent of a Plan/DFM chip: the project `[dfm] auto_run` setting + * and `run_dfm`, kept as two controls because collapsing them would + * imply a tool argument that does not exist (INTERFACE.md §6.4). + */ + model: "Model", + effort: "Effort", + effortOff: "off", + noModels: "No models are declared in the provider configuration.", + addCurrentView: "Add current view", + addCurrentViewWhy: + "Include this page's view and selection in the context the agent is told. The preview below is advisory — the message is composed again when it is sent.", + dfmAutoRun: "DFM auto-run", + dfmRun: "Run DFM", + dfmNoPart: "No part is selected, so design-for-manufacture has nothing to evaluate.", + dfmWriting: "Writing the project setting…", + dfmRunning: "Running DFM…", + /** * §7A.2's create affordances. Two, both explicit, and the profile is shown * before it is used — "a user who does not know their session cannot diff --git a/web/src/stream/composerChrome.ts b/web/src/stream/composerChrome.ts new file mode 100644 index 00000000..a4b6644b --- /dev/null +++ b/web/src/stream/composerChrome.ts @@ -0,0 +1,162 @@ +// Copyright 2026 The Hephaestus Authors +// SPDX-License-Identifier: Apache-2.0 +// +// Composer session chrome, projected from existing routes (issue #13). +// +// The composer is still a thin client of `server/`. This module owns the +// *decisions* about what the chrome may show, so a component cannot invent a +// house model name or a thinking level the wire never offered: +// +// * **Model identifiers come from `GET /providers`.** The identifier is the +// provider's own `models[].id`, qualified by the provider id so two rows +// cannot collide. Nothing here mints a product name, and nothing here is +// used as an identifier except those two server fields. The composer +// *projects* the first declared id; it does not offer a Select, because +// `POST /sessions/{id}/prompt` admits `{text, context?}` and no model field +// (INTERFACE.md §7A.3). +// * **Effort is not a session field.** The levels below are Pi's closed +// thinking vocabulary, recorded so a later route can name them without +// inventing a house scale. A picker over them today would write nothing. +// * **There is no Plan mode in the engine.** `[dfm] auto_run` / `run_dfm` is +// the manufacturability equivalent, and it is a *project setting* plus a +// tool — not a per-message flag (INTERFACE.md §6.4). The chrome therefore +// does not grow a Plan toggle that would imply a tool argument that does +// not exist. +// * **No providers.json / no runtime is a named absence**, not a signed-in +// agent. `modelsFrom` returns nothing when the file does not exist, so the +// composer cannot render a picker of models nobody configured. + +import type { ProviderRow, ProvidersDocument } from "../api/providers"; + +/** + * One model the composer may name, as `GET /providers` declared it. + * + * `id` is the **identifier** — the provider's own model id. `name` is display + * text the server already sent; this module never substitutes a house name + * for either field. + */ +export interface ComposerModel { + readonly providerId: string; + readonly id: string; + readonly name: string; + readonly reasoning: boolean; +} + +/** + * Pi thinking levels. Closed, and offered only for a model that declared + * `reasoning: true` on the providers document. + */ +export const EFFORT_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"] as const; +export type EffortLevel = (typeof EFFORT_LEVELS)[number]; + +const EFFORT_SET: ReadonlySet = new Set(EFFORT_LEVELS); + +/** Whether a value is inside the closed effort vocabulary. */ +export function isEffortLevel(value: unknown): value is EffortLevel { + return typeof value === "string" && EFFORT_SET.has(value); +} + +/** + * The wire key for one model: `providerId/modelId`. + * + * The model id alone is the identifier the provider declared; the provider + * id qualifies it so two rows cannot share one option. Neither half is a + * house name. + */ +export function modelKey(model: ComposerModel): string { + return `${model.providerId}/${model.id}`; +} + +/** Parse a `modelKey` back into its two server fields. */ +export function parseModelKey(key: string): { readonly providerId: string; readonly id: string } | null { + const split = key.indexOf("/"); + if (split <= 0 || split === key.length - 1) return null; + return { providerId: key.slice(0, split), id: key.slice(split + 1) }; +} + +/** + * The models `GET /providers` declared, in document order. + * + * Returns `[]` when the configuration file does not exist, is malformed, or + * lists no models — the named absence, not a defaulted house model. A provider + * marked `available: false` is still listed: unavailability is a fact the + * row already carries, and dropping it here would silently substitute a + * neighbour. + */ +export function modelsFrom(document: ProvidersDocument | null | undefined): readonly ComposerModel[] { + if (document === undefined || document === null) return []; + if (!document.config_exists || document.config_malformed) return []; + const out: ComposerModel[] = []; + for (const row of document.providers) { + for (const model of row.models) { + if (model.id === "") continue; + out.push({ + providerId: row.id, + id: model.id, + name: model.name === "" ? model.id : model.name, + reasoning: model.reasoning === true, + }); + } + } + return out; +} + +/** The first declared model, or `null` when there is nobody to pick. */ +export function defaultModel(models: readonly ComposerModel[]): ComposerModel | null { + return models[0] ?? null; +} + +/** The effort options a given model actually supports. */ +export function effortOptionsFor(model: ComposerModel | null): readonly EffortLevel[] { + if (model === null || !model.reasoning) return ["off"]; + return EFFORT_LEVELS; +} + +/** + * Whether the composer may render the model/effort projection. + * + * False when the runtime is missing (`agent_unavailable`) or when the + * providers document names no models. A chip over an empty set — or a + * Select that wrote nothing — would read as a signed-in agent that is + * not there. + */ +export function showModelChrome( + agentUnavailable: boolean, + models: readonly ComposerModel[], +): boolean { + return !agentUnavailable && models.length > 0; +} + +/** + * The DFM chrome state. Closed at three: + * + * * `chip` — a part is selected and `GET /parts/{part}/dfm` answered, so the + * two §6.4 controls (auto_run toggle + Run DFM) can project that document; + * * `absent` — no part is selected, and the chrome says so rather than + * offering a control that writes nothing; + * * `hidden` — the runtime is missing, or the document has not arrived. The + * composer does not invent a DFM setting, and it does not put DFM chrome + * on the `agent_unavailable` refusal. + */ +export const DFM_CHROME = ["chip", "absent", "hidden"] as const; +export type DfmChrome = (typeof DFM_CHROME)[number]; + +export function showDfmChrome( + agentUnavailable: boolean, + part: string | null, + hasDfm: boolean, +): DfmChrome { + if (agentUnavailable) return "hidden"; + if (part === null) return "absent"; + return hasDfm ? "chip" : "hidden"; +} + +/** A provider row's models, for tests that build a document by hand. */ +export function modelsOf(row: ProviderRow): readonly ComposerModel[] { + return row.models.map((model) => ({ + providerId: row.id, + id: model.id, + name: model.name === "" ? model.id : model.name, + reasoning: model.reasoning === true, + })); +} diff --git a/web/src/stream/composerContext.ts b/web/src/stream/composerContext.ts index 813eedf1..722fd8f9 100644 --- a/web/src/stream/composerContext.ts +++ b/web/src/stream/composerContext.ts @@ -126,11 +126,15 @@ export function chipsFor(state: WorkspaceState, hiddenLabels: readonly string[]) * so an envelope carrying only navigation tokens is collapsed here rather than * sent for the server to collapse. (The server collapses it too; agreeing costs * one condition and means the wire shows what the model gets.) + * + * `added` is the explicit "Add current view" set (issue #13). `view` alone + * never names a reference; once the operator adds it, it does. */ export function envelopeFor( state: WorkspaceState, hiddenLabels: readonly string[], dropped: ReadonlySet, + added: ReadonlySet = new Set(), ): ContextEnvelope | null { const kept = (key: ContextMember): boolean => !dropped.has(key); const envelope: { @@ -172,12 +176,17 @@ export function envelopeFor( } if (kept("focus") && state.focus !== null) envelope.focus = state.focus; + // `view` is always present as navigation, but it does not *name* a + // reference on its own — a workspace with only a camera token is still + // the blank canvas. An explicit "Add current view" (issue #13) is the + // operator saying the view *is* the reference, so it counts then. const namesAReference = envelope.part !== undefined || envelope.artifact_ref !== undefined || envelope.selection !== undefined || envelope.hidden_labels !== undefined || envelope.section_plane !== undefined || - envelope.focus !== undefined; + envelope.focus !== undefined || + (added.has("view") && envelope.view !== undefined); return namesAReference ? envelope : null; } diff --git a/web/test/stream/composer.test.tsx b/web/test/stream/composer.test.tsx index 609579ce..d9809994 100644 --- a/web/test/stream/composer.test.tsx +++ b/web/test/stream/composer.test.tsx @@ -21,8 +21,19 @@ import { describe, expect, it } from "vitest"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { Composer, COMPOSER_STATES, DISABLED_REASONS } from "../../src/components/stream/Composer"; import { CONTEXT_MEMBERS, type ContextMember } from "../../src/api/sessions"; +import type { ProvidersDocument } from "../../src/api/providers"; +import type { DfmDocument } from "../../src/api/types"; import { refreshKeys } from "../../src/api/refresh"; import { keys } from "../../src/api/queries"; +import { + EFFORT_LEVELS, + defaultModel, + effortOptionsFor, + modelKey, + modelsFrom, + showDfmChrome, + showModelChrome, +} from "../../src/stream/composerChrome"; import { CHIP_ORDER, chipsFor, envelopeFor } from "../../src/stream/composerContext"; import { DEFAULT_STATE, type WorkspaceState } from "../../src/state/workspace"; @@ -32,9 +43,50 @@ function stateWith(patch: Partial): WorkspaceState { return { ...DEFAULT_STATE, ...patch }; } +function providersDocument(overrides: Partial = {}): ProvidersDocument { + return { + status: "ok", + config_path: "/tmp/p/.heph/providers.json", + config_exists: true, + config_malformed: false, + file_mode: "0600", + file_mode_private: true, + credential_allowlist: [], + auth_source: null, + auth_source_linked: false, + egress_acknowledged: [], + adopted_sources: [], + credential_sources: [], + attach: { attached: true, config_path: "/tmp/p/.heph/providers.json", generation: 1 }, + providers: [ + { + id: "heph-fake", + kind: "openai_compatible", + name: "Fake", + models: [{ id: "heph-fake-model", name: "Heph Fake Model" }], + source: "project", + health: "accepted", + last_observed_at: null, + available: true, + unavailable_reason: null, + }, + ], + ...overrides, + }; +} + /** The composer inside a query client, as `StreamPanel` mounts it. */ -function markup(props: Partial> = {}): string { +function markup( + props: Partial> = {}, + seeded: { providers?: ProvidersDocument; dfm?: DfmDocument } = {}, +): string { const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + if (seeded.providers !== undefined) { + client.setQueryData(keys.providers(), seeded.providers); + } + if (seeded.dfm !== undefined) { + client.setQueryData(keys.dfm(seeded.dfm.part), seeded.dfm); + } return renderToStaticMarkup( { const dropped: ReadonlySet = new Set(["part"]); expect(envelopeFor(stateWith({ part: "tread" }), [], dropped)).toBeNull(); }); + + it("lets an explicit Add current view make the view a reference", () => { + // Navigation tokens alone are still the blank canvas. Adding the view + // is the operator saying the camera token *is* the reference. + const added: ReadonlySet = new Set(["view"]); + const envelope = envelopeFor(DEFAULT_STATE, [], NOTHING, added); + expect(envelope).not.toBeNull(); + expect(envelope?.view).toBe(DEFAULT_STATE.view); + for (const key of Object.keys(envelope ?? {})) { + expect(CONTEXT_MEMBERS as readonly string[]).toContain(key); + } + }); }); describe("the chip row", () => { @@ -276,4 +340,140 @@ describe("the DOM contract", () => { expect(chipRow).not.toBeNull(); expect(chipRow?.[1] ?? "").not.toContain("data-source"); }); + + it("keeps the existing composer selectors when chrome is present", () => { + const html = markup({}, { providers: providersDocument() }); + expect(html).toContain("data-composer=\"\""); + expect(html).toContain("data-composer-input"); + expect(html).toContain("data-context-chips"); + expect(html).toContain("data-composer-send"); + expect(html).toContain("data-context-add-view"); + }); +}); + +// --------------------------------------------------------------------------- +// issue #13 — session chrome, still a thin client +// --------------------------------------------------------------------------- + +describe("session chrome from GET /providers", () => { + it("uses the provider's own model id as the identifier, never a house name", () => { + const document = providersDocument(); + const models = modelsFrom(document); + expect(models).toHaveLength(1); + expect(models[0]?.id).toBe("heph-fake-model"); + expect(modelKey(models[0]!)).toBe("heph-fake/heph-fake-model"); + expect(modelKey(models[0]!)).not.toMatch(/smith|arche|composer-1/i); + }); + + it("names no models when the configuration file does not exist", () => { + expect(modelsFrom(providersDocument({ config_exists: false, providers: [] }))).toEqual([]); + expect(showModelChrome(false, [])).toBe(false); + }); + + it("hides the model projection when the runtime is missing", () => { + const models = modelsFrom(providersDocument()); + expect(showModelChrome(true, models)).toBe(false); + const html = markup( + { + agentUnavailable: true, + attach: { + attached: false, + config_path: "/tmp/p/.heph/providers.json", + generation: 1, + cause: "no_provider_config", + }, + }, + { providers: providersDocument() }, + ); + expect(attribute(html, "data-disabled-reason")).toBe("agent_unavailable"); + expect(html).not.toContain("data-composer-model"); + expect(html).toContain("data-context-add-view"); + }); + + it("renders the declared model id as a projection, not a picker, when a runtime is attached", () => { + const html = markup({}, { providers: providersDocument() }); + expect(attribute(html, "data-composer-model")).toBe("heph-fake-model"); + expect(attribute(html, "data-composer-provider")).toBe("heph-fake"); + // §7A.3's prompt body is `{text, context?}`. A Select here would write + // nothing and read as hosted-chat chrome. + expect(html).not.toMatch(/ { + const plain = defaultModel(modelsFrom(providersDocument())); + expect(effortOptionsFor(plain)).toEqual(["off"]); + const reasoning = defaultModel( + modelsFrom( + providersDocument({ + providers: [ + { + id: "heph-fake", + kind: "openai_compatible", + name: "Fake", + models: [{ id: "reasoner", name: "reasoner", reasoning: true }], + source: "project", + health: "accepted", + last_observed_at: null, + available: true, + unavailable_reason: null, + }, + ], + }), + ), + ); + expect(effortOptionsFor(reasoning)).toEqual(EFFORT_LEVELS); + const html = markup( + {}, + { + providers: providersDocument({ + providers: [ + { + id: "heph-fake", + kind: "openai_compatible", + name: "Fake", + models: [{ id: "heph-fake-model", name: "Heph Fake Model" }], + source: "project", + health: "accepted", + last_observed_at: null, + available: true, + unavailable_reason: null, + }, + ], + }), + }, + ); + expect(html).toContain("data-composer-effort-absent"); + expect(attribute(html, "data-composer-effort")).toBe("off"); + }); +}); + +describe("the DFM chip is the engine equivalent, not a per-message flag", () => { + it("shows the two §6.4 controls only when a part's DFM document is in hand", () => { + expect(showDfmChrome(false, "tread", true)).toBe("chip"); + expect(showDfmChrome(false, "tread", false)).toBe("hidden"); + expect(showDfmChrome(false, null, false)).toBe("absent"); + expect(showDfmChrome(true, "tread", true)).toBe("hidden"); + }); + + it("names the absence when no part is selected and does not fake DFM chrome", () => { + const html = markup(); + expect(html).toContain("data-composer-dfm-absent"); + expect(html).not.toContain("data-dfm-auto-run-toggle"); + expect(html).not.toContain("data-dfm-run"); + }); + + it("hides DFM chrome on the agent_unavailable refusal", () => { + const html = markup({ + agentUnavailable: true, + attach: { + attached: false, + config_path: "/tmp/p/.heph/providers.json", + generation: 1, + cause: "no_provider_config", + }, + }); + expect(html).not.toContain("data-composer-dfm-absent"); + expect(html).not.toContain("data-dfm-auto-run-toggle"); + expect(html).toContain("data-context-add-view"); + }); });