Skip to content

Studio: keep a chat in sync across devices, and survive a phone lock at send time - #18143

Merged
shimmyshimmer merged 4 commits into
mainfrom
studio-chat-sync-keep-running
Nov 17, 2026
Merged

shimmyshimmer merged 4 commits into
mainfrom
studio-chat-sync-keep-running

Conversation

@shimmyshimmer

Copy link
Copy Markdown
Member

What changes for users

  • A chat open on one device now picks up what another device writes to it, without a reload. Before, a PC tab that stayed focused never re-read the open chat or the sidebar, so a turn sent from a phone only showed after the PC tab lost and regained focus, or after a restart. Now, while the tab is visible, the open chat shows new turns and answers written elsewhere within a few seconds, and the sidebar shows chats created, renamed or deleted elsewhere.
  • Locking the phone right after pressing Send no longer fails the turn. The check that decides whether a reply runs on the server could fail on the dropped socket and surface "Generation failed: Load failed". It now retries, and failures while the page is hidden do not count against it.
  • A connection dropped mid-reply is reported as "Response interrupted" (partial answer kept, Retry offered) instead of a raw "Generation failed: network error".

How

  • Backend: SQLite triggers on chat_messages and chat_threads keep change counters in a new chat_history_revisions table, one for the whole history and one per thread. GET /api/chat/revision?threadId=... reads them. Every writer moves them: the chat routes, server-side generation runs and imports. A thread's updatedAt cannot be used, because it does not move when an answer is written in place.
  • Frontend: while a tab is visible, remote-history-watch polls that endpoint every 4 s and also on focus, online and pageshow.
    • A history change sends the existing history-updated event, which the sidebar and the other listeners already act on.
    • A change to the open thread runs the existing recoverCurrentThread reconciliation. This is the same code a tab return already runs, so its guards still apply: no import over a local run, an open edit, or a deleted row. A busy view keeps the change pending until it is idle.
    • A server without the endpoint is asked once and then left alone.
  • supportsChatGenerationRuns retries transient failures with the same backoff createChatGenerationRun uses. A 4xx or a Stop is not retried. After 4 failures while the page is visible, it gives up.
  • streamChatCompletions maps a TypeError from reader.read() to StreamInterruptedError. An aborted request keeps its own error.

Verification

  • Backend: pytest tests/test_chat_history_storage.py tests/test_chat_history_routes.py (new: the counters move on insert, on an in-place edit that leaves updatedAt unchanged, and on delete; the route accepts repeated threadId and caps the count).
  • test_chat_sync_unchanged_rows.py compares whole-database snapshots of two write strategies; the new counter column counts writes, so it is excluded there like the existing wall-clock columns.
  • Frontend: npm run typecheck, npm test and npm run build all pass. New tests: remote-history-sync.test.ts, chat-stream-network-drop.test.ts, and the admission retry cases in chat-generation-reconnect.test.ts.
  • Live check on a local Studio: browser A had a chat open, and the REST API stood in for a second device. A showed the appended turn in 1.3 s, an answer edited in place in 3.8 s, and a new chat in the sidebar, all without a reload.

Not covered here

  • Replies from API / connected models, replies to attachments, Continue, temporary chats and browser-panel turns still stream through the tab. Keep Running does not apply to them, as the setting's hint already says, so locking the phone still stops those.
  • Not tried on a real phone. This host has no GPU, so no local model generated a reply during the live check.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T13:28:53.315189Z 50a7adc Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 50a7adce33

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

scheduleGenerationRecovery(remoteId, message, messages, aui);
}
}
return fromBackend;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep revisions pending when reconciliation is blocked by an edit

If the user opens a prompt editor after the poll's isIdle check but before the message read completes, reconcileOrdinarySavedMessagesInView refuses the import to preserve the draft. However, this callback still returns fromBackend === true, so the watcher acknowledges the revision even though the remote turns were not applied. Closing the editor does not trigger reconciliation, and subsequent polls skip the unchanged revision, leaving the chat stale until another remote write or recovery event. Recheck the busy guards after the read and return false when they prevent reconciliation, so a later idle poll retries.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this one: it needs an edit opened on this device within the one read's round trip after another device's write, then cancelled; saving the edit, the next remote write, a tab refocus or a thread switch all re-read and apply it, and nothing is lost on the server.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 17, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 50a7adce33

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 17, 2026
@shimmyshimmer
shimmyshimmer merged commit 212f4db into main Nov 17, 2026
@shimmyshimmer
shimmyshimmer deleted the studio-chat-sync-keep-running branch November 17, 2026 13:46
danielhanchen added a commit that referenced this pull request Nov 17, 2026
… extra red since #18143) (#18155)

The `Chat UI Tests (extra)` declared-polls gate
(`tests/studio/playwright_declared_polls.py`) fails on main since #18143
(seen on the staging run of #18075, an Ollama-only PR):

```
FAIL these paths are polled by the app but are not in the log budget:
  /api/chat/revision   8x within one dwell (~38.4/min)
```

## Cause

#18143 added cross-device chat sync: `remote-history-watch.ts` polls
`GET /api/chat/revision` every `REMOTE_HISTORY_POLL_MS` (4 s) while the
page is visible. Every polled path has to be declared in the log budget
and given a log class, otherwise each hit writes an access line (here
about 15 lines a minute per open tab, also mirrored into the desktop
log). The feature is right; the two declarations were missed.

## Fix

- `studio/backend/tests/log_budget/session.py`: `"/api/chat/revision":
(4.0, "declared")` in `IDLE_POLLS`, with the call site named.
- `studio/backend/loggers/handlers.py`: `/api/chat/revision` in
`_QUIET_SUCCESS_PATHS`. A 2xx read only carries a revision number; when
it changes, the thread fetch that follows still logs, and a failed read
(non-2xx) still logs.

## Verification

- `tests/test_log_budget.py` plus the access-log handler tests: 83
passed.
- The unit-side closure check holds both halves together: with the
handler class but without the `IDLE_POLLS` entry,
`TestClassificationClosure::test_every_classified_path_is_in_a_scenario`
fails.
- The Playwright gate reads `IDLE_POLLS` / `BUSY_POLLS` (`declared =
set(ALL_POLLS)`), so the path it reported is now declared.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 20, 2026
…othai#18483)

The open chat polls `/api/chat/revision` every 4 s (unslothai#18143) and re-reads
the thread when its counter moves. The counters are bumped by SQLite
triggers on every write to `chat_messages` and `chat_threads`, so
nothing separates this tab's own writes from another device's. Every
finished turn moves the counter (user message, assistant message, the
final sync). The poll holds the change while the reply streams, then
within 4 s of the reply ending `recoverCurrentThread` re-reads the chat
this tab just wrote: a thread GET, the full message list, an IndexedDB
read and two `thread.export()` calls. On a 150 turn chat that list is
about 720 KB, every turn. Renames, title updates and thread settings
saves from this tab do the same. The history counter echoes too, so the
sidebar refreshes a second time.

There is a second source of extra re-reads on other devices.
`_bump_chat_thread_updated_at` ran `UPDATE chat_threads SET updated_at =
MAX(...)` even when the value did not change. AFTER UPDATE triggers fire
on no-op updates, so re-saving an unchanged message list still moved the
counter, and every other open device re-read a chat that had not
changed.

## Change

- `storage/studio_db.py`: `chat_revision_probe(thread_id)` is a context
variable that `upsert_chat_thread`, `update_chat_thread`,
`upsert_chat_message` and `sync_chat_messages` fill. Right after `BEGIN
IMMEDIATE` and right before `COMMIT` they read the thread's and the
whole history's revision. `chat_revision_span` returns the before and
after values only when every probed transaction committed, and committed
back to back. Without a probe (generation runs, research, imports) the
writers behave exactly as before.
- `routes/chat_history.py`: `POST /threads`, `PATCH /threads/{id}`, `PUT
/threads/{id}/messages/{mid}` and `PUT /threads/{id}/messages` return
`X-Unsloth-Chat-Revision: <thread before>,<thread after>,<history
before>,<history after>` on success. A rejected or failed write sends no
header. `main.py` exposes the header for cross-origin clients (Tauri,
tunnels).
- `_bump_chat_thread_updated_at` skips the write when `updated_at` would
not change. Rows whose value does change are written exactly as before.
- `chat-api.ts`: `threadWriteFetch` reads the header and publishes it to
`subscribeOwnChatHistoryWrites` listeners. An older server sends no
header, nothing is published, and the poll re-reads as it does today.
- `remote-history-sync.ts`: `noteOwnWrite` records each own write as a
step `before -> after`. The baseline follows these steps only from the
revision it last saw, so a write from anywhere else leaves a gap and is
still re-read. Steps can arrive out of order or after a poll already saw
the new counter, and they still chain. A poll answer that an own write
overtook while it was in flight is ignored instead of rolling the
baseline back. Own writes only skip the re-read once the open chat has
synced through one successful re-read, because a chat's first baseline
can already count another device's write that the loaded view lacks; so
the first own turn after opening a chat still re-reads once, as `main`
does, and later turns do not. The history baseline works the same way,
so the sidebar refresh fires only for other devices. Re-reads still wait
while a reply runs, and a failed re-read is still retried. That retry
also holds if this tab writes while the re-read is in flight.

Focus, wake and thread-switch recovery, the busy hold, cross-tab
`localStorage` sync and error handling are unchanged.

## Results

Production builds of `main` and this branch. The real
`routes/chat_history.py` runs on a temporary `studio.db`, the rest of
`/api` is stubbed, and Chromium is headless. The chat has 150 turns (306
messages). Each assistant turn has reasoning, two tool calls, six
sources, code, a table and math, so the message list is about 720 KB.
The reply is a fixed 10 ms per frame stream. Counts cover the 14 s after
each reply ends (at least 3 polls). There were 3 runs of 3 turns per
side, `main` and this branch interleaved. Earlier runs that were not
interleaved (2 more on `main`, 3 more on this branch) gave the same
counts.

| per own turn, after the reply | `main` | this PR |
| --- | --- | --- |
| `GET /threads/{id}` | 1 | 0 |
| `GET /threads/{id}/messages` (full list) | 1 (722 KB) | 0 |
| chat API bytes received | 727.6 KB | 4.5 KB |
| `POST /sidebar/rows` | 4 | 2 |
| `GET /threads/{id}/forks` | 2 | 1 |
| thread remounted / scroll moved | no | no |

The re-read never remounted the thread: every mounted row survived, and
the distance to the bottom did not change, on both sides. Main-thread
time over the same window was 163 ms median on `main` (126 to 263) and
112 ms on this branch (62 to 172). On this shared host the repeated
`main` runs alone spread from 134 to 208 ms, and idle 14 s windows from
46 to 106 ms, so no time saving is claimed. In the page, the network
part of one re-read costs 2.9 ms to read the body and 1.8 ms to parse it
and build the per-message keys (median of 15). The IndexedDB read, the
two exports and the reconcile pass come on top of that.

Two clients on one backend, same thread:

| check | `main` | this PR |
| --- | --- | --- |
| tab B sends a turn while A is idle: A shows it, separate browser
contexts (8 runs, B's send at 0 to 3.5 s after one of A's polls) | 2.23
s (0.47 to 3.94) | 2.22 s (0.37 to 3.88) |
| same, two tabs of one browser sharing `localStorage` (8 runs) | 2.21 s
(0.26 to 3.89) | 2.20 s (0.40 to 3.89) |
| A's own turn: message-list re-reads in the 13 s after it ends | 1 | 0
|
| another device adds a message and renames the chat while A streams:
re-reads after A's reply ends | 1 | 1 |
| that re-read carries the other device's message | yes | yes |
| the rename shows in A's sidebar | yes | yes |

Cross-tab latency is the time from B's first write reaching the server
to A showing it. On both sides it is about 4 s minus the offset to A's
next poll, and A always picks the change up at that next poll: own
writes only move A's baseline from the revision A last saw, so another
tab's writes are never absorbed.

## Tests

New `studio/backend/tests/test_chat_write_revision.py` (6 tests):
- Each of the four write routes returns the revisions read just before
and after its write, and they match `/revision`.
- A write from elsewhere between two of this tab's writes shows as a
gap.
- A rejected write (409) sends no header.
- Re-saving an unchanged message list moves no revision, and a real edit
still does (fails on `main`).
- `updated_at` still only moves forward.
- The header is listed in the CORS `expose_headers`.

New `studio/frontend/tests/own-chat-write-revision.test.ts`: the header
is published for message saves, message syncs and thread patches.
Nothing is published with no header, with a malformed header or for a
failed write.

`remote-history-sync.test.ts`, 7 new tests, all failing on `main`:
- An own write is not re-read, and the sidebar does not refresh for it.
- A write from elsewhere before or after an own write is re-read once.
- A remote write during a run is recovered once the view is idle.
- Own writes answered out of order, or after the poll already saw them,
stay quiet.
- An own write to a chat that is not open does not hide its later
changes.
- A failed re-read is retried even if this tab wrote meanwhile.

The existing "a busy view keeps the change pending until it is idle"
test is unchanged and passes.

Frontend: 107 test files that import `chat-api`, `runtime-provider`, the
remote history, saved history or chat history modules. 1559 pass here
and 1548 on `main` (the difference is the 11 new tests). `npm run
typecheck` and `eslint` on the changed files are clean.

Backend: `test_chat_history_routes.py`, `test_chat_history_storage.py`,
`test_chat_sync_unchanged_rows.py`,
`test_studio_db_hot_path_indexes.py`,
`test_studio_db_write_lock_contention.py`,
`test_research_runs_storage.py` and
`tests/studio/test_chat_thread_title_cas.py`: 440 passed on both sides.
The chat settings, thread settings, library, sandbox storage, auth lock
and OpenAI auto-switch suites: 1632 passed on both sides. In both runs
the same two `test_openai_auto_switch.py` fixture checks fail under
`pytest -n 4`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant