Frontend: apps/desktop
apps/desktop is a second React workbench in the same workspace, built from the v0.1 design. It is intended to replace apps/web, and it is what the Electron shell loads. apps/web still owns the root path until SCIENCE_AGENT_WEB_DIR is changed; both front ends are served by the same control API and share one token key, so switching between them needs no second sign-in.
1. Stack and relationship to apps/web
- React 19, Vite,
@vitejs/plugin-react, plain CSS; no router, no state library, no UI kit — the same constraints asapps/web. - Markdown through
react-markdownandremark-gfmonly. - Types come from
@sciencediscovery/schemathroughsrc/api/types.ts, which re-exports them withimport type. That re-export is what keeps the schema barrel out of the browser bundle; adding a value import there would pull the whole catalog intodist. apps/desktopdepends on no service and on no other app. The architecture checker treatsapps/*as hosts, so this direction is the allowed one and packages may never reach back into it.
2. Source layout
| Path | Purpose |
|---|---|
src/main.tsx |
entry: consume #token=, then mount |
src/App.tsx |
boot gate (auth / loading / offline / wizard / shell) and the three-column assembly |
src/local-access-token.ts |
fragment to localStorage["sciencediscovery-token"], then strip the fragment |
src/api/ |
client.ts, stream.ts, models.ts, sessions.ts, settings.ts, remote.ts, types.ts |
src/app/use-workspace.ts |
all app state and every write; the only place that owns ordering |
src/app/use-loaded.ts |
the read-on-mount, reread-after-write hook every settings page shares |
src/app/bootstrap.ts |
the two startup decisions: connection state, and which model to adopt as default |
src/app/session-order.ts |
the sidebar's order rule and which Session a launch opens, kept pure |
src/app/panel-width.ts |
the right panel's width arithmetic — the drag, the two bounds, the fold into a viewport — kept pure |
src/app/use-panel-width.ts |
the width as state: the remembered value, the one the window currently allows, and the pointer drag between them |
src/app/file-tree.ts |
folding one path per file into a directory tree — a node per level, directories first, name order within each group; kept pure |
src/app/preview-tabs.ts |
the right panel's tab placement rule, kept pure |
src/app/settings-format.ts |
the settings pages' value conversions (proxy policy options, Runner state wording, the allowlist box), pure |
src/app/use-language.ts |
the interface language as state: one subscription that re-renders its caller when the language changes |
src/app/remote-format.ts |
the execution machines' value conversions (destinations, key fingerprints, reachability, usability, the machine allowlist), pure |
src/app/resource-format.ts |
a machine's reported resources as bars and numbers (disk, memory, load, uptime, NPU cards), pure |
src/molecular.ts |
whether an artifact is a molecular or crystal structure, and which format it is; pure, and free of any Mol* import |
src/app/tool-io.ts |
a tool's input and output split for display: one labelled section per value, by the shape the value has rather than the name it was given; kept pure |
src/run-stream/ |
model.ts (state shape, text merging), reducer.ts (event fold), permission.ts (which requests are still open, and which a grant would cover) and replay.ts (a finished run rebuilt from its events, and where it goes in the transcript) |
src/views/ |
one file per surface: Sidebar, SessionBar, Conversation, AssistantTurn, Composer, WorkspacePanel, StructureViewer, SettingsDialog, SetupWizard, ModelForm, plus dialogs |
src/views/settings/ |
the settings dialog's five pages, one file each, plus rows.tsx carrying the shared row, switch and loading frame, RemoteHosts.tsx carrying the machine list and the Project allowlist, and RunnerResources.tsx the resource, NPU, ssh_config and key-browser panels |
src/text.ts |
the active language, its store, and the TEXT proxy every component reads |
src/text/zh.ts, src/text/en.ts |
every user-visible string in the two languages; Text is typeof ZH, so the English dictionary is checked key for key against the Chinese one |
src/styles/ |
the design's cascade, split at the prototype's own section markers |
3. Server communication
Requests go through ApiClient, which injects authorization: Bearer <token> and turns a non-2xx into an ApiRequestError carrying the server's own error, code and details. PUT /api/settings is a whole-object write, so setGlobalModel() always reads first and sends every existing override back with the one field changed; anything omitted would be erased through store.replaceGlobalSettings.
Streams use fetch plus body.getReader(), never EventSource, because the token has to travel in a header. SseFrameDecoder frames on the blank line, ignores : keep-alives, and holds a partial frame until its terminator arrives — a chunk boundary can land anywhere, including between \r and \n. Frames carry id: <n>, which is the ?after= replay cursor; a reconnect resumes from the largest one seen rather than replaying the whole run.
The two stream entry points differ in what they mean:
| Call | Meaning |
|---|---|
POST /api/sessions/:id/messages |
sends one message and streams the run it starts; the server closes the response at the terminal status, so the end of the body is the end of the run |
GET /api/sessions/:id/runs/:runId/events?after=N |
follows an existing run as SSE; the same URL read as JSON is the replay of a finished run, and rebuilding a timeline uses that one because it ends by itself instead of on a stream that has to be closed |
A client disconnect cancels nothing. Only POST /api/sessions/:id/runs/(:runId|current)/cancel stops a run, which is why the composer's stop button is the only way out of a live turn. Leaving a session mid-run is therefore allowed: the run keeps going on the server, and opening that session again replays it and resumes following the live one. Switching away while a turn runs is how a user gets on with something else, so neither the sidebar nor the new-session button is disabled for it.
The 新增会话 button creates the Session at click time with POST /api/projects/:id/sessions, rather than waiting for the first message. The sidebar lists what the server has, so a draft that exists only in the interface makes the button look dead and makes the first message look like it conjured a second Session out of nowhere; creating first means the click, the sidebar and the composer are talking about the same Session from the first second. Sending a first message with no Session open takes the same creation path, so the two entry points produce one Session, not one each; a repeated click while that request is in flight shares the same request. Startup opens the most recently used Session as soon as the first listing arrives, which is the same Session a click on that row would open: without it a launch would begin as a draft beside a conversation the sidebar already shows, and the first message would create a second Session next to it. 新增会话 is the way to start a fresh one. Deleting the open Session returns to the no-session draft, and the next write (a message or an upload) creates one — conjuring a replacement empty Session after a deletion is not this app's call to make.
The 最近 list holds every Session rather than stopping at a fixed count: it takes the height the sidebar has left and, when that runs out, scrolls on its own with a vertical bar on the list's right edge, while the brand, 新增会话 and the settings entry stay put — hiding a Session that still exists reads as having been deleted. The list scrolls on one axis only: overflow-y: auto computes the other axis to auto as well, so one row a little too wide would put a horizontal bar along the bottom; overflow-x is therefore hidden, and the bar itself is a thin 8 px rail.
4. Event-to-UI mapping
| Event | UI |
|---|---|
run.queued, run.started |
run id and model name; the POST that starts a run never returns an id, so it is picked up here |
assistant.thinking.delta, assistant.thinking.snapshot |
the collapsed 思考过程 block; a snapshot replaces, a delta appends, and a truncated snapshot never shortens what is already on screen |
assistant.response.started, assistant.delta, assistant.snapshot |
one body block per model invocation, so a turn interrupted by a tool call renders as two |
assistant.response.settled |
the block stops showing a spinner |
run.status |
terminal-ness, using the same status set the server closes the response on; the run it carries also brings startedAt and finishedAt, which is where the fold's elapsed time comes from |
run.completed |
the persisted message wins over the assembled deltas; the streamed blocks are sealed |
run.failed, run.cancelled |
failure code and cancellation reason in the run status line |
run.history.truncated |
a note that earlier events could not be replayed |
tool.started, tool.completed |
a 工具调用 card, woven between the answer blocks at the index the call was made from |
permission.required, permission.resolved |
a 需要权限 card with three answers, keyed by request id so a redelivered snapshot cannot undo a decision |
artifact.*, plan.*, subagent.*, agent.*, session.updated |
deliberately deferred; counted in a separate set so they do not inflate the unknown-event counter |
Two events need more than a row. Tool calls are placed rather than listed: an AssistantTool records after, the index of the responses entry it followed, with -1 for "before the first". Read the direction carefully: after === i puts the call after the i-th answer, because the value is recorded as responses.length - 1 when tool.started arrives, and at that moment the model has just finished that answer. Treating it as "insert before the i-th" renders a tool card ahead of the sentence it explains. What the index buys is the shape of an agent loop: the model says something, calls a tool and is re-invoked. tool.completed does not repeat the arguments, so the reducer carries them forward from the start event; older records that do ship them again win the spread.
The layout is two sides of a conversation: the reader's own turn sits on the right with a default grey silhouette for an avatar — a shape rather than the character that used to stand for the reader, which read as a role badge — while the model's answer stays on the left under the model name's initial. The user turn's body comes before its avatar in the DOM and the grid places it in the right-hand column with the avatar on the outer edge, so a screen reader and a narrow window reach the text before the decoration. The bubble shrinks to its content and stops at 560 px rather than spanning the column.
Everything a run does between the question and its answer is folded into a single line, and the fold is closed from the press rather than at the end: a hundred-turn run costs one line of transcript instead of a hundred, and the line is there while the run is going instead of appearing once the answer starts. For a message just sent, the pending message is what renders it — a second after the press rather than in the same frame, because a placeholder that lands with the press reads as a canned animation rather than as a receipt, and anything the stream has actually produced is drawn at once. Its title says 正在思考 while the run is live — with a ring turning beside it, the one moving icon in the transcript, so the line says work is happening without the reader having to trust a still glyph — and 排队中 or 等待授权 when the run is waiting rather than working, where the glyph stays still because waiting is not working. Once the run is over the line reads 用时 12 分 3 秒, measured from the startedAt and finishedAt the run carried, and the ring is gone. A run with no measured span, recorded before those times existed, falls back to its status word. The streaming indicator belongs to a response, not to a turn: only the response whose settled is still false spins. Asking "is this the turn's last response" marks every turn, because every turn has a last response of its own.
Two things are deliberately outside the fold. The answer: the last response in the whole run that produced any prose, so the model can be re-invoked a dozen times and the user still watches the sentence they are waiting for grow in place, spinner and all — and, while the run is live, that has to be a response of the newest turn, or the sentence that introduced a running tool call would be shown as the result for as long as the tool runs and then pulled back into the fold. And an unanswered authorization card, which is a question addressed to the reader: a question folded shut behind a summary is a run that appears to have stopped for no reason. A plain question and answer has nothing in between, so it gets no line at all; and a run that left nothing at all — one that opened a turn and streamed no prose, a gateway rejection being the usual way — does not get the model-name row either, only its status line, since the alternative is a second avatar over an empty body.
And a tool's output is not in the run state at all. It is written to a substream of its own, tool-<toolCallId>, and the card reads it once, on first open, from GET /api/sessions/:id/runs/:runId/streams/:streamId/events — the one JSON read among the SSE ones, because it is a different stream. A run replayed with ?after=0 contains no tool.output at all, only the tool.completed trace pointing at the substream, which is why the trace is what carries the pointer. The live response does fan those frames out, and they carry no id: line; they are dropped in a set of their own so they neither count as unknown events nor advance the replay cursor.
Thinking has no persisted form: ChatMessage carries only the final text. So opening a session replays its runs and renders each reconstruction in the place of the answer that run wrote — falling back to the stored message when the replay yields nothing visible, which is what keeps a reconnect that found no events from rendering a blank answer.
Every finished run is replayed, not just the newest, and each is a state of its own: the reducer keys a turn by the number the event carries, and those numbers restart at 1 for every run, so folding two runs into one state would quietly merge the second run's first turn into the first run's. A session that took several turns therefore has one replay per turn — a run interrupted by an automatic wake is replayed on its own side of the wake notice, with its own thinking and its own tool calls, instead of leaving a bare answer behind. Since the turn numbers come from the server and restart per run, two segments of one transcript can both start at 第 1 轮; the numbering is not re-based, because a continuous count would print numbers the server never produced.
Placement is by message: a reconstruction takes the place of the answer its run wrote, and a run that never wrote one — cancelled first — goes after the message that started it. Only a run matching neither is left for the end of the transcript. The run still streaming has no persisted answer yet, so it renders last until the next settle re-reads the session and folds it in with the rest.
The wake notice itself is no longer drawn. An automatic wake carries no user-authored body — the schema keeps the model-facing prompt out of content precisely so a wake is never shown as something the user typed — so its card was a blank strip with an avatar, saying nothing the run below it does not say better. But the message stays in messages all the same: it is where the run the wake started is anchored, and dropping it would send that run to the end of the transcript instead of to the place it happened.
Two questions are asked of a replay, and they are not the same one. Whether it is worth holding at all: a run with no persisted events folds to a state with nothing in it, and holding that would hang an empty turn in the transcript. And whether it may stand in for a stored answer: only an answer can, so a run that failed or was cancelled before saying anything keeps its status line — the whole account of what became of it — while the stored message stays where it is. Losing that distinction is what makes a failed run leave no trace at all.
The right panel is tabbed rather than sectioned. It opens on one tab titled 新标签页 holding the 产物 section and the workspace tree, and the first document opened replaces that tab's content in place — the only tab that is ever overwritten, so looking at one artifact never costs a second tab. A document opened while a document is already showing gets its own tab, which is what keeps a link followed from inside a preview non-destructive. Closing the last tab collapses the panel and leaves a fresh home tab behind; there is no empty tab and no zero-tab panel. Leaving a session discards its open documents, because they belong to that session's workspace.
Both lists come from the service, so both are re-read while a run writes into them: an artifact.upserted or workspace.changed frame asks refreshPanel for a read, throttled by app/panel-refresh.ts — the first frame of a quiet run reads at once, and further frames inside 1.2 s collapse into one read when the window closes. A new artifact therefore appears in 产物 during the reply rather than when it ends, while a tool call that writes file after file still costs one request per window and not one per file. The two halves are read independently, so an artifact listing that fails does not leave the tree on the files it had before the run. A document already open is read again when the listing shows its size or modification time moved (app/file-changes.ts): the tree is only the index, and a report the run rewrites in place would otherwise sit behind its own updated row. The transcript draws nothing for either event; the panel is the only surface that moves.
The panel's width is draggable, from 280 px — below which the tree's names, sizes and ages stop fitting on one row — to 720 px, above which the side column has become the main one and the transcript it was opened to comment on is what gets squeezed. One value drives both places the width appears: App sets --panel-width on .app-shell, the grid's third track is var(--panel-width), and the panel reads the same variable for its own width, so the column and what fills it cannot disagree. The remembered width and the rendered one are deliberately two different numbers: what the user asked for is what goes to localStorage (clamped to the panel's own bounds only), and what is rendered is that folded into what the window can currently show, which leaves a minimum for the conversation column. Folding the remembered value instead would make a narrow window destructive — the ceiling would be written down in place of the width, and widening the window again would leave the panel as narrow as the smallest window it had ever been seen in. The drag itself runs on the splitter's own captured pointer events, which keep arriving after the pointer has left the splitter's six pixels — the panel grows out from under the cursor immediately — and only the width the drag stops at is written to storage, because serializing it on every pointer move would be the one part of the drag that could stutter.
The workspace tree is one row per level: antibody_pipeline/runs/<run>/… folds into a real tree with antibody_pipeline on one row and runs on a row beneath it, rather than one name with the path's slashes written into it. The fold is a pure function, app/file-tree.ts — it touches no DOM, so it is unit-tested directly: split on /, a node per segment, and one directory path reusing one node, so a directory cannot show up twice (grouping by the whole path printed runs again under every <run>). Directories come before files within each level, each sorted by name; a file shows its file name (the reason the 产物 section gives), with the full path left to the tooltip. A directory row's right-hand column is the count of every file below it, recursed to the bottom, so what is inside is known without expanding anything. Expansion is <details open>, open by default, so the panel still shows the whole list at first glance — only with shorter names and a legible hierarchy. Depth costs width, and at 280 px a four-level path has spent it, so the right-hand columns are given up a level at a time: the size first (a directory row never had one, and a file three levels down is being read for its name), then the age (the parent's count and the 产物 section both say it again), which leaves the indent and the name — the whole point of drawing a tree.
The structure browser is one of this panel's previews, not a second kind of window. Molecular and crystal structures (pdb, ent, pqr, cif, mcif, mmcif, mol, sdf, mol2, xyz) are rendered in place by Mol* inside the document tab, and every other document still takes the markdown, JSON or source path. It is not a modal because it is a document like any other: the tab rule already answers "does opening a second one hide the first", and giving this one file type its own presentation would only create two routes to the same document — two routes that would eventually disagree.
Whether a file goes to Mol* is decided in src/molecular.ts, by filename extension first, then media type, then a sniff of the content. A .json name never goes to Mol*: Mol* reads no JSON at all, and the only JSON this platform calls a structure is its own .structure.json atom list, which should preview as a document. A .cif is split once more — one carrying _atom_site.Cartn_x goes to the mmCIF parser, one carrying only _atom_site_fract_x and cell parameters goes to CIF core; feeding the latter to mmCIF yields zero models, so the box says "No models found" instead of showing a structure. Crystallographic files also go through the symmetry-expanding unitcell preset first, because the general preset draws only the asymmetric unit and hides the cell box — two atoms, for rock salt — and fall back to the general preset with the cell box drawn explicitly when the file carries no usable symmetry and the preset declines.
Mol*'s own panels are built for a whole window, and this is a document tab inside a side column that is 360 px wide by default, so the plugin is mounted with every region hidden, and the two strips of controls it draws over the canvas — the animation picker in the top left, the viewport buttons on the right — are hidden with them: none of them is about this box, whose own way in is a click on the model. Dragging the panel wider is not a reason to bring them back — at 720 px the question becomes whether Mol*'s panels are about this box at all, and the answer is still no. That click, or a click on the document's name above it, opens the same view full screen, which is again the box escaping the column: the canvas is not remounted, so the angle the model was turned to is the one it keeps, and Esc and the ✕ both close it.
The panels come back with the full-screen view. The plugin is not rebuilt for it — a second instance would mean a second WebGL context and a second parse of the same file — so the layout is changed on the running plugin instead, through PluginCommands.Layout.Update. That is the only path that both merges the state and emits layout.events.updated, which is what the plugin's own layout component listens for; the four regions are conditionally rendered on showControls, so a value assigned through plugin.layout.setProps() would leave them unmounted with nobody told. The one thing deliberately left alone is isExpanded: Mol* reads that flag as its own full-screen mode, rewriting document.body.style and moving the viewport meta tag into its own container, and this overlay belongs to this app — the page underneath has to stay where it was. The plugin is asked to resize afterwards, because the panels are width the canvas no longer has; the two directions are both needed, since a document opened from a link inside another one is mounted into a tab that is already expanded. A ResizeObserver on the box covers the third way its size changes: a drag of the panel changes the box without any state changing, so nothing in the component would otherwise run, and the model would keep the size it was first drawn at. The observer ignores a zero-sized box — a hidden panel is one, and measuring a WebGL canvas down to nothing and back is how a context gets lost — and it redraws, because a resize without a redraw leaves the new region blank until the next pointer event, which on a still image can be a long time. Full screen also trades the floating name and badge for a real header bar, because Mol*'s panels now own two of the corners those sat in. Rendering is left to Mol*'s adaptive preset — cartoon for a polymer, ball-and-stick for a ligand, the symmetry-expanded cell for a crystal — which is the truthful answer before anyone has chosen, and the only one that does not lie. The badge states exactly two things — the file's format, and the atom count read out of the plugin's state; where there is no source for a number, no number is shown.
Mol* and its dependencies are about 3.2 MB, so this view is its own dynamically imported chunk: it is fetched only when a structure file is actually opened, and the main bundle is unaffected. That is also why it cannot be rendered in this repository's test environment, which has no browser and no WebGL: whatever can be tested is deliberately kept outside it — format detection in src/molecular.ts, and the panel's own decision to render the name as the way in, which a static render reaches through the Suspense fallback without pulling Mol* in.
5. First run and settings
GET /api/models returning an empty list is the first-run condition, because nothing can be sent without a model. The wizard then walks the workspace location, the environment check and the provider configuration in turn, and the model step must pass POST /api/models/:id/test before the main screen becomes reachable. The local service was already started by the shell before this bundle loaded, so the check step does not start it again: it asks the shell for the live backend status and polls the same three items the shell's boot page does (local API, execution engine, optional default model) until they are ready, and only marks a still-pending item failed after three minutes. The workspace step only records the directory the user picks.
The order below is fixed by the API, not by preference: PUT /api/settings normalizes through the live model catalog and drops a modelId naming no existing profile.
POST /api/providers— orPUT /api/providers/:idwhen the base URL already has a provider, so a corrected key does not leave a duplicate behind.POST /api/providers/:id/models—{model}is the only required field; a hand-typed name lands on the same path as a discovered one.POST /api/models/:id/test.PUT /api/settingswith the merged overrides.
The listing button uses POST /api/providers/preview-models, which fetches from the form's endpoint and key and persists nothing — GET /api/providers/:id/models would require saving a half-filled provider first. A gateway that cannot list models is expected; the model name can always be typed.
A preset supplies apiProtocol and apiVariant; only the custom branch asks for a protocol, because a wrong variant against a right URL reads as a broken key.
设置 › 模型 is two blocks: the configured models (each card carrying 测试 and 设为默认, with the current default marked by a tag) and the add-model form. The default is no longer a block of its own at the top of the page — it appears only on the cards. The form prints no sentence under its fields and no "not tested yet" line; its bottom row is three buttons, each doing one thing. 测试 first writes the configuration into the catalog, then calls POST /api/models/:id/test and reports the answer — a connectivity test only accepts a profile that already exists, and writing the same provider and model name twice is idempotent on the server, so testing before saving leaves no duplicate behind; it changes no default and does not close the form. 保存 walks the whole chain — write, test, set as default — and only closes once that passes. 取消 just closes the form and writes no settings (the wizard has no cancel button; without a working model it does not reach the main screen).
The data directory is fixed by the shell before launch, and the wizard's workspace step only records it: no route reports or changes the live data directory, which comes from the service's launch arguments, so editing this field never moves existing data.
The settings dialog is three groups over five pages — 通用 under 系统, model and skills under 智能, network and remote under 连接 — and every page other than 通用 reads its own data on mount through useLoaded. 通用 is this browser's page rather than the service's: its one row is the interface language (简体中文 or English), applied on the pick and stored under sciencediscovery-desktop:locale, the same immediate-apply behaviour as apps/web. The default is Chinese rather than the browser's own preference, because this UI ships for a Chinese-first deployment and an English browser would otherwise open it in English without saying that a setting exists. Nothing in TEXT is read at module scope: TEXT is a proxy over the current dictionary, App subscribes to the store so a switch re-renders the tree, and strings that used to be literals in components or captured in module-level label tables (the notice kinds, the sandbox modes, the run status words, the workspace's relative times, 未命名会话, 你, 第 N 轮) are all dictionary entries now, and even the fold's 展开/收起 hint, which CSS prints from details[open], carries its translated words in data-expand/data-collapse instead of a literal content. <html lang> follows the choice, set before the first paint and on every switch. A section heading stands alone: every page used to print one sentence under its headings explaining what the block was for, and those are gone — the heading is the introduction. A page whose read fails renders the reason and a retry rather than an empty list, because on a settings screen an empty list is a claim about the server and not about the request.
Which layer a write lands in is not uniform, and the difference is not visible from the UI:
| Setting | Route | Why that route |
|---|---|---|
| default model, sandbox network | PUT /api/settings, or the dedicated route |
global, and the whole-object write needs a read-merge-write |
| skills | GET /api/jiuwenswarm/skills, PUT /api/jiuwenswarm/skills/:name, PUT /api/jiuwenswarm/skills-by-id/:skillId, PUT /api/jiuwenswarm/skills-batch |
JiuwenSwarm owns the global switches; ScienceDiscovery bundled skills default to enabled; tasks import their selected enabled bundled packages before the first model turn; managed catalog packages are imported on first enable. Runs never mirror Project/Session selections into those switches. Native mode retains catalog browsing and creation without these switches. |
| installing and editing a Skill | POST /api/skills/import (one SKILL.md or ZIP), POST /api/skills/import-git/inspect, POST /api/skills/import-git, PUT /api/skills/:id, PUT /api/skills/:id/files/:path, GET /api/skills/:id/resources/:path |
技能 draws its own header: 添加技能 offers 从零开始写, 上传技能 and 从 GitHub 导入, and each — like 编辑 — swaps the pane for a sub-page with a back control rather than opening a modal, so the list stays one press away. Imports install into the catalog this app owns rather than the web's Skill Library, which has no desktop surface. A Git import first inspects the repository and then imports each chosen package at the inspected commit; replacing an installed Skill requires the revision the user saw (expectedRevision with overwrite), so an edit made in another window is a 409 rather than a silent overwrite. The editor rebuilds SKILL.md from its fields and therefore sends back license, compatibility, metadata and allowed-tools, which its form does not show. The package-file route can write a file but not delete one, so the editor adds and overwrites only. Closing 设置 bumps an epoch that re-reads the catalog for the composer's / palette. |
| a remote machine's registration, credentials and host key | POST /api/remote-hosts, PUT /api/remote-hosts/:id/credentials, POST /api/remote-hosts/:id/trust-host-key |
credentials only ever travel inward, and the response to a credential write is itself the result of a fresh probe; accepting a host key is a step of its own and cannot be folded into another write |
| which machines a Project may use | PATCH /api/projects/:id (runnerIds) |
it is a field of the Project itself, and it has to be sent whole — it is a complete list, not a delta |
The composer used to carry 会话配置 between the model pill and the paperclip: one button whose only row was 权限模式. It is gone, and with it the Session-level write of approvalMode — the route still exists, but nothing in this app sends it. The one thing that still depends on the mode is the run itself: the server keeps whatever the Session was created with, and a turn that needs an authorization still stops and asks through a permission card.
Idea Tree's parameters — research template, exploration intensity, score direction, maximum depth, maximum nodes — can also be changed for one Session at a time. The idea-tree row under 程序演进实验 in 会话设置 opens the parameters card; the card opens on the deployment settings with this Session's pins applied (and says so on the card); 只用于本次会话 writes ideaTreeOverride through PATCH /api/sessions/:id, carrying the fields that differ from the deployment — re-saving therefore re-sends the pins still in force, while an unpinned field equal to the deployment is not written; 覆盖全局设置 carries only the fields this visit actually changed, and writes nothing when nothing changed. 跟随全局设置 sets it to null and the Session inherits again. The value is read where a research is created (services/api/src/idea-tree/research.ts calls resolveIdeaTreeSettings(sessionId)), so a change applies to the next research started there and never to one already running; the run snapshot deliberately does not freeze it, because that path clears it, and a freeze would only record a promise nothing reads. The scope is system and session only: a Global or Project write has the field stripped, so one deployment-wide edit cannot silently become every Session's research parameters.
What is absent from the panel is absent by request, not because the capability is gone: settings no longer carries the specialists, connectors, permissions and feedback pages, 通用 carries only the interface language (the recorded data directory it once showed is gone, not a setting), network keeps only the sandbox policy — 无网络, 域名白名单 and 开放网络: the allowlist carries a domain box and a 保存 of its own, because the service refuses an empty allowlist and the box is grey and disabled in the other modes, so picking that mode only stages it and the save writes the mode and the domains together; 无网络 and 开放网络 are written on the pick, with 开放网络 still asking first; the private-network switch, the egress route and the save warning are still not offered, and the proxy server list is no longer read here — remote keeps only the Runner and no longer offers the 测试连接 button on its cards (connecting, trusting a host key and saving credentials still probe), the composer has no 会话配置 button, and sessions are no longer archived or restored from this app: the sidebar row menu is 重命名 and 删除. The session bar no longer hangs a ⋯ menu either — renaming is the double-click on the title, or the row menu in the sidebar.
The remote page's execution machines
GET /api/runners returns the local machine plus every remote one. The local entry is synthesized by the server (its id is always local): it always exists and cannot be deleted or re-addressed, so 远程 leaves it out of the Runner cards — the page manages machines other than this one, and a card for the machine the app is already running on would be the one row none of the page's actions apply to. It stays on the allowlist below, where "may this Project run here" is a real question and the local machine is a valid answer. Every row that remains stands for a remote machine record. The two remote kinds travel different paths: ssh has this host hold an SSH connection and deploy the Runner across it, while direct talks to a Runner already running elsewhere, needing only an address and an access token.
Registering an SSH machine has to get past the host key, and that is not a failure. A first connection answers 409 SSH_HOST_KEY_UNTRUSTED, and a machine trusted before that now presents a different key answers SSH_HOST_KEY_CHANGED; both carry details.hostKey (algorithm and fingerprint) and details.hostId. The UI presents it as a question, printing the fingerprint verbatim as ssh-ed25519 · SHA256:… — the line OpenSSH itself prints and the user compares — and only replays the failed action once it is accepted. No fingerprint, no question: asking someone to accept a key without saying which one is asking for a blind yes. When a probe fails but did obtain a key, the server returns the stored machine with hostKey.trusted === false; that is still a question, so the same card handles it rather than reporting a failed save.
Credentials are write-only: only the fields present in PUT /api/remote-hosts/:id/credentials are overwritten, absence keeps the stored value, and null forgets it. So the credential form opens with every box empty, its placeholders say "keep the stored one", and the fact that a machine has a password or key stored is stated by the machine card as a tag — a value that cannot be read back cannot pretend to be. A private key is given as a path, because the machine that has to read it is the API host; when the key is in the user's own hands instead, the form generates a pair on the spot and shows only the public half, with a note saying where it has to be installed.
Connecting and disconnecting are two different contracts: POST /api/runners/:id/disconnect always succeeds, while connect returns 200 only when ready and otherwise answers 503 with the failed status as its body. A failed connect therefore comes with no reason in it — the reason is in the connect log. While a connect is in flight the UI polls GET /api/runners/:id/connect-log every 800 ms and lays the lines out under the card, fetching once more after a failure so the last lines stay on screen naming the cause, and clearing the log on success. Those lines are operator diagnostics, not UI copy, so they are shown as they arrive.
A connected machine reports what it has. runnerStatus.resources carries the workspace disk, memory, CPU count, 1-minute load, uptime and a capture time, and a machine card folds all of it behind 机器详情. Every reading is drawn as a bar with the number beside it, and a reading the machine did not report is stated as unknown rather than drawn as zero — the disk is the case that matters, since "0 GiB used" is a claim the server never made. The disk bar turns warning-coloured below a fixed 5 GiB free, not a percentage: what the Runner needs is room for an essentials image plus two conda environments, and that is an absolute quantity no matter how large the disk is. 更新于 carries the capture time, so a reading that has stopped updating is visible as one.
NPU cards appear under the same fold, one row each: name, health, HBM used against total, AI Core percentage, temperature and power. Cards a sandbox cannot open are marked with the reason the driver gave, shown verbatim. The tick boxes are the machine's npuDevices selection; unusable cards cannot be ticked unless they already are, because removing a card needs no judgement while adding one does — which is the same rule the PUT /api/runners/:id/npu-devices route applies. The list is read from GET /api/runners/npu once for all machines rather than per machine record, so a failing read cannot take the machine list down with it, and nothing is written until 保存勾选 is pressed: the ticks are a draft, and 放弃修改 throws them away.
An SSH machine can also be filled in from the host's own ~/.ssh/config. Picking an entry resolves it through GET /api/remote-hosts/ssh-config?alias= and copies the result into this app's own fields — host name, port, user, identity file. The copy is the point: the product does not then keep reading ssh_config, so what the form shows is what will be used. An identity file the API host cannot read is reported as such rather than silently dropped from the form.
Both the registration form and the credential form take a private key as a path, because the machine that has to read it is the API host, and both offer a browser onto that host's filesystem — GET /api/remote-hosts/key-files?path=&offset=. Which machine is being browsed is worth stating plainly: it is the API's, not the browser's and not the remote target's. The listing is paged and directory-by-directory, with no filtering, since what NFS or a mounted share puts at any given path is not knowable from here.
Below it, 哪些机器可以被项目使用 is the open Project's own runnerIds. It is a complete list rather than a hint about defaults: an empty array is an explicit decision (nothing, the local machine included), and a project with no list is read through the older remoteRunnerHostIds field, where the local machine was implicitly available. The list offers only machines that can actually run — the local one always, a remote one only when it is ready and either direct with an address and a token or ssh reporting a Linux platform, since the deployed Runner bundle is a Linux one — because a checkbox for a machine that cannot run only buys a run that fails at the last step. Unusable machines stay in the Runner list above, where the reason is visible. Every toggle writes the whole list and then rereads it from the server, so an id the server refused cannot linger on screen.
6. Development and tests
pnpm --filter @sciencediscovery/desktop dev # 127.0.0.1:5174, /api and /health proxied to 4310
pnpm --filter @sciencediscovery/desktop test # tsx --test tests/*.test.ts
pnpm --filter @sciencediscovery/desktop build # -> apps/desktop/dist
pnpm --filter @sciencediscovery/desktop exec vite preview # built output on 4174, same proxies
localStorage is per origin, so the token has to be injected once per front end: open http://127.0.0.1:5174/#token=<token> the first time. The token key is shared with apps/web, so on the same origin no re-injection is needed.
Serving this app at the root path instead of the built-in one is a restart with SCIENCE_AGENT_WEB_DIR=apps/desktop/dist; the static directory is read at boot.
Tests cover the transport (bearer header, 401 classification, SSE framing including comment frames and split chunks), the reducer (thinking and body folding, snapshot-versus-delta, truncated snapshots, terminal close, counters, permission requests and their resolution, tool traces, and the run times the fold's elapsed line is measured from — recorded once and never moved by a later snapshot), the replay layer (folding a log into a closed state, the three anchors a reconstruction can land on, and which runs are worth holding at all — an empty log is not, and a run that failed before answering keeps its status line without hiding the stored message), the transcript merge itself (a replayed run replacing its own answer in place, a run with no replay keeping its persisted answer, a run with no answer following the message that started it, a replayed run's unanswered authorization rendering disabled, the streaming run staying last, a message just sent showing its own text at once while the run's placeholder waits its beat, and a wake notice drawing no card while the run it started keeps its place), the fold (its line saying 正在思考 while the run works and 用时 … once it stops, a ring turning on that line only while the model is actually working and never while it is queued or over, falling back to a status word with no measured span, the thinking and the tool calls going inside it, and an unanswered authorization or a running tool call's sentence staying outside it), the tool card's two pure layers (the primary field picked by name rather than position, a single argument shown as its bare value, a labeled result split into sections with the leading text kept as a residual, the residual labelled Error when the call failed, and runner placeholders dropped rather than shown as data), the workspace tree (a node per segment, no directory repeated under one parent, directories before files in name order, a directory's count recursed to the bottom, and empty segments and doubled slashes dropped), the panel's width arithmetic (drag direction, both bounds, a window too narrow for both columns, and the ceiling that leaves the transcript its minimum), the tab placement rule, the startup decisions (empty catalog, an existing default is not rewritten, a default naming a deleted profile is replaced), the sidebar's recency order, which Session a launch resumes (the most recently used one, and nothing over a Session already open), structure detection (the precedence of extension, media type and sniffing, and the two .cif parsers), the settings surface as it is offered now — five pages under three groups, with 通用 carrying the language select and nothing else, the allowlist box read as entries (newlines and commas both separate them, blank lines dropped), vocabulary the network and remote pages no longer own (the private-network switch and the egress route, the Runner's 测试连接), an add-model form with no sentence under any field and three buttons in order (测试, 保存, 取消 — the last one absent when the caller has its own way back), and a composer row that is a model pill and a paperclip with no 会话配置 between them — the execution machines' value conversions (both host-key failures, destinations, reachability, usability, the local machine left out of the cards, the allowlist and toggling it) and their resources (a reading the machine did not report stated as unknown, the disk warning at a fixed free-space floor, NPU cards that cannot be added but can be removed), the language store (Chinese unless chosen otherwise, a switch reaching every top-level section of TEXT including its functions, subscribers firing once per real change and not at all on a no-op, and 通用 offering both languages with the one in force selected), and the composer's model pill and paperclip.
pnpm build emits a separate chunk of about 3.2 MB for the structure browser (about 880 kB gzipped) against a main bundle of about 500 kB; only the former is downloaded when a structure file is opened, so that large chunk in the build output is not a startup cost.
7. Conversational configuration cards
apps/web and apps/desktop share the form, credential-draft, preview and confirmation
logic in packages/configuration-ui. Hosts supply locale, API error identity, terminal
record presentation and API actions. The desktop app/use-configuration-requests.ts
loads and polls the current session, merges monotonic versions and rejects late responses
from another session. A session without chat messages can still show a pending card.
Exact destination consent, the dedicated credential channel, independent security-policy consent and final manual save stay separate. Saving refreshes settings and follows the server-created continuation without resending the user's message. Terminal receipts appear once at their persisted notice. Archived/evidence-only sessions and failed refreshes block writes.
The shared renderer includes frontend compatibility for Memory, MCP, model/provider, security-policy and proxy modules. This does not register backend capabilities or imply that those modules are deployed. Corresponding backend adapters and endpoints are still required. When merging branches that edit the old Web card paths, retain their changes in the shared package instead of reintroducing two implementations.
Both hosts send independent security-policy acknowledgments to
POST /api/sessions/:sessionId/configuration-requests/:requestId/security-consent,
with the displayed revision, target digest and explicit acknowledgment. Security-policy
capabilities from #758 and
proxy.default from #734
require their corresponding backend and this route. This change registers neither
capabilities nor routes, and sends no security-consent request unless a server-projected
card requires it and the user explicitly acknowledges and confirms. If that card's route
is unavailable, the request fails closed; endpoint consent and ordinary Apply cannot
substitute for security consent.
test/journey-desktop-configuration.spec.ts drives the actual public API and desktop entry
through timeout preview, save, reload and refusal in both languages and a narrow window.
It makes no live model or external-service calls. Missing browser/runtime prerequisites
are a coverage gap, never a pass; component tests do not replace rendered screenshot review.
The pinned Playwright environment discovers both language cases automatically through
test/helpers/e2e.ts, @mocked and category:e2e; no per-file package-script entry is
needed. Its status:reviewed, model:mock and isolation:global tags include both
language cases in the default pnpm ci:e2e / PR plan, in the serialized standard-config
shard. It owns its temporary records and restores the timeout settings it changes.
Use pnpm test:list --slice e2e to inspect the shared plan without executing it;
listing tests does not verify the browser journey.
From the repository root, prepare the pinned environment once, then list this file:
node test/sync-e2e.mjs --write
npm --prefix .e2e ci
.e2e/node_modules/.bin/playwright install chromium
npm --prefix .e2e run test:list -- journey-desktop-configuration.spec.ts
To execute it, first start an isolated stack from the same committed revision
using the E2E isolation instructions.
Set E2E_BASE_URL to that stack's API URL and E2E_API_TOKEN to its generated token;
never point this test at a personal instance. The spec starts and stops its own desktop
Vite entry on port 4178, so keep that port free. Then run from the repository root:
npm --prefix .e2e run test:mocked -- journey-desktop-configuration.spec.ts
The journey reporter saves step screenshots and report.md / report.html under
.e2e/journey-reports/ (or E2E_JOURNEY_REPORTS when set).
Related documentation
- Web frontend — the current root front end
- Control plane — the routes and their contract
- Configuration reference —
SCIENCE_AGENT_WEB_DIRandSCIENCE_AGENT_AUTH_TOKEN