Report a busy chat on subscribe after a reload
The room that records a server-run turn is torn down when its last client leaves, so a page reload re-subscribed to a new room that no longer knew the turn was running and never replayed the step-started marker. Claude Code does not re-announce a running turn to a new stream either, so the activity row and Stop control vanished until the next streamed delta. chat_subscribe now also replays the marker when the room's stream announced a turn (CLI-originated or re-announced on attach) or when the broker reports its own turn in flight through the optional chatTurnReporter (Claude Code reads its in-process running flag; the chat manager routes it without I/O).
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_transcript_cache.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_response_pending.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
/// A session whose turn is already running when the client attaches: the
|
||||
/// server answers chat_subscribe and then replays the live `step started`
|
||||
/// marker, the only snapshot of the turn a reload or a reopened chat gets.
|
||||
FakeChatGateway _busySession() {
|
||||
final gateway = FakeChatGateway();
|
||||
gateway.onSubscribe = () =>
|
||||
Future.microtask(() => gateway.emitEvent(chatStepFrame('started')));
|
||||
gateway.history = (_) async => chatPage([
|
||||
chatMessage(
|
||||
'u',
|
||||
'user',
|
||||
parts: [
|
||||
{'type': 'text', 'id': 'ut', 'text': 'Do the long task'},
|
||||
],
|
||||
),
|
||||
]);
|
||||
return gateway;
|
||||
}
|
||||
|
||||
Future<void> _pump(WidgetTester tester) async {
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('a thread opened on a busy session shows the activity at once '
|
||||
'and hides it when the turn ends', (tester) async {
|
||||
final gateway = _busySession();
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ChatThreadView(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
onBack: () {},
|
||||
drafts: MemoryChatDraftStore(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await _pump(tester);
|
||||
// No text, reasoning or tool frame has arrived: the replayed marker alone
|
||||
// draws the activity row and the Stop control.
|
||||
expect(find.text('Do the long task'), findsOneWidget);
|
||||
expect(find.byType(ChatResponsePending), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-turn-activity')), findsOneWidget);
|
||||
|
||||
gateway.emitEvent(chatStepFrame('ended'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(ChatResponsePending), findsNothing);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
|
||||
test(
|
||||
'a reopened chat with a cached transcript is running after attach',
|
||||
() async {
|
||||
final gateway = _busySession();
|
||||
final controller = ChatThreadController(
|
||||
gateway,
|
||||
's',
|
||||
cached: ChatTranscriptSnapshot(
|
||||
messages: [chatMessage('u', 'user')],
|
||||
cursor: '',
|
||||
hasMore: false,
|
||||
),
|
||||
);
|
||||
addTearDown(() {
|
||||
controller.dispose();
|
||||
gateway.close();
|
||||
});
|
||||
expect(controller.running, isFalse);
|
||||
await controller.load();
|
||||
await pumpEventQueue();
|
||||
expect(controller.running, isTrue);
|
||||
gateway.emitEvent(chatStepFrame('ended'));
|
||||
await pumpEventQueue();
|
||||
expect(controller.running, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('a resync on attach keeps the turn running through the re-subscribe '
|
||||
'replay', () async {
|
||||
final gateway = _busySession();
|
||||
final controller = ChatThreadController(gateway, 's');
|
||||
addTearDown(() {
|
||||
controller.dispose();
|
||||
gateway.close();
|
||||
});
|
||||
await controller.load();
|
||||
await pumpEventQueue();
|
||||
expect(controller.running, isTrue);
|
||||
// A harness that cannot replay the turn's earlier deltas asks for a
|
||||
// resync; the held turn is settled and the re-subscribe proves it again.
|
||||
gateway.emitEvent({'session_id': 's', 'kind': 'resync'});
|
||||
await pumpEventQueue();
|
||||
expect(
|
||||
gateway.calls.where((call) => call.type == 'chat_subscribe').length,
|
||||
2,
|
||||
);
|
||||
expect(controller.running, isTrue);
|
||||
});
|
||||
}
|
||||
@@ -297,6 +297,19 @@ func (c *Chat) Stream(ctx context.Context, id string, ready func(), emit func(pr
|
||||
}
|
||||
}
|
||||
|
||||
// TurnRunning reports whether the CLI is working on a turn for id, so a client
|
||||
// that attaches mid-turn (a page reload) still shows the turn running although
|
||||
// its step-started frame was emitted before that client subscribed.
|
||||
func (c *Chat) TurnRunning(id string) bool {
|
||||
s := c.session(id)
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.running
|
||||
}
|
||||
|
||||
// Interrupt asks the CLI to cancel the in-flight turn, including queued turns.
|
||||
func (c *Chat) Interrupt(ctx context.Context, id string) error {
|
||||
s := c.session(id)
|
||||
|
||||
@@ -93,6 +93,15 @@ type chatShellReleaser interface {
|
||||
ReleaseShells(sessionID string)
|
||||
}
|
||||
|
||||
// chatTurnReporter is implemented by a broker that knows, without I/O, whether
|
||||
// a session's turn is in flight in the harness itself. The hub's room forgets a
|
||||
// turn when its last client leaves (a page reload), and a harness such as Claude
|
||||
// Code does not replay a step-started frame to a new stream, so chat_subscribe
|
||||
// asks the broker before deciding whether to replay the live marker.
|
||||
type chatTurnReporter interface {
|
||||
TurnRunning(sessionID string) bool
|
||||
}
|
||||
|
||||
// operatorRegistry is the server-side operator-session seam. *pipeline.Store
|
||||
// satisfies it. It is a table of its own, separate from the pipeline stage
|
||||
// ownership (SessionOwner/run_session_owners) that settles a run: chat_sessions
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// busyChat is a broker whose harness reports a turn in flight on its own
|
||||
// (Claude Code keeps it in-process) and whose stream can announce a turn the way
|
||||
// a harness re-announces one on attach.
|
||||
type busyChat struct {
|
||||
*fakeChat
|
||||
running bool
|
||||
announce bool
|
||||
}
|
||||
|
||||
func (b *busyChat) TurnRunning(string) bool { return b.running }
|
||||
|
||||
func (b *busyChat) Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error {
|
||||
if ready != nil {
|
||||
ready()
|
||||
}
|
||||
if b.announce {
|
||||
if err := emit(protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func subscribeChat(t *testing.T, ctx context.Context, conn *websocket.Conn, id string) {
|
||||
t.Helper()
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: id, ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ack protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &ack); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ack.Type != protocol.ChatSubscribe || ack.ID != id {
|
||||
t.Fatalf("subscribe ack = %+v", ack)
|
||||
}
|
||||
}
|
||||
|
||||
// readStepStarted reads frames until an authoritative step-started arrives.
|
||||
func readStepStarted(t *testing.T, ctx context.Context, conn *websocket.Conn) {
|
||||
t.Helper()
|
||||
for {
|
||||
var message protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &message); err != nil {
|
||||
t.Fatalf("no step-started frame: %v", err)
|
||||
}
|
||||
event := message.ChatEvent
|
||||
if event != nil && event.Kind == protocol.ChatEventStep && event.Step != nil && event.Step.Status == protocol.ChatStepStarted && !event.Step.Intermediate {
|
||||
if event.SessionID != "ses_1" {
|
||||
t.Fatalf("step frame session = %q", event.SessionID)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatSubscribeReportsHarnessBusyTurn pins the reload case: the page's only
|
||||
// subscription went away (so the room and its record of the prompt are gone)
|
||||
// while the harness kept working. A fresh subscribe must report the session
|
||||
// busy immediately instead of waiting for the next streamed delta.
|
||||
func TestChatSubscribeReportsHarnessBusyTurn(t *testing.T) {
|
||||
broker := &busyChat{fakeChat: scriptedChat(), running: true}
|
||||
ctx, _, conn := dialChat(t, broker)
|
||||
subscribeChat(t, ctx, conn, "sub1")
|
||||
readStepStarted(t, ctx, conn)
|
||||
}
|
||||
|
||||
// TestChatSubscribeIdleHarnessReplaysNoTurn keeps the idle case honest: no turn
|
||||
// marker is fabricated for a session whose harness is not working.
|
||||
func TestChatSubscribeIdleHarnessReplaysNoTurn(t *testing.T) {
|
||||
broker := &busyChat{fakeChat: scriptedChat()}
|
||||
ctx, _, conn := dialChat(t, broker)
|
||||
subscribeChat(t, ctx, conn, "sub1")
|
||||
readCtx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
for {
|
||||
var message protocol.Message
|
||||
err := wsjson.Read(readCtx, conn, &message)
|
||||
if err != nil {
|
||||
if !errors.Is(readCtx.Err(), context.DeadlineExceeded) {
|
||||
t.Fatalf("read: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if message.ChatEvent != nil && message.ChatEvent.Kind == protocol.ChatEventStep {
|
||||
t.Fatalf("idle session replayed a step: %+v", message.ChatEvent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatSubscribeReplaysStreamAnnouncedTurn covers a turn no prompt of this
|
||||
// room started (a CLI-originated turn, or one re-announced on attach): a second
|
||||
// device that subscribes later is still told it is running.
|
||||
func TestChatSubscribeReplaysStreamAnnouncedTurn(t *testing.T) {
|
||||
broker := &busyChat{fakeChat: scriptedChat(), announce: true}
|
||||
ctx, _, conns := dialChatConns(t, Options{Chat: broker}, 2)
|
||||
subscribeChat(t, ctx, conns[0], "sub1")
|
||||
readStepStarted(t, ctx, conns[0])
|
||||
subscribeChat(t, ctx, conns[1], "sub2")
|
||||
readStepStarted(t, ctx, conns[1])
|
||||
}
|
||||
@@ -666,3 +666,18 @@ func (m *chatManager) ReleaseShells(sessionID string) {
|
||||
releaser.ReleaseShells(sessionID)
|
||||
}
|
||||
}
|
||||
|
||||
// TurnRunning reports the routed harness's own in-flight state. It reads only
|
||||
// the backend cache (filled once the session is observed) and an already
|
||||
// attached client: no registry read and no harness probe.
|
||||
func (m *chatManager) TurnRunning(sessionID string) bool {
|
||||
m.mu.Lock()
|
||||
backend := m.cache[sessionID]
|
||||
m.mu.Unlock()
|
||||
adapter := m.opencode
|
||||
if backend != "" && backend != "opencode" {
|
||||
adapter = m.attached(backend)
|
||||
}
|
||||
reporter, ok := adapter.(chatTurnReporter)
|
||||
return ok && reporter.TurnRunning(sessionID)
|
||||
}
|
||||
|
||||
@@ -127,6 +127,11 @@ type chatRoom struct {
|
||||
queue []*chatQueuedPrompt
|
||||
running bool
|
||||
streaming bool
|
||||
// observedTurn is set by an authoritative step-started frame this room's
|
||||
// stream delivered (a CLI-originated turn, or one a harness re-announced on
|
||||
// attach) and cleared when the turn ends, so a later subscriber is told the
|
||||
// turn is running even though no prompt of this room started it.
|
||||
observedTurn bool
|
||||
// observing is non-nil while one caller is attaching the shared broker
|
||||
// stream. It prevents concurrent subscribers from opening duplicate global
|
||||
// event streams before streaming can be published.
|
||||
@@ -407,6 +412,9 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) {
|
||||
if room != nil && frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded && !frame.Step.Intermediate {
|
||||
h.clearCompactionLocked(room)
|
||||
}
|
||||
if room != nil && frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepStarted && !frame.Step.Intermediate {
|
||||
room.observedTurn = true
|
||||
}
|
||||
var priorStep *protocol.ChatStep
|
||||
if frame.Kind == protocol.ChatEventStep && frame.SessionID != "" {
|
||||
priorStep = h.turnLocked(frame.SessionID).step
|
||||
@@ -516,6 +524,7 @@ func (h *chatHub) replaceShellsLocked(sessionID string, shells []protocol.ChatSh
|
||||
func (h *chatHub) finishTurnLocked(room *chatRoom) {
|
||||
h.clearCompactionLocked(room)
|
||||
room.running = false
|
||||
room.observedTurn = false
|
||||
room.nativeTurnID = ""
|
||||
if room.turnDone != nil {
|
||||
close(room.turnDone)
|
||||
@@ -596,12 +605,20 @@ func (h *chatHub) submitPrompt(sessionID string, p *chatQueuedPrompt) (queued bo
|
||||
// turnRunning reports whether the session has a turn in flight. A client that
|
||||
// subscribes after a turn started (for example the operator's browser while the
|
||||
// CLI harness is working) needs this to show Stop and the live activity line;
|
||||
// the room's own frames only cover events after the subscription.
|
||||
func (h *chatHub) turnRunning(sessionID string) bool {
|
||||
// the room's own frames only cover events after the subscription. A turn the
|
||||
// room's stream announced counts too, and so does a turn the broker itself
|
||||
// reports in flight: the room is rebuilt when its last client reloads, so its
|
||||
// own record of an earlier prompt does not survive the reload.
|
||||
func (h *chatHub) turnRunning(sessionID string, broker chatBroker) bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
room := h.rooms[sessionID]
|
||||
return room != nil && room.running
|
||||
running := room != nil && (room.running || room.observedTurn)
|
||||
h.mu.Unlock()
|
||||
if running {
|
||||
return true
|
||||
}
|
||||
reporter, ok := broker.(chatTurnReporter)
|
||||
return ok && reporter.TurnRunning(sessionID)
|
||||
}
|
||||
|
||||
// pendingFrames returns a copy of the room's unresolved approval requests so a
|
||||
|
||||
@@ -213,7 +213,7 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH
|
||||
// frame in its future, so replay the live marker. The composer's Stop control
|
||||
// and the transcript's one activity row read it; the later `step ended` frame
|
||||
// settles them normally.
|
||||
if hub.turnRunning(query.SessionID) {
|
||||
if hub.turnRunning(query.SessionID, broker) {
|
||||
sub.send(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &protocol.ChatEventFrame{
|
||||
SessionID: query.SessionID,
|
||||
Kind: protocol.ChatEventStep,
|
||||
|
||||
Reference in New Issue
Block a user