Merge: /new starts a fresh context in the same chat

This commit is contained in:
2026-11-03 14:11:38 +00:00
21 changed files with 910 additions and 131 deletions
@@ -7,45 +7,41 @@ import '../domain/chat_commands.dart';
/// Shows one local line in the conversation the command ran in.
typedef ChatCommandNoticeCallback = void Function(String text, {bool failed});
/// Hands a created session row to the destination with the line the new
/// conversation opens on. The destination owns navigation: it lists the row,
/// opens it and refreshes the list from the server.
typedef ChatCreatedSessionCallback =
void Function(JsonMap session, String notice);
/// Hands the chat's row under its fresh native session id to the destination,
/// with the id it replaces and the line the fresh conversation opens on. The
/// destination owns navigation: it swaps the list row in place, opens the new
/// id and refreshes the list from the server.
typedef ChatNewSessionCallback =
void Function(String previousId, JsonMap session, String notice);
/// Runs the recorded commands that act on the open session: `/new`, `/close`
/// and `/rename <title>`.
///
/// Every outcome is a local notice, never a prompt. The requests are the
/// repository's existing create, close and rename calls, exactly as the list's
/// New chat dialog, Close chat confirm and Rename dialog send them. `/stop` and
/// `/help` are not run here; [runs] says which commands are.
/// Every outcome is a local notice, never a prompt. `/new` is the server's
/// `chat_new_session` (the same chat on a fresh context, as the harness's own
/// `/new` or `/clear`); `/close` and `/rename` are the Close chat confirm's and
/// Rename dialog's requests. `/stop` and `/help` are not run here; [runs] says
/// which commands are.
class ChatCommandActions {
ChatCommandActions({
required this.repository,
required this.sessionId,
required this.directory,
required this.showNotice,
required this.confirmClose,
required this.openCreatedSession,
required this.startedNewSession,
this.onRenamed,
this.onClosed,
this.newOperationId,
});
final ChatRepository repository;
final String sessionId;
/// The open session's recorded directory, blank when the row is unknown.
/// `/new` starts the created session there.
final String directory;
final ChatCommandNoticeCallback showNotice;
/// Opens the row's `Close chat?` confirm; false sends nothing.
final Future<bool> Function() confirmClose;
final ChatCreatedSessionCallback openCreatedSession;
final ChatNewSessionCallback startedNewSession;
/// The server accepted the shared rename with this trimmed title.
final void Function(String title)? onRenamed;
@@ -53,9 +49,6 @@ class ChatCommandActions {
/// The server accepted the close; the conversation is finished here too.
final void Function()? onClosed;
/// Test/fixture seam; production mints one id per create intent.
final String Function()? newOperationId;
/// Whether [command] is one this runner performs.
static bool runs(ChatCommand command) => const {
chatCommandNew,
@@ -81,42 +74,28 @@ class ChatCommandActions {
}
}
/// `/new`: the existing `chat_create` with the web's fixed title and brief,
/// in this session's directory, with no backend or model field. The reply's
/// row is handed to the destination with the notice the new conversation
/// opens on; a refusal stays in this conversation.
/// `/new`: `chat_new_session` keeps this chat (row, title, colour, star,
/// directory, model and mode) and moves it to a fresh native session, so the
/// agent starts from an empty context. The reply's row, under its new id, is
/// handed to the destination with the notice the fresh conversation opens
/// on; a refusal (a running turn, say) stays in this conversation.
Future<void> _startSession() async {
if (directory.isEmpty) {
showNotice(chatNoDirectoryReport, failed: true);
return;
}
try {
final reply = await repository.create(
title: chatNewSessionTitle,
directory: directory,
operationId: _operationId(),
final reply = await repository.newSession(
sessionId,
instructions: chatDefaultSessionInstructions,
);
final session = reply['chat_session'];
if (session is! Map) {
final id = session is Map ? '${session['id'] ?? ''}'.trim() : '';
if (session is! Map || id.isEmpty || id == sessionId) {
throw const ProtocolError(
'The server did not return the new chat session.',
'The server did not return the new session for this chat.',
);
}
final row = Map<String, dynamic>.from(session);
final title = '${row['title'] ?? ''}'.trim();
openCreatedSession(
row,
chatSessionStartedNotice(
title.isEmpty ? chatNewSessionTitle : title,
directory,
),
);
final row = Map<String, dynamic>.from(session)..remove('previous_id');
startedNewSession(sessionId, row, chatNewSessionNotice);
} catch (error) {
showNotice(
chatSessionStartFailedNotice(directory, _reason(error)),
failed: true,
);
showNotice(chatNewSessionFailedNotice(_reason(error)), failed: true);
}
}
@@ -148,10 +127,6 @@ class ChatCommandActions {
}
}
String _operationId() =>
newOperationId?.call() ??
'native-chat-${DateTime.now().microsecondsSinceEpoch}';
/// The server's words without a Dart runtime prefix, as the web prints them.
String _reason(Object error) =>
describeErrorReason(error, fallback: 'The server gave no reason.');
@@ -80,7 +80,7 @@ class ChatThreadView extends StatefulWidget {
this.scrollPositions,
this.transcripts,
this.initialNotice,
this.onCreatedSession,
this.onNewSession,
this.onSessionRenamed,
this.onSessionClosed,
this.fileBridge = const ArtifactFileBridge(),
@@ -99,10 +99,10 @@ class ChatThreadView extends StatefulWidget {
/// the `/new` notice for a session it just created and opened.
final String? initialNotice;
/// `/new` created this row; the destination lists it, opens it with the
/// notice and refreshes the list. Without a destination the notice shows
/// here instead, since the session already exists on the server.
final ChatCreatedSessionCallback? onCreatedSession;
/// `/new` moved this chat to a fresh native session; the destination swaps
/// the row in place, opens the new id with the notice and refreshes the
/// list. Without a destination the notice shows here instead.
final ChatNewSessionCallback? onNewSession;
/// `/rename` was accepted with this title, so the header can follow it.
final ValueChanged<String>? onSessionRenamed;
@@ -423,22 +423,21 @@ class _ChatThreadViewState extends State<ChatThreadView> {
}
/// The runner for this session's `/new`, `/close` and `/rename`, rebuilt per
/// build so an adopted row's directory and title are the current ones.
/// build so an adopted row's title is the current one.
ChatCommandActions _commandActions() {
final session =
widget.session ?? {'id': widget.sessionId, 'title': widget.title};
final onCreated = widget.onCreatedSession;
final onNewSession = widget.onNewSession;
return ChatCommandActions(
repository: ChatRepository(widget.gateway),
sessionId: widget.sessionId,
directory: '${session['directory'] ?? ''}'.trim(),
showNotice: _showCommandNotice,
confirmClose: () => confirmCloseChat(context, session),
openCreatedSession:
onCreated ?? (created, notice) => _showCommandNotice(notice),
startedNewSession:
onNewSession ??
(previousId, created, notice) => _showCommandNotice(notice),
onRenamed: widget.onSessionRenamed,
onClosed: _sessionClosed,
newOperationId: widget.newOperationId,
);
}
@@ -174,6 +174,18 @@ class ChatRepository {
});
}
/// `/new`: the same chat continues on a fresh native session with an empty
/// context. The reply's `chat_session` is the chat under its new id, with
/// `previous_id` naming [sessionId].
Future<JsonMap> newSession(String sessionId, {String instructions = ''}) =>
gateway.call('chat_new_session', {
'chat_new_session': {
'session_id': sessionId,
if (instructions.trim().isNotEmpty)
'instructions': instructions.trim(),
},
});
Future<JsonMap> rename(String sessionId, String title) =>
gateway.call('chat_rename', {
'chat_rename': {'session_id': sessionId, 'title': title.trim()},
+16 -16
View File
@@ -29,7 +29,7 @@ const String chatCommandHelp = 'help';
const List<ChatCommand> chatCommands = <ChatCommand>[
ChatCommand(
name: chatCommandNew,
summary: 'Start a fresh session in this directory',
summary: 'Clear the context: continue this chat in a fresh session',
usage: '/new',
),
ChatCommand(
@@ -131,8 +131,8 @@ String chatUnknownCommandReport(String word) =>
String chatCommandUnavailableReport(String word) =>
'“$word” is not available yet, so nothing was sent to the agent.';
/// The behaviour brief a `/new` session is created with, verbatim from the web
/// client's `DEFAULT_CHAT_INSTRUCTIONS`.
/// The behaviour brief a new chat, and a `/new` fresh session, starts with,
/// verbatim from the web client's `DEFAULT_CHAT_INSTRUCTIONS`.
const String chatDefaultSessionInstructions =
"Act as a careful coding agent. Read the repository's AGENTS.md and the "
'relevant skills before acting. Inspect the current state, keep changes '
@@ -140,9 +140,6 @@ const String chatDefaultSessionInstructions =
'changed and what was not verified. Ask only about real ambiguity, '
'destructive actions or changes outside the request.';
/// The title every `/new` session is created with, as the web client sends it.
const String chatNewSessionTitle = 'New chat';
/// `/new` and `/close` act on the open session alone, so an argument is a
/// usage error the web reports in these exact words.
String chatCommandArgumentReport(ChatCommand command) =>
@@ -152,18 +149,21 @@ String chatCommandArgumentReport(ChatCommand command) =>
const String chatRenameUsageReport =
'Usage: /rename <title> — renames this session.';
/// `/new` needs the open session's directory; without one nothing is sent.
const String chatNoDirectoryReport =
"Can't start a new session here: the server reported no directory for "
'this chat.';
/// The line the fresh conversation opens on after `/new`: the chat is the
/// same, the agent's context is empty.
const String chatNewSessionNotice =
'New session started. The agent no longer sees the earlier conversation; '
'the previous session can still be resumed in a terminal.';
/// The notice the created session opens with.
String chatSessionStartedNotice(String title, String directory) =>
'Started a new session “$title” in $directory.';
/// The line a conversation opens on when another device started its new
/// session.
const String chatNewSessionElsewhereNotice =
'Another device started a new session in this chat. The agent no longer '
'sees the earlier conversation.';
/// The failed notice the current session shows when the create is refused.
String chatSessionStartFailedNotice(String directory, String reason) =>
"Couldn't start a new session in $directory: $reason";
/// The failed notice the current session shows when `/new` is refused.
String chatNewSessionFailedNotice(String reason) =>
"Couldn't start a new session: $reason";
/// The notice after the server accepted the shared rename.
String chatSessionRenamedNotice(String title) =>
+27 -8
View File
@@ -15,6 +15,7 @@ import 'conversation/chat_thread_view.dart';
import 'conversation/chat_transcript_cache.dart';
import 'conversation/composer_focus_request.dart';
import 'data/chat_repository.dart';
import 'domain/chat_commands.dart';
import 'ui/sessions/chat_sessions_controller.dart';
import 'ui/sessions/chat_sessions_screen.dart';
@@ -59,7 +60,7 @@ class _ChatScreenState extends State<ChatScreen> {
/// conversation's command changes a session.
late final ChatSessionsController _sessions = ChatSessionsController(
ChatRepository(widget.gateway),
);
)..onSessionReplaced = _replacedElsewhere;
/// Rows this visit has opened, used for the native title and the recorded
/// model facts. The mounted list also reports its loaded rows, so a routed id
@@ -122,17 +123,35 @@ class _ChatScreenState extends State<ChatScreen> {
}
}
/// `/new` created [session]: list it at the head before its conversation
/// opens, open it on [notice], then re-read the list from the server.
void _openCreated(JsonMap session, String notice) {
/// `/new` moved the chat [previousId] to a fresh session: [session] takes
/// its list row, the fresh conversation opens on [notice], then the list
/// re-reads from the server.
void _startedNewSession(String previousId, JsonMap session, String notice) {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
_sessions.insertCreated(session);
_startNotice = (id: id, notice: notice);
_open(session);
_sessions.replaceSession(previousId, session);
_followNewSession(previousId, session, notice);
unawaited(_sessions.refresh());
}
/// Another device started a new session in a chat: only an open chat
/// follows it; the list already swapped the row.
void _replacedElsewhere(String previousId, JsonMap session) {
if (!mounted || _selected != previousId) return;
_followNewSession(previousId, session, chatNewSessionElsewhereNotice);
}
/// Opens the chat under its new id on the server's row, which carries every
/// shared field (an omitted one is unset, so the old row is not merged in).
/// A model switch accepted here in this visit moved with the chat.
void _followNewSession(String previousId, JsonMap session, String notice) {
final id = '${session['id'] ?? ''}';
final accepted = _acceptedModels[previousId];
if (accepted != null) _acceptedModels[id] = accepted;
_startNotice = (id: id, notice: notice);
_open(<String, dynamic>{...session}..remove('running'));
}
/// `/rename` was accepted for [id]: the opened row follows the shared title
/// and the list re-reads it.
void _renamed(String id, String title) {
@@ -264,7 +283,7 @@ class _ChatScreenState extends State<ChatScreen> {
onBack: onBack,
onModelChanged: (applied) => _modelChanged(selected, applied),
onModeChanged: (mode, name) => _modeChanged(selected, mode, name),
onCreatedSession: _openCreated,
onNewSession: _startedNewSession,
onSessionRenamed: (title) => _renamed(selected, title),
onSessionClosed: _closed,
onColorSelected: (color) => _sessions.setColor(selected, color),
@@ -90,11 +90,22 @@ 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.
///
/// A row naming `previous_id` is a chat another device moved to a fresh
/// session (`/new`): it replaces that row in place and [onSessionReplaced]
/// lets the destination follow it if that chat is open here.
void _sessionChanged(JsonMap frame) {
final changed = frame['chat_session'];
if (changed is! Map) return;
final id = '${changed['id'] ?? ''}';
if (id.isEmpty || _disposed) return;
final previousId = '${changed['previous_id'] ?? ''}'.trim();
if (previousId.isNotEmpty && previousId != id) {
final row = Map<String, dynamic>.from(changed)..remove('previous_id');
replaceSession(previousId, row);
onSessionReplaced?.call(previousId, row);
return;
}
var found = false;
_sessions = [
for (final row in _sessions)
@@ -338,17 +349,32 @@ class ChatSessionsController extends ChangeNotifier {
return Map<String, dynamic>.from(session);
}
/// Lists a session the server just created at the head of the loaded rows,
/// so the row is present before its conversation opens; the caller re-reads
/// the list from the server afterwards. A row with the same id is replaced,
/// never duplicated.
void insertCreated(JsonMap session) {
/// Called when another device moved a listed chat to a fresh session, with
/// the id it left and its row under the new id.
void Function(String previousId, JsonMap session)? onSessionReplaced;
/// `/new` moved the chat [previousId] to a fresh native session: [session]
/// takes that row's place in the list (it is the same chat), so it is
/// present before its conversation opens; the caller re-reads the list from
/// the server afterwards. A row unknown here is listed at the head, and a
/// row already under the new id is never duplicated.
void replaceSession(String previousId, JsonMap session) {
if (_disposed) return;
final id = '${session['id'] ?? ''}';
_sessions = [
session,
for (final row in _sessions)
if ('${row['id'] ?? ''}' != id) row,
];
if (id.isEmpty) return;
var placed = false;
final next = <JsonMap>[];
for (final row in _sessions) {
final rowId = '${row['id'] ?? ''}';
if (rowId == previousId) {
if (!placed) next.add(session);
placed = true;
} else if (rowId != id) {
next.add(row);
}
}
_sessions = placed ? next : [session, ...next];
if (activeSessionId == previousId) activeSessionId = id;
_seedLocal();
_notify();
}
@@ -16,7 +16,7 @@ class _ModeScreenGateway implements ApiGateway {
_claude('s', 'Wire chat', mode: 'default', name: 'Ask for permission'),
];
/// The `chat_session` a create replies with.
/// The `chat_session` a `/new` replies with, for the chat `s`.
JsonMap created = _claude('n1', 'New chat');
/// Holds list reads while set, so a test can look before the re-read lands.
@@ -33,8 +33,10 @@ class _ModeScreenGateway implements ApiGateway {
final rows = [...sessions];
await listGate?.future;
return {'chat_sessions': rows};
case 'chat_create':
return {'chat_session': created};
case 'chat_new_session':
return {
'chat_session': {...created, 'previous_id': 's'},
};
case 'chat_messages':
return {
'chat_history': {
@@ -234,7 +236,7 @@ void main() {
}
testWidgets(
'a created chat whose reply names its mode shows it before the list re-reads',
'a new session whose reply names its mode shows it before the list re-reads',
(tester) async {
final gateway = _ModeScreenGateway()
..created = _claude('n1', 'New chat', mode: 'plan', name: 'Plan');
@@ -258,7 +260,7 @@ void main() {
);
testWidgets(
'a created chat whose reply lacks its mode shows it when the list re-reads',
'a new session whose reply lacks its mode shows it when the list re-reads',
(tester) async {
final gateway = _ModeScreenGateway();
await _pump(
@@ -271,12 +273,9 @@ void main() {
await tester.pumpAndSettle();
gateway
..listGate = Completer<void>()
..sessions = [
_claude('n1', 'New chat', mode: 'plan', name: 'Plan'),
...gateway.sessions,
];
..sessions = [_claude('n1', 'New chat', mode: 'plan', name: 'Plan')];
await runNew(tester);
// The row is open on the create reply, which names no mode.
// The row is open on the /new reply, which names no mode.
expect(find.text('New chat'), findsWidgets);
expect(_shown(tester), isNull);
@@ -0,0 +1,148 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/domain/chat_commands.dart';
import 'package:pipelines_app/features/chat/screen.dart';
/// A chat destination server whose `/new` re-keys chat `s` to `n1`, as the
/// registry does, and which can push another device's move.
class _NewSessionGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
final pushed = StreamController<JsonMap>.broadcast();
var current = _row('s');
@override
Stream<JsonMap> get frames => pushed.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type: type, fields: fields));
switch (type) {
case 'chat_sessions':
return {
'chat_sessions': [current, _other],
};
case 'chat_new_session':
current = _row('n1');
return {
'chat_session': {...current, 'previous_id': 's'},
};
case 'chat_messages':
final query = fields['chat_query'] as JsonMap;
final old = query['session_id'] == 's';
return {
'chat_history': {
'messages': [
if (old)
{
'id': 'm1',
'role': 'user',
'parts': [
{'type': 'text', 'text': 'Earlier question'},
],
},
],
'next_cursor': '',
'has_more': false,
},
};
}
return <String, dynamic>{};
}
Iterable<String> subscribed() => [
for (final call in calls)
if (call.type == 'chat_subscribe')
'${(call.fields['chat_subscribe'] as Map?)?['session_id']}',
];
}
JsonMap _row(String id) => {
'id': id,
'title': 'Wire chat',
'backend': 'claude',
'directory': '/w',
'color': 'teal',
'starred': true,
'resume_command': 'cd /w && claude --resume $id',
};
const JsonMap _other = {'id': 't', 'title': 'Other chat', 'directory': '/w'};
final _desktop = TargetPlatformVariant.only(TargetPlatform.linux);
Future<void> _pump(WidgetTester tester, _NewSessionGateway gateway) async {
tester.view.physicalSize = const Size(1400, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.linux),
home: Scaffold(body: ChatScreen(gateway: gateway)),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-row-s')));
await tester.pumpAndSettle();
expect(find.text('Earlier question'), findsOneWidget);
}
void main() {
testWidgets(
'/new keeps the chat in its row and opens the fresh, empty session',
(tester) async {
final gateway = _NewSessionGateway();
await _pump(tester, gateway);
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'/new',
);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
final field = tester.widget<EditableText>(
find.descendant(
of: find.byKey(const Key('chat-composer-field')),
matching: find.byType(EditableText),
),
);
if (field.controller.text.isNotEmpty) {
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
}
await tester.pumpAndSettle();
expect(gateway.calls.where((c) => c.type == 'chat_create'), isEmpty);
expect(find.byKey(const Key('chat-row-s')), findsNothing);
expect(find.byKey(const Key('chat-row-n1')), findsOneWidget);
expect(find.byKey(const Key('chat-row-t')), findsOneWidget);
expect(find.text(chatNewSessionNotice), findsOneWidget);
expect(find.text('Earlier question'), findsNothing);
expect(gateway.subscribed().last, 'n1');
},
variant: _desktop,
);
testWidgets(
'an open chat follows a new session started on another device',
(tester) async {
final gateway = _NewSessionGateway();
await _pump(tester, gateway);
gateway.current = _row('n1');
gateway.pushed.add({
'type': 'chat_session_changed',
'chat_session': {...gateway.current, 'previous_id': 's'},
});
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-row-s')), findsNothing);
expect(find.byKey(const Key('chat-row-n1')), findsOneWidget);
expect(find.text(chatNewSessionElsewhereNotice), findsOneWidget);
expect(find.text('Earlier question'), findsNothing);
expect(gateway.subscribed().last, 'n1');
},
variant: _desktop,
);
}
@@ -52,7 +52,7 @@ void main() {
}
expect(find.text('/new'), findsOneWidget);
expect(
find.text('Start a fresh session in this directory'),
find.text('Clear the context: continue this chat in a fresh session'),
findsOneWidget,
);
@@ -252,7 +252,7 @@ void main() {
expect(gateway.promptBodies, isEmpty);
expect(
find.text(
'/new — Start a fresh session in this directory\n'
'/new — Clear the context: continue this chat in a fresh session\n'
'/close — Finish this session for every client, keeping its history\n'
'/rename <title> — Rename this session\n'
'/stop — Stop the turn that is running\n'
@@ -13,20 +13,25 @@ import 'chat_composer_bar_fixtures.dart';
/// on-screen keyboard's Return breaks the line instead.
final _desktop = TargetPlatformVariant.only(TargetPlatform.linux);
/// Answers the session commands' create, close and rename requests.
/// Answers the session commands' new-session, close and rename requests.
class _SessionGateway extends ComposerBarGateway {
String? refuse;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (type == 'chat_create' ||
if (type == 'chat_new_session' ||
type == 'chat_close' ||
type == 'chat_rename') {
calls.add((type: type, fields: fields));
if (refuse != null) throw ProtocolError(refuse!);
if (type == 'chat_create') {
if (type == 'chat_new_session') {
return {
'chat_session': {'id': 'n1', 'title': 'New chat', 'directory': '/w'},
'chat_session': {
'id': 'n1',
'title': 'Old',
'directory': '/w',
'previous_id': 's',
},
};
}
return <String, dynamic>{};
@@ -44,6 +49,7 @@ void main() {
late _SessionGateway gateway;
JsonMap? created;
String? createdNotice;
String? replacedId;
String? renamed;
var closed = 0;
@@ -51,6 +57,7 @@ void main() {
gateway = _SessionGateway();
created = null;
createdNotice = null;
replacedId = null;
renamed = null;
closed = 0;
});
@@ -71,7 +78,8 @@ void main() {
drafts: MemoryChatDraftStore(),
transcripts: transcripts,
newOperationId: () => 'op-1',
onCreatedSession: (session, notice) {
onNewSession: (previousId, session, notice) {
replacedId = previousId;
created = session;
createdNotice = notice;
},
@@ -95,32 +103,37 @@ void main() {
await tester.pumpAndSettle();
}
testWidgets('/new creates in this directory and hands the row over', (
testWidgets('/new keeps this chat on a fresh session and hands it over', (
tester,
) async {
await pump(tester);
await run(tester, '/new');
final body = gateway.sent('chat_create').single['chat_create'] as JsonMap;
expect(body['title'], 'New chat');
expect(body['directory'], '/w');
expect(body['operation_id'], 'op-1');
expect(gateway.sent('chat_create'), isEmpty);
final body =
gateway.sent('chat_new_session').single['chat_new_session'] as JsonMap;
expect(body['session_id'], 's');
expect(body['instructions'], isNotEmpty);
expect(replacedId, 's');
expect(created?['id'], 'n1');
expect(createdNotice, 'Started a new session “New chat” in /w.');
expect(created?['title'], 'Old');
expect(created?.containsKey('previous_id'), isFalse);
expect(createdNotice, startsWith('New session started.'));
expect(gateway.promptBodies, isEmpty);
}, variant: _desktop);
testWidgets('/new without a directory sends nothing and reports it', (
testWidgets('/new refused keeps the reason here and hands nothing over', (
tester,
) async {
await pump(tester, directory: '');
gateway.refuse = 'a turn is still running in this chat';
await pump(tester);
await run(tester, '/new');
expect(gateway.sent('chat_create'), isEmpty);
expect(gateway.sent('chat_new_session'), hasLength(1));
expect(created, isNull);
expect(
find.text(
"Can't start a new session here: the server reported no directory "
'for this chat.',
"Couldn't start a new session: a turn is still running in this chat",
),
findsOneWidget,
);
@@ -18,7 +18,7 @@ void main() {
'/help',
]);
expect(chatCommands.map((command) => command.summary), [
'Start a fresh session in this directory',
'Clear the context: continue this chat in a fresh session',
'Finish this session for every client, keeping its history',
'Rename this session',
'Stop the turn that is running',
@@ -0,0 +1,74 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/data/chat_repository.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
/// `/new` keeps a chat: its row changes id in place, here and on the other
/// devices that receive the move as `chat_session_changed` with `previous_id`.
void main() {
late FakeChatGateway gateway;
late ChatSessionsController controller;
setUp(() async {
gateway = FakeChatGateway();
gateway.sessionsHandler = () async => {
'chat_sessions': [
{'id': 's1', 'title': 'First', 'directory': '/w'},
{'id': 's2', 'title': 'Second', 'directory': '/w', 'color': 'teal'},
{'id': 's3', 'title': 'Third', 'directory': '/w'},
],
};
controller = ChatSessionsController(
ChatRepository(gateway),
localStore: MemoryChatSessionLocalStore(),
);
await controller.refresh();
});
tearDown(() => controller.dispose());
List<String> ids() => [for (final row in controller.sessions) '${row['id']}'];
test('a new session takes the row it replaces, in place', () {
controller.replaceSession('s2', {
'id': 'n2',
'title': 'Second',
'directory': '/w',
'color': 'teal',
});
expect(ids(), ['s1', 'n2', 's3']);
expect(controller.sessions[1]['color'], 'teal');
});
test('a replaced row this device never listed joins at the head', () {
controller.replaceSession('gone', {'id': 'n9', 'title': 'Elsewhere'});
expect(ids(), ['n9', 's1', 's2', 's3']);
});
test('another device\'s /new swaps the row live and is reported', () async {
final lists = gateway.count('chat_sessions');
final replaced = <(String, JsonMap)>[];
controller.onSessionReplaced = (previous, row) =>
replaced.add((previous, row));
gateway.pushed.add({
'type': 'chat_session_changed',
'chat_session': {
'id': 'n2',
'previous_id': 's2',
'title': 'Second',
'directory': '/w',
'color': 'teal',
'resume_command': 'cd /w && claude --resume n2',
},
});
await pumpEventQueue();
expect(ids(), ['s1', 'n2', 's3']);
expect(controller.sessions[1].containsKey('previous_id'), isFalse);
expect(controller.sessions[1]['resume_command'], contains('n2'));
expect(replaced.single.$1, 's2');
expect(replaced.single.$2['id'], 'n2');
expect(gateway.count('chat_sessions'), lists);
});
}
@@ -0,0 +1,49 @@
// `/new` for the `?chats=N` fixture chats (tool/perf/perf_fixture.dart).
//
// A `chat_new_session` moves chat i to a fresh native id, as the server
// re-keys the registry row: the chat keeps its index (title, directory,
// colour, star) and its new id opens an empty transcript.
import 'package:pipelines_app/core/api_gateway.dart';
final Map<int, int> _generation = {};
/// The current native id of fixture chat [index].
String perfChatId(int index) {
final generation = _generation[index] ?? 0;
return generation == 0
? 'perf-chat-$index'
: 'perf-chat-$index-new$generation';
}
/// The fixture chat index an id (current or replaced) belongs to.
int perfChatIndex(String id) =>
int.tryParse(id.replaceFirst('perf-chat-', '').split('-').first) ?? 0;
/// Whether [id] is a fresh session `/new` started, whose transcript is empty.
bool perfChatIsFresh(String id) => id.contains('-new');
/// Answers `chat_new_session` with [row] (the chat under its new id) built
/// after the move, or an error for a chat id that is not current.
JsonMap perfChatNewSessionReply(
JsonMap request,
JsonMap Function(int index) row,
) {
final body = request['chat_new_session'];
final previous = body is Map ? '${body['session_id'] ?? ''}' : '';
final index = perfChatIndex(previous);
if (previous != perfChatId(index)) {
return {
'id': request['id'],
'type': 'error',
'error': 'this chat has already started a new session',
};
}
_generation[index] = (_generation[index] ?? 0) + 1;
final session = {...row(index), 'previous_id': previous};
return {
'id': request['id'],
'type': 'chat_new_session',
'chat_session': session,
'chat_sessions': [session],
};
}
+19 -4
View File
@@ -12,8 +12,11 @@
// them, and keeps colours picked with chat_color;
// `?msgs=`, `?rich=1`, `?older=1`, `?live=N` vary the chat transcripts for
// scroll captures (tool/perf/chat_scroll_fixture.dart).
// `/new` in a fixture chat moves it to a fresh, empty session
// (tool/perf/chat_new_session_fixture.dart).
import 'package:pipelines_app/core/api_gateway.dart';
import 'chat_new_session_fixture.dart';
import 'chat_scroll_fixture.dart';
Map<String, String> _params = const {};
@@ -45,7 +48,7 @@ const _colorNames = ['teal', 'purple', null, 'amber', 'red', null, 'blue'];
final Map<String, String?> _pickedColors = {};
JsonMap _chatRow(int i) {
final id = 'perf-chat-$i';
final id = perfChatId(i);
if (!_colors) {
return {
'id': id,
@@ -199,8 +202,7 @@ JsonMap? perfChatReply(JsonMap request) {
final session = query is Map ? '${query['session_id'] ?? ''}' : '';
final color = query is Map ? query['color'] as String? : null;
_pickedColors[session] = color;
final index = int.tryParse(session.replaceFirst('perf-chat-', '')) ?? 0;
final row = _chatRow(index);
final row = _chatRow(perfChatIndex(session));
return {
'id': id,
'type': 'chat_color',
@@ -222,6 +224,8 @@ JsonMap? perfChatReply(JsonMap request) {
'content': json ? '{"messages":[]}\n' : '# Fixture chat\n',
},
};
case 'chat_new_session':
return perfChatNewSessionReply(request, _chatRow);
case 'chat_subscribe':
return {'id': id, 'type': 'chat_subscribed'};
case 'chat_shells':
@@ -229,13 +233,24 @@ JsonMap? perfChatReply(JsonMap request) {
case 'chat_messages':
final query = request['chat_query'];
final session = query is Map ? '${query['session_id'] ?? ''}' : '';
if (perfChatIsFresh(session)) {
return {
'id': id,
'type': 'chat_messages',
'chat_history': {
'messages': const [],
'next_cursor': '',
'has_more': false,
},
};
}
if (_scrollVariety) {
return {
'id': id,
'type': 'chat_messages',
'chat_history': chatScrollHistory(
session,
int.tryParse(session.replaceFirst('perf-chat-', '')) ?? 0,
perfChatIndex(session),
query is Map ? '${query['cursor'] ?? ''}' : '',
),
};
+24
View File
@@ -71,6 +71,30 @@ command noise are excluded, and paging is bounded. A session file larger than
The live user turn keeps the client's optimistic id when it can be matched to the
recorded prompt.
## Fresh context (`/new`)
The composer's `/new` sends `chat_new_session`. It keeps the chat and clears the
agent's context, like `/new` or `/clear` in the harness's own TUI. The server
creates a fresh native session on the chat's own harness, in the same directory
and with the same title. OpenCode makes a new `ses_` session, Codex a new thread
and Claude Code a new session UUID. The server then re-keys the
`operator_sessions` row in one transaction. The new row keeps the title,
directory, tag, backend, colour, star, creation time, model override and mode.
The old row is not deleted: it records `replaced_by`, is no longer listed, and
its native session can still be resumed in a terminal.
The row is re-keyed rather than mapped from a stable id because every other
layer is keyed by the native id: rooms, queues, transcripts, shells, exports and
resume commands. The reply, and the `chat_session_changed` push to other
connections, carry the new row with `previous_id`. Each client swaps that row in
place, and an open conversation follows it to the fresh, empty transcript. A
running turn is refused, so stop it first. A second `/new` from an id that has
already been replaced is refused too.
Claude Code also accepts `/clear` in `-p --input-format stream-json` mode, but
the CLI then picks the new session id itself. Re-keying keeps one path for all
three harnesses and lets the server choose the id.
## Web interaction contract
All advertised chat adapters (OpenCode V2, Codex and Claude Code) implement the
+50 -2
View File
@@ -169,7 +169,55 @@ func (s *Store) migrateOperatorSessions() error {
// ephemeral marks a chat created for automated verification. It is hidden from
// OperatorSessions but still a real row, so the session stays usable and
// closable. Existing rows default to 0 (a normal, listed chat).
return s.addColumnIfMissing("operator_sessions", "ephemeral", "INTEGER NOT NULL DEFAULT 0")
if err := s.addColumnIfMissing("operator_sessions", "ephemeral", "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
// 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 ''")
}
// ErrOperatorSessionReplaced reports that a chat was already moved to another
// native session, so a second, concurrent /new cannot fork it.
var ErrOperatorSessionReplaced = errors.New("this chat has already started a new session")
// ReplaceOperatorSession re-keys one operator chat onto a fresh native session
// in one transaction: a row for newID takes every shared field of oldID (title,
// directory, tag, backend, colour, star, created_at, model and mode) and is
// marked used now and open, and the old row records replaced_by so it is no
// longer listed. The old row is kept, not deleted, so its id still resolves
// and its native session stays resumable. A row already replaced, or an id
// that is not a recorded operator chat, changes nothing.
func (s *Store) ReplaceOperatorSession(ctx context.Context, oldID, newID string) error {
if oldID == "" || newID == "" || oldID == newID {
return errors.New("a distinct current and new session id are required")
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var replacedBy string
err = tx.QueryRowContext(ctx, `SELECT replaced_by FROM operator_sessions WHERE session_id=? AND tag<>''`, oldID).Scan(&replacedBy)
if errors.Is(err, sql.ErrNoRows) {
return errors.New("session " + oldID + " is not an operator chat session")
}
if err != nil {
return err
}
if replacedBy != "" {
return ErrOperatorSessionReplaced
}
now := time.Now().UnixMilli()
if _, err := tx.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at,starred_at,color,backend,ephemeral,chat_model,chat_model_provider,chat_mode)
SELECT ?,directory,title,tag,created_at,?,0,starred_at,color,backend,ephemeral,chat_model,chat_model_provider,chat_mode FROM operator_sessions WHERE session_id=?`, newID, now, oldID); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `UPDATE operator_sessions SET replaced_by=? WHERE session_id=?`, newID, oldID); err != nil {
return err
}
return tx.Commit()
}
// SetChatModelSelection saves a Pipelines next-turn override, not a remote
@@ -354,7 +402,7 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
// 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
FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
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
}
+22
View File
@@ -43,6 +43,15 @@ const (
// ChatRename records the operator's shared chat title on the server. Unlike
// a local override, every browser and device then lists the same name.
ChatRename = "chat_rename"
// ChatNewSession is the composer's /new: the same chat (list row, title,
// colour, star, directory, model and mode) continues on a fresh native
// harness session with an empty context, as /new or /clear do inside the
// harness's own TUI. The body is ChatNewSessionRequest. The registry row is
// re-keyed to the new native id; the reply and the chat_session_changed push
// carry the new row with PreviousID naming the id it replaced, so every
// client swaps the row in place and an open conversation follows it. The
// previous native session is untouched and stays resumable in a terminal.
ChatNewSession = "chat_new_session"
// ChatExport returns one operator chat as a file the client saves or
// shares. The body is ChatExportRequest and the reply carries
// ChatExportFile: a Markdown or JSON transcript built from the same history
@@ -306,6 +315,11 @@ type ChatSession struct {
// Color is the operator's shared highlight, a ChatColors name; omitted when
// none is set. Clients map the name to their own theme-tuned shade.
Color string `json:"color,omitempty"`
// PreviousID is set only on a chat_new_session reply and its
// chat_session_changed push: the native session id this chat ran on until
// the operator started a fresh session. Clients replace the row with that
// id by this one; it is never part of a listed row.
PreviousID string `json:"previous_id,omitempty"`
}
// Chat export formats accepted by chat_export.
@@ -776,6 +790,14 @@ type ChatRenameRequest struct {
Title string `json:"title"`
}
// ChatNewSessionRequest is the chat_new_session body: the chat whose context
// is replaced, and an optional behaviour instruction preloaded on the fresh
// session where the harness supports one (like chat_create's Instructions).
type ChatNewSessionRequest struct {
SessionID string `json:"session_id"`
Instructions string `json:"instructions,omitempty"`
}
// ChatAnswerRequest is the chat_answer body: the form id and a field-keyed
// answer object. It is deliberately separate from ChatQuery because its payload
// is structured answers, not a session-scoped read.
+3
View File
@@ -203,6 +203,9 @@ type Message struct {
ChatAnswer *ChatAnswerRequest `json:"chat_answer,omitempty"`
// ChatRename is the chat_rename body; the reply echoes the updated session.
ChatRename *ChatRenameRequest `json:"chat_rename,omitempty"`
// ChatNewSession is the chat_new_session body; the reply carries the
// re-keyed session in ChatSession with PreviousID set.
ChatNewSession *ChatNewSessionRequest `json:"chat_new_session,omitempty"`
// ChatExport is the chat_export body and ChatExportFile its reply.
ChatExport *ChatExportRequest `json:"chat_export,omitempty"`
ChatExportFile *ChatExportFile `json:"chat_export_file,omitempty"`
+3
View File
@@ -210,6 +210,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatRename:
handleChatRename(ctx, request, broker, registry, hub.changes(), clientID, write)
return true
case protocol.ChatNewSession:
handleChatNewSession(ctx, request, broker, hub, registry, clientID, write)
return true
case protocol.ChatExport:
handleChatExport(ctx, request, broker, registry, write)
return true
+149
View File
@@ -0,0 +1,149 @@
package server
import (
"context"
"errors"
"strings"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatSessionReplacer re-keys an operator chat onto a fresh native session,
// keeping every shared field (see pipeline.Store.ReplaceOperatorSession).
type chatSessionReplacer interface {
ReplaceOperatorSession(ctx context.Context, oldID, newID string) error
}
// handleChatNewSession answers chat_new_session: the composer's /new. The chat
// keeps its list row, title, colour, star, directory, model and mode, and
// continues on a fresh native session of the same harness, so the model starts
// from an empty context exactly as /new or /clear do in the harness's own TUI.
//
// The registry is the only place that knows "this chat": every other layer
// (rooms, queues, transcripts, shells, exports, resume commands) is keyed by
// the native id, so the row is re-keyed in one transaction rather than mapped.
// The previous native session is not touched and remains resumable in a
// terminal. A running turn is refused rather than abandoned. Every other
// connection receives the new row as chat_session_changed with PreviousID set,
// so its list swaps the row in place and an open conversation follows it.
func handleChatNewSession(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) {
fail := func(message string) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: message})
}
if broker == nil {
fail("chat is not configured on this server")
return
}
replacer, ok := registry.(chatSessionReplacer)
if registry == nil || !ok {
fail("operator session registry is not configured on this server")
return
}
body := request.ChatNewSession
if body == nil || !validChatSessionID(strings.TrimSpace(body.SessionID)) {
fail("a valid chat session id is required")
return
}
oldID := strings.TrimSpace(body.SessionID)
current, found, err := registry.OperatorSession(ctx, oldID)
if err != nil {
fail(err.Error())
return
}
if !found {
fail("session " + oldID + " is not an operator chat session")
return
}
if hub.turnInFlight(oldID) {
fail("a turn is still running in this chat; stop it before starting a new session")
return
}
backend := current.Backend
if backend == "" {
backend = "opencode"
}
var created protocol.ChatSession
if creator, ok := broker.(chatCreateBackend); ok {
created, err = creator.CreateBackend(ctx, current.Title, current.Directory, backend)
} else if backend == "opencode" {
created, err = broker.Create(ctx, current.Title, current.Directory)
} else {
err = errors.New("chat backend " + backend + " is not available")
}
if err != nil {
fail("could not start a new " + backend + " session: " + err.Error())
return
}
if !validChatSessionID(created.ID) || created.ID == oldID {
fail("the " + backend + " harness did not return a new session id")
return
}
// A fresh chat_create activates the manager skill before its first prompt;
// a fresh context must start from the same footing.
if err := broker.ActivateSkill(ctx, created.ID, "pipelines-manager"); err != nil {
fail("session " + created.ID + " was started but manager bootstrap failed while activating pipelines-manager: " + err.Error())
return
}
if err := replacer.ReplaceOperatorSession(ctx, oldID, created.ID); err != nil {
if errors.Is(err, pipeline.ErrOperatorSessionReplaced) {
fail(err.Error() + "; reopen the chat to continue it")
return
}
fail("session " + created.ID + " was started but the chat could not move to it: " + err.Error())
return
}
// Nothing queued for the old context may run in the new one; with no turn
// in flight this is normally already empty.
hub.clearQueue(ctx, oldID)
row, found, err := registry.OperatorSession(ctx, created.ID)
if err != nil || !found {
fail("session " + created.ID + " was recorded but could not be read back")
return
}
wire := chatSessionFromOperator(row)
wire.PreviousID = oldID
// The model override moved with the row too; the harness's own read folds
// it in (chatManager.Session), else the create's report stands.
model := created
if read, ok, err := broker.Session(ctx, created.ID); err == nil && ok {
model = read
}
wire.Model, wire.ModelProvider, wire.Agent = model.Model, model.ModelProvider, model.Agent
wire.ModelSelection = model.ModelSelection
wire.Mode, wire.ModeName = created.Mode, created.ModeName
// The stored mode moved with the row, so name it now rather than the
// harness default the create reported before the row existed.
if moded, ok := broker.(interface {
withMode(context.Context, protocol.ChatSession) protocol.ChatSession
}); ok {
wire = moded.withMode(ctx, wire)
}
wire.InstructionStatus = "not_requested"
if instructions := strings.TrimSpace(body.Instructions); instructions != "" {
wire.InstructionStatus = "unsupported"
if instr, ok := broker.(chatInstructioner); ok {
err := instr.SetInstruction(ctx, created.ID, "pipelines.behavior", instructions)
switch {
case err == nil:
wire.InstructionStatus = "applied"
case errors.Is(err, errChatInstructionsUnsupported):
wire.InstructionError = err.Error()
default:
wire.InstructionStatus = "failed"
wire.InstructionError = err.Error()
}
}
}
_ = write(protocol.Message{
Type: protocol.ChatNewSession,
ID: request.ID,
ChatSession: &wire,
ChatSessions: []protocol.ChatSession{wire},
})
if changes := hub.changes(); changes != nil {
pushed := wire
pushed.InstructionStatus, pushed.InstructionError = "", ""
changes.broadcast(clientID, pushed)
}
}
+201
View File
@@ -0,0 +1,201 @@
package server
import (
"context"
"strings"
"testing"
"time"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/codex"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func chatNewSessionRequest(id, session string) protocol.Message {
return protocol.Message{Type: protocol.ChatNewSession, ID: id, ChatNewSession: &protocol.ChatNewSessionRequest{SessionID: session}}
}
// TestChatNewSessionKeepsTheChatOnEveryHarness is the /new evidence for all
// three harnesses: the same chat (title, colour, star, directory, backend,
// mode) moves to a fresh native session of its own harness, the reply and the
// other devices' push name the replaced id, the list shows the one chat under
// its new id, and the resume command names the new native session while the
// old row still resolves.
func TestChatNewSessionKeepsTheChatOnEveryHarness(t *testing.T) {
cases := []struct {
backend, oldID, newID string
}{
{"opencode", "ses_old", "ses_fresh"},
{codex.Backend, "11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222"},
{claude.Backend, "33333333-3333-4333-8333-333333333333", "44444444-4444-4444-8444-444444444444"},
}
for _, tc := range cases {
t.Run(tc.backend, func(t *testing.T) {
store := newOperatorStore(t)
open, codexFake, claudeFake := scriptedChat(), scriptedChat(), scriptedChat()
owner := map[string]*fakeChat{"opencode": open, codex.Backend: codexFake, claude.Backend: claudeFake}[tc.backend]
owner.created = protocol.ChatSession{ID: tc.newID, Title: "Feature"}
owner.sessionFound = true
for _, fake := range []*fakeChat{open, codexFake, claudeFake} {
fake.sessions = []protocol.ChatSession{{ID: tc.oldID}, {ID: tc.newID}}
}
manager := newChatManager(context.Background(), open, store,
(&fakeHarness{available: true, client: codexFake}).probe(),
(&fakeHarness{available: true, client: claudeFake}).probe(), time.Now)
ctx, _, conns := dialChatConns(t, Options{Chat: manager, OperatorRegistry: store}, 2)
if err := store.RecordOperatorSession(ctx, tc.oldID, "/work/a", "Feature", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if err := store.SetOperatorSessionBackend(ctx, tc.oldID, tc.backend); err != nil {
t.Fatal(err)
}
if err := store.SetOperatorSessionColor(ctx, tc.oldID, "teal"); err != nil {
t.Fatal(err)
}
if err := store.SetOperatorSessionStar(ctx, tc.oldID, true); err != nil {
t.Fatal(err)
}
if err := store.SetChatMode(ctx, tc.oldID, "plan"); err != nil {
t.Fatal(err)
}
if err := wsjson.Write(ctx, conns[1], protocol.Message{Type: protocol.Ping, ID: "p1"}); err != nil {
t.Fatal(err)
}
if pong := readMessage(t, ctx, conns[1]); pong.ID != "p1" {
t.Fatalf("ping reply = %+v", pong)
}
if err := wsjson.Write(ctx, conns[0], chatNewSessionRequest("n1", tc.oldID)); err != nil {
t.Fatal(err)
}
reply := readMessage(t, ctx, conns[0])
got := reply.ChatSession
if reply.Type != protocol.ChatNewSession || reply.ID != "n1" || got == nil {
t.Fatalf("chat_new_session reply = %+v", reply)
}
if got.ID != tc.newID || got.PreviousID != tc.oldID || got.Title != "Feature" || got.Directory != "/work/a" ||
got.Backend != tc.backend || got.Color != "teal" || !got.Starred || got.Closed {
t.Fatalf("new session row = %+v", got)
}
if tc.backend != "opencode" && !strings.Contains(got.ResumeCommand, tc.newID) {
t.Fatalf("resume command %q does not name the new session", got.ResumeCommand)
}
if calls, title, directory := owner.createQuery(); calls != 1 || title != "Feature" || directory != "/work/a" {
t.Fatalf("harness create = %d %q %q", calls, title, directory)
}
pushed := readMessage(t, ctx, conns[1])
if pushed.Type != protocol.ChatSessionChanged || pushed.ChatSession == nil ||
pushed.ChatSession.ID != tc.newID || pushed.ChatSession.PreviousID != tc.oldID {
t.Fatalf("watcher push = %+v", pushed)
}
if mode := manager.CurrentMode(ctx, tc.newID); mode != "plan" {
t.Fatalf("stored mode after /new = %q, want plan", mode)
}
if err := wsjson.Write(ctx, conns[0], protocol.Message{Type: protocol.ChatSessions, ID: "l1"}); err != nil {
t.Fatal(err)
}
listed := readMessage(t, ctx, conns[0])
if len(listed.ChatSessions) != 1 || listed.ChatSessions[0].ID != tc.newID || listed.ChatSessions[0].PreviousID != "" {
t.Fatalf("chat_sessions after /new = %+v", listed.ChatSessions)
}
if old, found, err := store.OperatorSession(ctx, tc.oldID); err != nil || !found || old.Title != "Feature" {
t.Fatalf("old row = %+v found=%v err=%v", old, found, err)
}
})
}
}
// TestChatNewSessionRefusesWithoutCreating proves a refused /new never starts
// a native session: a foreign id, a running turn, and a second /new on a chat
// already moved on.
func TestChatNewSessionRefusesWithoutCreating(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
broker.block = true
broker.started = make(chan struct{})
broker.created = protocol.ChatSession{ID: "ses_fresh"}
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if err := wsjson.Write(ctx, conn, chatNewSessionRequest("x", "ses_unknown")); err != nil {
t.Fatal(err)
}
if reply := readMessage(t, ctx, conn); reply.Type != protocol.Error || !strings.Contains(reply.Error, "not an operator chat") {
t.Fatalf("foreign reply = %+v", reply)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "long"}}); err != nil {
t.Fatal(err)
}
if ack := readMessage(t, ctx, conn); ack.Type != protocol.ChatPrompt {
t.Fatalf("prompt ack = %+v", ack)
}
<-broker.started
if err := wsjson.Write(ctx, conn, chatNewSessionRequest("busy", "ses_1")); err != nil {
t.Fatal(err)
}
for {
reply := readMessage(t, ctx, conn)
if reply.ID != "busy" {
continue
}
if reply.Type != protocol.Error || !strings.Contains(reply.Error, "turn is still running") {
t.Fatalf("busy reply = %+v", reply)
}
break
}
if calls, _, _ := broker.createQuery(); calls != 0 {
t.Fatalf("a refused /new created %d sessions", calls)
}
}
// TestReplaceOperatorSessionMovesEveryField pins the registry re-key: the new
// row takes every shared field, the old row is kept but unlisted, and a second
// replace of the same chat is refused.
func TestReplaceOperatorSessionMovesEveryField(t *testing.T) {
store := newOperatorStore(t)
ctx := context.Background()
if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "Title", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
_ = store.SetOperatorSessionBackend(ctx, "ses_a", claude.Backend)
_ = store.SetOperatorSessionColor(ctx, "ses_a", "red")
_ = store.SetOperatorSessionStar(ctx, "ses_a", true)
_ = store.CloseOperatorSession(ctx, "ses_a")
if err := store.SetChatModelSelection(ctx, "ses_a", "anthropic", "opus"); err != nil {
t.Fatal(err)
}
before, _, _ := store.OperatorSession(ctx, "ses_a")
if err := store.ReplaceOperatorSession(ctx, "ses_a", "ses_b"); err != nil {
t.Fatal(err)
}
after, found, err := store.OperatorSession(ctx, "ses_b")
if err != nil || !found {
t.Fatalf("new row found=%v err=%v", found, err)
}
if after.Title != "Title" || after.Directory != "/work/a" || after.Backend != claude.Backend || after.Color != "red" ||
after.StarredAt != before.StarredAt || after.CreatedAt != before.CreatedAt || after.ClosedAt != 0 {
t.Fatalf("new row = %+v, old = %+v", after, before)
}
if provider, model, _ := store.ChatModelSelection(ctx, "ses_b"); provider != "anthropic" || model != "opus" {
t.Fatalf("model selection = %q %q", provider, model)
}
rows, _ := store.OperatorSessions(ctx)
if len(rows) != 1 || rows[0].ID != "ses_b" {
t.Fatalf("listed rows = %+v", rows)
}
if _, found, _ := store.OperatorSession(ctx, "ses_a"); !found {
t.Fatal("the replaced row was deleted")
}
if err := store.ReplaceOperatorSession(ctx, "ses_a", "ses_c"); err == nil {
t.Fatal("a chat already moved on was replaced again")
}
if err := store.ReplaceOperatorSession(ctx, "ses_missing", "ses_d"); err == nil {
t.Fatal("an unknown chat was replaced")
}
}