GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — #551 Per-turn diff and parent link on v2 by ivanfenenko · Pull Request #775 · opencode-mobile/opencode-mobile

Conversation

@ivanfenenko

@ivanfenenko ivanfenenko commented Oct 20, 2026 •
edited by blacksmith-sh Bot
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Collaborator

Summary

  • v2 Last turn: getSessionDiff calls GET /api/session/{id}/diff with from = the turn's user message and context=12, replacing the synthetic 404. The response uses the same FileDiff.Info shape as v2 Working tree, so the viewer is unchanged. The tool-card changes tap and the Review Changes pill read the same capability, so they turn on with it.
  • Release gating: the /openapi.json contract probe now reads per-turn diff support alongside archive (V2SessionArchiveContract → V2ServerContract, returning V2ServerFeatures). Servers before opencode 2.1.0 keep Working tree only, with no error.
  • Refetch on idle: a Changes screen showing Last turn refetches when its session sends session.idle. This covers a Changes screen opened from a tool card mid-turn, where v2 compares against the working copy. It applies on v1 too, which also pushes no per-turn diff.
  • v2 child create: createSession sends parentID and leaves out location when a parent is set.
  • Android child lockout: the composer also locks when the loaded session has a parentId, not only when the navigation route has a parent. iOS already worked this way.

Checks

  • Android: :app:assembleDebug succeeds. 332 tests pass across the affected classes (SessionChatViewModel, Changes, SessionProtocolRepository, ConnectionProbeService, V2ServerContract, ActiveConnectionManager*, ServerProtocol*), 12 of them new. ktlintCheck reports nothing in the changed files.
  • iOS: xcodebuild test on an iPhone 17 simulator (iOS 26.5), 99 tests in 6 suites pass (ChangesViewModel, V2ServerContract, SessionProtocolRepository, ActiveConnectionManagerSessionArchive, ServerProtocolClassifier, ServerProtocolMatrix), 8 of them new.
  • Route, query parameters, response envelope and create body checked against upstream packages/protocol/openapi.json.

Issue

  • Fixes OPE-277: Per-turn diff and sub-sessions (v2) #551

Risks / Follow-ups

  • Not yet run against a real v2.1.0 server (scenario harness). Unit tests cover the wire shape only.
  • On a refetch, Changes keeps the current file list while it reloads, the same behavior as pull-to-refresh.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith with what you need.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@ivanfenenko @claude
#551 Per-turn diff and parent link on v2
63e0926
- v2 Last turn calls GET /api/session/{id}/diff (from, context 12); the
  /openapi.json probe now reads turn diff support next to archive, so
  servers before 2.1.0 keep Working tree only
- Changes refetches Last turn when its session goes idle
- v2 createSession sends parentID and omits location when a parent is set
- Android child lockout follows the loaded session's parentId

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@linear-code

linear-code Bot commented Oct 20, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
OPE-277 Per-turn diff and sub-sessions (v2)

Two v2 server features the apps only half-use today. Everything below is from upstream anomalyco/opencode branch v2 (fetched 2026-10-09, head 229b422bd6) and opencode-mobile/opencode-mobile HEAD (f9d5d13). Guesses are marked (guess).


1. Per-turn diff

What it is (plain English)

After the agent finishes a "turn" (you send a prompt, the agent works, the session goes idle), the server can tell you exactly which files that turn changed: one entry per file with +/- counts, a status (added / modified / deleted) and a unified-diff patch. That's what the user expects behind Review Changes: "here's what the agent just did", separate from all the other uncommitted changes in the repo.

What counts as a "turn"

A turn starts at the first user prompt after the session was last idle and ends at the next idle marker. Prompts you steer in while the agent is still busy belong to the same turn. Sessions that have no idle markers at all (older history) fall back to "one prompt until the next user message".

Upstream API (v2)

GET /api/session/{sessionID}/diff, operationId session.diff. Defined in packages/protocol/src/groups/session.ts (~L582), handler in packages/server/src/handlers/session.ts (~L525), logic in packages/core/src/session/diff.ts.

Query params (all optional):

  • from: a user message ID whose turn you want. If you leave it out, you get the turn of the newest user message.
  • to: a later user message ID. The range then runs through the end of that turn, so you can diff several turns at once.
  • context: how many unchanged lines to keep around each hunk. If you leave it out, the server uses PATCH_CONTEXT_LINES = 2_147_483_647, which gives a full-file patch. The TUI sends 12.

Response: { "data": FileDiff.Info[] }, with each item shaped { file: string, patch: string, additions: int, deletions: int, status: "added"|"deleted"|"modified" } (packages/schema/src/file-diff.ts). There are no before/after fields; the legacy before/after shape is v1-only (FileDiff.LegacyInfo).

Errors: 404 for an unknown session or message. 400 InvalidRequestError (Session.TurnRangeError) when from/to isn't a user message, when to comes before from, or when the range crosses a location switch. You also get a snapshot failure error, or location errors.

If no step in the turn recorded a start snapshot, the server returns an empty array. Snapshots only run in git locations with snapshots enabled (Snapshot.enabled = vcs.type === "git" && enabled).

How it's computed

It doesn't use your git history. OpenCode keeps its own snapshots, which are content-addressed git trees of the working copy. Each assistant step stores snapshot.start / snapshot.end (see the session.step.started and session.step.ended events; step.ended also carries files: RelativePath[]). The diff compares the first recorded start snapshot in the range with the last recorded end snapshot, using git tree diff (packages/core/src/snapshot.ts). If the last step is still running in an active session, the server compares against a fresh capture of the working copy instead, so it works mid-turn too.

Events

v2 has no session.diff push event (checked event-manifest.ts and session-event.ts). Clients refetch when it makes sense. The TUI refetches when the session goes running → idle ("Each completed turn replaces the last one"). The useful signals are session.status (idle/busy), session.step.ended (which has files), and session.execution.succeeded.

v1 equivalent

GET /session/{id}/diff?messageID=… returns a bare SnapshotFileDiff[] (file?, patch?, additions, deletions, status?). It reads summary.diffs precomputed on the user message (packages/opencode/src/session/summary.ts on dev). With no messageID it returns []. v1 also has a session.diff SSE event {sessionID, diff[]}.

Mapping v1 → v2: messageID → from. The response becomes {data: [...]} with required file and status. The v2 turn covers steered prompts too.

How upstream shows it

  • TUI diff viewer (packages/tui/src/feature-plugins/system/diff-viewer.tsx): a source switcher with All (branch + local), Committed, Uncommitted, and Last turn ("Latest session turn"). Last turn only shows up inside a session. It calls session.diff({sessionID, context: 12}) and auto-refetches when the session goes idle. Config diffs.source: "turn" makes it the default, and other options cover a file tree, single-file mode, and split/unified/auto layout.
  • The web/desktop app (packages/app) doesn't call session.diff today; it only uses vcs.diff.

Commits

  • 2816d1c849 feat(session): add turn diff route (#47821), 2026-09-13. Added the route, session/diff.ts, snapshot fields on steps, and tests.
  • 995f76cb63 feat(tui): add last turn source to diff viewer (#51639), 2026-09-27.
  • fee337c462 refactor(tui): anchor turn token usage on idle markers (#49001), 2026-09-14. Same idle-marker turn definition.

2. Sub-sessions (parentID)

What it is (plain English)

A session can have child sessions. Upstream mostly uses this for subagents: the main agent hands a task to a specialised agent, and that agent works in its own child session with its own transcript. The user sees a "subagent" card in the parent chat and can tap into it to watch what the subagent did. Since Sep 30, any client can also create a child session directly by sending parentID.

Upstream API (v2)

  • Create: POST /api/session with body { parentID?, title?, agent?, model?, location?, metadata?, permissions?, id? }. The description says "A parentID creates a linked child session at its parent's location." When parentID is set, the handler ignores location. The child inherits the parent's location, metadata and permissions unless you override them. An unknown parent returns 404. See session.ts group ~L220 and Session.create in packages/core/src/session.ts ~L262.
  • List children: v2 has no /children route. Use GET /api/session?parentID=<id>. parentID=null returns root sessions only, and leaving it out returns everything. Other params are limit, order, search, cursor, directory, project and subpath.
  • Session.Info has parentID? and, separately, fork?: {sessionID, boundary}.
  • Delete cascades: Session.remove deletes all children first.
  • Events: session.created carries parentID?, plus session.deleted. session.status (idle / busy / retry) is per session. Nothing pushes child status up to the parent automatically; clients derive it.

Agent-spawned vs user-created vs fork

  • Agent-spawned (subagent): the subagent tool (packages/core/src/tool/plugin/subagent.ts) calls sessions.create({parentID: <current>, title: description, agent, model}), then prompts the child with "You are a subagent spawned by another session." Input is {agent, description, prompt, model?, sessionID? (continue an existing child), background?}. Output is {sessionID, status: "completed"|"running", output}. While it runs, it emits session.tool.progress with metadata {sessionID, status: "running"}, so the parent's tool card knows the child ID right away. Nesting depth is limited by experimental.subagent_depth (default 1). In background mode the parent is notified when the child finishes.
  • User/plugin-created: a client sends parentID to POST /api/session. This was added for plugins in 19f203837e feat(plugin): support parent session creation (#52359), 2026-09-30.
  • Fork is not a child. POST /api/session/{id}/fork {before?} creates a session with parent_id = null and fork.sessionID = parent (projector). Forks show up as root sessions, even though the endpoint description says "child session".

How the web app (packages/app) shows them

  • The home list and command palette load only roots (session.list({parentID: null})).
  • The subagent tool card in session-ui/src/tools/tool-renderer.tsx shows the agent name and color, the description as subtitle ("(background)" when backgrounded), and a spinner while the child's session_status isn't idle. Tapping it navigates into the child session.
  • Inside a child session, the composer is replaced by "Subagent sessions cannot be prompted. Back to main session." The header shows a breadcrumb back to the parent chain and a working indicator while the child runs. Permission and question requests from children bubble up to the root (session-request-tree.ts).
  • TUI keybinds: session.parent (up), session.child.next / session.child.previous (right/left) and session.child.first (down, "Toggle subagent picker"). The composer's subagent picker supports navigate and interrupt (ctrl+d).

v1 equivalent

POST /session {parentID?, title?, …}, GET /session/{id}/children, and the task tool, whose child ID sits in tool metadata sessionId.


3. App today

Per-turn diff

  • Android domain/session/V2SessionRemote.kt: getSessionDiff throws SessionError.Http(404, "session message diff is not available") without calling the server. v1 (V1SessionRemote.kt → SessionsApi.getSessionDiff, GET session/{id}/diff?messageID=) works.
  • iOS Domain/Session/V2SessionRemote.swift: the same hardcoded 404. v1 goes through SessionsAPIClient.getSessionDiff.
  • Capability gate: ServerCapabilities.supportsSessionMessageDiff is true for V1 and false for V2. It lives in android/.../domain/connection/ServerProtocol.kt and ios/.../Domain/Connection/ServerProtocol.swift.
  • Changes screen: ui/changes/ChangesViewModel.kt and UI/Changes/ChangesViewModel.swift have the sources WorkingTree ("Git changes", vcs/diff context 12) and LastTurn ("Last turn changes", getSessionDiff(sessionId, messageId), no context). On v2 only Git changes is offered, because the capability is false.
  • Review Changes pill: ui/sessionchat/region/SessionChatReviewChanges.kt/.swift plus LastTurnReviewChangesStore.kt/.swift. The candidate is the last non-pending user message, and only when the capability is on and the session isn't busy. The pill only shows after the Changes screen has loaded and published a summary, so it never appears on v2.
  • From a tool card into Changes: on Android, Navigation.kt (SessionToolGroup → Changes(messageId = owningTurnMessageId, LastTurn)) and SessionChatScreen.kt (fileChangeNavigationTarget) are both no-ops when supportsSessionMessageDiff is false.
  • SessionDomainAdapter.toFileDiff already handles file/path, patch, and the legacy before/after fields.

Sub-sessions

  • Create: Android SessionsApi.createSessionV2(directory, title) and iOS SessionsAPIClient.createSessionV2(directory:title:) build V2CreateSessionRequestDto(title, location) and have no parentID field. V2SessionRemote.createSession drops parentId on both platforms (iOS names it parentID _). v1 passes it through via CreateSessionRequestDto(parentId, title). (guess) No current UI calls createSession with a parent anyway: Android SessionChatViewModel calls createSession(directory = worktree).
  • List children: v2 is already implemented. Android V2SessionRemote.listChildSessions → listSessionsV2(directory, parentId = id), and iOS → listSessionsV2(parentID:). I didn't confirm any UI caller; GitHub code search doesn't index the private repo.
  • Home list: listSessionsV2 sends no parentID, so the server returns all sessions. Android MainScreenViewModel and iOS ProjectListHomeViewModel then filter client-side with .rootSessions().
  • Subagent rows in chat: this works on v1 and v2. SessionChatTimelineBlocks.kt and .swift treat tools named task or subagent as ChildSessionRow (agent name from agent/subagent_type, child ID from metadata sessionId/sessionID, with a live elapsed timer). SessionChatChildSessionRow.kt/.swift and OpenCodeChildSessionRow render the row. Tapping it pushes a child SessionChat(parentId = parent): Android through Navigation.kt onChildSessionClick, iOS through SessionChatView.swift childSessionTarget.
  • Child lockout: both platforms have ChildLockout composer states. Android derives it from the navigation parentId (SessionChatScreen.kt, isChildSession = parentId != null). iOS derives it from session.parentID. On Android, a child opened without a parent in the route would show a normal composer (guess, not verified).
  • Permission tree: orderedPermissionRequests in Android SessionChatViewModel.kt walks root → children by parentId.
  • Mapping: SessionDomainAdapter.toSession(V2SessionDto) maps parentId, with the comment "A fork is a top-level session; only a real parentID marks a subagent child."

To do

Per-turn diff (v2)

  • ☐ Add getSessionDiffV2(id, from, to?, context?) → GET api/session/{id}/diff that decodes {data: FileDiff.Info[]}, on Android (SessionsApi.kt) and iOS (SessionsAPIClient.swift).
  • ☐ Wire V2SessionRemote.getSessionDiff (Kotlin and Swift) to it. Map messageId → from, and pass context=12 so we don't download full-file patches (the server default is full file).
  • ☐ Set supportsSessionMessageDiff = true for V2, or split it into a v2-specific flag gated on server version if older v2 servers (before 2026-09-13) must keep working (guess: older v2 servers return 404 for this route).
  • ☐ Map 400 TurnRangeError ("spans a location change") and an empty array to friendly empty or error states in Changes.
  • ☐ Review Changes pill: on v2, consider fetching the summary (counts only) when the session goes idle instead of waiting for the Changes screen, mirroring the TUI's running→idle refetch. Today the pill only shows after Changes has been opened.
  • ☐ Per-turn entry points: make the tool-card "changes" tap (owningTurnMessageId) work on v2, and consider a "Changes in this turn" action on each user message.
  • ☐ UI ideas: a source switcher like the TUI's (Last turn / Uncommitted / Branch), a multi-turn range (to) such as "since this prompt", and a live diff while busy (the server diffs against the working copy for a running step).
  • ☐ Tests: adapter decoding for {data:[…]}, and capability and source selection in ChangesViewModel on v2.

Sub-sessions (v2)

  • ☐ Add parentID to V2CreateSessionRequestDto on both platforms, and don't send location when parentID is set (the server ignores it).
  • ☐ Pass parentId through V2SessionRemote.createSession (Kotlin and Swift).
  • ☐ Home list: send parentID=null in listSessionsV2 for root-only lists. That cuts payload and paging; keep the client-side rootSessions() as a fallback.
  • ☐ Child sessions screen or section: use the existing listChildSessions to show a parent's subagents (title = task description, agent, status from session.status / api/session/active), including ones whose tool card has scrolled away.
  • ☐ Android: derive child lockout from session.parentId, not only the route parentId, like iOS does, so deep links and notifications into a child are also locked.
  • ☐ Child header: breadcrumb or "Back to main session" to the parent, plus a working indicator while the child is busy (upstream web pattern).
  • ☐ Parent status: show "subagent running" on the parent while any child is busy (derive from session.status events for children).
  • ☐ Optional: a user-facing "New sub-session" action. (open question) Upstream's web UI has none, and children can't be prompted in the web UI.
  • ☐ Make sure forks (fork.sessionID, parentID null) stay top-level and aren't shown as children.

Open questions

  1. Should the app prompt into a user-created child session? Upstream web blocks prompting in all child sessions ("Subagent sessions cannot be prompted"), but the server itself doesn't seem to block it (guess: only the UI blocks it).
  2. Is there a server version or capability flag to detect session.diff and parentID-on-create support on v2, or do we probe and treat 404 as unsupported?
  3. Default context for the per-turn diff: 12 like the TUI and our VCS call, or full-file for the in-app "expand context" feature (FileViewerState.toggleContextMode)?
  4. Should Review Changes default to Last turn on v2 (like v1 does today) or to Git changes?
  5. Is listChildSessions currently called anywhere in the UI? This needs a local grep, since GitHub code search doesn't index the private repo.

Review in Linear

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ivanfenenko
ivanfenenko marked this pull request as ready for review October 20, 2026 21:02
@ivanfenenko

ivanfenenko commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator Author

Real-app evidence (v2)

Both apps built from this branch (63e09263), talking to a real opencode v2 server (~/Projects/opencode dev bc5ebf00a4, /api/info version local) through the scenario harness. The scripted model played tool-row-tour, which runs glob, grep, read, edit src/format.ts, write test/rounding.test.mjs, and a shell command that waits for permission. Devices: iPhone 17 simulator (iOS 26.5) and Pixel 9a emulator.

The server's own answer for that turn: GET /api/session/{id}/diff?from=<user msg>&context=12 → src/format.ts modified +5 −1, test/rounding.test.mjs added +11 −0.

Chat (v2) Tool-card tap → file diff Changes · Last turn
iOS
Android

Tapping the Edit card opens Changes on Last turn, scrolled to the tapped file. Going back shows the turn's 2 files with the same counts the server reports. Before this PR, on v2 this tap did nothing and Last turn was hidden.

Contract probe

Harness request log, one probe per app on connect:

248 GET /openapi.json 200  OpenCode Mobile/1 CFNetwork   (iOS)
502 GET /openapi.json 200  ktor-client                   (Android)

This server declares /api/session/{sessionID}/diff, so Last turn is enabled.

Refetch when the session goes idle

A second run was held on its shell permission (screens below). I opened Changes from the Edit card mid-turn, then answered the permission as another client. Harness log for that session:

iOS
435/439 app GET /api/session/ses_…MxpS/diff?context=12&from=msg_…BshC  200   (opened mid-turn)
466     server.event session.execution.succeeded                         (turn ends)
467     app GET /api/vcs?…                                                (refresh resolves sources)
468     app GET /api/session/ses_…MxpS/diff?from=msg_…BshC&context=12  200   (refetch, no user action)

Android
684     app GET /api/session/ses_…2us/diff?from=msg_…Wa5m&context=12   200   (opened mid-turn)
711     server.event session.execution.succeeded
715     app GET /api/session/ses_…2us/diff?from=msg_…Wa5m&context=12   200   (refetch, no user action)
iOS mid-turn Android mid-turn

In this scenario the edit and the write both happen before the permission, so the file list is the same before and after the refetch. The request log is the evidence that it refetched.

Not covered on device

  • parentID on v2 create: no app screen creates a child session, so this is covered by unit tests only (v2CreateSession_withParentSendsParentIdWithoutLocation / v2CreateSessionWithParentSendsParentIDWithoutLocation).
  • Android child lockout from session.parentId: the device path through a subagent card already passes the route parent. The new path (a child opened without one) is covered by loadedChildSessionExposesParentWithoutNavigationParent.
  • v1: not re-run on a device. The v1 diff path is unchanged, and the new idle refetch is protocol-independent and unit-tested.

Screenshots are on the evidence/ope-277 branch.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ivanfenenko
ivanfenenko merged commit 9c9c07b into main Oct 20, 2026
@ivanfenenko
ivanfenenko deleted the feature/ope-277-per-turn-diff-sub-sessions-v2 branch October 20, 2026 21:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

OPE-277: Per-turn diff and sub-sessions (v2)

Uh oh!

There was an error while loading. Please reload this page.

1 participant

@ivanfenenko
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.