Skip to content

Runtime Seams

matthew edited this page Aug 29, 2026 · 1 revision

Runtime seams

The mechanisms that make a feature a deletable plug-in: the feature registry, the dock, the IPC bridge, keybindings, project systems, debugging, multi-window, worktrees, notifications, the workspace ribbon, modal windows, logging, model runtimes and API documents. Read Architecture first.

4. The runtime seams

These mechanisms are why a feature is a deletable plug-in. Know them before adding or changing a feature.

4.1 Feature registry (tab views, ribbons + status)

shared/angular/services/feature-registry holds a multi-provider FeatureRegistry keyed by tab-type string. Each feature contributes a descriptor:

interface FeatureDescriptor {
  readonly type: string; // the tab-type identifier and registry key, e.g. 'terminal'
  readonly view: Type<unknown>; // mounted per tab; MUST declare tabId + isActive inputs
  readonly ribbon?: Type<unknown>; // contextual ribbon shown while the tab is active
  readonly status?: Type<unknown>; // status strip shown while the tab is active
  readonly documentPanel?: Type<unknown>; // lean editor surface for a document well, if any
  readonly chrome?: Partial<{ ribbon: boolean; status: boolean }>; // e.g. settings = full-bleed
}

A feature exposes <f>.feature.ts = provide<F>Feature() returning makeEnvironmentProviders([provideFeature(descriptor), …eager initializers]), and adds one line to config.ts. The shell (content-host, ribbon-strip-container, root chrome gating) is purely registry-driven — it looks the active tab's type up in the registry via ngComponentOutlet and contains no @switch on tab type and no feature-type string.

NG0303: any view mounted by the registry MUST declare tabId and isActive inputs (FeatureViewInputs), or Angular throws at mount — even if the view ignores them.

welcome is the exception: it is shell-slotted (root mounts <app-welcome-screen> directly, it is not a tab type), which is why it has no descriptor.

Chrome belongs to the active view, never to a registry. The ribbon and the status strip are both mounted for the active tab and destroyed on a tab switch, so neither can describe a view the user is no longer looking at. They differ only in how they reach view state:

  • A ribbon is created in the shell's injector, so it drives the view through a per-feature command registry the active view registers a handler with (ApiExplorerCommands, ContainersCommands, …).
  • A status component is created through the view's OWN injector, published while the view is active by createViewInjectorRegistrar({ isActive }) into ViewInjectors (keyed by tab id). It therefore injects the view's per-tab services directly (ApiWorkspace, Workspace, CodeStatus) with no forwarding registry, no owner keys, and nothing to clear. A worktree container tab's sub-views share one tab id, and the selected checkout's injector is the one published.

⛔ Do not push a view's status into the shared StatusBar. That registry is for ambient segments only — app-wide facts that outlive any tab, like the running-container count. An owner key there survives the view that set it, which is exactly how a closed editor left Ln 1 Col 1 LF UTF-8 stranded over Mission Control. View status goes in the feature's status component.

The strip renders the view region (feature status, or the active tab's title as a fallback), then the ambient region (StatusBar segments, the language-server drop-up, the notification bell). Segments are always composed from app-status-strip-segments / app-status-strip-segment — a feature never emits status markup of its own. A document well additionally has its own strip (DockStatusStrip, fed by DocumentStatus) describing the active document in that well; the window strip describes the active tab.

4.2 The dock (per-tab panel catalogue + layout)

shared/angular/{services,components}/dock is a generic docking framework that names no feature panel. A tab specialises its dock by providing a DockBlueprint via the DOCK_BLUEPRINT injection token: createLayout() returns the initial DockNode tree, and panels[] is the catalogue the DockPanelRegistry seeds from. The workspace tab provides WORKSPACE_DOCK_BLUEPRINT, the repository tab REPOSITORY_DOCK_BLUEPRINT — each cataloguing its own feature panels. defaultLayout() (pure ID strings) stays in the dock; the panel components are contributed by the blueprint.

Two drag gestures, and the difference is what moves. A group's title bar (or a document well's grip, standing in for the title bar it does not have) docks the active panel alone; the group's tab rail docks the whole group, every tab travelling with it — tool stacks and document wells alike. A tab itself keeps its own CDK drag (reorder within a strip, move between same-role strips), so the rail gesture only starts on the rail's own surface. Both run through DockDrag — begin() for a panel, beginGroup() for a group — and resolve against the same compass, a group docking by its stack's role exactly as a panel docks by its own. A group move is a single DockState commit (one undo step), and a group released over nothing stays where it is: the floating layer and pop-out windows hold single panels, so neither can take a group.

4.3 IPC — a generic bridge

The preload exposes a dumb pub/sub transport, so it can live in shared without naming features:

// src/shared/api/bridge.ts — the only IPC contract in shared
interface Bridge {
  invoke<T>(channel: string, ...args: unknown[]): Promise<T>;
  send(channel: string, ...args: unknown[]): void;
  on(channel: string, listener: (...args: unknown[]) => void): () => void; // returns unsubscribe
}
// exposed as window.bridge by src/shared/electron/preload.ts — imports zero feature code

Per-domain slices live in src/shared/api/<domain>-channels.ts (a channel enum + payload types + a <Domain>Client interface). A per-domain @Service() client in shared/angular wraps window.bridge and exposes a nullable ops object, so consumer call-sites don't change when the transport does. The "am I in Electron?" probe everywhere is window.bridge !== undefined.

window.host (src/shared/api/host.ts) is the static/synchronous counterpart — platform and display startup facts the async bridge can't carry before the first paint (read pre-bootstrap in main.ts).

Security is preserved and non-negotiable. The renderer is untrusted: every main-process handler validates its arguments, an invoke to an unregistered channel rejects, and send is driven by main. The generic transport changes only who names the channel, not the validation guarantees.

4.4 Path aliases

tsconfig.json paths map @shared/* → src/shared/* and @features/* → src/features/*, honoured by the Angular esbuild builder, tsc, and the preload/main esbuild steps (pointed at the tsconfig via --tsconfig). Use aliases for cross-unit imports; keep ./sibling relatives only within a directory. Aliases make files location-independent, so moves are cheap.

4.5 Keybindings (keyboard accelerators)

shared/angular/services/keybindings holds a generic Keybindings registry that names no feature. A view registers its chord→command bindings under its tab id in the same activation lifecycle where it registers its ribbon command handler, and clears them on deactivation (deactivate) and disposal (forget). Only the active scope dispatches. The shell installs the sole listener: root has one window:keydown HostListener → keybindings.dispatch, at the bubble phase so an embedded editor (Monaco, Milkdown, xterm) consumes the keys it owns first — only chords it leaves unhandled reach the router, and the allowlist never intercepts incidental typing. Chords use the platform-neutral Mod modifier (⌘ on macOS, Ctrl elsewhere). In the terminal, bind only Mod+Shift chords — a bare Mod is Ctrl on Windows/Linux and collides with the shell's own control codes.

The editing chords do not come from here, and nothing may claim them. ⛔ No feature contributes a menu entry bound to ⌘Z, ⌘⇧Z, ⌘X, ⌘C, ⌘V or ⌘A. Ever. CoreMenu carries Undo/Redo/Cut/Copy/Paste exactly once, as native roles, and Chromium routes a native role to whatever holds focus — so every control serves its own chord, which is how this behaved before there was a menu at all. A feature entry claiming one of those accelerators replaces the core's (AppMenu.withoutClaimed) and then runs the tab's command wherever the caret happens to be. That is the whole bug, and it shipped three times.

Two facts generate every failure mode here, and neither is negotiable: on macOS the application menu is the only thing binding those chords into the window at all (remove the Edit section and they are simply dead), and a menu accelerator is consumed before the renderer sees the keydown (so no renderer-side listener can win one back). A previous round tried to reconcile the two with a focus-routing layer on dispatch; it was deleted, because the chords are not the menu's to route. A feature wanting a clipboard or history command puts it on a ribbon button — pressing one is an explicit instruction to act on that view — and leaves the chord alone.

editing-chords.contract.spec.ts enforces this by reading the feature sources, because a jsdom test cannot see the native-menu path and so every earlier round's unit tests passed while the app was broken. Select All is the one renderer-side exception: EditingChords.handleSelectAll serves ⌘A for a plain text box from the window listener and bails on defaultPrevented, so any editor that binds ⌘A to its own selection model still wins. It is a fallback, not a claim.

4.6 Project systems, capabilities & .studio

The directory workspace is language-agnostic: it never hard-codes an ecosystem. A ProjectSystem provider (shared/electron/project-system, e.g. dotnet, node) turns a workspace root into a ProjectModel and declares a capability descriptor — actions (Build/Clean/Rebuild…), buildConfigurations, a target axis, and a debug adapter. A provider never infers run configurations from a root: what to run is authored, not guessed. The model (with its capabilities and kind) travels to the renderer over ProjectChannel.ModelLoad; adding an ecosystem means adding a provider, never touching the shell or ribbon.

Three renderer seams carry the active workspace's state to the root ribbon. Each is an app-level singleton — the ribbon lives above the tabs, so it can never inject a tab's scoped services. They resolve the active tab's workspace instead: WorkspaceCapabilities/Builds are registered into by the active tab's per-workspace services (mirroring how a tab registers its build handler), while StudioConfig reads the active root from the ActiveWorkspace seam. Injecting the scoped Workspace here is a bug — its root is never set at the root injector, so .studio would never load.

  • WorkspaceCapabilities — the active model's capabilities + provider kind. The Solution group gates Build/Clean/Rebuild on actions; the Target group's configuration/target selectors are driven by buildConfigurations/target and hidden when absent. An undeclared action is not rendered, not greyed — and the group goes with the last of them, so an ecosystem with no build step (Python) shows no dead buttons. Actions may be per root where the root decides them: Node declares the actions its manifest's conventional build/clean/test scripts back. Capabilities are authoritative; a root with no provider falls back to discovered tasks so Gradle/Make still build.
  • Builds — dispatches to the active workspace's BuildRunner: build() (the first discovered build task, the fallback for a root with no capability model), runConfiguration() (a .studio run configuration compiled to a command), and runAction() (any declared action, compiled per ecosystem — the path every declared Build/Clean/Rebuild takes). Discovered tasks back the Solution group only — they never reach the Run dropdown. Runs are concurrent: activeRuns lists every in-flight run, cancel(runId) stops one and cancelAll() stops the lot; the ribbon's Start becomes a Stop split-button whose menu stops a single run. Cancelling kills the task's whole process tree (POSIX process group, taskkill /T on Windows) with a SIGKILL escalation — signalling only the wrapping shell leaves children holding the output pipes open, so the run never appears to end. A run configuration streams into its own Output channel (run:<id>) so parallel runs stay readable; build/test/action output shares build.
  • StudioConfig — the active workspace's .studio persistence.

.studio (shared/electron/studio, platform-neutral model in shared/api/studio.ts) persists run configurations per project: workspace.json is shared and committed (the run configurations); workspace.user.json is git-ignored and holds only transient selections (last configuration, target, build configuration). The main-process StudioStore owns atomic reads/writes and seeds a .gitignore entry on first write; it never authors run configurations itself. The renderer reloads on external edits through the directory-watch feed, guarding against its own writes. The Run group's dropdown lists exactly the configurations workspace.json declares — a workspace with none has nothing to run — and the Configure dialog edits them. A configuration that names members is a compound: starting it starts each member as its own run, in parallel (expandRunConfiguration resolves them, tolerating unknown members and cycles), so each member stays individually stoppable.

Authoring is either by hand or by agent — never inferred. The Configure dialog's Auto-configure and Ask agent buttons dispatch to the active workspace's own agent (RunConfigurationAgent resolves the active tab's live AgentHost), so the work runs in the agent the user already has: its transcript appears in the Agent panel and Mission Control, and it inherits write confinement, per-tool policy, and the audit log. The agent writes through three project/editor-surface MCP capabilities — list_run_configurations (read-only, auto-allowed), save_run_configurations, and delete_run_configurations (gated writes) — handled in the renderer against StudioConfig, so the Run dropdown and the dialog update as the agent works. Every write is validated as a whole (findRunConfigurationIssues: duplicate ids, members naming nothing, compound cycles) and refused with a reason the agent can act on. The dialog is modal, so it renders the agent's own pending permission prompts inline (AgentRequestCard) — otherwise a run blocked on "Allow Bash?" would stall behind it, unanswerable.

4.7 Debugging (DAP)

Debugging is built on the Debug Adapter Protocol, mirroring the LSP subsystem's shape. DAP is not JSON-RPC — it shares LSP's Content-Length framing but uses a {seq, type, command, request_seq} envelope, and (unlike LSP) the adapter's initialized event fires after the client sends launch. The client, session manager, adapter registry, and provisioner live in shared/electron/debug; the Debugger app-level seam and per-workspace DebugSession mirror Builds/BuildRunner.

  • Adapters differ in transport, hidden behind one surface. DapClient speaks DAP over a DapTransport — StdioTransport for a spawned process (netcoredbg), or TcpServerTransport/TcpClientTransport for a debug server reached over TCP (js-debug). Everything the manager drives goes through the DebugAdapterConnection interface, so the renderer treats every adapter as one linear session.

  • js-debug is a compound session. js-debug is not a single adapter but a server hosting a tree of DAP connections: a parent the debuggee is launched on, and one child target session per process, each started via a startDebugging reverse request. The real debugging happens on the targets. JsDebugSession hides the whole tree behind DebugAdapterConnection: it answers the parent's initialized/startDebugging internally, surfaces the first target's initialized (so the renderer sends breakpoints once), routes requests to the active (last-stopped) target, replays breakpoints to later targets, and reports terminated once every target has. The Node project system declares debug: { adapter: 'js-debug' } and resolves the launch target to the package's main entry (confined to root; no build — Node is interpreted).

  • Adapters are provisioned, not vendored. DebugProvisioner (mirror of LspProvisioner) first locates an adapter (override → project-local node_modules/.bin → PATH), then ensures a downloadable one: it fetches a pinned, SHA-256-verified archive per ${platform}-${arch}, extracts it under userData/debug-adapters, and caches it. Each platform entry carries its own URL and checksum — upstream may publish different releases per platform (e.g. netcoredbg dropped osx-amd64 after 3.1.3, so Intel Macs pin an older release than Apple Silicon).

  • .NET uses netcoredbg, never vsdbg. vsdbg (the Microsoft C#/VS debugger) is licensed for use only inside Microsoft's own products — shipping it here would violate its EULA. netcoredbg (Samsung, MIT) is the license-clean adapter and is what the dotnet project system declares (debug: { adapter: 'netcoredbg' }).

  • Launch targets resolve in main. The renderer never builds a project or locates an artifact. DebugLaunchResolver (DebugChannel.Resolve) delegates to the owning project system's resolveDebugTarget, which is confined to the open workspace root; for .NET it compiles the project (defaulting to the Debug configuration so symbols exist) and reads its TargetPath from MSBuild. DebugSession folds the returned program/cwd into its DAP launch request.

  • Breakpoints persist per developer through SettingsStore (debug.breakpoints); adapter-reported verification is layered on transiently and never persisted. The gutter and current-execution-line marker live in the shared code-document core so both the well and standalone code leaves show them.

4.8 Multi-window (pop-out panels)

Studio is one Angular application in one main window, plus secondary OS windows that are always viewers over state owned elsewhere — never second owners.

  • WindowManager (main) owns every BrowserWindow: a kind-aware registry (main | popout | modal, the last being the modal windows), per-kind bounds persistence (window-state.json, off-screen bounds re-centred; modals persist nothing), and applyWebContentsSecurity on every window it creates or adopts. Push-style IPC still targets the main window by default; invoke-style handlers reply to their caller and are window-agnostic.
  • One pop-out mechanism, one chrome. The dock group title bar offers pop-out (cards icon) through the per-view PopoutPanels seam, handled by PanelPopout for every panel: a same-renderer auxiliary window — one of the two window.open targets the security guards allow (AUX_PANEL_URL, the other being the modal windows' MODAL_WINDOW_URL); everything else is still denied (#116). The child shares the renderer process, so the panel component renders into the child's document with the owning view's injector and keeps its real services; AuxiliaryWindows mirrors stylesheets and theme attributes into open children. No per-panel data plumbing exists — do not add mirrors or per-window IPC routing for popped panels. The terminal panel works this way too: its panes live in the opener's JS context wherever their DOM renders, so PTY output keeps flowing over the main window's bridge, and a popped pane re-attaches through the same scrollback replay as any remount (the pop-out never disposes a PTY — panes are persistent).
  • Pop-out windows are real docks. A pop-out window is titled after the workspace (or repository) and hosts a full DockContainer via PopoutDockHost, whose component providers scope a fresh set of dock services (state, geometry, drag, floating, auto-hide, focus, reveal, a handler-less PopoutPanels) to the window — including DOCUMENT overridden to the child's — while the panel registry, tab context, and every panel's backing service resolve through the parent chain to the owning view. Window layouts are ephemeral (DockBlueprint.key is optional; no key → no persistence). Closing a window returns every panel it hosts to the main-dock position it left; closing a panel inside a window closes it exactly as the main dock would.
  • Window-scoped CDK. PopoutDockHost also provides OverlayContainer, the outside-click dispatcher, ScrollDispatcher, DragDropRegistry, and a fresh-measuring ViewportRuler subclass (windowScopedCdkProviders(), shared with modal windows). CDK resolves these through the triggering element's injector (createOverlayRef / createDragRef), so menus and overlays opened from a popped panel render in ITS window (and close on outside clicks there), CDK tab drag-reorder tracks the child document, and positioning measures the child viewport. Main-window triggers keep resolving the root instances — never route overlays across windows by hand.
  • Keyboard accelerators per window. Accelerators enter through one bubble-phase keydown listener per window: the shell's (Root.onWindowKeydown) for the main window, and one PanelPopout attaches to each pop-out, dispatching with the OWNING view's scope (Keybindings.dispatch(event, scope)) so chords act on that view even while another tab is active in the main window. Bubble phase keeps editor-first semantics — an embedded engine consumes the keys it owns before the router sees them.
  • Drag gestures. A tool tab dragged beyond its window's edge tears out into a new pop-out at the drop point (DockDrag.registerExternalDrop; the requested position rides the window.open features string, parsed and display-clamped by the main process). Dropped onto an open pop-out window, it joins that window's dock; dragged out of a pop-out over the main window, it returns to the position it originally left. Hit-testing uses the child windows' own screen rects and only engages outside the source viewport, so overlapping windows never shadow in-window drops; in-window void drops still float, and document tabs never tear out.
  • Move, not clone. A panel (and a terminal session) renders in exactly one window; closing a pop-out docks the panel back to the stack/index it left. Closing the main window quits the app; pop-outs never gate lifecycle. DockReveal focuses a popped panel's window instead of touching the dock. Run configurations may declare presentation: 'window' to pop the terminal panel on launch.
  • Cross-window sync rides SettingsStore.onExternalChange (localStorage storage events, which fire only in non-writing windows — the built-in echo guard); Theme and Settings re-apply external changes live.

4.9 Worktree containers (multi-branch workspaces)

A worktree is Studio's product concept, deliberately NOT git's worktree feature: a container directory holding independent full clones of one repository (GUID-named checkout directories, each on its own branch) plus .studio/worktree.json (the container's self-identification and checkout registry — unrelated to a checkout's own committed .studio run configurations). The model, defensive parsing, and strict checkout-id validation live in @shared/api/worktree; the disk/git mechanics in the Electron-free WorktreeOperations (promotion moves the entire working copy — including its .studio — into the first checkout, in place and rolled back on failure; removal goes to the OS trash, never a hard delete), wrapped by WorktreeManager behind WorktreeChannel.

  • The host decides what a tab is. The directory tab type mounts DirectoryHost, which resolves the opened folder's kind (worktree → workspace → folder, container first) before any view exists. Single mode renders one DirectoryView exactly as before; container mode renders one kept-alive DirectoryView per visited checkout — mount-all/hide-inactive one level down, created lazily on first activation — so switching checkouts is purely visual and every checkout keeps its documents, terminals, agent conversation, and debugger state.
  • WorktreeSession (host-provided, one per tab) is the shared container state: descriptor, per-checkout statuses, the active-checkout selection, add/remove mutations, and host root ownership — roots the host registered (the container, each opened checkout) are "claimed", and a sub-view whose root is claimed releases local state on destroy (Workspace.releaseFolder) instead of closing the root. Never close a claimed root from a view.
  • Sub-view identity is the view scope (tabId alone, or tabId:checkoutId): it keys keybinding scopes, pop-out dispatch (DockTabContext.tabId), and status-bar owners, so a container's sub-views never collide on scope-keyed registries. Anything needing the REAL tab id (agent-host registration, document ownership, ActiveWorkspace) still uses the raw input.
  • Layouts key on the container: a checkout's dock reads its layout pick from the container path (DockTabContext.presetRoot), so all checkouts of one container share one pick. The Worktrees panel is catalogued for every workspace tab but synced into the layout only while the tab is a container; checkouts are labelled by alias or branch, never by GUID.

4.10 Notifications (toasts + the status-strip centre)

shared/angular/services/notifications is the app-wide notification store. app-toast-host (slotted in root) renders its toast stack bottom-right above the status strip; the status-strip bell opens its bounded history flyout. Raise events with Notifications.notify():

  • Severity (info|success|warning|error) drives the icon, colour, and default stickiness: an error toast stays until dismissed — a failure must never vanish silently — everything else auto-dismisses after notifications.toastDuration (hover pauses the timer).
  • Route picks the surfaces: default (toast + history), history-only (record without an interruption — used when the source is already on screen), toast-only (transient state that would be stale as a record, e.g. an agent ask; retract it with dismissByKey).
  • Coalescing key — a repeat outcome replaces its live toast in place (a retried push), keyed per source and root so parallel workspaces never coalesce each other's outcomes.
  • Main window only, by design. Pop-out windows share the renderer, so an action taken in a pop-out raises through the same singleton and its toast renders in the main window. Never add per-window toast hosts or notification IPC.
  • User-initiated endings stay silent. A cancelled run, a stopped agent turn: no toast — ending it was the user's own action. Anything ending on its own always surfaces (or lands history-only when its surface is visible).
  • Sources today: Repository (network ops + the commit → Push offer, wired at the mutate funnel so every commit surface is covered), BuildRunner (run/build exits, with a Show-terminal action), Agent.onStatus (attention-aware: history-only while the owning tab or Mission Control is active), and AgentRequestToasts (pending asks, behind notifications.agentRequestToasts; the title-strip inbox itself is gated by notifications.agentRequestsInTabList).

4.11 Workspace ribbon (command seams + layouts)

A contextual ribbon is rendered by the shell, not inside the view it acts on, so it resolves the root injector. A workspace tab's state — its document well, its repository, its search — lives in per-view services provided by directory-view, which the ribbon therefore cannot inject. Every workspace ribbon control routes through a registration seam instead: the active view registers a handler while it is active, the ribbon calls the seam, and the seam forwards to whichever view is registered (or does nothing when no directory tab is active).

  • WorkspaceDocumentCommands — File group: save, saveAll, plus canSave/hasUnsavedChanges signals that gate the buttons.
  • WorkspaceSourceControlCommands — the everyday git actions (commit, push, pull, open in source control), with hasRepository gating the whole Source Control group.
  • WorkspaceFind — reveals the multi-file Search panel.
  • SourceControlCommands — the repo-global remainder: fetch, stash, and the worktree promotion pair. Deliberately small; it shrank as the panels took over the selection-scoped actions.

Ribbon or panel? The ribbon carries only actions that are repo-global and act on no selection — Commit (which sets the stage rather than committing), the network trio, Promote. Anything acting on something the user can see and select — a branch, a stash, an individual change, the diff layout — belongs on that thing's panel, as a row action or a PanelToolbar button.

A panel owns its tool strip by declaring ownsToolStrip: true on its DockPanel and rendering <app-panel-toolbar> itself; the dock then omits the generic strip (whose DEFAULT_TOOLS are presentational stubs). The Repository rail owns branch creation and the stash actions; the Commit panel owns the diff-layout toggle and Discard All. Both are catalogued in REPOSITORY_DOCK_BLUEPRINT, which the workspace merges into its own catalogue — so a panel flagged there is flagged for every surface that shows it.

Two seams, one group. WorkspaceSourceControlCommands and SourceControlCommands are both registered by directory-view and both consumed by the ribbon's Source Control group; the split is historical (the first was the workspace's everyday facade, the second the retired repository view's wider one) rather than a design boundary. Merging them is a fair future cleanup.

Adding a workspace ribbon control? Add a method to the matching seam and register it in directory-view — never inject a view-scoped service into a ribbon. A control that appears to do nothing at runtime is almost always this mistake.

Editor commands reach well documents by document id. CodeDocumentPanel registers an EditorCommandHandler with EditorCommands under its document id (activating and standing down with the well's active document, forgetting it on destroy) exactly as a standalone code tab registers under its tab id. This is what lets the ribbon's Edit group — the clipboard and history pairs, Find, and the tidying pair (Format / Code Cleanup) — and its save actions act on the focused well document; without the registration they resolve no handler and are silent no-ops. The tidying pair lives in Edit, not behind Solution's Clean: it tidies a document, not a build, and Solution disappears entirely for an ecosystem with no build step.

Layouts (shared/angular/services/layouts) name which panels exist and where they dock.

Every layout is the user's own — there are no built-in layouts. What ships is a set of templates (directory-view/layout-templates.ts: Default, Source Control, Agentic Engineering), which are starting points only: they are listed nowhere but the layout manager's picker, are never applied directly, and are never the default. Choosing one copies its tree into a layout the user then renames, saves over and deletes like any other. On a first run every template is seeded as a real layout, so the list is never empty and nothing behaves specially; the seed is guarded on the definitions having never been written, so deleting every layout is respected rather than undone. With no layouts at all the dock falls back to the first template's tree — unlisted, uneditable, and unreachable the moment a layout exists.

The persistence model is deliberately narrow — three things and nothing else:

  • Definitions are app-wide, agnostic to the loaded workspace (layout.presets).
  • Each workspace root remembers its active pick (layout.active-presets).
  • One layout is the app-wide default (layout.default-preset) — the View button's target, and what a root falls back to before it has a pick. With none chosen the first layout stands in. Deleting the default clears the choice rather than stranding it.

(The storage keys keep their original preset spelling: the concept was renamed, not re-homed, and an existing user's layouts must survive the rename rather than being seeded over.)

Session layout is ephemeral by ruling: closing, moving, or resizing panels writes nowhere, and every launch, layout switch, and reset re-applies the showing layout's saved definition. Save As is the only write, and there is no separate Save — layout names are unique, so saving over an existing name replaces that layout in place, keeping its identifier so the default marker and every root that picked it stay pointed at the same layout. The active view registers a LayoutSession (exactly as it registers its build runner) through which the ribbon captures the current layout and re-seeds the dock.

A layout is a best case, not a demand. It names every panel the user wants when everything it mentions is there; DockPanelAvailability (view-scoped, beside DockState) says which of those the open folder can actually back, and the dock passes over the rest at render time — the tab is not drawn, and a slot that can show nothing takes no width (its splitter goes with it) until its panels return. The layout tree is never rewritten to match, which is the point: a layout applied to a plain folder still asks for the Solution Explorer, so saving from that session cannot quietly lose it. The view's panel syncing is therefore additive only — it adds a panel no layout named (Debug on a session start, Search on the find accelerator) and never takes one away.

4.12 Modal windows

Every modal is a real window. app-modal does not draw an overlay over the window that raised it; it opens a child BrowserWindow and renders its content there, with the raising window blurred and inert behind it (ModalBackdrop + app-modal-backdrop, refcounted so a modal over a modal keeps it up). It is the pop-out mechanism with a different intent — the second (and last) window.open target the security guards allow, MODAL_WINDOW_URL; the main process gives it dialog chrome (hiddenInset, no minimize, resizing and closing only when the modal asks) and parents it to the opener. Modal bounds are never persisted: a modal opens sized to what it currently holds.

  • Content is a marked template. Callers write <ng-template appModalContent>, never plain projection: the template is instantiated in the modal's window under ModalWindowHost, whose providers scope the CDK layer (windowScopedCdkProviders(), shared with PopoutDockHost) and DOCUMENT to that window. That is what makes a menu, an overlay, or a drag inside a modal happen in ITS window. Bindings and handlers still act on the component that declared the template — the content keeps the view's services, exactly as a popped-out panel does. The marker is required because modal content routinely contains templates of its own (a CDK menu panel); an unmarked query would seize one. <ng-content> inside the template works, which is how the markdown form modal carries each caller's projected fields across.
  • Sized by intent. A dialog is measured: the window fits its content and re-fits as the content changes. expandable makes it filling instead: a user-resizable window whose content takes the room it is given, at height (or a share of what is available). The measured path needs a non-stretching content wrapper, or the measurement is just the window's current height. Either way the size is held within minWidth/minHeight/maxWidth/maxHeight (rem, and the window's real resize limits) and within 90% of the space available — the window it is raised over, or the display when it is free-standing, since a hidden opener may be far smaller than the modal standing in for it. A stated minimum outranks the available space: a modal that cannot fit is better oversized than unusable.
  • A modal raised from inside a modal is DECLARED inside it. Nest the <app-modal> within the outer modal's appModalContent template and it belongs to that window: it resolves the host's DOCUMENT and ModalBackdrop, so it opens from that window, parents to it, and dims it. Declared as a sibling it is instead raised from the window its component lives in — which for the welcome screen is the HIDDEN main window, and attaching a child to a hidden window (or handing focus back to it as the child closes) puts that window on screen. adoptModalWindow refuses a hidden parent as a backstop, but the declaration is what makes the dialog dim the right window.
  • Measuring a window is timing-sensitive, in two ways. The host view is rendered synchronously (detectChanges) before it is measured and observed: an unrendered host measures as nothing, which would collapse the window to its minimum with no observer attached to correct it. And the window's chrome is measured ONCE and remembered — a window part-way through a resize reports a fresh outer size against a stale inner one, so the difference is not chrome at all (it can be negative), and a refit landing on that frame would shrink the window inside its own content.
  • Theming crosses the window boundary by copy. Custom properties whose value at the call site differs from the document root's are written onto the modal window's body — not its root, whose style attribute ChildWindowStyling mirrors from the opener and would overwrite. App-wide tokens are left to resolve live from the mirrored stylesheets, so a theme switch reaches an open modal.
  • Dismissal is the window's, plus the backdrop's. A modal window closes on Escape (handled in its own document), on its own close button, and on a click on the backdrop over the window behind — the last belonging to the topmost modal alone, which is why ModalBackdrop stacks the open modals rather than counting them. A modal that is not dismissable ignores all three.
  • The welcome screen is the special case. With no tabs open it IS the application: ShellPresence hides the main window, and the welcome modal is freestanding — no parent (a child of a hidden window is not displayed at all on macOS), no backdrop, and centred on the display rather than on its hidden opener. Closing that window closes the application through the main window's own quit protocol. The main window is shown by the renderer (WindowChannel.Show/Hide), never on ready-to-show, so a cold start never flashes an empty IDE; a main-process timer shows it anyway if the renderer never speaks for it, retired the moment it does. Two related traps: maximizing a window that has not been shown SHOWS it on macOS, so a persisted maximized state is applied when the window is first shown (WindowManager.showWindow), not when it is created; and a window paints its backgroundColor until its content arrives, so a modal passes the colour its panel will land on (bgcolor in the features) rather than flashing black.
  • Child-window lifetime has two traps, both already sprung: pagehide fires when a child's initial about:blank load commits, so a close is only believed once window.closed agrees (watchChildWindowClosed, shared with pop-outs); and orphaned children are closed when the main window STARTS a load, never after it finishes — the incoming renderer opens its welcome window within milliseconds of booting, and cleaning up after that would take it with it.
  • The inline overlay survives as a fallback for environments with no window opener (unit tests, headless runs), which is why modal.html/modal.scss still exist. It is not a supported presentation: nothing may rely on modal content being in the raising window's DOM. E2E drives modals through modalWindow(app) (e2e/helpers.ts), not through the main page.
  • The tab-scoped document-conflict prompt is not a modal and stays in-document by ruling: it belongs to a tab's content area, not to the window.

4.13 Logging (structured, per-session)

Studio has an application-wide structured logging service (epic #395); its records populate the System Monitor tool's per-session log audit and a per-session JSONL file. New code is expected to log — this is not optional plumbing, it is how the running app is observed.

  • How to log.
    • Main process: import the shared singleton — import { logger } from '@shared/electron/logger' — and call logger.info/debug/trace/warn/error(source, message, ...details). There is exactly one instance; never new Logger().
    • Renderer: inject the service — private readonly log = inject(Log) (@shared/angular/services/log/log) — and call log.info/debug/trace/warn/error(...) with the same shape.
  • Source (the "Where"). A stable component/service name, optionally Name.method — 'GitManager', 'TerminalManager.spawn', 'containers.view'. Keep it stable; the audit filters on it.
  • Severity discipline (log like a production app):
    • trace — fine-grained flow: notable operation entry/exit, per-item detail, IPC payloads.
    • debug — diagnostics for investigation: resolved paths, chosen config, cache hits, state transitions.
    • info — notable normal events: lifecycle, workspace loaded, container started, agent session created, file saved, build started/succeeded.
    • warning — recoverable or unexpected-but-handled: retry, fallback, missing optional resource, permission denied.
    • error — failures and every caught exception.
  • Exceptions are always logged as errors. Every catch that handles a real failure logs logger.error(source, 'what failed', error) (or log.error). The Error's stack is preserved in the record — pass the error object as the last argument, don't stringify it. This complements Conventions › Error handling — catch, narrow, log the error, then rethrow/handle.
  • Global safety net (already wired). Main-process uncaughtException/unhandledRejection are logged as errors in main.ts; renderer uncaught errors/rejections reach the audit through Angular's provideBrowserGlobalErrorListeners() → ErrorHandler → console (captured by the ConsoleForwarder). Don't swallow errors silently anywhere.
  • No raw console.* in new code. Use the logger. The ConsoleForwarder captures renderer console.* as a baseline (coarse console source), but main-process console.* is not captured at all — main code must use logger. Logging never throws (the API swallows its own failures), so it is always safe to call.
  • Instrument meaningful events, not every line — the test is "would an operator want this row in the audit?".

4.14 Local model runtimes (the AI Model Manager)

The AI Model Manager tab (epic #407) owns the local model lifecycle: installing the runtime, starting and stopping its server, and pulling, inspecting and removing model weights. Ollama is the first — and currently only — implementation.

  • The seam is ModelRuntime (shared/electron/contributions/model-runtime/model-runtime.ts): a provider slot covering status, the installed/running/inspect/remove reads, pull, and the server lifecycle (installation, install, start, stop, diskUsage). A second runtime is a new implementation plus a line in the contribution's factory; nothing upstream changes. The view reads its heading from the runtime's displayName, so it never names Ollama.
  • Everything is absent-safe by contract. A query against a runtime whose server is not running resolves to an empty result, a null, or an unavailable status — never a throw. "Not running" is an ordinary state the manager renders, not an error; it is the state the user opened the tab to fix.
  • Detection prefers a system install (OLLAMA_EXECUTABLE → PATH → platform locations) over Studio's managed copy, so a user who already runs the runtime never downloads a second one. The managed path mirrors LspProvisioner: pinned version, hard-coded SHA-256, version-scoped directory.
  • Studio only stops a server it started. One the user is running is reachable but not ours to kill; ModelRuntimeStatus.startedByStudio is how the view knows to disable the control rather than offer one that silently does nothing. A spawned server is registered with the pid journal.
  • Status is polled, not watched — Ollama has no event stream — but only while a view is subscribed (ref-counted, as System Monitor does with sampling) and pushed only on genuine change.
  • The catalogue (ModelCatalog) is a source slot in the shape of the package-management registries: a bundled, offline curated list plus live Hugging Face search. Source failures are isolated and named, so losing the network degrades the list rather than emptying it.
  • The boundary with connections (#254) is deliberate and load-bearing. This feature owns the runtime and the weights; connections own endpoint config, auth, and which model ids reach the agent picker. ModelConnections is the only crossing: it writes a pulled model's id (and its real context window from /api/show) into local Ollama connections, and removes it again on delete. It acts only on explicit installs and removes, never as a background sweep, so it cannot undo a user's own picker edits.

4.15 API documents (the API Explorer's file)

The API Explorer tab is a document, and its document is a file: *.api.json, holding the environments, collections and requests of one API workspace (ApiDocument, in the shared API contract). Two things identify it, and both matter:

  • The name suffix routes it. FileOpener sends a *.api.json to an API Explorer tab, the way it sends a .md to the markdown editor. Only the name is consulted, so routing costs nothing — a plain .json file is never touched.
  • The moniker inside verifies it. ApiFiles.parse requires "kind": "onixlabs.studio.api" and a version this build can read. A *.api.json that is someone else's schema, malformed, or from a newer Studio is declined, and the opener falls through to the text editor — which is where a user needs to be to fix it. A file is never half-loaded.

ApiFiles is the shell-side seam, the direct analog of Workspaces for directory tabs: it opens (or re-activates) the tab and stashes the parsed document under its id for the view to consume once on init. It names no feature — it opens a tab type the shell already knows.

The workspace has two modes, and the difference is where edits go. Untitled, it auto-saves to the session store on every edit, so a scratch workspace survives a restart and never prompts — there is no file for it to be out of step with. Bound to a file, the file is the only thing that matters: edits mark the document dirty, the tab wears the dot, Save writes it, and the view registers with UnsavedWorkRegistry so closing the tab or the window asks first. Save As appends the suffix when the user does not type it (replacing a bare .json), so a saved document is always one that can be opened again.

Clone this wiki locally