editor implementation
Declared HTTP patterns
src/apiContract.ts::apiRoutes declares all 15 root routes, including rename/copy, without importing handlers or accessing files. Each descriptor owns method, path, root mount, access, summary, canonical Zod inputs, credential policy and response kind. src/api.ts::registerEditorApi spreads the descriptor through its wrapper and acquires only the existing host file facade. Raw and Office responses are binary; the other responses are JSON. Managed dispatch receives the same descriptor rather than maintaining another input declaration. Packaged provides.apiRoutes is generated from this object through core's canonical security projector, with 15 method/path declarations and rootMount: true. The registration regression parses that manifest with the selected core and verifies each actual registration against it; the manifest contains no summaries, schemas or handlers.
Handlers invoke lazy req.json, req.parseQuery and req.parseParams with those exact schema objects at the existing admission points. Root selection, Project admission and host/guest path and version checks retain their order. Body schemas preserve the existing record-or-null ingress; filesystem-specific path/content validation and CAS remain with their current host or guest owner. In particular, malformed JSON still escapes the host handler for core's HTTP 400 mapping but is caught by managed dispatch as HTTP 503; parsed null is rejected by the managed input boundary with HTTP 400. Version conflicts remain HTTP 409, and invalid commit hashes keep the existing host/guest distinction. tests/pluginApiProjectsPurposes.test.ts captures registrations and characterizes lazy parsing and admission using core's real raw-body parsers.
Core 0.30.4 first resolved the complete /projects/:id/... declarations before invoking src/api.ts; the manifest records the coordinated core and shared-API floors. req.path is empty; req.params.id and the commit-diff req.params.hash are decoded once by core. An undeclared suffix returns dispatcher 404 before Project lookup, Sandbox dispatch or filesystem access. Editor owns route/root validation, Project membership and the response surface. Core owns canonical host System admission/path guard and typed Git execution; a named Project whose path is / still uses the ordinary Project guard. Host Git reads require the plugin's git read capability; file access keeps project-files.
Project selection
UI API 62 supplies the exact host utils.projectName and components.ProjectIcon for the
administrator picker. The ordinary picker uses ProjectFilterPills, which composes that same pair.
Both receive the complete /projects projection, including computer.label and execution kind.
The computer slug remains an identifier; workspace status and icon-picker descriptions use the same
name helper. The system root retains its separate hard-drive option.
src/api.ts::projectFor awaits the host's current Project row before any root or filesystem work. A deleted or inaccessible Project returns the existing HTTP 404 response.
The Project pickers need UI API 62. Project members use the host ProjectFilterPills catalog adapter, which renders the shared single-choice list and accepts value, onChange and includeAll. The retired variant option is removed from the consumer. Picking a project retains the editor's existing root selection, remembered destination and dirty-draft confirmation. Administrators still use the authorized system selector. This presentation change adds no file requests or inference work; project icons use the host's existing root-aware image loader.
Paired computer Projects
projectFor resolves a local Project through Sandbox's resolveLocalTarget for the acting account.
It passes the resolved cwd and platform into the same managed/context.ts backend as managed Projects.
The context selects {kind:'local',projectId}, uses shared localTargetPath for native POSIX or Windows
path resolution and returns slash-separated relative tree names to the browser. Editor requests remain
confined to the selected root. Download headers use the native basename without the computer's directory
path. Project means the connection's cwd; System means its filesystem root, including a Windows drive
or UNC share. These navigation roots do not confine the computer's OS user or add a second filesystem transport.
Every file operation calls the live sandbox.projectFiles({project,accountUserId,operation}) control.
Core holds and releases its daemon binding, checks live member-only canExecute and counts writes
through the device's existing file-edit accounting. The five Git reads call ctx.host.git() with
{local:{project:{kind:'local',projectId},accountUserId}}; core dispatches them through the existing
authorized one-shot executor with the project-command kind, live computer membership and connection
admission. No plugin Git argv or Git sandbox.runCommand call remains, and a stopped or offline computer
stays an error rather than falling back to a host path. The core Git overview uses localGitReader.
Uploads retain the host's shared resumable upload client and may name the computer Project without
a conversation; core pins their connection through commit or abort and keeps collision suffixes.
Stable computer refusals retain their HTTP code: local_target_forbidden 403,
local_target_unavailable 404, and LOCAL_TARGET_OFFLINE, LOCAL_EXECUTION_LOST 409. The browser receives curated wording, never provider diagnostics.
Missing Sandbox remains 503. An administrator who is not a member cannot inspect or modify files.
Every paired CLI client serves its file and command paths; the manifest records the coordinated core floor.
The browser reads computer.cwd and computer.fileSystemRoot from the core Project projection
only for captions. It offers both roots and keeps System Git controls hidden. Office documents on
computers use the existing download view; no converter or shell-specific utility is launched.
No additional connection, background worker or inference request is introduced by the plugin.
View modes
Edit, the available preview and Diff are one single-choice control, and the plugin owns no
presentation for it. ProjectEditor builds one descriptor list — value, label and glyph per
option, with the preview only for a Markdown or CSV file and Diff only outside the System root — and
passes it to components.Segmented, the host component published on ElowenUiRuntime since UI API 2.
The host draws it as a Radix radiogroup of radio options, so the choice carries the checked state,
the roving tab stop and the arrow/Home/End keyboard model without the plugin reimplementing any of
them; selecting an option never clears the set. The caller states the track step (size="md", the 36px
default field, 44px under a coarse pointer) and nothing else: no option takes a height, a padding box
or a touch floor of its own, and the plugin ships no CSS for the control.
The phone layout draws the same descriptors in its shared ActionMenu, marking the current view with
a check, so both layouts offer the same modes and the same action runs on either. The plugin's own
ViewSwitch.tsx and the tablist/tab roles it drew are gone with it; no external contract named
them. A view that stops being offered (a preview on a text file, Diff under the System root) falls back
to Edit through the existing derived value, so the control never states an option it does not list.
The desktop caller draws the control only when more than one mode is left (viewOptions.length > 1):
a plain text file under the System root leaves Edit alone, and a switch over a single choice is not a
choice. The phone menu keeps its entries either way, because it is also the row's action menu.
web-src/runtime.tsx narrows the published entry to the props this caller passes. The host publishes
every component as ComponentType<never> — the runtime carries no prop types — so a bundle declares the
shape it uses and AssertPublished checks the name, which is why a wrong size or a missing label is
a build error here. That narrowing is a compile-time check only: the published component validates no
props at runtime, so the caller keeps value inside its own option list.
Browser draft lifecycle
web-src/editor/useEditorDrafts.ts owns the selected file, open tabs, draft text, dirty paths, content versions, per-path save queues and discard confirmation for ProjectEditor. Callers key the editor by Project identity. A root change confirms unsaved work, then clears tabs, drafts, expanded folders and the selection and returns the view to Edit. The chosen root remains remembered per device. ProjectEditor fills the workspace height supplied by EditorPage.
fileData.ts::editorDirectoryQuery(projectId, root, directory) owns directory request options and keys beneath the Project/root prefix. The first tree level and ProjectIconPicker use that same host QueryClient cache. Opened levels in useLazyDirs reuse the directory request while retaining their generation-owned in-flight reads; after a mutation, a new generation cannot join a response started before that mutation. Tree mutations invalidate the root prefix, including the currently open icon directory; lazy levels retain their epoch/root reset and discard responses from an obsolete generation. The picker only reads when its managed environment is ready. Each read lists one directory and spends no inference calls; unopened directories do no work.
Each save captures Project, root, path and text and publishes through the existing root-aware fileData.ts query keys and host QueryClient. Writes to one path serialize even without a content version; different paths can proceed together. A queued write uses the previous response's version. Save completion retires only a draft that still matches the sent text, so typing during a pending save remains visible and dirty. Every operation reports its own result. Closing a dirty tab asks for confirmation; rename remaps tabs and drafts, while deletion forgets the affected path and descendants. Desktop fullscreen preserves the mounted draft state; mobile close still passes through the discard guard.
web-src/editor/menu.ts builds tree context menus and File, View and Settings descriptors. Desktop passes them to the host ContextMenu; phones flatten those same descriptors for ActionMenu and run the selected action after the menu closes. The tree opens its menus only through the host's components.ContextMenuTrigger (UI API 71): FileTree.tsx wraps every row button in one trigger for that node and the whole tree in one for the project root, and ProjectEditor turns the point the trigger reports into the menu state. A right-click opens under the pointer, the Menu key or Shift+F10 under the focused row, and a 500 ms touch or pen press under the finger on every platform, iOS included; moving or scrolling cancels the press, its release click neither opens nor selects the row, and Android's own long-press menu never opens a second one. The innermost trigger owns the event, so a row never also opens the root menu. The plugin carries no onContextMenu, key or timer code of its own. The File, View and Settings bar is a row of buttons that opens the same host ContextMenu under the clicked button and needs no trigger. The host ContextMenu runs a chosen action after the menu closed and focus returned to the row or button that opened it, so the name prompt and the delete confirmation open over a settled page. Actions receive the current root, selection, preferences and existing callbacks. A directory's context menu opens the file picker with that exact upload directory captured until selection completes. Empty selection keeps selection-dependent actions disabled; host Projects omit the managed root submenu, and System roots omit Git views.
Managed request ownership
The managed server dispatcher in src/managed.ts keeps the existing mount and method checks, linked-account and provider admission, unsupported-operation HTTP 501 and final error response. The API's authorized Project and root target enters src/managed/context.ts once per request. That context derives the guest root and binds confined paths, live provider resolution, shared-client reads and follow-stat, request input and refusal mapping. File and command operations resolve the live provider again rather than retaining the admission provider for execution.
Named handlers in src/managed/files.ts own listings, text saves, entry mutations, streamed downloads and Office previews, including the shared two-conversion limit. src/managed/git.ts owns the read-only history routes and rejects them outside the Project root. Every handler receives the same authorized context; these modules add no backend registration or public core API. The dispatcher awaits handlers inside its error boundary, so validation, upload and access refusals retain their existing status and wording while unknown failures remain sanitized HTTP 503. A guest already_exists on a write answers HTTP 409 with already exists; rename and copy answer HTTP 409 with target already exists. The provider's diagnostic and internal paths are not forwarded. Existing-directory mkdir remains idempotent.
Managed command and browser contracts
Editor's remaining Office utility, converter and cleanup workloads execute one-shot project commands with sandbox.runCommand(input, actor, options). The host authorizes the prepared target and owns byte capture, heartbeat, timeout, cancellation and lease release; the actor preserves the caller's account and allowed roots. They use leaseKind: 'project-command', a 30-second timeout and an 8 MiB combined output bound, return sanitized stdout and reject nonzero results. Git reads are not plugin commands: they use the typed ctx.host.git() facade, and OneDrive's Git scans use the same facade. Missing Sandbox support makes an Office utility unavailable. Long-lived services retain raw prepareExecution sessions. No consumer timer or second capture loop is required.
tests/p65ManagedConsumers.test.ts supplies both the exit verdict and stdout/stderr EOF for completed prepared sessions. The host runner must drain both streams before returning or releasing the lease. Pending, interrupted and rejected sessions retain their distinct cancellation and partial-output paths; the fixture does not replace them with successful closure.
The binary preview and status bar read the viewer locale from the existing host translation hook and pass it to the published host byte formatter; switching languages changes numeric captions without a local formatter.
Editor JSON writes call runtime.api(path, { method, json: payload }) through ElowenUiRuntime['api']; the host owns serialization, headers, authentication and request lifecycle. File saves omit an undefined version and preserve an explicit null version. Omitting json retains raw request behavior, including downloads and multipart uploads. Consumers still validate their domain responses.
Host file listings
The authorized GET /projects/:id/files handler awaits listProjectFiles(root, maxDepth, from) inside its existing error boundary. The function returns a promise of the same flat FileNode[]. Directory reads, target stats and realpath checks use asynchronous filesystem operations so a large host tree does not occupy the daemon event loop until completion. Traversal remains sequential and depth-first, with directories sorted before other directory entries and names ordered by the existing locale comparison. The depth budget, ignored names, staging prefix, system virtual-filesystem exclusions, symlink containment and visited-realpath set are unchanged. Missing roots return an empty tree; unreadable directories and entries retain their existing skip behavior.
For an administrator System request, the handler awaits core projectFiles().systemGuard() after Editor's reserved-id/admin check and on every authenticated request; it is never cached at registration. Core verifies the live linked administrator identity without HTTP Policy, refuses VFS aliases and dangling links, and keeps a named Project at / on the ordinary guard. Editor guards from through that returned guard before listing. Directory symlinks are shown but followed only within the real root, once per real directory. Managed listings continue through the existing account-bound Sandbox transport. No background task, listing cache or parallel read pool is introduced. Async filesystem round trips can increase total listing time while allowing unrelated daemon requests to run between operations. tests/hostFileWalks.test.mjs checks ordering, depth and event-loop progress; the existing Project, System and managed route suites retain authorization coverage.
File writes
Host mutation request parsing uses isRecord from
elowen-plugin-shared/record after the existing JSON parser. It accepts
non-null, non-array objects without imposing a prototype requirement.
Malformed JSON, null, scalars and arrays retain the parser's null result;
each route retains its required-field refusal and performs no file write
when those fields are absent. Empty objects pass the basic guard but not
required-field validation. Project authorization and managed dispatch are
unchanged; the guard has no I/O or persistence policy.
Browser uploads call runtime().utils.uploadProjectFile(file, { projectId, directory }, { signal, onProgress }), published by UI API 56. The implementation lives in the host's web/lib/projectUploads.ts, also called by chat, so the plugin bundles no upload transport. Core opens an account-bound session, accepts sequential Blob parts at durable offsets, retries resumable failures and commits the verified size. There is no type or total size limit. Existing destinations and in-flight managed upload reservations gain a collision suffix rather than being replaced.
ProjectEditor renders each pending file with the host Progress component and cancel button. Commit refreshes the root listing and opened directories. Cancellation, unmount or changing Project/root aborts pending work; a failure shows the core refusal and leaves other files queued. Upload is offered only in the Project view: the core target directory must remain inside that Project, and System browsing/editing retains its existing authorization.
The old PUT /projects/:id/upload, editor session map, managed helper and browser client are removed. Core rechecks current Project membership and destination identity at every part and commit, confines host symlink paths and aborts guest handles resolved outside the Project before sending bytes. Host listings hide the reserved .elowen-upload- staging prefix. Sandbox guest list and walk own managed staging visibility: they omit .elowen-upload-, .elowen-write- and .elowen-copy- before producing a page, including symlinks, and never descend into staging directories. Editor consumes those results without a staging filter under Project and System roots, including linked directory expansion. It retains repository ignores and System virtual-path rules. Sandbox also owns staging cleanup. Host staging adds its prefix after filename sanitization. A daemon restart loses in-memory sessions; core's existing boot/daily attachment worker reclaims host staging after an hour without writes, while Sandbox owns guest staging expiry. Ordinary .part files remain visible and are not swept.
All guest file I/O uses elowen-plugin-shared/guestFiles with the editor's authorized projectFiles binding. writeGuestFile(files, path, bytes, { expectedVersion }) selects a single write up to 512 KiB and chunked upload above it, creating parents only after parent_missing. The client also owns stat, metadata-only listing of every page, bounded walk, mkdir, remove, rename and copy. The plugin retains root confinement, listing filters, request validation and HTTP refusal mapping; it constructs no guest operation literals. Tree duplication calls copyGuestFile(files, from, to, { expectedVersion }) after statting the selected source. The guest preserves symlinks and refuses an existing destination; only parent_missing asks the client to create the target parent and repeat the same source CAS copy. Deletion calls removeGuestFile(files, path, { expectedVersion, recursive: source.kind === 'directory' }). Directory CAS pins the selected entry's existing version, not a whole-tree snapshot. Both mutations retain the authorized root and HTTP guards and start no commands. Office conversion retains its command workload; Git reads no longer start one. Without Sandbox, the request is unavailable.
File downloads
web-src/editor/fileUrls.ts::downloadEditorFile(projectId, root, path) is the shared download action for ProjectEditor menus and BinaryPreview. It builds the root-aware raw URL with download=1, names the attachment with the existing basename helper, clicks a temporary anchor and removes it. Authentication stays with the same-origin cookie proxy; the action buffers no bytes and creates no object URL. With no download action, it performs no work.
The existing authorized /projects/:id/raw route returns a streamed PluginHttpResponse.body; download=1 adds the attachment header. Project selection stays in Editor; an administrator System request uses the core per-request systemGuard() described above. Binary files, and image, PDF, Office and media files above their preview limits, show an enabled Download button instead of reading their content into the browser. An oversized text file shows a notice and no download button.
Host Project and System downloads use their existing path guard, re-authorize the resolved leaf and open it with O_NOFOLLOW, and take size metadata from that same descriptor. A Node read stream owns the descriptor and reads in 64 KiB blocks; EOF, errors and core-managed client cancellation close it. Invalid ranges close the descriptor before returning HTTP 416. A pathname replacement after opening cannot switch the download to another file.
Managed Project and System downloads adapt readGuestStream(files, path, { offset, length, expectedVersion, expectedTotalBytes }) to a pull-based web byte stream. No content is read before the consumer pulls. The client owns read boundaries, the initial version and size pin, subsequent version checks and the final follow-stat after multi-page reads. A file opened through a symlink is validated against its target on that closing check as well. A failed, changed or incomplete read errors the stream with a sanitized message; it cannot change an HTTP status whose headers were already sent. Cancellation stops subsequent reads and lets at most one bounded in-flight read settle without enqueueing or exposing an unhandled rejection. Empty files need no guest read.
Both paths preserve byte ranges, HTTP 206 and content-range, with the existing 8 MiB maximum range response. The plugin requires the coordinated core release named in its manifest; the current manifest requires shared API 16.
The plugin has no configuration fields. Disabling it removes the editor and its file API; Project registration and task Git history remain available.
Next: GitHub
Shared file and Git reads
ProjectEditIcon opens the existing icon picker through the host's Button variant="ghost" size="icon" with the Pencil glyph. The pencil follows the stored icon path in the Icon row, or appears alone when no icon is set; chooseIcon supplies its tooltip and accessible name, not a visible text label. The Git panel uses Button variant="ghost" size="sm" for Show all. The plugin adds no action-link styles; the host owns hover, focus and disabled presentation.
The Git panel consumes core GET /projects/:id/git; RealGitReader currently returns the newest 15 commits. Its Show all action unfolds the whole history IN the drawer from the host's hooks.useProjectCommits (UI API 59), fifty commits per page: every page is requested from the head the Git snapshot named, so a retry cannot shift the window onto a newer history, and the next page is read when the [data-commit-sentinel] marker below the list comes into view. A failed page is named inside the group with a retry that re-reads that same anchored page, and the open fold is held per project, so selecting another project shows the preview again. The notGit line is drawn only for a Project whose files sit on the host itself (executionKind absent or host): a managed Project's checkout lives in its environment and a paired computer's files live on that machine, so their drawer stays silent about Git rather than claiming a fact about a filesystem this panel never read. Editor retains /head, /changed, /changes, /commit/:hash and /commit/:hash/diff. Unused /diff and /commits routes and their parser are removed. All five reads call ctx.host.git(): projectFileAtHead, projectCommit, projectCommitFileDiff, projectChangedFiles and projectWorkingDiff. Core owns Git argv, NUL-safe changed and commit filenames, literal pathspecs, disabled external diff/text conversion, bounds and the strict nonrepository/error distinction. No plugin Git argv, process, status parser, SHA regex or copied parity helper remains.
The canonical shared isGitSha accepts 4–40 hexadecimal characters. A host invalid hash keeps the existing empty payload; managed and local invalid hashes answer 400 invalid commit. A legitimate nonrepository result stays empty; corrupt objects, missing Git, permission failures, timeouts and transport failures reject, never a clean tree. Host Git failures are redacted 503 git unavailable; managed and local reads retain their existing sanitized mapping. Host System returns empty Git payloads, guest and computer System answer 409, and neither launches Git.
The five checkout reads — /head, /commit/:hash, /commit/:hash/diff, /changed and /changes — are the plugin's own queries in web-src/editor/gitData.ts, on the host's generic api and useQuery and its single QueryClient. Core no longer publishes useProjectFileAtHead, useProjectCommit, useProjectCommitFileDiff, useProjectChanged or useProjectChanges. The cache keys stay project-head, project-commit, project-commit-file, project-changed and project-changes, each followed by the Project id and, where they apply, the commit hash and path: fileData.ts invalidates ['project-changed', id] after every tree mutation, so a renamed key would leave the tree's change dots stale. The paths name no root selector — these reads describe the checkout, so the daemon derives the target from the authorized Project row and refuses them under a system root — and the view passes a null Project id there, so a system root issues no Git request at all. A refusal remains the query's own error and is drawn with the daemon's wording (503 as gitUnavailable), never as an empty clean tree. The project overview (useProjectGit on core's /git), the anchored commit log (useProjectCommits) and useProjectEnvironmentState stay host hooks.
A host that still publishes the five private Git hooks does nothing for this bundle, and a bundle that still reads them crashes on a host that has dropped them: core and the Editor bundle are upgraded together, with no alias window.
src/fileTypes.ts owns PROJECT_FILE_IGNORE, MAX_EDITABLE_BYTES, MAX_OFFICE_CONVERSIONS, parseByteRange and downloadHeaders. Both raw handlers use its strict single-range parser before streaming: bytes=-3 selects the final three bytes; unsafe suffix/start/end numbers return 416 with content-range bytes */size. Valid ranges keep 206 and the 8 MiB response bound; no Range streams the whole authorized file, including empty files.
editorApiPath uses URLSearchParams to produce a path without the BFF prefix for runtime().api. editorFileUrl passes that same path to the host's typed apiUrl, so images, media, PDF previews and downloads use the host's cookie proxy address without restating or stripping its prefix. No transport, token or retry owner is added.
The editor renders the published components.MarkdownPreview directly, retaining only pane padding, height and scrolling; the host owns Markdown sanitization. The hero uses components.StatusDot, and the failed Git-read retry uses the shared ghost Button. The removed local Markdown wrapper has no runtime or test callers.
useEditorBlobUrl(projectId, root, path) in fileData.ts owns the ImagePreview object URL. It fetches raw through the cookie proxy, returns url/failed and revokes on cleanup. Obsolete responses publish no URL. Pending/refusal rendering and preview-size admission remain caller-owned.
PDF files and converted Office documents use the host's components.PdfPreview (UI API 70) inside the pane's padded box: src is editorFileUrl(projectId, 'raw' | 'office-preview', root, { path }) and title the selected path. The host reads the bytes over the same cookie proxy, frames them only as application/pdf, revokes its object URL when the file, root or Project changes, and draws the shared spinner and its own "The preview could not be loaded" state. The editor keeps size admission (MAX_BUFFERED_BYTES, MAX_OFFICE_BYTES) and the computer-Project Office download. The plugin's own PdfPreview and its previewFailed string are removed; the Office conversion route and its limits are unchanged.
Editor runtime declarations include only consumed host members: no Project notes/pr_enabled, EditorComponents ControlSurfaceDocument or utils.baseName. Host publication is unchanged; filename callers use editor/helpers backed by fileTypes. Local retry copy is removed; treeRetry and host common.retry remain.
Browser bundle and completion limits
The browser source requires host UI API 73, and one-shot managed commands require the host Sandbox runner; both arrive with the core release named in the manifest and marketplace entry.
On a phone the editor frame is the app's full-screen workspace takeover, and its action dropdown uses the same menu the rest of the app uses. Back goes through the editor's own close action rather than around its discard guard, so unsaved changes are still confirmed; without a selected Project, Back leaves the page directly. No inner editor opens fullscreen on its own.
Uploads travel as sequential parts whose size core chooses, 16 MiB. Core transport limits, declared-size validation and available storage still apply. In a managed Project, a text save larger than one guest chunk (512 KiB) goes through the guest upload path, and smaller saves use a single write.
A Project icon is stored guest-absolute for a managed Project and relative for a Project folder. Core validates both before saving and refuses the same kernel interface directories the picker skips. Returning an adopted Project to host execution clears a guest system icon and preserves a relative one. The System root of a managed Project is that environment's own filesystem, and it is available to any account that can access the Project, not only to administrators.