Chat list: order chat_session_changed pushes by a registry revision

operator_sessions gains a revision bumped by a trigger on every update; the
wire row carries it, and the app ignores a push (or a list read) older than
the row it holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 00:34:16 +00:00
parent 9f13c93be6
commit fbc09528ec
6 changed files with 163 additions and 7 deletions
@@ -143,6 +143,10 @@ class ChatSessionsController extends ChangeNotifier {
/// Another device changed a chat's shared colour, star or title: the row
/// takes the server's values at once, with no re-list. Each field the
/// registry row omits is cleared, since omitted means unset on the wire.
/// The server sends these pushes concurrently, so they can arrive out of
/// order: one whose `revision` is older than the row held here is stale and
/// ignored (a row or push without a revision, from an older server, is
/// always applied).
///
/// A row naming `previous_id` is a chat another device moved to a fresh
/// session (`/new`): it replaces that row in place and [onSessionReplaced]
@@ -165,8 +169,14 @@ class ChatSessionsController extends ChangeNotifier {
if ('${row['id'] ?? ''}' == id)
() {
found = true;
if (chatSessionPushIsStale(row, changed)) return row;
final next = <String, dynamic>{...row};
for (final key in const ['color', 'starred', 'starred_at']) {
for (final key in const [
'color',
'starred',
'starred_at',
'revision',
]) {
if (changed.containsKey(key)) {
next[key] = changed[key];
} else {
@@ -404,8 +414,14 @@ class ChatSessionsController extends ChangeNotifier {
final runningRevision = _runningRevision;
final sessions = await repository.sessions();
if (generation != _generation) return;
// A push applied while this list was read can be newer than its row.
final held = {for (final row in _sessions) '${row['id'] ?? ''}': row};
_sessions = [
for (final row in sessions) _withActivity(row, runningRevision),
for (final row in sessions)
_withActivity(
newerChatSessionMetadata(row, held['${row['id'] ?? ''}']),
runningRevision,
),
];
_seedLocal();
_loading = false;
@@ -644,3 +660,41 @@ class ChatSessionsController extends ChangeNotifier {
super.dispose();
}
}
/// The registry revision a chat list row or push carries; 0 when absent.
int chatSessionRevision(Map<dynamic, dynamic> row) {
final value = row['revision'];
return value is num ? value.toInt() : 0;
}
/// Whether [pushed] is older than [held]: both carry a revision and the
/// push's is lower. A push is never stale against a row with no revision.
bool chatSessionPushIsStale(
Map<dynamic, dynamic> held,
Map<dynamic, dynamic> pushed,
) {
final incoming = chatSessionRevision(pushed);
return incoming > 0 && incoming < chatSessionRevision(held);
}
/// [fetched] with the shared metadata (colour, star, title, revision) of
/// [held] when [held] is newer: a list read that started before a push was
/// applied must not revert it.
JsonMap newerChatSessionMetadata(JsonMap fetched, JsonMap? held) {
if (held == null || !chatSessionPushIsStale(held, fetched)) return fetched;
final next = <String, dynamic>{...fetched};
for (final key in const [
'color',
'starred',
'starred_at',
'title',
'revision',
]) {
if (held.containsKey(key)) {
next[key] = held[key];
} else {
next.remove(key);
}
}
return next;
}
@@ -266,6 +266,45 @@ void main() {
expect(gateway.count('chat_sessions'), lists);
});
test('a push older than the row held is ignored', () async {
JsonMap push(int revision, String color) => {
'type': 'chat_session_changed',
'chat_session': {
'id': 's2',
'title': 'Plain chat',
'color': color,
'revision': revision,
},
};
// The server sends pushes concurrently: revision 7 lands before 6.
gateway.pushed.add(push(7, 'pink'));
gateway.pushed.add(push(6, 'blue'));
await pumpEventQueue();
expect(row('s2')['color'], 'pink');
expect(row('s2')['revision'], 7);
gateway.pushed.add(push(8, 'amber'));
await pumpEventQueue();
expect(row('s2')['color'], 'amber');
// A list read older than the applied push does not revert it.
var listed = <String, dynamic>{
'id': 's2',
'title': 'Plain chat',
'directory': '/w',
'revision': 5,
};
gateway.sessionsHandler = () async => {
'chat_sessions': [listed],
};
await controller.refresh();
expect(row('s2')['color'], 'amber');
expect(row('s2')['revision'], 8);
// A newer list row wins.
listed = {...listed, 'color': 'teal', 'revision': 9};
await controller.refresh();
expect(row('s2')['color'], 'teal');
expect(row('s2')['revision'], 9);
});
test('a refused colour is undone and the reason shown', () async {
gateway.failures['chat_color'] = 'unknown chat colour';
await controller.setColor('s2', 'blue');
+21 -5
View File
@@ -41,6 +41,9 @@ type OperatorSession struct {
// protocol.ChatColors by name, or "" for none. The name, not a shade, is
// stored so every client renders its own theme-tuned colour.
Color string
// Revision increases with every change to the row (a trigger bumps it), so
// a client receiving list metadata pushes out of order keeps the newest.
Revision int64
}
// ChatCreateBootstrap is the durable progress record for one chat_create
@@ -175,7 +178,20 @@ func (s *Store) migrateOperatorSessions() error {
// replaced_by names the native session a chat moved to when the operator
// started a fresh session (/new). The replaced row is kept, unlisted, so the
// old id still resolves; existing rows default to '' (current).
return s.addColumnIfMissing("operator_sessions", "replaced_by", "TEXT NOT NULL DEFAULT ''")
if err := s.addColumnIfMissing("operator_sessions", "replaced_by", "TEXT NOT NULL DEFAULT ''"); err != nil {
return err
}
// revision orders a row's states: every update that does not set it bumps
// it, so the chat_session_changed pushes (sent concurrently) can be ordered
// by the client. SQLite does not re-fire a trigger from its own update.
if err := s.addColumnIfMissing("operator_sessions", "revision", "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
_, err := s.db.Exec(`CREATE TRIGGER IF NOT EXISTS operator_sessions_revision AFTER UPDATE ON operator_sessions
FOR EACH ROW WHEN NEW.revision = OLD.revision BEGIN
UPDATE operator_sessions SET revision = OLD.revision + 1 WHERE session_id = NEW.session_id;
END`)
return err
}
// ErrOperatorSessionReplaced reports that a chat was already moved to another
@@ -409,9 +425,9 @@ func (s *Store) SetOperatorSessionColor(ctx context.Context, sessionID, color st
// returned). It is one indexed lookup and never mutates the row.
func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) {
var session OperatorSession
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color,revision
FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color); err != nil {
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color, &session.Revision); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return OperatorSession{}, false, nil
}
@@ -430,7 +446,7 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
// operator can still see and reopen what they finished. It is one bounded
// statement; recency is never mutated here.
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) {
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color,revision
FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 AND replaced_by = '' ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
if err != nil {
return nil, err
@@ -439,7 +455,7 @@ FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 AND replaced_by = '' OR
sessions := []OperatorSession{}
for rows.Next() {
var session OperatorSession
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color); err != nil {
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color, &session.Revision); err != nil {
return nil, err
}
sessions = append(sessions, session)
@@ -320,3 +320,45 @@ func TestOperatorSessionsMigrationAddsEphemeral(t *testing.T) {
t.Fatalf("verification session listed after migration: %+v err=%v", listed, err)
}
}
// Every change to an operator session bumps its revision, so clients can order
// concurrent chat_session_changed pushes.
func TestOperatorSessionRevisionIncreasesOnEveryChange(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "revision.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "A", "operator"); err != nil {
t.Fatal(err)
}
revision := func() int64 {
t.Helper()
session, found, err := store.OperatorSession(ctx, "ses_a")
if err != nil || !found {
t.Fatalf("read: %v %v", found, err)
}
return session.Revision
}
last := revision()
for i, change := range []func() error{
func() error { return store.SetOperatorSessionColor(ctx, "ses_a", "red") },
func() error { return store.SetOperatorSessionStar(ctx, "ses_a", true) },
func() error { return store.SetOperatorSessionTitle(ctx, "ses_a", "Renamed") },
func() error { return store.SetOperatorSessionColor(ctx, "ses_a", "") },
} {
if err := change(); err != nil {
t.Fatal(err)
}
next := revision()
if next != last+1 {
t.Fatalf("change %d: revision %d after %d", i, next, last)
}
last = next
}
sessions, err := store.OperatorSessions(ctx)
if err != nil || len(sessions) != 1 || sessions[0].Revision != last {
t.Fatalf("listed %+v %v, want revision %d", sessions, err, last)
}
}
+4
View File
@@ -357,6 +357,10 @@ type ChatSession struct {
Tag string `json:"tag,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
UpdatedAt int64 `json:"updated_at,omitempty"`
// Revision increases with every change to the chat's registry row. The
// chat_session_changed pushes may arrive out of order; a client ignores one
// older than the row it holds. 0 (older servers) is unordered.
Revision int64 `json:"revision,omitempty"`
// Busy is retained for wire compatibility only: it is never set by this
// server. A session is never read-only, any number of clients may watch and
// write it, and only a turn is serialised (a waiting prompt is acknowledged
+1
View File
@@ -156,6 +156,7 @@ func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSess
CreatedAt: session.CreatedAt,
UpdatedAt: session.UpdatedAt,
Backend: session.Backend,
Revision: session.Revision,
}
if session.ClosedAt > 0 {
out.Closed = true