The Svelte workspace

How Svelte renders the main chat and specialist transcripts with shared components, groups adjacent tool calls, and merges older pages.

intermediate13 min read

You leave half a sentence in one chat, open a second chat, and come back to find the sentence still in the message box. Meanwhile the first chat may have a new reply from the server. Both appear on the same screen. They get there by different routes, and App.svelte brings them together.

In this chapter

  • Find the state behind the sidebar, transcript, message box, and dialogs.
  • Follow a conversation update from the browser’s watcher to the rendered text.
  • Explain how your draft survives a reload and how Send handles a lost reply.
  • Trace the files Vite builds to the routes Hono serves.

App.svelte owns the view you’re in

Inside the workspace
  • App.svelte

    Holds the selection, sidebar summaries, model and profile lists, and open panel. It keeps a Transcript for the selected chat and a Drafts map for unsent messages.

    • Transcript

      Transcript joins the recent snapshot window with older pages and builds rows. TranscriptView renders those rows and live activity in both the main chat and specialist transcripts.

      • ChatEntry

        Uses SentMessage for user bubbles, Markdown for assistant text, and ToolActivity for results without a matching call.

      • ToolGroup

        A single call gets its own row. Adjacent calls share a disclosure that opens to the individual activities in call order.

      • WorkspaceApproval

        Shows the arguments in a pending workspace request and lets you approve or deny it.

      • DelegateTranscript

        Opens a specialist’s own transcript. While it is collapsed, the delegateActivity snippet in App can still render WorkspaceApproval cards for pending decisions.

      • WebArtifact

        Shows a saved HTML preview card or a file download card. ChatEntry renders a direct artifact, and App renders a specialist’s handed-back cards below its disclosure.

    • Message form

      App reads the selected draft from Drafts, passes text, attachments, and editing callbacks down, and handles submission.

      • ComposerInput

        Handles the text area, attachments, and the slash menu.

      • RuntimePicker

        Lives in the composer toolbar. Shows the profile, model, and reasoning effort, and shows the destination for a chat with a workspace.

    • Screens and dialogs

      App loads these components on demand. It also prefetches some dialogs after startup.

      • Access

        The locked screen. ChatGPTLogin is a separate dialog for connecting the model account.

      • Settings

        The Account tab holds sign-out, passkeys and the ChatGPT connection when available. Workspace holds Developer’s workspace controls. Extensions holds browser extension switches and registration errors.

      • Routines

        Manages routines for one chat or lists routines across chats.

App.svelte

Holds the selection, sidebar summaries, model and profile lists, and open panel. It keeps a Transcript for the selected chat and a Drafts map for unsent messages.

Select a box to find the component behind that part of the workspace. The groups follow the screen rather than the directory layout.

When you open Pipal, packages/web/index.html puts “Opening workspace…” in the page. The browser entry point, src/main.ts, clears that placeholder and mounts App.svelte, the root component, into #app. From there App decides which screen the tab can show. index.html main.ts

App starts importing enabled UI extensions as the component initializes. On mount, it sends five GET requests in parallel under /api/v1/ at the build’s base path. They fetch models, profiles, conversations, providers/openai/status, and access. After all five succeed, App waits for the extension registry, restores drafts, switches to ready, and resolves the chat from the address bar. App.svelte

If the first startup failure is a 401, App enters locked and the Access screen fetches access again to choose the sign-in form. Other startup failures leave App at unavailable, with a button to retry. The Hono server follows the sign-in request on the host. App.svelte Access.svelte

Once you’re in, the rows at the left and the chat at the center have different jobs. App keeps sidebar summaries and refreshes the selected row when a snapshot arrives. The Transcript instance holds the snapshot and earlier pages. App keeps the selected ID, model and profile lists, and open panel, and derives the active draft from its Drafts map. Runtime settings come from the selected row in an existing chat and from draftSettings in a new one. App.svelte

Open Settings → Workspace and DeveloperWorkspace.svelte loads the server’s choices in the Developer workspace panel. On a fresh install every locationThe place a chat uses for project tools, either the Pipal host, an account reached over SSH, or a Docker project. starts off. An upgrade can carry over a configured SSH or Docker grant. The owner can enable locations and choose Default for new chats when more than one is enabled. This machine runs commands as the Pipal service user, with access to chats and the saved model login. SSH machine and Docker use the destinations the operator configured, as Three ways to touch a project explains. The hint beside Docker reads “Shell commands run without network access.” DeveloperWorkspace.svelte workspace-locations.ts

Svelte 5 uses runesA Svelte 5 compiler instruction that marks things such as reactive state, computed values, effects, or component inputs. to say what should update when a value changes. Read $state.raw below as “track which Transcript App is using,” and $derived as “compute this from the current inputs.” The YOLO badge follows the saved chat or the draft’s approval mode. The last two flags follow the current snapshot.

packages/web/src/App.svelte
let chat = $state.raw(new Transcript());
let current = $derived(chat.snapshot);
// …
let { profile, model, thinkingLevel, project, location: workspaceChoice } =
$derived(rowsById.get(selected) ?? draftSettings);
// …
let yolo = $derived(selected ? rowsById.get(selected)?.yolo : draftYolo);
// …
let running = $derived(current?.status === 'running');
let hasConversation = $derived(!!current);
Deep diveHow a prop change reaches the rendered Markdown

$state declares a value Svelte can track, such as the selected chat or open panel. $state.raw tracks assignment to the variable without wrapping the assigned object in a deep reactive proxy. App replaces the Transcript instance on a chat switch. Inside each instance, snapshot has its own $state.raw declaration, so replacing a snapshot still updates the values derived from it. App.svelte transcript.svelte.ts

packages/web/src/lib/Markdown.svelte
let { text }: { text: string } = $props();
// …
$effect(() => {
// …
if (text === renderedText) return;
const previous = renderedText;
const append = previous !== undefined && text.startsWith(previous);
renderedText = text;
// …

$props reads the inputs from the parent. Here text comes from a saved entry in ChatEntry or from the partial reply in TranscriptView. $derived describes a value, such as whether the reply is running. $effect runs work that reaches outside that calculation, such as updating the browser’s document. The Markdown effect reads text and can skip the work when the string is unchanged. TranscriptView.svelte Markdown.svelte

The address chooses the chat, the tab keeps the draft

Copy a chat link and you get /chats/:id, with :id standing for the selected chat’s ID. New chat opens /chats/new, where you can pick a profile and compose before a conversation exists on the server. App builds both addresses from Vite’s import.meta.env.BASE_URL, so a build mounted at /ai/ uses /ai/chats/new. Browser Back and Forward restore the selection and the recent or archived filter. App.svelte

Open the workspace home and App first tries the ID in the tab’s pipal.current session storage key, then the first unarchived row it received from the server. An explicit chat link takes precedence over that remembered choice. If App can’t find the chat from a link in its rows, you land in a new chat with “Conversation not found.” Opening the new-chat screen clears pipal.current. App.svelte

The tab saves drafts in session storage under pipal.draft:<base>:<id>, where <base> is Vite’s BASE_URL and the ID is empty for a new chat. A new draft can remember its location and approval mode, including an explicit Ask before edits and commands when the workspace default is YOLO. Retry records and acknowledged upload IDs survive a reload. Other attachments come back by name and need to be reattached. drafts.ts App.svelte

Deep diveWhich browser preferences survive a closed tab

The workspace uses local storage for preferences that can carry across tabs and visits on the same origin. workspace-choice.ts supplies Runtime’s location labels and options and remembers a project per location under pipal.project:<base>:<location>. It also knows the older pipal.project:<base> key, which can supply an SSH project when there is no saved preference for that location. The appearance initializer saves the mode, the two palette IDs, and the corner style in pipal.appearance. The sidebar resizer saves its preferred width in pipal.sidebarWidth, and the Markdown toolbar remembers its last Wrap choice in pipal.codeWrap. Only the project key among these four includes the base path. workspace-choice.ts appearance-init.js SidebarResizer.svelte Markdown.svelte

Each disabled browser extension has a pipal.disabledExtension:<base>:<id> key. Disabling writes 1, while enabling removes the key. The switch in Settings → Extensions takes effect on reload, as Extending the UI explains. extension-preferences.ts Settings.svelte

Deep diveWhat a retry remembers when the reply never arrives

api() is the JSON convenience wrapper around request(). Both use apiPath(), which adds the build base and api/v1/. A failed HTTP response becomes an ApiError with its status and any server error code. A failed fetch instead gives “Could not reach Pipal,” except that a canceled request keeps its original error. App treats an ApiError with status 401 as an ended workspace session and clears drafts for this build base and resets the open chat when it locks. api.ts App.svelte drafts.ts

There are two receipts to lose on the first Send. App saves the creation request before posting it, reuses it if the selected location and project still match, and moves the draft to the returned chat ID after creation succeeds. For the message itself, App computes a digest, a SHA-256 fingerprint of the JSON payload, including any text files or upload IDs. If the digest matches the saved attempt, App reuses that request ID. A changed digest gets a fresh ID. App records the attempt before posting and deletes the draft on success only if it is still the same draft. A 400 on creation clears the saved creation request if the draft still holds that attempt. The draft stays in place. App.svelte drafts.ts

On reload, App can tell you that delivery is unconfirmed. It leaves the retry to you. The browser test loses a create response and then a message response, reloads, and checks that a manual retry reaches the same chat and leaves one copy of the message. The test reattaches the local file before each retry and changes the profile after the lost create reply. App applies the profile change to the returned chat before trying the message. Follow one message follows the request after it leaves the browser. App.svelte chat.spec.ts

The transcript stays readable while it changes

From snapshot to screen
  • Hono app.ts
  • Watcher
  • App
  • Transcript
  • View TranscriptView.svelte
  1. Watcher → Watcher · Return

    You come back to a tab with a chat open

    Hiding the tab closed the stream. Showing it again reconnects for the same chat and keeps its Transcript in memory.

  2. Watcher → Hono · Open stream

    The watcher subscribes for this chat

    The watcher opens an EventSource for the selected ID with ?delta=1. The first event provides a fresh copy of the server view.

  3. Hono → Watcher · Snapshot

    The host sends the current view

    The first event carries a full snapshot with the recent saved messages and any live output. Later events can carry changes to that view.

  4. Watcher → App · Apply view

    The watcher hands App a checked snapshot

    The watcher checks its shape and chat ID. App also uses the snapshot to refresh the sidebar row.

  5. App → Transcript · Merge

    Transcript joins the recent window to history

    When the windows overlap and the history cursor moves, Transcript can keep displaced messages for a reader who has scrolled away from the latest reply or requested earlier history.

  6. Transcript → Transcript · Pair

    A read result fills in its call

    Transcript matches a saved result to its call by ID and name in the same round. A result whose call is on an older page can stand on its own.

  7. Transcript → View · Rows

    Two adjacent reads share one row

    If the assistant goes straight from the first read to the second, the row says 2 tool calls. Open it to find both calls. If the assistant writes a progress update before the next call, that text starts a new row.

  8. View → View · Render

    Live activity fills in the thread

    A matching live tool updates its call’s status and output. TranscriptView shows approval cards and specialist transcripts separately, and puts the current partial answer through Markdown.

  9. App → App · Follow?

    The view follows the answer if you were following already

    After the markup updates, App checks that the chat and follow state still match before scrolling to the latest message.

Hono app.ts
Watcher
App
Transcript
View TranscriptView.svelte

Watcher → Watcher

You come back to a tab with a chat open

Hiding the tab closed the stream. Showing it again reconnects for the same chat and keeps its Transcript in memory.

Return to a tab with a chat open and follow a fresh snapshot to the screen. Transcript arranges the entries, TranscriptView renders them, and App decides whether to scroll.

Open a saved chat and the first thing you read is the newest part of its history. watch-conversation.ts gives App a snapshot, the server’s view of that chat at a moment in time. The recent saved messages in it form a transcript window. Live streams shows how the watcher keeps that snapshot current over the wire. watch-conversation.ts

A chat keeps the location and any project it was created with. If the owner disables that location, the chat gets an updated view over its open stream. App uses the snapshot’s workspaceUnavailable flag to show a banner when the original workspace is unavailable. While you compose a new-chat draft, App keeps its chosen destination when the profile list refreshes. If that location is now disabled or unavailable, App shows a banner and blocks Send for the draft. index.ts App.svelte

Deep diveWhen the watcher opens a fresh stream

Switching chats or unmounting App stops the old watcher. Hiding the tab closes the connection and cancels its timer. Showing the tab again opens a new connection for the same chat. For an ordinary stream error that EventSource can retry, the watcher resets its local copy of the server view and lets EventSource reconnect. App.svelte watch-conversation.ts

If EventSource reports an error with the source closed, a delta cannot be applied, or the server sends resync, the watcher schedules a fresh connection in three seconds. It does the same if it hears nothing for 45 seconds. The server’s heartbeat is 15 seconds, and pings count only after the watcher has received an initial snapshot. An unsupported version or malformed full snapshot stops the watcher and asks you to reload. contracts.ts app.ts watch-conversation.ts

App refreshes the profile list when the watcher reports a reconnect and again when the next view comes in. A restarted host may offer different projects, and a 401 from that request tells App to lock the workspace. App.svelte

After a workspace settings save, workspaceChanged() writes a signal to pipal.workspace:<base> in local storage and refreshes /profiles. In a ready workspace with location-aware profiles, App refreshes /profiles on that storage event or when the window regains focus. The focus check can pick up changes made in another browser. The settings panel itself reloads its server settings on the storage signal when idle and free of unsaved changes. App.svelte workspace-choice.ts DeveloperWorkspace.svelte

Click Load earlier messages and Transcript asks for the page before the messages you already have. App measures the scroll area before and after inserting the page. It shifts the scroll position by the height added above you, so you can carry on reading from the same place. As the reply grows, App follows it while you are following the tail. Scroll back to read and Latest message gives you a way back down. App.svelte

As the assistant writes, both live and saved assistant text go through Marked, which turns Markdown into HTML, and DOMPurify, which keeps the permitted elements and attributes. A link can survive this pass. Markdown image syntax becomes a link, so opening a reply doesn’t embed the image it names. Markdown.svelte

Adjacent calls share a row

Two reads share a collapsed 2 tool calls row if they’re adjacent on screen, even across rounds. A single read gets its own row. transcript.svelte.ts ToolGroup.svelte

The group updates while closed. Open it to see the calls in order, then open a call for its output and any Arguments. Approvals, specialist transcripts, and artifacts get separate rows. ToolGroup.svelte TranscriptView.svelte

SentMessage and ToolActivity render your prompt and tool output as plain text, including any angle brackets. SentMessage.svelte ToolActivity.svelte

Deep diveHow paging, live calls, and Markdown updates keep their place

A history request starts retaining displaced messages before the network reply comes back. If the live window advances during the request, Transcript.apply() can keep the entries that fell off its start. prepend() checks that the requested cursor, the position marking where to fetch older history, is still current and filters out message IDs already present. If a fresh snapshot shares no IDs with a previously nonempty window, Transcript drops the older pages and starts again at the fresh cursor. That avoids displaying a gap as if it were consecutive history. transcript.svelte.ts chat.spec.ts

Transcript clears its call lookup at every non-tool message, so a reused provider call ID cannot borrow a result from a previous round. It matches the first result with the same call ID and name, and that result takes precedence over a matching live slot. An unmatched result stays in the thread. An artifact card occupies its own row. A delegate result with child details also occupies its own row and updates its matching call’s status and output. Any separate saved row breaks a group. Assistant prose, hosted search activity, or source links give an assistant message a row of its own. transcript.svelte.ts

ToolGroup shows the call count, up to three distinct tool names, and counts by status, such as awaiting result or failed. A checkmark appears when the whole group is complete. When you open the group, a read can show its path and a shell call can show its description or command and a short excerpt of its output or failure. ToolGroup.svelte tool-summary.ts

TranscriptView shows an unmatched live tool on its own. A matching slot updates the existing call. Approval and delegation branches run before that check. A running or failed Bash or PowerShell activity opens to the end of its output by default once the activity is mounted. A collapsed group mounts its activities on first expansion, so you can see a running status before you choose to see the log. TranscriptView.svelte ToolGroup.svelte ToolActivity.svelte

The Markdown renderer also keeps work it can reuse. On an append, it leaves settled blocks in the document and lexes the open tail, so the last paragraph or fence can still change shape as text arrives. Reference definitions, raw HTML, and carriage returns can require a full render. The renderer sanitizes the fragments it creates and reuses code toolbars where available, preserving a button’s focus across the update when it can. Markdown.svelte

Two ways to reach the same command

In a new chat, type /model in the composer or search for Choose model with ⌘K or Ctrl K. Both reach the action App defined once. slashCommands picks available actions with slash names. The quick switcher uses available actions too, alongside entries for loaded chats and profiles. Submitting an exact command name without attachments runs the action if it is available. An unavailable name shows an error instead of sending a message. App.svelte

From source files to build output
  • packages/web/
    • index.html
      Page shell and policy
    • src/
      • main.ts
        Browser entry point
      • App.svelte
        Workspace state and layout
      • lib/
        Views and browser helpers
    • public/
      • manifest.webmanifest
        App name, scope and icons
      • sw.js
        Network fallback for the launch URL
    • vite.config.ts
      Build rules
    • build/
      • index.html
        Served by Hono
      • assets/
        Compiled, hashed files
      • pipal-base-path.txt
        URL prefix read at startup
    • index.html
      Page shell and policy
      • main.ts
        Browser entry point
      • App.svelte
        Workspace state and layout
      • lib/
        Views and browser helpers
      • manifest.webmanifest
        App name, scope and icons
      • sw.js
        Network fallback for the launch URL
    • vite.config.ts
      Build rules
      • index.html
        Served by Hono
      • assets/
        Compiled, hashed files
      • pipal-base-path.txt
        URL prefix read at startup
The browser starts at the generated index.html. Hono reads the base-path file next to it to learn where the build belongs.

Vite’s Svelte plugin compiles the workspace into static files under packages/web/build/. The pipal-deployment-path plugin requires an absolute path such as /ai/ and writes it to pipal-base-path.txt. Server startup reads and validates that file before setting the route prefix. Hono serves the built index.html at /chats/:id under that prefix, so App can read a saved link when you open it directly. vite.config.ts main.ts

The pipal-precompress plugin tries to make Brotli and gzip copies of built JavaScript, CSS, and HTML files of at least 1 KiB so Hono can serve precompressed files when available. The other Pipal plugins prepare palettes and watch extension activation records, as Extending the UI shows. vite.config.ts app.ts

The build can also launch as an installed app in a browser that supports installation. The manifest gives it a name, icons and a standalone window, with a launch URL relative to the build. In a secure browser context with service worker support, main.ts attempts to register sw.js, a service worker that can respond to navigation requests. manifest.webmanifest main.ts

The worker tries the network when you navigate to the installed app’s launch URL. If that fetch fails, it serves “Can’t reach Pipal” with a retry link. This fallback applies to a GET navigation to the exact launch URL. Opening chats still needs the host connection. sw.js

You’ve seen where App puts the message box and how it decides which actions appear. Where would you add a button that puts a prompt in that box? Extending the UI follows the bundled example and how an extension joins the build.

Recap

  • App holds the workspace selection and panels, reads drafts from Drafts, and derives runtime choices from the selected row or new-chat settings.
  • Transcript merges pages and groups adjacent calls. TranscriptView shows approvals, specialist transcripts, and artifact cards separately from those groups.
  • Vite produces static files, and Hono serves them at the build’s base path.
Check yourself
  1. A friend opens your chat link in a signed-in browser. Where does that browser get the messages and the draft?
    • The URL contains both
    • The host supplies the saved messages and the browser uses its own draft
    • The host supplies both from the chat record
    Answer and explanation

    The host supplies the saved messages and the browser uses its own draft

    The URL identifies a conversation. Its saved messages come from the host, while App restores drafts from this tab’s session storage.

  2. You request earlier history while a reply is still arriving. Why does Transcript start retaining displaced messages before the request returns?
    • The live window can advance while the page is in flight
    • The server stops streaming until history loads
    • The history endpoint sends the entire chat each time
    Answer and explanation

    The live window can advance while the page is in flight

    A recent message can fall out of the live window while the older page is still loading. Retaining it lets the page join the live window without a hole.

  3. The assistant runs a read, gets its result, and calls another read without writing any text. Where do you find the two results?
    • In one expandable tool group, under the original calls
    • In a new tool group for each model round
    • In the assistant’s next Markdown message
    Answer and explanation

    In one expandable tool group, under the original calls

    Each result fills in its matching call. With no intervening visible row, the two calls share a group even across rounds.

  1. A friend opens your chat link in a signed-in browser. Where does that browser get the messages and the draft?

  2. You request earlier history while a reply is still arriving. Why does Transcript start retaining displaced messages before the request returns?

  3. The assistant runs a read, gets its result, and calls another read without writing any text. Where do you find the two results?

In the source

Book contents

Search the book