Skip to content

Add T3 as a second connection engine (experiment) - #345

Draft
ivanfenenko wants to merge 43 commits into
mainfrom
t3-experiment
Draft

ivanfenenko wants to merge 43 commits into
mainfrom
t3-experiment

Conversation

@ivanfenenko

@ivanfenenko ivanfenenko commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Experimental branch that adds T3 as a second connection engine alongside OpenCode on both iOS and Android. A Connection Profile can now pair with a T3 server, and home, Session Chat, and the composer work against T3 threads through the same product-level Screen Models.

Protocol reference: the T3 contracts packages/contracts/src/orchestrationV2.ts and rpc.ts.

What's included (both apps)

  • T3 engine runtime: socket transport with reconnect/teardown, liveness, protocol re-validation on connect, readable error text
  • Pairing: T3 pairing links and QR, profile-edit re-pairing fix, auth errors
  • Home: T3 project repository routing, live home updates, shell live stream, archived/settled rows with unarchive/unsettle, Settled page and snooze
  • Home status: a session waiting on a tool approval shows Needs approval, ahead of Running and Snoozed. Questions do not. T3 reads this from the shell snapshot. OpenCode loads GET /api/permission/request once per open project, then refetches only the project that owns the permission event.
  • Session Chat: user-input questions, approval detail, outbound image attachments plus PDF and text files when the server advertises fileAttachments, session controls
  • Composer: harness and model selection (catalogue from server.getConfig, resolver follows the web client's chain and lock rules), runtime mode selection
  • message.dispatch sends the required creation fields
  • Thread titles: the first message.dispatch sends titleSeed (collapsed prompt, or Image: <filename>). The server shows that immediately and replaces it with a generated title. Later messages omit the seed.
  • Pending prompts: a message sent during a running turn leaves the timeline and shows in the Up next strip. Steer now dispatches queued-message.promote-to-steer; Delete dispatches queued-run.cancel.

Known gaps

  • No Linear ticket or ticket-named branch yet
  • Older T3 servers that omit fileAttachments stay images only. Zip and other file types are still outside the composer
  • The model picker and connecting label are covered by unit tests only, not verified on a device
  • ktlintCheck still reports pre-existing nits in T3 files

Test plan

  • Android T3 attachment unit tests (T3AttachmentUploaderTest, T3FileAttachmentTest, ServerProtocolMatrixTest)
  • Android title-seed unit tests (T3RpcCodecTest, T3RuntimeTest.sendPrompt_seedsTitleUntilTheThreadHasMessages)
  • iOS T3 attachment unit tests (T3AttachmentUploaderTests, ServerProtocolMatrixTests)
  • Android queued-run tests (T3MessageMapperTest.queuedRun_marksTheUserMessageWaitingAndSkipsAutomaticDeliveries, T3RpcCodecTest.promoteQueuedToSteer_namesTheQueuedRunAndTheActiveTurn, ServerProtocolMatrixTest)
  • iOS T3EngineTests and ServerProtocolMatrixTests on the iPhone 17 simulator, including the queued-run case
  • Android home approval tests (DefaultPermissionLiveStoreTest, MainScreenViewModelTest pending-permission and T3 skip, SessionListStatusMappingTest, T3SessionControlsTest)
  • iOS PermissionLiveStoreTests, ProjectListHomeViewModelTests, SessionListStatusMappingTests, and T3SessionControlsTests on the iPhone 17 simulator
  • Android unit tests (./gradlew testDebugUnitTest)
  • iOS unit tests
  • Pair with a local T3 server on simulator/emulator and run a thread end to end
  • Verify OpenCode v1/v2 profiles are unaffected

🤖 Generated with Claude Code


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

@ivanfenenko

Copy link
Copy Markdown
Collaborator Author

@cursor review

@ivanfenenko
ivanfenenko marked this pull request as ready for review October 7, 2026 10:46

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 3 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c33c1b0. Configure here.

@ivanfenenko
ivanfenenko marked this pull request as draft October 7, 2026 14:08
ivanfenenko and others added 20 commits October 12, 2026 00:49
A connection profile can pair with a T3 environment instead of an
OpenCode server. Session, project, and message calls go through an
engine repository, and the session screen reads SessionCapabilities
rather than branching on the server. T3 keeps one timeline: list, open,
send, stop, and settle, with markdown, image attachments, and turn
activity. OpenCode-only controls stay hidden. Settle stays separate
from archive.
Same seam as Android. A profile pairs with a T3 environment, and the
session screen follows SessionCapabilities instead of a third remote.
Threads, markdown, image attachments, and turn activity (reasoning,
tools, and subagents) come from that environment. OpenCode-only
controls stay hidden, and settle stays separate from archive.
Add T3ProjectRepository (projects from the shell snapshot, probe seeds the
profile's worktrees with project roots while keeping user-added ones) and
EngineProjectRepository so home no longer hits OpenCode REST on T3.

T3SessionRepository now filters threads by worktree or project root, picks
the project for the requested directory on create, refreshes the shell
before answering permissions or interrupting runs, returns the new title
after rename, and throws "X is not available on T3" for unsupported
operations. Root-strategy threads get the owning project's root as their
Session.directory.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Editing a saved T3 profile no longer routes through pairing: a rename-only
save skips the network, a host change re-validates the environment descriptor
(protocol check) and keeps the stored access token, and only a freshly pasted
pairing token triggers a new token exchange. The stored access token is never
shown in the form; the field reads "Paste a new pairing token to re-pair".

T3 Code pairing links (desktop `/pair#token=` and hosted
`app.t3.codes/pair?host=…`) are accepted through the existing QR scan path on
both platforms, which is now offered for the T3 engine too. 401/403 from a T3
host map to a dedicated access-revoked error with a user-readable message; raw
server bodies stay diagnostics-only. Hosts typed without a scheme default to
https for T3 only; opencode keeps http.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
- Re-subscribe the observed thread from its last sequence on every new
  socket; subscription ids are reset per connection.
- Proactive reconnect with backoff while foregrounded on a T3 profile,
  driven through ForegroundEventStream start/stop via T3LiveSession.
- Disconnect and clear runtime caches on background stop and profile
  switch; reconnect lazily on foreground.
- Subscribe to orchestration.subscribeShell (resuming from
  snapshotSequence) and publish synthetic session.created/updated/deleted,
  session.status and permission.* events so home updates live; REST
  refreshes still publish status and approval diffs.
- Debounce the REST shell refresh triggered by thread-stream run events.
- Lossless frame delivery: unbounded channel, queue before ack.
- Merge project roots into added worktrees instead of replacing them.
- Surface a refused thread subscription as LoadFailed on the message flow.
- T3Socket seam plus fakes and JUnit coverage for the above.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The T3 engine reused a dead websocket forever, hung pending requests on
close, never re-subscribed a thread after a drop, never reset on profile
switch or background, and reported a hard-coded "connected" indicator.

- T3RpcSession: socket transport abstraction (URLSession default, fakes
  in tests), 15 s connect timeout, 30 s per-request timeout, 15 s client
  keepalive Ping, Pong reply, Interrupt on timeout/cancel/stream
  termination, Ack only for tracked streams, isClosed state, and every
  pending request or stream fails when the socket dies.
- T3EnvironmentClient: rpc() never reuses a closed session (fresh ticket
  and socket), shell cache and cachedThread are bound to the connection
  identity, reset() closes the socket on profile switch and background via
  T3LiveSignals lifecycle, socket state is published for the indicator,
  subscribeThread throws instead of swallowing errors, launchThread takes
  an optional projectID.
- T3MessageRepository: observers keyed by session, subscription loop
  re-establishes after a drop from the last known snapshotSequence with
  backoff, surfaces failures as loadFailed, cancels the server-side
  subscription when the last observer leaves, clearMessageCache resets
  sequences and transcripts.
- EngineMessageRepository.clearMessageCache clears both engines.
- DefaultForegroundEventStream follows the published T3 socket state
  instead of sleeping on .connected, and forwards start/stop lifecycle.
- ConnectionSessionCoordinator resets the engine runtime on profile switch.
- Swift Testing coverage with in-memory socket/HTTP fakes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
T3EnvironmentClient now implements launchThread(title:projectID:) directly.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Outbound attachments were silently dropped from T3 message.dispatch
(the payload always carried an empty attachments list). Both apps now
run the T3 upload sequence before dispatch: attachments.createUploadUrl
over the RPC socket, POST the exact bytes to the signed relative URL on
the environment origin with the profile bearer, then reference the
stored id as a ChatAttachment {type, id, name, mimeType, sizeBytes}.

- Android: T3AttachmentUploader (socket mint + OkHttp byte transport),
  T3Assets upload payload/result helpers, T3Commands.messageDispatch
  attachments, T3MessageRepository uploads then dispatches.
- iOS: T3AttachmentUploader (T3AttachmentUploadClient + byte transport
  protocols, URLSession default), T3RpcCodec chatAttachmentPayload,
  T3MessageRepository uploads then dispatches, one internal rpcRequest
  on T3EnvironmentClient for the mint/delete round trips.
- Non-image or unsupported-mime attachments and images over the 10 MB
  contract cap are rejected up front with a user-facing message; a
  failed transfer deletes the pending upload and surfaces through the
  existing send-error path. Attachment-only sends with empty text stay
  allowed (the contract's text is a plain string).
- Tests: upload sequence against fake transports, dispatch payload with
  attachments, oversize and non-image rejection, transfer failure
  cleanup, disconnected/no-credential fast failure.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
A thread whose pending runtime request is `user_input` was dropped on
both platforms. Parse the `user_input_request` turn item (questions,
options, multiSelect, allowCustomAnswer) and `runtimeRequests` from the
thread projection and map them to the domain QuestionRequest so the
existing question card renders; `listPendingQuestions` honours the
directory filter like permissions. Replies dispatch
`runtime-request.respond` with an `answers` record keyed by question id
(option value, or an array for multi-select, custom text passed through)
as the T3 web client does; rejecting dispatches
`thread.user-input.dismiss`.

Approvals now carry what is being approved: the `approval_request` turn
item's prompt and requestKind (or the in-flight tool item for
`dynamic_tool_call`) populate the permission name, patterns, and
metadata (kind, tool, title, command / filepath / prompt).

The Android shell diff publishes synthetic `question.asked` /
`question.replied` events when the pending user_input request appears or
clears, mirroring the permission events.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Subscribe to orchestration.subscribeShell while a T3 profile is live
(lifecycle start/stop), keep the client's cached shell current from
snapshot / thread.* / project.* items, and re-subscribe from the last
applied sequence after a reconnect. Diff the shell on every live update
and REST refresh and publish the same synthetic session.created /
session.updated / session.deleted / session.status / permission.asked /
permission.replied events Android does, routed through T3LiveSignals
into DefaultForegroundEventStream.

Coalesce forced shell REST fetches (shared in-flight request plus a
400 ms window) so bursts of thread activity collapse into one request,
never regress the cache below a newer live sequence, and register the
socket connect task atomically so concurrent callers cannot open two
sockets.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
- iOS publishes question.asked / question.replied for pending user_input
  requests from both refreshActivity and the shell stream, matching Android.
- Both apps re-check the environment descriptor before the first socket of
  the app session per profile; a protocol mismatch is terminal (no reconnect
  loop), shown as AuthFailed on the connection state and as a readable
  error on the message stream, and forgotten on stop so a re-pair can retry.
- Every T3 error that can reach a snackbar now carries a short message
  (connection lost, request rejected, unreadable response, host unreachable)
  while the server body or cause stays available for diagnostics.
- iOS streams inbound images and abandons the download at the 10 MB cap
  (declared Content-Length or first byte past the cap) like Android.
- The first full shell snapshot no longer publishes session.created for
  every existing thread; status, permission and question events still do.
- T3 socket connect / disconnect / reconnect and protocol failures go
  through the diagnostic log (connection area) on both platforms.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Runtime mode picker and read-only model selection in the session menu,
archived/settled threads on home with unarchive/unsettle, thread createdAt
from the shell, provider labels derived from the instance id, and repository
command tests for both platforms.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Creating a T3 thread no longer depends on the project's nullable default
model. The app now loads the provider catalogue (server.getConfig),
resolves the new-thread model the way the T3 web client does (project
override, global default, first usable harness), and lets the composer
chip pick a harness and model.

- T3Runtime caches the catalogue per profile, refreshes it on reconnect
  and on request, and clears it in stop(); start() reports connecting so
  a fresh chat no longer reads offline.
- createSession takes an additive SessionCreateOptions overload for an
  explicit harness/model and runtime mode; OpenCode keeps its signature.
- The composer model chip reads "<harness> · <model>", pins to the
  thread's recorded selection, dispatches thread.model-selection.set on
  existing threads, and blocks provider switches or
  requiresNewThreadForModelChange changes on started threads with a notice.
- The runtime-mode sheet offers only the harness's supported modes.
- EngineSessionRepository now delegates the T3 session controls
  (runtime mode, model selection, archive/settle restore) to T3.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Fetch the provider catalogue (server.getConfig) per connection, resolve new
thread selections with the T3 web fallback chain, and let thread creation
take an explicit harness, model, and runtime mode. The composer model chip
and picker now list T3 harnesses and their models, change the thread's
selection with the web client's started-thread rules, remember the last pick
per profile and worktree, and limit runtime modes to the harness's supported
ones. The chat warms the T3 socket on bind so the indicator leaves offline.

EngineSessionRepository now forwards the T3 session controls (runtime mode,
model selection, archived list, unarchive, unsettle) instead of falling back
to protocol defaults.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The composer's runtime-mode badge is now a control on engines that can
set the mode: tapping it opens the same runtime-mode sheet as the session
overflow menu. It stays a display-only badge elsewhere.

A not-yet-created T3 thread no longer ignores the choice. The view model
keeps the pending mode, shows it in the badge at once, and launches the
thread with it through SessionCreateOptions.runtimeMode. A mode picked
after the launch request left is applied through setRuntimeMode once the
thread exists; started threads keep the server round trip.

New threads start on the last mode chosen for the profile and worktree,
stored next to the remembered new-session model selection, else
Supervised. The sheet lists the selected harness's supported modes when
the catalogue is loaded, else all four.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The composer runtime-mode badge opens the runtime-mode sheet when the
engine can set it. On a not-yet-created T3 thread the pick is held,
shown in the badge, and passed as the launch runtime mode; a pick made
after launch started follows as a server round trip. The last chosen
mode is remembered per profile + worktree and pre-fills new threads.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The T3 orchestration contract requires createdBy and creationSource on
message.dispatch; without them the server rejected the first message on a
thread at schema validation. Send createdBy "user" and creationSource
"mobile", and log the server's Exit failure cause with T3 dispatch and send
failures so rejections are diagnosable.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The T3 contract spreads OrchestrationV2CreationFields into message.dispatch,
so createdBy and creationSource are required; without them the server
rejects the first send at schema validation. Send createdBy "user" and
creationSource "mobile" like the web client.

Keep the server cause in diagnostics: Exit failure causes now unwrap Effect
Fail/Die reasons (a schema rejection arrives as a Die defect) instead of
logging just the reason tag, dispatchCommand logs the command type with the
cause, and DiagnosticLogCause includes T3 error detail. Snackbar text is
unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Settled threads leave the ladder and open from a link at the end.
Snoozed threads stay in their day bucket. After settle, snooze, or
wake, home reloads the active list and the settled list. OpenCode
home is unchanged.
The settled-list mapping called crossProjectRows with a trailing lambda
that bound the wrong parameter, and the snooze sheet was missing its
button import. Unit tests needed the model-selection types and a brace
left over from splicing the harness tests back into the class.
Keep both sides of the additive conflicts: T3 settle/snooze fields and
capabilities next to main's v2 server unread state (#655), and the T3
capability-gated Session Chat overflow with main's new Fork entry (#419),
shown only where forking is supported (hidden on T3).

Route markSessionViewed through the engine session repositories so
OpenCode v2 profiles still report views, and treat Snoozed rows as not
unread on iOS.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ivanfenenko and others added 15 commits October 14, 2026 13:34
T3 keeps the model on the session, so on iOS the composer never loads a
catalogue and has no selected model. The attach button asked that empty
selection whether it accepts images and stayed disabled. When the engine
owns the model, offer photos (and files when the server allows them)
and let the server validate. Android gets the same rule so a failed
catalogue load cannot disable it either.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
T3 refuses thread.settle while a run is active or a runtime request is
pending. Home offered Settle anyway, so the swipe and the long-press
entry failed with a bare "T3 rejected the request".

- Swipe gestures: a running or waiting thread gets no Settle or Snooze
  gesture; Wake and Unsettle are unchanged.
- Long-press sheet: Settle is disabled and labelled with the same reason
  as Snooze ("Settle · Still running" / "Settle · Waiting on you").
- chooseSettle() returns early when the row is blocked.
- The T3 session repository maps the server's "cannot be settled"
  rejection to SessionSettleBlocked, and Home shows "Can't settle while
  the thread is running or waiting on you." for it.

Same behaviour on iOS and Android, with unit tests on both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eases

The composer re-requested server commands, mentionable agents and selectable
agents when a T3 thread replaced its optimistic placeholder (iOS rebind) and on
every bind (Android selectable agents). On T3 those are OpenCode endpoints:
iOS probed /global/health and fetched /agent, Android fetched /agent. Gate the
loads on the engine's agent capability on every composer path.

On iOS a deliberate T3RpcSession.close() now fails pending work with
T3SocketError.released, and the shell, archived shell and thread subscription
loops log that at info instead of warning. Server closes and network drops
remain warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Session Chat's settle now shows "Can't settle while the thread is
running or waiting on you." when the repository reports
SessionSettleBlocked, matching Home; other failures still show
"Couldn't settle session.". The chat overflow entry stays enabled:
Session Chat state does not carry the thread's block reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Typing / on a T3 thread lists user-invocable skills for the selected harness and inserts $name as a prompt mention. A worktree snapshot replaces the harness-wide list.
A background stop or profile switch closes the socket on purpose. Publishing that as a lost connection hid the transcript until a later event arrived.
The server generates a title only when the first message.dispatch includes titleSeed. Android and iOS send a collapsed prompt, or Image: filename, and omit the seed once the thread has messages.
A follow-up sent while a turn is running was already queued, but the apps never read the run list, so the message looked sent and Steer stayed hidden.
T3 takes the flag from the shell snapshot. OpenCode home loads the pending permission list once per project, then refetches only the project that owns the permission event. Questions stay off the pill.
A todo_list for the active run stays on the existing pill while that run is still going, including after every step is done. The list clears when the run settles. proposed_plan stays off the pill.
The command and file list scroll inside about eight lines. Shorter approvals still hug their text.
A connected T3 socket was not a live target, so later refreshes and pull-to-refresh never ran.
The list replaces the home screen in place, so Android back and the iOS edge swipe were leaving the app. Consume that input and return to the ladder.
Keep T3 capability gating alongside file mentions, the add-project path sheet, and the iOS keyboard layout. Factory registrations stay onMainActor. The home snooze sheet uses the current bottom-sheet keyboard API, and the home view is split so the combined sheet chain type-checks.
Settled was a flag that swapped the home list in place, so it had no
back-stack entry or route transitions. It is now a route on both
platforms: a Navigation 3 entry on Android and a navigationDestination
on iOS. It slides in like a session and pops with system and predictive
back. On iOS the home sheets attach to the NavigationStack, so session
actions also present over the pushed Settled page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ivanfenenko ivanfenenko added do not merge Must not be merged; draft or experiment only experiment Exploratory work, not intended to ship as-is blocked Blocked; do not merge until unblocked labels Oct 21, 2026

This branch had an error being deployed

2 failed (outdated) deployments
ios-release — ffa89d40 Deployed Oct 14, 2026 by ivanfenenko
android-release — ffa89d40 Deployed Oct 14, 2026 by ivanfenenko
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocked Blocked; do not merge until unblocked do not merge Must not be merged; draft or experiment only experiment Exploratory work, not intended to ship as-is

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant