OpenProgram Docs

File changes, Review and recovery

A historical rewind marker is shown only beside its anchor message in the loaded history window. An offscreen anchor must not move its marker to the latest message. Pending rewind controls remain at the current end.

Undo, Revert, Rewind

Undo latest turnRevert this turnRewind to here
ScopeLatest turn on the current branchOne historical turnSuffix of the source branch after the chosen checkpoint
FilesRestored after every file passes preflightRestored only with no later same-path dependency and a matching digestTarget state projected from the journal, applied under a durable intent
ConversationHEAD and all messages stayUnchangedThe current branch moves back; its withdrawn suffix is recovery history, not another branch
BranchNone created or movedHEAD staysThe same branch identity and name stay; later messages extend its rewound head
ConflictAny path mismatch blocks the whole operationNo automatic reverse mergeAny unrecoverable item blocks it
AfterRevert transaction appended; card shows Reverted; Redo when preflight allowsBranch Review folds the revert; Reapply when preflight allowsOriginal prompt prefilled; no workspace-alignment choice

Turn cards show the applicable Undo or Revert; user checkpoints open a Restore sheet. Redo and Reapply are new transactions, with no linear redo stack. The transcript offers no branching; Copy conversation is in the conversation's ⋯ menu.

Shared workspace and same-branch rewind

A conversation branch records a route through messages, not a private filesystem. Fork and retry retain their existing explicit conversation versions; switching them never restores files, pauses tools or asks which files to use. The model receives a current-workspace note and must reread files before editing.

Rewind is a different operation: withdraw the selected prompt and its suffix on the current branch, and restore its recorded file changes when code recovery is selected.

Existing sibling branches and their shared messages remain intact. Withdrawn messages remain in durable recovery storage for Undo and crash recovery, but disappear from branch lists, version navigation, the conversation graph and normal context.

A later message extends the same named branch. Undo and Redo change the withdrawal view on that same branch; their existing message-only semantics are stated explicitly and do not restore files.

Recovery must not overwrite later writes by another branch, another session or a human. A code recovery with an unsafe, missing or conflicting file is blocked before any file or conversation change; conversation-only recovery remains an explicit alternative.

Previews bind the head, target, file states and mode. Duplicate requests replay their recorded outcome; failures roll back and interrupted operations recover before exposure. Existing legacy intents retain their original recovery semantics. Old workspace-alignment flags have no authority to stop a message or tool.

Acceptance pathRequired outcome
Switch after edits, failed retry, old mismatch flagFiles unchanged; message and ordinarily permitted tools work; stale read baselines cleared on switch.
Rewind then send, including first promptSame branch identity and name; no withdrawn version offered; current file contents match the confirmed recovery.
Sibling shares part of withdrawn historyThe sibling and its necessary ancestors survive; only the selected branch is withdrawn.
Conflict, stale preview, running writer, archiveNo partial conversation or file change; a specific refusal explains recovery eligibility.
Undo, Redo, duplicate request, restart during applyConsistent branch visibility, identity and files; recorded transactions determine the outcome.

Branch identity is independent of its head message. When two rewinds converge at one checkpoint or ROOT, each ref retains its name and remains selectable by branch id. Undo marks belong to that identity. Selecting by head alone remains compatible for unambiguous legacy clients.

Sources of truth

Trusted mutators write, edit, apply_patch, validated adapters receipt Mutation journal before/after digests, blobs Review This turn, Branch Generic Bash, external writes no receipt, no turn Undo Git workspace HEAD, index, worktree Review Unstaged, Staged Conversation DAG nodes, HEAD, branches History planner reads all three; only the journal authorizes recovery Durable intent lock, apply, verify then HEAD, if needed
  1. Trusted mutatorswrite, edit, apply_patch, validated adapters

    Generic Bash, external writes: no receipt, no turn Undo

  2. Mutation journalfeeds This turn and Branch Review
  3. Git workspacefeeds Unstaged and Staged Review
  4. History plannerreads all three, with the conversation DAG; only the journal authorizes recovery
  5. Durable intentlock, apply, verify, then HEAD if needed

Bash may run in sandboxes or worktrees. Git shows current changes without proving their turn or granting Undo.

File window

Files open in preview. Edit autosaves. History lists human and model changes.

FormatPreviewEdit
Text, code, MarkdownRenderedSource, autosave
DOCX, PPTX, XLSXLocal engine, full page or slide; text extraction is no substituteFull edit in the local engine, formulas and structure kept
DOC, PPT, XLSYesSaved explicitly as OOXML, never over the original
ODT, ODS, ODPYesOriginal-format export
CSV, TSVTableText
PDFContinuous pages, zoom, search, outline, thumbnailsHighlights and free-text notes; 64 MiB limit
PNG, JPEG, WebPZoomCrop, rotate, drawing, shapes, text. Conversions create a separate PNG. 64 MiB, 16 million pixels, 16384 px per side.
Animated or 16-bit PNG, BMP, GIF, SVG, TIFFYesRead-only; a save never rasterizes silently
PSDComposite and layer listRead-only until a lossless round trip is verified
Audio, videoLocal HTML playersRead-only
Corrupt, encrypted, oversized, unsupportedExplicit status and downloadNone
SituationBehaviour
Switch tabs after editingEdits persist as local drafts, then write in the background. No Save action or persistent Saved label.
Another program changed the file“File changed by another operation.” The draft stays; inspect the disk version or Save a copy. Never overwrites.
Open an old versionThe current file's previewer, read-only. Recovery is a new recorded operation that keeps pre-recovery content and can be reapplied.
Opening, adapters and engines
TopicContract
File referenceStable project or session ownership plus relative path. Display paths are not credentials.
Adapter choiceExtension, type and contents verified first
Adapter surfaceReceives document content and version only, no disk access. Exposes byte or Blob export, change and error events, destroy.
LoadingLarge Office and image resources load only for relevant files. KaTeX keeps complete WOFF2 without legacy fallbacks. Budgets: 2 MiB compressed initial transfer, 350 KiB compressed per chunk.
Large binariesBounded byte uploads or local staging, not chat messages. Size enforced while reading; temporary files cleaned on cancel.
Active contentEngine messages validate origin, instance and request ID. Document scripts, macros, active HTML and SVG get no main-window authority.
Third-party servicesOnly by explicit user configuration, with notice that files go there
No safe original-format writeExport a labelled copy; never PNG or OOXML bytes under another extension
EngineRole
PDF.jsPDF viewer, pinned
ONLYOFFICEOffice editing, local, optional install. Complete servers remain configurable adapters. Candidates compared: OnlyOffice browser/WASM, LibreOffice WASM.
fabricBitmap editing
ag-psd, utifPSD and TIFF decoding. ag-psd's colour-mode, text-layer and effect limits mean originals are kept.
PhotopeaThird-party hosted: never loaded and never sent local files by default

Markdown rendering

ItemRule
Raw HTMLEscaped
LinksLocal references, bare fragments, HTTP(S), mailto. Protocol-relative destinations use HTTPS.
ImagesScoped local-file URLs and HTTP(S). Data and executable schemes rejected.
Local queriesNever supply authorization parameters; SVG fragments stay separate from disk paths
MathTokens outside literal code, escaped before typesetting, never restored through raw placeholder replacement
Outside this subsetWiki links, embeds, outline, Agent section attachments

Markdown heading navigation

Key
From visible inline heading text: Unicode letters and numbers kept, lowercased, punctuation other than _ and - removed, whitespace runs become -. Empty uses section.
Repeats
First unused numeric suffix, unique per parse, including collisions with explicitly numbered names. State resets per render.
Bare fragment
Percent-decoded once; searches only the originating article by heading-key attribute, never through a CSS selector. Invalid or missing: no scroll.
Cross-file link
Keeps the fragment through the existing destination parser and authorized opening path
Section request
Ephemeral view state outside CenterTab, tab history, snapshots and window-transfer payloads. Holds a unique sequence, physical tab id, expected document identity and fragment.
Section requests in detail
  • Project-file opens use the resolved destination id, including history-reused tabs. Attachment previews use the resolved file-preview id, not activeId, which may remain the chat.
  • A rejected auto-open creates no request; an accepted no-section open clears an older one. Close or retarget invalidates it. Consumption compares the sequence, so an older render cannot remove a newer request.
  • PersistentFilePanes keeps one physical DocumentWindow per document identity. A section request picks the active alias as preferred host and never creates a second DocumentController.
  • The request travels through FileTabPane, DocumentWindow, FileViewer, TextViewer as view context, keeping authorization. It switches source mode to preview without discarding dirty bytes and waits for that exact draft or version to render.
  • Links in a selected historical version use that version's headings. Attachment paths keep their read-only flag and original session.
CaseRequired result
Unicode, inline text, repeated headings, code fencesStable unique keys; only headings participate
Two mounted documents share a headingBare fragment scrolls only its originating article
Cross-file load or repeated same-section requestSurvives loading; each sequence scrolls once after rendering
History-reused id or chat-active previewReaches the actual file pane
Two aliases, dirty draft, source mode, selected versionOne controller and buffer; correct alias and rendered version navigated
Rejected auto-open, no-section reopen, close, retarget, reloadNo stale request applies

PDF reading and annotations

Layout
Document tab above a flat toolbar; removable 180 px left sidebar with thumbnails and outline; continuous pages. Annotation row is contextual; narrow panels wrap controls without covering text.
Controls
Page navigation, fit width, fit page, numeric zoom, selection, in-document links, highlighted search. 32 px high, application font at 13 px. Only implemented tools appear.
Colour
Application theme tokens. Reference: ink #202124, toolbar #27272a, canvas #151517, paper #ffffff, divider #414145, focus #4a90e2.
Stylesheet
Upstream viewer CSS is scoped to [data-pdf-reader], root variables included, so generic names cannot change the shell
Copy
Layout line breaks joined; paragraph breaks and punctuation kept; CJK joined without spaces; ordinary hyphens kept; soft hyphens removed. Clipboard only, text layer only. A visible checkbox keeps original breaks.
Annotations
Standard PDF highlights and free-text notes, saved through the DocumentController rich-editor lease, durable drafts and revision checks. Draft-byte updates do not recreate the viewer or lose undo. History and attachments are read-only.
Disabled
PDF scripting and external upload. Out of scope: original-text editing, OCR, page surgery, format conversion.

PDF runtime

Decoder
PDF.js 6.3.289, module and worker from legacy/build, served from same-origin /document-assets/pdfjs/. The manifest records version and distribution. Local CMaps, fonts, WASM and licence inventory are kept.
Why legacy
The compatibility code must load in the page and the worker; a page-only polyfill cannot repair the worker. The modern build needs Uint8Array.prototype.toHex. Upstream: browser support.
Shell policy
connect-src 'self' blob: lets decoders read retained versions through object URLs. External HTTP and WebSocket stay blocked; blob scripts, eval, objects and third-party frames stay off.
Viewer reference
viewer source, PDF Expert features. EmbedPDF is not used: a second rendering engine adds nothing for reading, highlights and notes.

Office install and loading

TopicBehaviour
Default buildsApp, runtime and Python builds omit Office assets and do not download them. PDF is independent.
ChoiceOpening an Office document checks local availability only. If missing: formats, about 699 MiB, local processing, ONLYOFFICE licence, Install and Cancel. Cancel downloads nothing.
InstallOwner-authenticated local-origin POST; fixed release URL, pinned archive SHA-256. Bounded download and extraction, unsafe paths and links rejected, full manifest verified, atomically published to the profile cache. Concurrent requests share one install.
FailurePrevious pack stays selected; temporary downloads removed
After installThe current worker serves it without restart and the document opens. Closing the document stops its requests; a requested install may finish.
Older packsProfile resources stay usable; App-bundled resources are no longer selected. Development staging is a standalone command that ordinary builds ignore.
IsolationSeparate origin, resource-tree GET and HEAD only; no main API, authentication or WebSocket. Both pages validate origin, instance, request. Macros off. Remote deployments without a separate origin disable editing.
LoadingFull-size surface; nothing is drawn over it while resources load and the document opens. Only an install the user asked for shows a centered, theme-aware overlay with its progress, no simulated percentage. A startup error shows with Retry.
TeardownPinned mount and activate API, so closing destroys a pending host. An AbortSignal cancels availability and activation under a bounded deadline. Failed instances never attach to the controller.
Not providedGeneric extension registry, automatic updates, uninstall controls, third-party upload

Back and Forward

Each tab keeps its own page history: Folder A, subfolder B, file 1, file 2. Opening somewhere new after Back replaces forward history. Folders restore path, expansion and scroll; files keep autosave.

Only explicit positioning, search navigation or restoration moves the viewport; list paging, background refresh and size updates do not. Navigation history never mixes with file-version History, writes to disk or polls.

Version lifecycle

SituationStoredShown
Repeated edits, one turnOriginal before; after updated. Records replaced only after the new version commits.One net change
Interrupted savePending-confirmation marker. Success not inferred; after not invented from disk.Incomplete, no exact recovery; never “no changes”
Cancelled attempt, confirmed uncommittedMarked abortedNo change
Corrupt or unsupported manifestKept; no empty history created, nothing overwrittenExplicit error. Only a truly absent manifest means no records.
Reopen sessionSame durable records; never script output or memorySame files, Undo or Reapply
File changed laterUnchangedRecovery blocked, later edits kept
Save order and publication
  1. Write each before and after as an independently complete file; verify it; fsync the version directory.
  2. Publish the manifest. A failed update leaves referenced content intact; a failed attempt never overwrites published versions.
  3. Retry rereads the current file as before only after explicit cancel of an unsuccessful attempt. A success keeps the turn's first before.
  • Regular-file snapshots compare descriptor metadata before and after reading, and path metadata before opening and after reading.
  • Device and inode must agree; metadata from different OS APIs is never compared as if alike. Any change aborts publication.
  • The path observation supplies the stored mode.
  • Legacy migration on Windows opens staged files writable before flushing and keeps the source until publication succeeds.

Old manifests and blob_ref stay readable without bulk rewrites. Lost history is not reconstructed. OS crashes and programs ignoring locks may need manual recovery: evidence is kept, uncertain overwrites refused.

Publishing documents: write(file_path, source_path=...)
TopicContract
ArgumentsExactly one of content or source_path. The source is a local regular file under read permission, up to 64 MiB. Identical paths, directories, links and oversized or unreadable sources fail before any change.
Target checksTargets keep write authorization, read baseline and approval fingerprint. Source and target fingerprints join approval waits and are rechecked before publication.
WriteBytes go to a complete temporary file in the target directory, then replace. Failure cleans up and keeps the target. Raw bytes, never text-converted.
LocksAdvisory locks serialize cooperating writers only. Windows closes handles lacking delete sharing before replacement and revalidates; no OS conditional replace.
Read firstModels read originals, then generate staged versions. Binary reads return type and byte count. New files need no prior read.
CallersGenerators call this path; text tools keep write, edit and apply_patch and share prepare, commit and abort. CheckpointStore owns state; Review and summaries are projections.
Not providedWord tracked changes, PPT visual diffs, Office semantic diffs, remote stores (these need conditional writes and verifiable version IDs before claiming recovery), full-disk scans, polling, plugin registry
Human edits, autosave and editor lifetime
TopicContract
Shared pathHuman and model writes share version validation, complete-file publication and immutable before and after. project_file_write idempotency records hold results and fingerprints, not versions.
AttributionHuman records use actor=user; model records link the real session and turn. No fabricated chat turns; human history never becomes a sidebar session. History aggregates by file; turn Review keeps attribution.
RetentionHuman project edits belong to projects, model records to sessions. Aggregate indexes reference versions without copies. Archived sessions stay readable. Permanent deletion removes owned versions and caches must not redisplay them; Memory sources show “Original session deleted” or lose links. Project files and human history survive chat deletion. Moved projects recover by current location; offline access is read-only. Legacy history backfills in bounded batches; unverifiable ownership is unavailable.
AutosaveEditor undo handles immediate changes. Drafts persist first; files publish after a short coalescing window, never waiting for a history period. Each publication validates the read revision; retries are idempotent; late responses cannot overwrite newer drafts. Failures keep drafts with a retryable error and do not close tabs.
History periodContinuous editing about five minutes apart. Switching documents, ending editing or recovery also closes a period. Restart reads records, never current files.
Rich editorsIndependent of tabs: views hide while exporting engines live, and engines release only after the newest content reaches durable drafts. Office iframes survive React remounts and DOM moves. Rename and recovery await final export; failure keeps editor and draft. Preview and edit share one instance; history instances cannot write. Rename disables editing and reopens the new path after success.
ClosingNever waits: the tab goes at once and the pane stays mounted out of sight until the export is saved. A native editor is exported only for changes it reported: closing, refreshing or replacing one nobody changed never writes the file. Edits not yet exported are asked about first: Save, Don't Save or Cancel.
Incomplete readsAn engine that reads a file with slides or sheets missing would, on export, write back only what it kept. So a writable PPTX or XLSX editor is not bound to the document until one export, made as it opens and never kept, lists as many slides or sheets as the file (apps/web/lib/documents/office-fidelity.ts). One that lists fewer is not opened: an error names both counts and the file is left as it is.
MeasuredONLYOFFICE read a 10-slide deck written by python-pptx as 0 slides and, on close, replaced the file with an empty one

Mutation journal

One manifest per turn, under CheckpointStore (openprogram/state/store/snapshot/checkpoint/). Each file entry:

path, operation
create, modify, delete, rename
before, after
{kind: "regular", digest, blob_ref, mode, size} or {kind: "absent"}
status
Prepared, committed or aborted, with prepared_at, committed_at
stats, diff_state
Lines added and removed, binary; available, large, binary or timeout
recoverability
Exact or unavailable, with unavailable_reason
mutation_sequence
Durable and monotonic; multi-turn folding uses this, not DAG order
Invariants
ItemInvariant
Prepared, committedPrepared persists before the write; committed only after confirming the after state. If preparing fails, the mutator stops before touching disk.
absentAbsence was confirmed. A baseline read failure is recoverability=unavailable, never absent.
unavailableOnly for journaled mutations whose size or type policy omits blobs, never to hide journal failures
FoldingSame-file edits in a turn fold to net first-before to last-after; rename keeps lineage. Regular before and after both keep blob refs.
PathsRecanonicalized at capture, plan and apply; parent chain, leaf lstat, device, inode and link count are checked with validated handles or no-follow primitives
Revert, Restore, ReapplyAlso transactions; originals are immutable. Current branch folds the active lineage only.
BoundariesEach prompt defines before_turn, assistant completion after_turn; the UI names the restored boundary

Four Review scopes

ScopeSourceContainsRecovery
This turnCommitted change sets of an origin turnParent's change set plus owned children, each with its own producer turn, deduplicated, actors shownUndo or Revert: exact receipts across the closure, terminal actors, matching digests
UnstagedGit working tree against the index, plus git ls-files --others --exclude-standardChanges not yet staged, honouring .gitignoreNo turn Undo; hunk Revert; Stage. Non-Git: unavailable.
StagedGit index against HEADChanges staged for the next commitNo turn Undo; Unstage. Non-Git: unavailable.
BranchActive-lineage journal projectionAll turns and explicit revert, rewind, reapply; no siblings or external writesFrom a specific turn or checkpoint; no one-click branch Undo

Rewind

One plan, one transaction. WebSocket phase defaults to plan; apply needs plan_hash and idempotency_key. Plan statuses: ready, unavailable, blocked, stale_plan, error. Intent ends committed, rolled_back, recovery_required or aborted.

PhaseRuleOn failure
Resolve lineagePredecessors from HEAD to the target non-root user turn; subtrees only through explicit ownershipOff the active branch: rejected
Target stateEach prompt that starts a turn has a checkpoint, .file-recovery/<session>/checkpoints/<user_msg_id>.json: every tracked path to a state, content in shared blobs/<sha256>. A path it does not list takes the state recorded just before its first later edit. A prompt with no checkpoint (older sessions, steered messages) folds the journal on read, with no data rewrite.A failed capture never blocks the tool; the path is unavailable. A prompt with no usable backup (evicted, journal_gap, no_checkpoint) reports unavailable for code modes; Conversation only stays.
Plan rowsEach target against the file on disk: restore, delete or skip with a reason and +A −D (1 MiB per file, 3 s budget). Only paths written by the withdrawn turns are eligible. Later changes outside that range are protected, including shell, manual, hunk Revert and Undo changes. Planning writes nothing and runs no crash recovery while a run owns the session.Any skipped row blocks the entire code recovery before mutation: other_session (another session started or finished a trusted write after the target state was read; per-path index of each session's newest write under mutation-locks/last-writers/), changed_since_edit (the file no longer matches the recorded writes, or those writes have an intervening change), unsafe_path, parent_missing, no_backup, changed_while_reading. A running owned job blocks with job_running.
Other branchesA checkpoint names its turns (turn_ids); a file's state before a turn's first edit is recorded in that turn's checkpoint. The target is the listing read earliest in the range. For a path another prompt's turn also wrote, it is the earliest listing read after that write and before the range's own first write (first_sequence in the turn's journal record). A write a committed rewind took back (restores_through on its intent) is not counted.That write is later than the range's own first write, or no listing was read between the two: changed_since_edit. See two branches.
Prepare intentHolding the run slot, save the current content of each planned path as a blob, so a change no journal saw can still roll back; persist plan id, expected head, before and target images, mode, skipped rows; idempotentPlan rebuilt under the workspace lock; a different hash returns stale_plan, zero writes
ApplyWorkspace lock; per-action state persisted; atomic replace; delete only on matching digestRollback only if the digest still equals what this transaction applied; otherwise recovery_required, external content kept
BranchMove the current branch with expected-head compare-and-set. The branch identity, withdrawal visibility and recovery metadata commit together. A pre-first-turn target uses the persistent ROOT.Files restored per intent; source and active branch stay
FinalizeAppend transaction and navigation events; old nodes not marked; writer epoch advances so old tasks cannot write backStartup finishes or rolls back open intents, never guesses

Multi-file recovery is not one filesystem atomic operation. The guarantee comes from durable intents, rollback staging, per-file atomic replacement and restart recovery. A preflight over thousands of files pages its conflicts; once applying, it finishes or rolls back.

ModeFilesConversationNext turn
Code and conversationRestoredCurrent branch rewound after commit; prompt prefilled; withdrawn messages remain only as recovery historyNormal
Conversation only (conversation)KeptCurrent branch HEAD compare-and-set to the message before the target; later messages are withdrawn, not exposed as a branchTold files were not reverted; send not blocked
Code only (code)RestoredKept; the transaction compares and sets HEAD to itselfTold files went back without the conversation

After a rewind

ItemRule
Rewind edgeSession meta rewind_edges, written with the HEAD move. Marks computed for the current chain: pending until the next send, then back; forward after Undo.
Undo, RedoCompare-and-set HEAD along the edge while holding the run slot. Messages only.
Note to the modelSession meta pending_rewind_note, read once when the next turn builds its system prompt: conversation_only, restored, branch_kept_files, partial (an earlier conversation-only rewind still warns about files), code_only, undo_kept_files.
Read trackingRewind, Undo and Redo drop the session's read baselines; the next edit reads the file first.
Copying a sessionbranch_session carries checkpoints, blobs and write provenance for the copied messages and records source and mutation sequence in origin.json, so the source's earlier writes do not count as another session.
Retention100 turn directories and 100 checkpoints per session, counted separately. intents, intent-locks, checkpoints, blobs are never turn directories. Removed turn ids go to evicted-turns.json; a blob goes when no kept checkpoint or open intent refers to it.
Recovery objects
ObjectPurpose
BranchStable id, HEAD, head_version, writer epoch; sessions store active_branch_id. Explicit Rewind moves the current branch HEAD backward; normal branch navigation never restores files.
CheckpointThe recovery destination, without duplicating file lists
Change setProducer and origin turn, actor. Cards group by origin and keep producers.
PlanRead-only preview; plan hash prevents preview-to-confirm races
IntentConfirmed durable record: idempotency_key, plan_hash, expected_head_id, target_head_id, source and target branch, actions. Restart never infers progress from directories.

Branches and actors

ScenarioMeaningFiles
Branch from a resultTarget branch created and activated; source HEAD unchangedUnchanged, “Files stay as they are”
Fork into a new taskSource task and HEAD kept; conversation history copiedFiles stay shared unless the user explicitly requests filesystem isolation.
Checkout siblingSelects another conversation lineage, without changing files or demanding file alignmentAll ordinary branches share the current workspace. Clear read baselines and tell the model that files were not restored. Reads and writes follow normal permissions and current-file checks.
Owned childBy relation, creates_agent, origin turn; own producer and change setsRunning blocks parent restore. Finished joins the closure.
Independent actorBackground terminals, job runners, channels, schedulersRunning blocks same-workspace restore; writer epoch stops old write-backs
Existing peer, cross-sessionLinked, not ownedNot modified; listed in impact; overlap blocks code recovery
Worktree childIndependent stateParent Undo or Rewind never touches it; a merge is its own transaction
Sibling branchOutside RewindJournals unchanged; current files shared on return
Resume, Archive, Purge
OperationContractNever
ResumeUnknown session: not found. Open transactions recover before real node ids, branch and revision load.Treat an unknown id as new or fabricate ids
Empty branchHEAD is the persistent ROOT. Web, TUI and CLI share one branch result.Pick another tip automatically
ArchiveRefs only; nodes, journals and checkpoints stayDelete shared ancestors
PurgeReference-counted, explicit, exclusive objects onlyDelete leaves one by one or bypass references

Conflicts and unavailability

SituationResult
Later edit to the same file: RevertNo reverse merge
Later edit to the same file: RewindLater changes outside the withdrawn range block the complete code recovery; conversation-only remains available
Plan changed after confirmationstale_plan, zero writes
Running turn or background taskNo confirmable plan
Symlink, hardlink, special fileNot followed or overwritten; path and reason shown
Blobs garbage-collectedReview readable, code restore off
Large file, no blobPath and size exact; line counts unknown; no Undo
Non-Git workspaceJournal scopes work; Unstaged and Staged unavailable
ReapplyNeeds post-revert digest, no later same-lineage mutation, after blobs
Crash during applyRolled back, or recovery_required if rollback would destroy external writes
Exact edit to ignored or authorized outside pathJournaled, Undo works, not in Unstaged
Ignored background log growthExcluded by design
Databases, APIs, deploys, installs, Git index, processes, network, unrecorded BashOutside Restore; confirmation lists possible repeated effects

Interface

PlaceShowsDoesNever
Assistant turn cardFile count, net additions and deletions including zero, first three files, about 40 px header, 19 px FeatherIcon, 2.5 px two-colour proportion bar. Basenames emphasized. At 420 px or less: “N files”.Latest: Undo, then Redo. Historical: Revert, then Reapply. Every turn: Review. Header shows executable actions; unavailable and blocked explanations in the footer.Header chips, disabled badges, product branding
User messageRestore checkpointImpact sheet, named boundary, default code and conversationRestore on click
Conversation ⋯ menuCopy conversationHistory only; files stayImplicit restore
Changes tabFour scopes; file list and single-file diff; source labels; counts over the full filtered resultUnified or side-by-side, line comments, Open file, Reveal. A scope or filter change clears cursor, selection and diff.Turn Undo in Workspace; client-only filtering
Impact sheetPrompt, turn and file counts, branch result, mode, conflictsConfirm; cancel has no effectForce while blocked
Branch switchConversation changes; files stayContinue talking and working on current filesFile-alignment prompts or tool restrictions caused by branch history

File queries

Project explorer and Review read server snapshots. The order is fixed: resolve owner, snapshot, filter and sort on the server, paginate, render one page.

QuerySourcePageGoes stale on
DirectoryProject root by project_id; normalized, root-relative, no traversal or symlink escapeDirectories then files, by path; 100 per pageDirectory version, ignore rules, project, path, sort
Project searchSame root and rules, independent of expanded nodes; names or relative pathsFiltered, ranked, then pagedProject switch, expired snapshot, root version
Review scopeJournal, or Git HEAD, index, worktreeServer filters by category, path, operation, diff state; 100 per page; totals cover the full resultScope, message, filter, sort, snapshot, candidate or identity change
Review file diffPaths from the same snapshot; recorded blob pairs200 lines or 256 KiB per requestSnapshot, candidate, identity or blob pair change

Stale answers are STALE_SNAPSHOT or STALE_CURSOR; clients restart from page one.

Cursors and Workspace snapshots
  • Cursors are opaque and valid only for the same snapshot, owner, query kind, filter and sort. Offsets, path anchors and cross-project tokens are rejected. Directory, search, Review list and diff cursors are not interchangeable.
  • Snapshots keep a stable candidate order. Later pages never rescan. Capacity and TTL eviction report stale.
  • A Workspace snapshot fixes staged, unstaged, untracked and rename or delete paths by relative path, pinning HEAD base, index blob and worktree identity, and old and new paths. Diffs render from that pair, never a later git diff.
  • Before later pages or diffs: status vector, index tree and no-follow worktree identity are reread. Any change is stale.
  • The worktree side compares as Git does: when text, eol or core.autocrlf clean line endings, CRLF becomes LF first (for auto, only when the indexed blob has no CR), so a CRLF checkout of an LF blob shows only edited lines.
  • Hunk revert edits the file in its own line endings.
  • Snapshot blobs share Review quotas; missing or expired blobs report stale, never approximate from the worktree.

File WebSocket requests

RuleContractNever
request_idClient UUID on every browse, read, write, rename, copy, delete, reveal and Review request; echoed on every resultMatch by type, path or arrival
Response checkSole pending key, plus action, project, session, snapshot, target. Unmount or new query forgets old keys.A global queue
idempotency_keySeparate key on side effects, with optimistic-lock conditionsTreat a new request_id as a new write
Errorserror_code: STALE_SNAPSHOT, NOT_FOUND, CONFLICT, INVALID_REQUEST, IDEMPOTENCY_KEY_CONFLICT, OUTSIDE_PROJECT, TOO_LARGE, RECOVERY_REQUIREDApply unidentified frames
Write idempotency
TopicRule
Record keyOwner (profile and project), action, key
FingerprintAction, owner, canonical payload (normalized paths, parameters, digests), preconditions (mtime or digest, paths, overwrite conditions, directory versions). request_id is excluded.
RecordMoves from in_flight to completed, conflict or error, with operation_id and the terminal result, claimed in the same durable scope as the mutation
Same key, different fingerprintIDEMPOTENCY_KEY_CONFLICT, zero writes
Same fingerprint, in flightBinds the operation until the deadline, then reports in flight; clients retry that key only
Same fingerprint, completedReplays without re-executing
RestartRecovers or classifies in-flight records before replay. Expiry never deletes them or replays a different fingerprint.

Cache and drafts

StoreLimitRules
Read cache64 entries, 16 MiB, LRU; keyed project, path, revisionSuccessful complete reads only; no dirty text
Text drafts32 entries, 8 MiBIndexedDB openprogram-file-drafts, stores drafts, project_index; never evicted by LRU
Binary document drafts32 entries, 64 MiB each, 256 MiB totalStores document_drafts, document_draft_metadata; per-file Blobs
Draft rules
TopicRule
KeyProject plus canonical path; never shared across projects
ContentsUTF-8 text, baseline bytes, revision, mtime, update order. Quotas count TextEncoder bytes of draft, baseline and metadata.
KeptReload, unmount, project switch and cache eviction keep dirty drafts. Server changes keep them in conflict state, saving against the original baseline.
Never resets buffersTree refresh, Review changes, registry gaps, background responses
Create, update, rename, discardDraft and index in one transaction
QuotaOver quota: no writes. Budget is checked before accepting input; full storage offers save, revert, export or discard. On QuotaExceededError the last durable version stays and growth pauses.
Rename, copy, deleteRename moves keys atomically; copy shares none; failed operations change nothing. Deleting a file with a draft requires save, export or discard.
Project cleanupWaits for an explicit command, which does not exist yet; absence from list_projects is not authorization. Startup rebuilds a missing index by scanning, without deletion.
PrivacyThis origin's IndexedDB only, outside logs, telemetry, model context, WebSocket and sync. Recovery never uploads automatically.

Limits, security, parity

TopicRule
Turn finalizeCost depends only on changed paths. Summaries persist and return with transcripts; cards mount at most 20 rows and no diffs.
Diff budgetOver budget returns timeout metadata, never blocking the Agent or approximating
Recovery blobsContent-addressed, deduplicated, local-user only, outside session Git.
GCNever collects pinned checkpoints, active tasks, unresolved conflicts, open intents or branch-referenced checkpoints
SecretsBlobs outside logs, telemetry and model context. Session deletion cleans unreferenced blobs. External paths need authorization at capture and recovery.
Older sessionsRead as they are. Journal gone or discontinuous: code cannot be restored, Conversation only offered
TUI, CLI, App, WebSame server plan before mode selection and confirmation, same idempotency; UI renders server impact without recomputing
Line commentsBound to change set, blobs, side, hunk and line. Scope or recovery changes mark them stale.
Modules
ModuleDoesDoes not
openprogram/interfaces/server/ws_actions/files/Root authorization, listings, search, reads, mutations; validates ids and snapshotsReview computation, browser cache
openprogram/interfaces/server/ws_actions/turn_files/Review scopes, filtered pages, snapshot-bound diffsProject search
openprogram/runtime/conversation/rewinds/revert.py, rewind.pySingle-turn and multi-turn transactionsGit reset or revert; those keep separate entries
apps/web/lib/net/ws/ws-request.tsRequest ids, pending registry, timeouts, response checksMatch by type
apps/web/lib/files/files-shared.tsBounded read cache, drafts, invalidationReview pages, socket listeners
FileTree, FilesPageServer pages and search resultsScan loaded nodes as search
ReviewTabPaneScope, filter, snapshot, cursor, selectionCurrent-page filtering
FileTabPaneBuffers, conflicts, draft lifecycleDirect turn diffs; comparisons open in Review
Compared with Claude Code and Codex
SystemConfirmedTakenNot taken or unknown
Claude Code checkpoints (SDK)Per prompt, tracks Write, Edit, NotebookEdit, not Bash. Restore code, conversation or both. Other subagent changes not restored except foreground context: fork. Non-regular paths skipped with warnings. 100 per session; cleaned by cleanupPeriodDays, default 30.Prompt checkpoints, separate options, explicit unavailableWe block or roll back on any path failure; skipped paths cannot succeed
Fork, VS Code/branch copies conversation onlyExplicit conversation Branch and source-preserving Fork share current files; worktree isolation is a separate explicit actionUndisclosed reuse of current files after fork
Desktop, WebFile list and single-file diff, line comments; Web also Create PRSeparate Review, on-demand diffs, line feedbackBranding, dimensions, PR controls. Review code on Web unconfirmed.
Codex turn diffIn-memory aggregator of exact deltas for the current turn; inexact data invalidates itExact deltas as attribution; we add durable receipts and blobsA durable Undo journal is not claimed for Codex
Codex history, backtrackthread/fork copies history; thread/rollback deprecated; thread/revert conversation onlySource-preserving forks, immutable historyUnpublished per-turn file Undo unknown
Codex Git, reviewLast turn versus Git; Unstaged, Staged, Commit, Branch; multi-repo; --exclude-standardWorkspace sub-scopes, ignored-file exclusionGit Discard is not Restore
DeepSeek JSONL, repair, fs-localSynced temp files, exclusive publish, directory sync, corrupt versus missing; interrupted tools marked unknown; locking and version conditions without full-file undoIntegrity and interruption principlesSession-log recovery is not file recovery
Codex shell snapshotStaging, verification, replacement of shell environmentsThe staging patternIt is not document versioning

Neither public reference guarantees external-concurrency rules, multi-file atomicity, digest preflight or crash consistency. Complete preflight, workspace locks, durable intents, rollback staging and crash recovery are OpenProgram's.

Acceptance

AreaBoundaryMust hold through public entriesExcludes
Journalprograms/tools/files/, turn finalize, checkpoint storeAn existing file over 5 MiB is not new on first edit; ignored Bash logs stay out; failed edits leave no receiptReview UI, user Git
Undo, Revertconversation/rewinds/revert.py, workspace lock, intentLater same-file edits: zero writes. Mismatched digests prevent deletion. Mid-operation I/O never partly succeeds.Multi-turn HEAD moves
Rewindconversation/rewinds/rewind.py, head API, intent recoveryOne file across three turns; file failure keeps HEAD; siblings unaffected; stale plans write nothingCompaction, DAG schema
Reviewturn_files/, metadata, center tab, cardHistory does not query per message; Workspace excludes ignored files; one bounded diff mounted; consistent provenance. Plain replies mount no card; empty hides; failures retry.Third pane, new window
Shared workspace, ownershipCheckout, active-lineage fold, ownershipSwitching permits normal work on current files, with rereads before edits. Running owned children block parent restore; finished ones join. Peers and worktrees untouched.Workspace cloning
Query snapshotsfiles/ query, FileTreeSearch finds unexpanded files. Directory changes after page one cannot enter old cursors; cross-project cursors rejected. Concurrent create or rename restarts in stable order.Full-text search, layout
Request identityFile dispatch, ws-request.ts, idempotencyOut-of-order responses reach the right caller. Missing request_id rejected. Retries replay; different fingerprints conflict.Non-file protocols
Cache, draftsfiles-shared.ts, IndexedDB, tab lifecycleOnly clean LRU entries evicted. Dirty drafts survive reload, tab and project changes. Quota failure keeps old drafts atomically and shows a notice.Collaboration, remote sync
Filtered Reviewturn_files/, ReviewTabPaneCategories cover all pages. Changes invalidate cursors and diffs. Later index or worktree changes report stale.New fact sources
Single entry pathFile module call graphNo global queues, id-less actions, direct turn_file_diff UI calls or legacy fallbacksHidden compatibility switches
Documentswrite, sessions, historyDOCX and PPTX versioned; byte-identical undo and reapply; external changes conflict; failed writes keep targets; text writes still validOffice diffs
Each formatFileViewer, DocumentWindowReal files, not fabricated binaries: edit, write back, reopen, recover. Concurrent edits, interrupted writes, corruption, oversized files, cancel, offline, project moves, legacy history.Partial-format success
PDFUnder the real shell policyNonblank selectable pages, clipboard cases, sidebar, zoom, search, read-only history, annotations persisted and read by a separate decoder, failure retention, external fetch refused, same checks without native toHex and Math.sumPrecise in page and workerA permissive harness is not installed-App evidence
CrashEvery intent phaseEnds committed, rolled back or per-path recovery_required; never false commit or external overwrite

Implementation status

ItemState
BuiltJournal, Undo, Revert, code-and-conversation Rewind, three Review scopes, query snapshots, request identity, durable mutations, bounded cache, drafts, unified file window, History, format adapters, optional Office install, document publication
PDFReader, annotations and runtime compatibility built
MarkdownRendering and heading navigation built; installed-App acceptance pending
Not builtProject unlink and its draft cleanup; Office semantic diffs; remote conditional storage

Chat turn visual specification

Shared workspace and same-branch rewind are implemented. Independent specification and quality reviews and the affected verification suite pass.

Last updated · 2026-11-25