Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Buddy sessions: compact New session chips, and a session from the main Buddy chat (#2427)

0xken155b5a8d4ab5c1
diff --git a/backend/integration/superTabBuddySessions.test.ts b/backend/integration/superTabBuddySessions.test.ts
index 31b6f0dd8..49c556ba5 100644
--- a/backend/integration/superTabBuddySessions.test.ts
+++ b/backend/integration/superTabBuddySessions.test.ts
@@ -262,7 +262,48 @@ describe('a Buddy thread session', () => {
expect(read.state.starts?.find(s => s.id === pending)?.error).toBeTruthy()
})
- it('is refused without saying whose: an old host, no Buddy, another person, a made-up thread, a plain main message', async () => {
+ it('starts from the person\'s own main-chat message, which roots its thread: only its session hears it, only the chat\'s readers see it', async () => {
+ const f = await swarm()
+ await f.say('Earlier in the main chat')
+ const ask = 'Measure prod CPU for the last day'
+ const sent = await f.execute({ type: 'message.send', conversationId: f.chat, text: ask, replyTo: null, recipientIds: [], newSession: true }, peer)
+ const root = String(sent.result.messageId), startId = String(sent.result.startId)
+ expect((await f.store.read(peer, f.tab)).state.conversations.find(c => c.id === f.chat)!.buddySessions).toMatchObject([{ thread: root, startId }])
+ const start = (await poolRows(f.store, peer, 'peer-mac')).find(p => p.tabId === f.tab)!.buddyStarts!.find(s => s.id === startId)!
+ expect(start.request).toMatchObject({ conversationId: f.chat, buddyOf: { personId: peer.sub }, buddySession: { thread: root } })
+ expect(JSON.stringify(start)).not.toContain(ask)
+ // Nobody receives it while its session starts: not the main Buddy, nor anyone else.
+ expect(await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: root } })).toEqual([])
+ await f.host({ type: 'agent.startDispatch', startId })
+ const agentId = String((await f.host({ type: 'agent.started', startId, harnessId: randomUUID(), configuration: config })).result.agentId)
+ // Then its session alone.
+ expect((await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: root } })).map(d => d.agentId)).toEqual([agentId])
+ // The main Buddy never reads it; its session reads its own thread from that root.
+ const mainReads = text(await f.store.messages(peer, f.tab, f.chat, {}, f.main))
+ expect(mainReads).toContain('Earlier in the main chat')
+ expect(mainReads).not.toContain(ask)
+ expect(text(await f.store.messages(peer, f.tab, f.chat, { messageId: root }, f.main))).toEqual([])
+ expect(text(await f.store.messages(peer, f.tab, f.chat, {}, agentId))).toEqual([ask])
+ // The person reads it in the main chat, as the root of its thread.
+ expect(text(await f.store.messages(peer, f.tab, f.chat, {})).slice(-2)).toEqual(['Earlier in the main chat', ask])
+ // Another member reads none of the chat, as before.
+ await expect(f.store.messages(owner, f.tab, f.chat, {})).rejects.toThrow()
+ // A reply in its thread reaches its session alone.
+ const next = String((await f.reply(root, 'And memory too')).result.messageId)
+ expect((await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: next } })).map(d => d.agentId)).toEqual([agentId])
+ })
+
+ it('roots a session only from the chat\'s own person: never another member, nor a Buddy, nor with a recipient', async () => {
+ const f = await swarm()
+ const top = (extra: Partial<Extract<Command, { type: 'message.send' }>> = {}) =>
+ ({ type: 'message.send' as const, conversationId: f.chat, text: 'x', replyTo: null, recipientIds: [], newSession: true as const, ...extra })
+ await expect(f.execute(top(), owner)).rejects.toThrow('unavailable')
+ await expect(f.execute(top(), peer, f.main)).rejects.toMatchObject({ code: 'BUDDY_SESSION_CHAT' })
+ await expect(f.execute(top({ recipientIds: [f.main] }), peer)).rejects.toMatchObject({ code: 'INVALID_RECIPIENT' })
+ expect((await f.store.read(peer, f.tab)).state.conversations.find(c => c.id === f.chat)!.buddySessions ?? []).toEqual([])
+ })
+
+ it('is refused without saying whose: an old host, no Buddy, another person, a made-up thread', async () => {
const old = await swarm({ capable: false })
const root = await old.say('Start')
await expect(old.reply(root, 'x', { newSession: true })).rejects.toMatchObject({ code: 'BUDDY_SESSION_UNSUPPORTED' })
@@ -271,8 +312,6 @@ describe('a Buddy thread session', () => {
await expect(f.execute({ type: 'message.send', conversationId: f.chat, text: 'x', replyTo: mine, recipientIds: [], newSession: true }, owner))
.rejects.toThrow('unavailable')
await expect(f.reply('ffffffffffffffffffffffff', 'x', { newSession: true })).rejects.toMatchObject({ code: 'INVALID_REPLY' })
- await expect(f.execute({ type: 'message.send', conversationId: f.chat, text: 'x', replyTo: null, recipientIds: [], newSession: true }, peer))
- .rejects.toMatchObject({ code: 'BUDDY_SESSION_CHAT' })
await f.execute({ type: 'buddy.remove', projectId: 'lead' }, peer)
await expect(f.reply(mine, 'x', { newSession: true })).rejects.toMatchObject({ code: 'BUDDY_SESSION_NO_BUDDY' })
})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index c40bb96b0..fbba905bb 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -884,7 +884,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
*/
const routeBuddySession = (chat: Conversation): { inSession: boolean; to: string | null } => {
if (command.type !== 'message.send') return { inSession: false, to: null }
- const thread = command.replyTo && !context.reply?.agentOnly ? context.reply?.thread ?? null : null
+ // A person's own top-level New session message roots its own thread (the message is that thread's root, its id the
+ // thread's): its session starts there, and the main Buddy never hears it.
+ const roots = actor.kind === 'person' && !!command.newSession && !command.replyTo
+ const thread = roots ? operationId : command.replyTo && !context.reply?.agentOnly ? context.reply?.thread ?? null : null
const self = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId) : undefined
const entry = sessionOf(state, chat, thread)
if (self?.buddySession) {
@@ -901,7 +904,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (actor.kind !== 'person') return { inSession: false, to: null }
if (command.newSession) {
const owner = requireChatOwner(state, chat, actor.userId)
- if (!thread) fail('BUDDY_SESSION_CHAT', 'Start a session from a thread: reply to a message, then choose New session.', 400)
+ if (!thread) fail('BUDDY_SESSION_CHAT', 'Start a session from a message of your own, or a reply in a thread.', 400)
if (entry) fail('BUDDY_SESSION_EXISTS', 'This thread already has its own session.')
if (command.alsoSend) fail('BUDDY_SESSION_THREAD', 'A session\'s thread stays in the thread.', 400)
if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index cb2ef23fb..975f4f01d 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -94,6 +94,10 @@ export interface Derived {
* true and the Buddy's machine reports it can run sessions. Absent from an older backend, whose strict schema refuses
* the field. */
threadSessions?: true
+ /** This server also takes `newSession` on a person's top-level message in their own Buddy chat: the message roots its
+ * own thread, which gets the session (commands.ts routeBuddySession). Desktop offers New session in that chat's main
+ * composer only where it is true. Absent from an older backend, which refuses it. */
+ sessionsFromChat?: true
}
export interface OtherProjectWorkView {
conversationId: string; projectName: string; title: string; owns: string[]; status: WorkStatus; agentName: string; pr: string | null
diff --git a/backend/src/superTabs/read/views.test.ts b/backend/src/superTabs/read/views.test.ts
index 2870c60f4..a5fdd5951 100644
--- a/backend/src/superTabs/read/views.test.ts
+++ b/backend/src/superTabs/read/views.test.ts
@@ -89,7 +89,7 @@ describe('reader view of the parts (design 4.1, 4.3)', () => {
it('says to every reader that this server takes New session in a thread reply', () => {
const { s, parts } = scene()
for (const actor of [owner, peer, agentActor(s.worker)]) {
- expect(readerView(parts, actor, NOW, { teamMachines: [] }).derived.threadSessions).toBe(true)
+ expect(readerView(parts, actor, NOW, { teamMachines: [] }).derived).toMatchObject({ threadSessions: true, sessionsFromChat: true })
}
})
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index faaf7504f..1c99de516 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -150,5 +150,6 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:
...(actor.kind === 'person' && extras.decisionsDigest !== undefined ? { decisionsDigest: extras.decisionsDigest } : {}),
...(teamAccountSwarm(state) ? {} : { teamAccounts: false as const }),
threadSessions: true as const,
+ sessionsFromChat: true as const,
}
}
diff --git a/desktop/lib/super_tabs/buddy_sessions.dart b/desktop/lib/super_tabs/buddy_sessions.dart
index 2e91a07f0..d8445d675 100644
--- a/desktop/lib/super_tabs/buddy_sessions.dart
+++ b/desktop/lib/super_tabs/buddy_sessions.dart
@@ -181,11 +181,17 @@ class _SuperTabThreadSessionLineState extends State<SuperTabThreadSessionLine> {
}
/// " · ⠋ Own session" at the end of a thread's line in the chat, while the
-/// thread has a session of its own.
+/// thread has a session of its own; "⠋ Own session · Starting…" as the whole
+/// line ([alone]) while its thread has no reply yet.
class SuperTabThreadSessionMark extends StatelessWidget {
- const SuperTabThreadSessionMark({super.key, required this.activity});
+ const SuperTabThreadSessionMark({
+ super.key,
+ required this.activity,
+ this.alone = false,
+ });
final HarnessActivity activity;
+ final bool alone;
@override
Widget build(BuildContext context) {
@@ -196,10 +202,15 @@ class SuperTabThreadSessionMark extends StatelessWidget {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- Text(' · ', style: DesktopChrome.metadata()),
+ if (!alone) Text(' · ', style: DesktopChrome.metadata()),
_mark(activity),
const SizedBox(width: grid.AppDesktop.menuInset),
- Text('Own session', style: DesktopChrome.metadata()),
+ Text(
+ alone
+ ? 'Own session · ${superTabSessionWords(activity)}'
+ : 'Own session',
+ style: DesktopChrome.metadata(),
+ ),
],
),
);
diff --git a/desktop/lib/super_tabs/composer_toggle.dart b/desktop/lib/super_tabs/composer_toggle.dart
new file mode 100644
index 000000000..931c4f424
--- /dev/null
+++ b/desktop/lib/super_tabs/composer_toggle.dart
@@ -0,0 +1,40 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
+
+/// A composer choice on the send row (New session, Also send): the shared
+/// compact pill, quiet and outlined when off, accent when on. Its hover hint
+/// says what it does, or why it can't be chosen now ([onChanged] null).
+class SuperTabComposerToggle extends StatelessWidget {
+ const SuperTabComposerToggle({
+ super.key,
+ required this.label,
+ required this.on,
+ required this.hint,
+ required this.onChanged,
+ });
+
+ final String label;
+ final bool on;
+ final String hint;
+ final ValueChanged<bool>? onChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Semantics(
+ toggled: on,
+ child: DesktopPill(
+ label: label,
+ compact: true,
+ choice: true,
+ textSize: 12,
+ selected: on,
+ foregroundColor: on ? DesktopChrome.accent : null,
+ tooltip: hint,
+ onPressed: onChanged == null ? null : () => onChanged!(!on),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 93007fbfd..e00e8d6db 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -69,7 +69,7 @@ const superTabSessionsUnavailable =
/// What a message refused for its form says, in place of the schema's own
/// words ('command: Unrecognized key: ...'), which name fields, not causes.
-const superTabRefusedAsSent = "The server couldn't take this message yet.";
+const superTabRefusedAsSent = "The server couldn't take this message.";
/// The schema's own words, as a refusal saved before this version kept them.
final _schemaWords = RegExp(r'Unrecognized key|^command(\.\w+)*: ');
@@ -1452,13 +1452,13 @@ class SuperTabController extends ChangeNotifier {
return result;
}
- /// A reply the server refused only for New session goes back into its
- /// thread's box, ready to send without it, when nothing was typed there
- /// since and it carries no files; else it stays Not sent, and its Retry
- /// goes without New session.
+ /// A message the server refused only for New session goes back into its
+ /// box (the thread of [root], or the chat's own when null), ready to send
+ /// without it, when nothing was typed there since and it carries no files;
+ /// else it stays Not sent, and its Retry goes without New session.
void _restoreSessionRefusal(
String conversationId,
- String root,
+ String? root,
String operationId,
) {
final kept = _refused[conversationId];
@@ -1468,13 +1468,23 @@ class SuperTabController extends ChangeNotifier {
final files = refused.command['attachmentIds'];
if (refused.error != superTabSessionsUnavailable ||
(files is List && files.isNotEmpty) ||
- threadDraft(root).trim().isNotEmpty) {
+ (root == null ? draft(conversationId) : threadDraft(root))
+ .trim()
+ .isNotEmpty) {
return;
}
kept.removeAt(i);
if (kept.isEmpty) _refused.remove(conversationId);
_sendOrder.remove(operationId);
- _threadDrafts[root] = refused.command['text'] as String? ?? '';
+ final text = refused.command['text'] as String? ?? '';
+ if (root == null) {
+ _drafts[conversationId] = text;
+ if (refused.mentions.isNotEmpty) {
+ _mentions[conversationId] = refused.mentions;
+ }
+ } else {
+ _threadDrafts[root] = text;
+ }
unawaited(
_persist().catchError((Object _) {
error = 'Could not save this change on this computer.';
@@ -1506,8 +1516,11 @@ class SuperTabController extends ChangeNotifier {
/// The open thread's chat when it is the reader's own Buddy chat, where a
/// thread may have a session of its own; null anywhere else.
- SuperTabConversation? get _ownBuddyChat {
- final id = openedThread?.conversationId ?? selectedId;
+ SuperTabConversation? get _ownBuddyChat =>
+ _ownBuddyChatOf(openedThread?.conversationId ?? selectedId);
+
+ /// Chat [id] when it is the reader's own Buddy chat; null anywhere else.
+ SuperTabConversation? _ownBuddyChatOf(String id) {
final chat = snapshot?.conversation(id);
return chat != null &&
chat.isBuddyChat &&
@@ -1517,6 +1530,18 @@ class SuperTabController extends ChangeNotifier {
: null;
}
+ /// Whether the selected chat's own composer shows New session: the reader's
+ /// own Buddy chat, with a Buddy, on a server that takes New session on a
+ /// top-level message. It may still show disabled, saying why
+ /// ([threadSessionBlocked]).
+ bool get offersChatSessions {
+ final chat = _ownBuddyChatOf(selectedId);
+ return chat != null &&
+ snapshot?.sessionsFromChat == true &&
+ _serverTakesThreadSessions &&
+ buddy(chat.projectId) != null;
+ }
+
/// Whether the open chat's thread composer shows New session: the reader's
/// own Buddy chat, with a Buddy, or in [root]'s thread that had a session
/// (its reply must start a new one). It may still show disabled, saying why
@@ -3687,9 +3712,8 @@ class SuperTabController extends ChangeNotifier {
/// What a person reads for [failure] of [command]: the server's own words,
/// except where a message was refused for its form (`VALIDATION_ERROR`, the
- /// schema naming fields): a thread reply with New session, by a server that
- /// does not take it yet, says so; any other says it plainly. Text length is
- /// held to the limit before sending, so a form refusal is a newer app's field.
+ /// schema naming fields): a reply whose New session the server does not know
+ /// says so; any other says it plainly.
static String _refusalText(
SuperTabFailure failure,
Map<String, dynamic> command,
@@ -3698,7 +3722,11 @@ class SuperTabController extends ChangeNotifier {
failure.code != 'VALIDATION_ERROR') {
return failure.message;
}
- return command['newSession'] == true
+ // Only the field itself unknown means the server can't start sessions;
+ // a reply refused for anything else (too many files) keeps New session.
+ return command['newSession'] == true &&
+ failure.message.contains('Unrecognized key') &&
+ failure.message.contains('newSession')
? superTabSessionsUnavailable
: superTabRefusedAsSent;
}
@@ -3776,10 +3804,15 @@ class SuperTabController extends ChangeNotifier {
/// Sends the selected conversation's draft. [onSending] is told when the
/// message is on its way and shows in [outgoing].
+ ///
+ /// With [newSession], in the reader's own Buddy chat, the message starts its
+ /// own thread's session (a top-level one roots that thread), and the thread
+ /// opens once the server took it, if this chat is still the one shown.
Future<Map<String, dynamic>?> send({
String? replyTo,
List<String> recipients = const [],
VoidCallback? onSending,
+ bool newSession = false,
}) async {
final text = draft(selectedId).trim();
final files = attachments(selectedId).files;
@@ -3788,7 +3821,9 @@ class SuperTabController extends ChangeNotifier {
selected!.archived ||
!canWrite ||
uploading ||
- ((saving || _pending != null) && (files.isNotEmpty || !canQueueText))) {
+ (newSession && !offersChatSessions) ||
+ ((saving || _pending != null) &&
+ (files.isNotEmpty || newSession || !canQueueText))) {
return null;
}
// A tag the text still says: an agent's is a recipient, a person's a tag.
@@ -3809,7 +3844,9 @@ class SuperTabController extends ChangeNotifier {
return null;
}
final conversationId = selectedId;
- if (files.isEmpty) {
+ // A text alone waits in the queue; one that starts a session goes now,
+ // so its answer can open its thread.
+ if (files.isEmpty && !newSession) {
final operationId = superTabOperationId();
_sendOrder.add(operationId);
final result = Completer<Map<String, dynamic>?>();
@@ -3854,6 +3891,7 @@ class SuperTabController extends ChangeNotifier {
'recipientIds': addressed,
if (tagged.isNotEmpty) 'mentions': tagged,
if (ids.isNotEmpty) 'attachmentIds': ids,
+ if (newSession) 'newSession': true,
});
// On its way: the message shows in the chat, and the draft is free for
// the next one. Both are in the save made before the request.
@@ -3868,6 +3906,17 @@ class SuperTabController extends ChangeNotifier {
}
final result = await sending;
_forgetRefusedUploads(result);
+ if (newSession && result == null) {
+ _restoreSessionRefusal(conversationId, null, operationId);
+ } else if (result?['messageId'] case final String id
+ when newSession &&
+ !_disposed &&
+ !accessRevoked &&
+ selectedId == conversationId) {
+ // Its thread opens beside the chat: the session answers there. A top-
+ // level message is its own thread's root.
+ openThread(_threadOf(conversationId, replyTo) ?? replyTo ?? id);
+ }
return result;
}
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index 96e317e8a..7b69ea65f 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -156,6 +156,9 @@ class SuperTabMessageRow extends StatefulWidget {
static bool groupsWith(SuperTabMessage current, SuperTabMessage? previous) {
if (previous == null ||
+ // A message that started a session stands on its own, with its line.
+ current.sessionRoot ||
+ previous.sessionRoot ||
current.replyTo != null ||
previous.replyTo != null ||
current.text.length > 280 ||
@@ -806,6 +809,17 @@ class SuperTabThreadLine extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
+ // A session's thread with no reply yet: its mark is the line, and opens it.
+ if (thread.replies == 0 && trailing != null) {
+ return Padding(
+ padding: const EdgeInsets.only(top: grid.AppDesktop.menuInset),
+ child: SuperTabLink(
+ label: 'Open thread',
+ onTap: onOpen,
+ child: trailing!,
+ ),
+ );
+ }
final count = thread.replies == 1 ? '1 reply' : '${thread.replies} replies';
final last = thread.lastAt;
final link = SuperTabLink(
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index e7a8a9d70..942d44baf 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -441,6 +441,7 @@ class SuperTabSnapshot {
localModels = SuperTabLocalModels.read(row['localModels']),
teamAccounts = row['teamAccounts'] != false,
threadSessions = row['threadSessions'] == true,
+ sessionsFromChat = row['sessionsFromChat'] == true,
mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0,
mentionsDigest = row['mentionsDigest'] as String?,
decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,
@@ -527,6 +528,11 @@ class SuperTabSnapshot {
/// where it says so (backend read/contract.ts `threadSessions`); an older
/// server's schema refuses the field.
final bool threadSessions;
+
+ /// Whether that server also takes New session on a top-level message in a
+ /// Buddy chat, which then roots its own thread (read/contract.ts
+ /// `sessionsFromChat`); false from an older one.
+ final bool sessionsFromChat;
final int mentionsWaiting;
/// Which tags wait, as a digest that moves when they change though the
@@ -954,6 +960,14 @@ class SuperTabDelivery {
/// What a page says about one thread (backend threads.ts): the line under its
/// root, and who it marks unread for.
class SuperTabThread {
+ /// A thread with no reply yet: a session's, started from the main chat.
+ SuperTabThread.empty(this.id)
+ : replies = 0,
+ lastSequence = 0,
+ lastAt = null,
+ authors = const [],
+ people = const [];
+
SuperTabThread.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
replies = (row['replies'] as num).toInt(),
@@ -1024,6 +1038,10 @@ class SuperTabMessage {
sessionEnded ? source['reason'] as String? : null;
bool get threadReply => thread != null && thread != id;
+ /// A Buddy chat message that started its own thread's session from the
+ /// main chat: its thread's root, in the session's thread.
+ bool get sessionRoot => buddySession && !threadReply;
+
/// Whether the main stream lists it: a thread reply only when also sent.
bool get inMainStream => !threadReply || alsoInChat;
final int sequence;
diff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dart
index bd968cd4f..3a6744991 100644
--- a/desktop/lib/super_tabs/parts.dart
+++ b/desktop/lib/super_tabs/parts.dart
@@ -348,6 +348,8 @@ class SuperTabParts {
if (_derived['teamAccounts'] == false) state['teamAccounts'] = false;
// Sent by a server that takes a thread reply's New session.
if (_derived['threadSessions'] == true) state['threadSessions'] = true;
+ // And one that also takes it on a top-level message in a Buddy chat.
+ if (_derived['sessionsFromChat'] == true) state['sessionsFromChat'] = true;
if (_readMarks.isNotEmpty) state['readMarks'] = Map.of(_readMarks);
if (_threadMarks.isNotEmpty) {
state['threadMarks'] = {
diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dart
index 433f1e43b..260a7750b 100644
--- a/desktop/lib/super_tabs/thread_panel.dart
+++ b/desktop/lib/super_tabs/thread_panel.dart
@@ -14,6 +14,7 @@ import '../widgets/new_harness_paste.dart';
import 'buddy_sessions.dart';
import 'composer_files.dart';
import 'composer_newline.dart';
+import 'composer_toggle.dart';
import 'controller.dart';
import 'jump_to_latest.dart';
import 'model.dart';
@@ -158,8 +159,9 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
advance(0);
}
- /// Where "Also send" also puts the reply, as the chat is named.
- String get _alsoSendLabel {
+ /// Where "Also send" also puts the reply, as the chat is named: its hover
+ /// says so, the chip itself stays short enough for the send row.
+ String get _alsoSendHint {
final group = c.selected;
if (group != null && c.snapshot?.isProjectLead(group.id) == true) {
return 'Also send to the project chat';
@@ -405,7 +407,34 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
grid.AppDesktop.groupGap,
grid.AppDesktop.groupGap,
),
- child: _composerBox(),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _composerBox(),
+ // Its place is kept while New session is offered, so the
+ // box never moves as the choice is toggled.
+ if (_offersSession)
+ Padding(
+ padding: const EdgeInsets.only(
+ top: grid.AppDesktop.controlGap,
+ ),
+ child: Visibility(
+ visible: _startsSession,
+ maintainSize: true,
+ maintainAnimation: true,
+ maintainState: true,
+ child: Text(
+ 'Your reply starts a new Buddy session',
+ key: const ValueKey('super-thread-session-note'),
+ style: DesktopChrome.metadata(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
),
],
),
@@ -513,14 +542,16 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
Expanded(
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
- spacing: grid.AppDesktop.controlGap,
+ spacing: 4,
+ runSpacing: 4,
children: [
if (_offersSession) _sessionChoice(writable),
if (_offersAlsoSend)
- _choice(
+ SuperTabComposerToggle(
key: const ValueKey('super-thread-also-send'),
- value: _alsoSend,
- label: _alsoSendLabel,
+ on: _alsoSend,
+ label: 'Also send',
+ hint: _alsoSendHint,
onChanged: writable
? (on) => setState(() => _alsoSend = on)
: null,
@@ -557,75 +588,28 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
);
}
- /// New session, left of Also send: checked and locked once the thread's
- /// session ended, unavailable (and saying why) at the limit.
+ /// New session, left of Also send: on and locked once the thread's session
+ /// ended; greyed while it can't start, its hover saying why.
Widget _sessionChoice(bool writable) {
final locked = _sessionLocked;
// What the server would refuse is said before sending: a block (paused,
// no Buddy, an older host) before the limit.
final blocked = c.threadSessionBlocked;
final full = !locked && blocked == null && c.buddySessionsFull;
- final choice = _choice(
+ return SuperTabComposerToggle(
key: const ValueKey('super-thread-new-session'),
- value: locked || (_newSession && !full && blocked == null),
- label: blocked != null
- ? 'New session · $blocked'
- : full
- ? 'New session · ${SuperTabController.maxBuddySessions} running, end one first'
- : 'New session',
- onChanged: writable && !locked && !full && blocked == null
- ? (on) => setState(() => _newSession = on)
- : null,
- );
- return Tooltip(
- message:
+ on: locked || (_newSession && !full && blocked == null),
+ label: 'New session',
+ hint:
blocked ??
(locked
? 'This thread\'s session ended. Your reply starts a new one.'
: full
- ? 'End a session to start another'
- : 'Answer this thread in its own session, while your Buddy keeps '
- 'answering the chat'),
- child: choice,
+ ? '${SuperTabController.maxBuddySessions} sessions running. End one to start another.'
+ : 'Starts a separate Buddy session for this thread'),
+ onChanged: writable && !locked && !full && blocked == null
+ ? (on) => setState(() => _newSession = on)
+ : null,
);
}
-
- /// A quiet checkbox and its label, both pressable, read as one control.
- Widget _choice({
- required Key key,
- required bool value,
- required String label,
- required ValueChanged<bool>? onChanged,
- }) => MergeSemantics(
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Checkbox(
- key: key,
- visualDensity: VisualDensity.compact,
- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
- value: value,
- onChanged: onChanged == null ? null : (on) => onChanged(on ?? false),
- ),
- Flexible(
- child: GestureDetector(
- onTap: onChanged == null ? null : () => onChanged(!value),
- child: MouseRegion(
- cursor: onChanged == null
- ? MouseCursor.defer
- : SystemMouseCursors.click,
- child: Text(
- label,
- style: DesktopChrome.control(
- color: onChanged == null && !value
- ? DesktopChrome.muted
- : null,
- ),
- ),
- ),
- ),
- ),
- ],
- ),
- );
}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 5d0d5e55e..d57716f7d 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -31,6 +31,7 @@ import 'pull_request_facts.dart';
import 'pull_requests.dart';
import 'composer_files.dart';
import 'composer_newline.dart';
+import 'composer_toggle.dart';
import 'controller.dart';
import 'dialog_scope.dart';
import 'folder_zip.dart';
@@ -132,6 +133,9 @@ class _SuperTabViewState extends State<SuperTabView>
final _awayFromEnd = <String>{};
final _unread = SuperTabUnreadLines();
final _replies = <String, SuperTabMessage>{};
+
+ /// The Buddy chats whose next message starts its own thread's session.
+ final _chatSessions = <String>{};
String? _selected;
int _scrollRequest = 0;
bool _jumpingToEnd = false;
@@ -693,8 +697,14 @@ class _SuperTabViewState extends State<SuperTabView>
// From here a zip still running belongs to neither this message, which
// took its files already, nor the next.
final dropped = _droppedFolders.remove(id);
+ final newSession =
+ _chatSessions.contains(id) &&
+ c.offersChatSessions &&
+ c.threadSessionBlocked == null &&
+ !c.buddySessionsFull;
final result = await c.send(
replyTo: _replies[id]?.id,
+ newSession: newSession,
// The reply goes with the message, which shows at the end at once.
onSending: () {
if (!mounted) return;
@@ -703,6 +713,21 @@ class _SuperTabViewState extends State<SuperTabView>
},
);
if (!mounted) return;
+ if (newSession && result != null) _chatSessions.remove(id);
+ // Refused for New session, its text is back as the chat's draft: it shows
+ // in the box, ready to send without it, unless another chat is shown or
+ // something was typed meanwhile.
+ if (result == null &&
+ newSession &&
+ c.selectedId == id &&
+ _composer.text.isEmpty &&
+ c.draft(id).isNotEmpty) {
+ final restored = c.draft(id);
+ _composer.value = TextEditingValue(
+ text: restored,
+ selection: TextSelection.collapsed(offset: restored.length),
+ );
+ }
setState(() {
if (result == null && dropped != null) {
// Not sent: its paths are still offered as zips, in a new record
@@ -716,6 +741,30 @@ class _SuperTabViewState extends State<SuperTabView>
});
}
+ /// New session in the reader's own Buddy chat's composer: the message
+ /// starts its own thread's session. Greyed while it can't start, its hover
+ /// saying why, as in a thread's reply box.
+ Widget _chatSessionChoice(bool writable) {
+ final id = c.selectedId;
+ final blocked = c.threadSessionBlocked;
+ final full = blocked == null && c.buddySessionsFull;
+ return SuperTabComposerToggle(
+ key: const ValueKey('super-chat-new-session'),
+ on: _chatSessions.contains(id) && blocked == null && !full,
+ label: 'New session',
+ hint:
+ blocked ??
+ (full
+ ? '${SuperTabController.maxBuddySessions} sessions running. End one to start another.'
+ : 'Starts a separate Buddy session for this message'),
+ onChanged: writable && blocked == null && !full
+ ? (on) => setState(
+ () => on ? _chatSessions.add(id) : _chatSessions.remove(id),
+ )
+ : null,
+ );
+ }
+
/// [path] as it goes into a message: as it is, or in double quotes when it
/// holds a space or anything else a shell reads specially, with `"`, `\`,
/// `$` and `` ` `` escaped, so it reads back as the same path.
@@ -2451,9 +2500,14 @@ class _SuperTabViewState extends State<SuperTabView>
(fetched != null && _shown(fetched) ? fetched : null);
final writable = c.canWrite && c.selected?.archived == false;
final root = message.thread;
+ // A message that started a session has its line before any reply comes,
+ // so the session is found again after its pane closes.
final thread = inThread || root != message.id
? null
- : c.thread(message.conversationId, message.id);
+ : c.thread(message.conversationId, message.id) ??
+ (c.threadSession(message.id) != null
+ ? SuperTabThread.empty(message.id)
+ : null);
final group = inThread
? null
: c.snapshot?.conversation(message.conversationId);
@@ -2524,6 +2578,7 @@ class _SuperTabViewState extends State<SuperTabView>
final session? => SuperTabThreadSessionMark(
key: ValueKey('super-thread-session-mark-${thread!.id}'),
activity: superTabSessionActivity(c, widget.app, session),
+ alone: thread.replies == 0,
),
null => null,
},
@@ -3545,6 +3600,13 @@ class _SuperTabViewState extends State<SuperTabView>
),
),
),
+ if (c.offersChatSessions)
+ Padding(
+ padding: const EdgeInsets.only(
+ left: grid.AppDesktop.controlGap,
+ ),
+ child: _chatSessionChoice(writable),
+ ),
fingerTarget(
enabled: _phone,
NewHarnessAttachButton(
@@ -3589,6 +3651,31 @@ class _SuperTabViewState extends State<SuperTabView>
),
),
),
+ // While New session can be chosen here, its line's place is kept, so
+ // the box never moves as the choice is toggled.
+ if (c.offersChatSessions)
+ Container(
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.only(
+ left: grid.AppDesktop.panelPadding,
+ right: grid.AppDesktop.panelPadding,
+ bottom: grid.AppDesktop.controlGap,
+ ),
+ child: Visibility(
+ visible:
+ _chatSessions.contains(chatId) &&
+ c.threadSessionBlocked == null &&
+ !c.buddySessionsFull,
+ maintainSize: true,
+ maintainAnimation: true,
+ maintainState: true,
+ child: Text(
+ 'Your message starts its own thread and Buddy session',
+ key: const ValueKey('super-chat-session-note'),
+ style: DesktopChrome.metadata(color: DesktopChrome.muted),
+ ),
+ ),
+ ),
if (!(group?.archived ?? true))
ListenableBuilder(
listenable: _composer,
diff --git a/desktop/lib/widgets/desktop_chrome.dart b/desktop/lib/widgets/desktop_chrome.dart
index 521c65209..04e61641b 100644
--- a/desktop/lib/widgets/desktop_chrome.dart
+++ b/desktop/lib/widgets/desktop_chrome.dart
@@ -137,6 +137,7 @@ class DesktopPill extends StatelessWidget {
this.foregroundColor,
this.surfaceColor,
this.compact = false,
+ this.choice = false,
this.quiet = false,
this.capsule = true,
this.textSize = 13,
@@ -160,6 +161,11 @@ class DesktopPill extends StatelessWidget {
/// An opaque base for pills that float directly above workspace content.
final Color? surfaceColor;
final bool compact;
+
+ /// An on/off choice that shares a narrow row with other controls (a reply
+ /// box's send row): the quiet pill's side padding, and only its outline
+ /// while off, in either appearance.
+ final bool choice;
final bool quiet, capsule;
final double textSize;
final bool truncateFromStart;
@@ -191,7 +197,7 @@ class DesktopPill extends StatelessWidget {
: 34,
),
padding: EdgeInsets.symmetric(
- horizontal: quiet
+ horizontal: quiet || choice
? 6
: compact
? 9
@@ -211,9 +217,12 @@ class DesktopPill extends StatelessWidget {
(states) => BorderSide(
// Reserve the same rim in every state; focus never moves text.
width: grid.AppDesktop.focusWidth,
- color:
- states.contains(WidgetState.disabled) ||
- (quiet && !highContrast)
+ color: choice && states.contains(WidgetState.disabled)
+ // A choice that can't be made now keeps its outline,
+ // greyed, so it still reads as the same control.
+ ? ink.withValues(alpha: highContrast ? .25 : .06)
+ : states.contains(WidgetState.disabled) ||
+ (quiet && !highContrast)
? Colors.transparent
: states.contains(WidgetState.focused) || highlightFocus
? (highContrast
@@ -233,7 +242,7 @@ class DesktopPill extends StatelessWidget {
: states.contains(WidgetState.focused) &&
!states.contains(WidgetState.disabled)
? ink.withValues(alpha: .10)
- : quiet
+ : quiet || choice
? Colors.transparent
: ink.withValues(alpha: .055),
),
diff --git a/desktop/test/super_tab_buddy_sessions_test.dart b/desktop/test/super_tab_buddy_sessions_test.dart
index 1e4246d66..96bd1934f 100644
--- a/desktop/test/super_tab_buddy_sessions_test.dart
+++ b/desktop/test/super_tab_buddy_sessions_test.dart
@@ -2,8 +2,11 @@ import 'dart:async';
import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/harness_attachments.dart';
+import 'package:harness/super_tabs/composer_toggle.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/message_row.dart' show SuperTabLink;
import 'package:harness/super_tabs/view.dart';
@@ -41,9 +44,14 @@ void main() {
/// The reader's own Buddy chat ('offline' in the fixture) with their Buddy
/// running, a root, and a second thread to switch to, on a server that takes
/// New session unless [sessions] is false (an older backend).
- ConversationServer buddyChat({bool buddy = true, bool sessions = true}) {
+ ConversationServer buddyChat({
+ bool buddy = true,
+ bool sessions = true,
+ bool fromChat = true,
+ }) {
final server = ConversationServer()..threads = true;
if (sessions) server.state['threadSessions'] = true;
+ if (sessions && fromChat) server.state['sessionsFromChat'] = true;
final chat = chatOf(server)
..['kind'] = 'buddy'
..['buddyOwnerId'] = 'owner'
@@ -170,8 +178,14 @@ void main() {
await tester.pumpAndSettle();
}
- Checkbox box(WidgetTester tester, Finder finder) =>
- tester.widget<Checkbox>(finder);
+ SuperTabComposerToggle box(WidgetTester tester, Finder finder) =>
+ tester.widget<SuperTabComposerToggle>(finder);
+
+ /// [finder] within the thread pane.
+ Finder inThread(Finder finder) => find.descendant(
+ of: find.byKey(const ValueKey('super-thread-panel')),
+ matching: finder,
+ );
Map<String, dynamic> lastCommand(ConversationServer server) =>
Map<String, dynamic>.from(server.posts.last['command'] as Map);
@@ -185,22 +199,19 @@ void main() {
expect(newSession, findsOneWidget);
expect(alsoSend, findsOneWidget);
- expect(box(tester, newSession).value, isFalse);
+ expect(box(tester, newSession).on, isFalse);
// Before Also send in reading order: left of it on one row, or above it
// where a narrow pane wraps them.
final a = tester.getRect(newSession), b = tester.getRect(alsoSend);
expect(a.top < b.top || (a.top == b.top && a.left < b.left), isTrue);
expect(
- find.byTooltip(
- 'Answer this thread in its own session, while your Buddy keeps '
- 'answering the chat',
- ),
+ find.byTooltip('Starts a separate Buddy session for this thread'),
findsOneWidget,
);
await tester.tap(newSession);
await tester.pump();
- expect(box(tester, newSession).value, isTrue);
+ expect(box(tester, newSession).on, isTrue);
// A session's thread stays in the thread.
expect(alsoSend, findsNothing);
@@ -213,8 +224,117 @@ void main() {
expect(sent['replyTo'], 'message-1');
expect(sent['newSession'], isTrue);
expect(sent.containsKey('alsoSend'), isFalse);
- // The next reply starts as plain again.
- expect(box(tester, newSession).value, isFalse);
+ // The thread's session is starting: no choice to make there now.
+ expect(tester.widget<Text>(state).data, 'Own session · Starting…');
+ expect(newSession, findsNothing);
+ });
+
+ testSessions('the choices are compact chips on the send row, not '
+ 'checkboxes', (tester) async {
+ final server = buddyChat();
+ final c = await show(tester, server);
+ await openThread(tester, c, 'message-1');
+ final panel = find.byKey(const ValueKey('super-thread-panel'));
+ expect(
+ find.descendant(of: panel, matching: find.byType(Checkbox)),
+ findsNothing,
+ );
+ expect(box(tester, newSession).label, 'New session');
+ expect(box(tester, alsoSend).label, 'Also send');
+ expect(find.byTooltip('Also send to the chat'), findsOneWidget);
+ // Both sit on the send row, left of its buttons, and are compact: no
+ // taller than the send button. (One line at real fonts: the PR's
+ // screenshots; the test font is far wider.)
+ final row = tester.getRect(send);
+ final surface = tester.getRect(
+ find.byKey(const ValueKey('super-thread-composer-surface')),
+ );
+ for (final chip in [newSession, alsoSend]) {
+ final rect = tester.getRect(chip);
+ expect(rect.right, lessThan(row.left));
+ expect(rect.height, lessThanOrEqualTo(row.height));
+ expect(surface.contains(rect.center), isTrue);
+ }
+ // The muted line shows only while the reply starts a session; its place
+ // is kept, so it never pushes the box up under the cursor.
+ final note = find
+ .byKey(const ValueKey('super-thread-session-note'))
+ .hitTestable();
+ final boxAt = find.byKey(const ValueKey('super-thread-composer-surface'));
+ final restingBox = tester.getRect(boxAt);
+ expect(note, findsNothing);
+
+ await tester.tap(newSession);
+ await tester.pump();
+ expect(box(tester, newSession).on, isTrue);
+ expect(alsoSend, findsNothing);
+ expect(
+ tester.widget<Text>(note).data,
+ 'Your reply starts a new Buddy session',
+ );
+ expect(tester.getRect(boxAt).bottom, restingBox.bottom);
+ // Its line sits under the box.
+ expect(
+ tester.getRect(note).top,
+ greaterThanOrEqualTo(
+ tester
+ .getRect(
+ find.byKey(const ValueKey('super-thread-composer-surface')),
+ )
+ .bottom,
+ ),
+ );
+
+ await tester.tap(newSession);
+ await tester.pump();
+ expect(box(tester, newSession).on, isFalse);
+ expect(alsoSend, findsOneWidget);
+ expect(note, findsNothing);
+ expect(tester.getRect(boxAt).bottom, restingBox.bottom);
+ });
+
+ testSessions('a reply takes at most 10 files, and the box says so', (
+ tester,
+ ) async {
+ final server = buddyChat();
+ final c = await show(tester, server);
+ await openThread(tester, c, 'message-1');
+ final files = c.threadAttachments('offline', 'message-1');
+ final problem = files.add([
+ for (var i = 0; i < 11; i++)
+ HarnessAttachment('f$i.txt', Uint8List.fromList([i + 1])),
+ ]);
+ await tester.pumpAndSettle();
+ expect(files.files, hasLength(10));
+ expect(problem, 'Attach at most 10 files.');
+ });
+
+ testSessions('a New session reply refused for another field keeps New '
+ 'session offered and says so plainly', (tester) async {
+ final server = buddyChat();
+ final c = await show(tester, server);
+ await openThread(tester, c, 'message-1');
+ server
+ ..refuse = {
+ 'code': 'VALIDATION_ERROR',
+ 'message':
+ 'command.attachmentIds: Too big: expected array to have <=10 items',
+ }
+ ..refuseStatus = 400;
+ await tester.tap(newSession);
+ await tester.enterText(composer, 'Continue the session');
+ await tester.pump();
+ await tester.tap(send);
+ await tester.pumpAndSettle();
+ expect(find.text(superTabSessionsUnavailable), findsNothing);
+ expect(find.textContaining('Too big'), findsNothing);
+ expect(find.text("The server couldn't take this message."), findsWidgets);
+ // Still offered: the server takes New session.
+ expect(c.offersThreadSessions('message-1'), isTrue);
+ expect(newSession, findsOneWidget);
+ // The reply stays Not sent with New session, for Retry.
+ final refused = c.outgoing('offline').single;
+ expect(refused.state, SuperTabOutgoingState.refused);
});
testSessions('a New session tick stays with its own thread', (tester) async {
@@ -223,9 +343,9 @@ void main() {
await openThread(tester, c, 'message-1');
await tester.tap(newSession);
await tester.pump();
- expect(box(tester, newSession).value, isTrue);
+ expect(box(tester, newSession).on, isTrue);
await openThread(tester, c, 'message-2');
- expect(box(tester, newSession).value, isFalse);
+ expect(box(tester, newSession).on, isFalse);
expect(alsoSend, findsOneWidget);
});
@@ -269,12 +389,15 @@ void main() {
}
final c = await show(tester, server);
await openThread(tester, c, 'message-1');
- expect(find.text('New session · 3 running, end one first'), findsOneWidget);
+ expect(inThread(find.text('New session')), findsOneWidget);
expect(box(tester, newSession).onChanged, isNull);
- expect(box(tester, newSession).value, isFalse);
- expect(find.byTooltip('End a session to start another'), findsOneWidget);
+ expect(box(tester, newSession).on, isFalse);
+ expect(
+ inThread(find.byTooltip('3 sessions running. End one to start another.')),
+ findsOneWidget,
+ );
// Tapping the words does nothing either; a reply goes plain.
- await tester.tap(find.text('New session · 3 running, end one first'));
+ await tester.tap(newSession);
await tester.enterText(composer, 'Plain');
await tester.pump();
await tester.tap(send);
@@ -362,7 +485,7 @@ void main() {
tester.widget<Text>(ended).data,
'Session ended: idle for 30 minutes',
);
- expect(box(tester, newSession).value, isTrue);
+ expect(box(tester, newSession).on, isTrue);
expect(box(tester, newSession).onChanged, isNull);
expect(alsoSend, findsNothing);
await tester.enterText(composer, 'Go on');
@@ -462,14 +585,14 @@ void main() {
await openThread(tester, c, 'message-2');
expect(find.text('Ending…'), findsNothing);
expect(newSession, findsOneWidget);
- expect(box(tester, newSession).value, isFalse);
+ expect(box(tester, newSession).on, isFalse);
hold.complete();
server.holdCommands = null;
await tester.pumpAndSettle();
expect(find.text('Ending…'), findsNothing);
expect(state, findsNothing);
expect(newSession, findsOneWidget);
- expect(box(tester, newSession).value, isFalse);
+ expect(box(tester, newSession).on, isFalse);
});
testSessions('a first read that failed and then recovered still offers New '
@@ -493,7 +616,7 @@ void main() {
sessionReply(server, 'message-1', 'Reading the logs…');
final c = await show(tester, server);
await openThread(tester, c, 'message-1');
- expect(box(tester, newSession).value, isTrue);
+ expect(box(tester, newSession).on, isTrue);
expect(box(tester, newSession).onChanged, isNull);
expect(alsoSend, findsNothing);
expect(tester.widget<Text>(ended).data, 'Session ended');
@@ -522,9 +645,9 @@ void main() {
tester.widget<Text>(ended).data,
'Session ended: its Buddy was removed or replaced',
);
- expect(box(tester, newSession).value, isTrue);
+ expect(box(tester, newSession).on, isTrue);
expect(box(tester, newSession).onChanged, isNull);
- expect(find.text('New session · Start your Buddy first'), findsOneWidget);
+ expect(find.byTooltip('Start your Buddy first'), findsOneWidget);
// A thread with no session past offers nothing without a Buddy.
await openThread(tester, c, 'message-2');
expect(newSession, findsNothing);
@@ -539,9 +662,10 @@ void main() {
server.revision++;
await c.refresh();
await tester.pumpAndSettle();
- expect(find.text('New session · $reason'), findsOneWidget);
+ expect(inThread(find.byTooltip(reason)), findsOneWidget);
+ expect(inThread(find.text('New session')), findsOneWidget);
expect(box(tester, newSession).onChanged, isNull);
- expect(box(tester, newSession).value, isFalse);
+ expect(box(tester, newSession).on, isFalse);
}
server.state['paused'] = true;
@@ -570,7 +694,7 @@ void main() {
server.revision++;
await c.refresh();
await tester.pumpAndSettle();
- expect(find.text('New session'), findsOneWidget);
+ expect(inThread(find.text('New session')), findsOneWidget);
expect(box(tester, newSession).onChanged, isNotNull);
});
@@ -788,10 +912,7 @@ void main() {
await tester.pumpAndSettle();
expect(find.textContaining('Unrecognized key'), findsNothing);
expect(find.text('Not sent'), findsOneWidget);
- expect(
- find.text("The server couldn't take this message yet."),
- findsOneWidget,
- );
+ expect(find.text("The server couldn't take this message."), findsOneWidget);
});
testSessions('a refusal saved with the server\'s own words before this '
@@ -825,10 +946,191 @@ void main() {
expect(c.outgoing('offline').single.text, 'Saved before');
expect(find.text('Not sent'), findsOneWidget);
expect(find.textContaining('Unrecognized key'), findsNothing);
+ expect(find.text("The server couldn't take this message."), findsOneWidget);
+ });
+
+ // ── The main Buddy chat (Scholes's part 3): a message there can start its
+ // own thread's session. ─────────────────────────────────────────────────
+
+ final chatSession = find.byKey(const ValueKey('super-chat-new-session'));
+ final chatComposer = find.byKey(const ValueKey('super-message-composer'));
+ final chatSend = find.byTooltip('Send message');
+ final panel = find.byKey(const ValueKey('super-thread-panel'));
+
+ testSessions('the main Buddy chat offers New session as a chip, and a send '
+ 'with it opens its own thread with its session starting', (tester) async {
+ final server = buddyChat();
+ final c = await show(tester, server);
+ expect(chatSession, findsOneWidget);
+ expect(box(tester, chatSession).on, isFalse);
+ expect(box(tester, chatSession).label, 'New session');
expect(
- find.text("The server couldn't take this message yet."),
+ find.byTooltip('Starts a separate Buddy session for this message'),
findsOneWidget,
);
+ // Left of the attach and send buttons, on the composer's row.
+ expect(
+ tester.getRect(chatSession).right,
+ lessThan(tester.getRect(chatSend).left),
+ );
+ final chatNote = find
+ .byKey(const ValueKey('super-chat-session-note'))
+ .hitTestable();
+ final restingBottom = tester.getRect(chatComposer).bottom;
+ expect(chatNote, findsNothing);
+ await tester.tap(chatSession);
+ await tester.pump();
+ expect(box(tester, chatSession).on, isTrue);
+ expect(
+ tester.widget<Text>(chatNote).data,
+ 'Your message starts its own thread and Buddy session',
+ );
+ // The line's place was kept: the box doesn't move.
+ expect(tester.getRect(chatComposer).bottom, restingBottom);
+ await tester.enterText(chatComposer, 'Measure prod CPU for the last day');
+ await tester.pump();
+ await tester.tap(chatSend);
+ await tester.pumpAndSettle();
+
+ final sent = lastCommand(server);
+ expect(sent['type'], 'message.send');
+ expect(sent['replyTo'], isNull);
+ expect(sent['newSession'], isTrue);
+ final root = server.messages.last['id'] as String;
+ // Its thread opens on the right, its session starting.
+ expect(panel, findsOneWidget);
+ expect(c.openedThread?.root, root);
+ expect(tester.widget<Text>(state).data, 'Own session · Starting…');
+ // The chip is off again, and the box empty.
+ expect(box(tester, chatSession).on, isFalse);
+ expect(chatNote, findsNothing);
+ expect(tester.widget<TextField>(chatComposer).controller!.text, isEmpty);
+ // In the chat the message stands on its own, not under the one before
+ // it, with its session's line: found again once the pane is closed.
+ final row = find.byKey(ValueKey('super-message-$root'));
+ expect(
+ find.descendant(of: row, matching: find.text('You')),
+ findsOneWidget,
+ );
+ c.closeThread();
+ await tester.pumpAndSettle();
+ expect(panel, findsNothing);
+ final mark = find.byKey(ValueKey('super-thread-session-mark-$root'));
+ expect(find.descendant(of: row, matching: mark), findsOneWidget);
+ await tester.tap(mark);
+ await tester.pumpAndSettle();
+ expect(c.openedThread?.root, root);
+ // Reached by keyboard too, and opened with Enter, as the reply count is.
+ c.closeThread();
+ await tester.pumpAndSettle();
+ final node = Focus.of(
+ tester.element(
+ find.descendant(of: mark, matching: find.byType(Text)).first,
+ ),
+ );
+ node.requestFocus();
+ await tester.pump();
+ expect(node.hasFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(c.openedThread?.root, root);
+ });
+
+ testSessions('a server that takes New session only on replies never offers '
+ 'it in the main chat', (tester) async {
+ final server = buddyChat(fromChat: false);
+ final c = await show(tester, server);
+ expect(chatSession, findsNothing);
+ // A thread still offers it.
+ await openThread(tester, c, 'message-1');
+ expect(newSession, findsOneWidget);
+ // And none at all from a server before New session.
+ await tester.pumpWidget(const SizedBox());
+ await shown.flush();
+ await show(tester, buddyChat(sessions: false));
+ expect(chatSession, findsNothing);
+ });
+
+ testSessions('New session in the main chat is greyed while it can\'t start, '
+ 'its hover saying why', (tester) async {
+ final server = buddyChat()..state['paused'] = true;
+ await show(tester, server);
+ expect(chatSession, findsOneWidget);
+ expect(box(tester, chatSession).onChanged, isNull);
+ expect(box(tester, chatSession).on, isFalse);
+ expect(find.byTooltip('New work is paused in this Swarm'), findsOneWidget);
+ // Elsewhere (a workgroup) it isn't there at all.
+ await tester.pumpWidget(const SizedBox());
+ await shown.flush();
+ await show(tester, ConversationServer()..threads = true, select: false);
+ expect(chatSession, findsNothing);
+ });
+
+ testSessions('a main-chat New session the server refuses as unknown keeps '
+ 'the text in the box and says so plainly', (tester) async {
+ final server = buddyChat();
+ final c = await show(tester, server);
+ refuseAsOlderServer(server);
+ await tester.tap(chatSession);
+ await tester.enterText(chatComposer, 'Measure it now');
+ await tester.pump();
+ await tester.tap(chatSend);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server)['newSession'], isTrue);
+ expect(
+ tester.widget<TextField>(chatComposer).controller!.text,
+ 'Measure it now',
+ );
+ expect(find.text(unavailable), findsOneWidget);
+ expect(find.textContaining('Unrecognized key'), findsNothing);
+ expect(c.outgoing('offline'), isEmpty);
+ expect(panel, findsNothing);
+ expect(chatSession, findsNothing);
+ server.refuse = null;
+ await tester.tap(chatSend);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server).containsKey('newSession'), isFalse);
+ expect(lastCommand(server)['text'], 'Measure it now');
+ });
+
+ testSessions('a main-chat New session answered after another chat opened '
+ 'opens no thread there', (tester) async {
+ final server = buddyChat();
+ final c = await show(tester, server);
+ final hold = server.holdCommands = Completer<void>();
+ await tester.tap(chatSession);
+ await tester.enterText(chatComposer, 'Measure it now');
+ await tester.pump();
+ await tester.tap(chatSend);
+ await tester.pump();
+ await c.select('lead');
+ await tester.pumpAndSettle();
+ hold.complete();
+ server.holdCommands = null;
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'lead');
+ expect(c.openedThread, isNull);
+ expect(panel, findsNothing);
+ });
+
+ testSessions('access lost while a main-chat New session is on its way opens '
+ 'nothing and keeps nothing', (tester) async {
+ final server = buddyChat();
+ final c = await show(tester, server);
+ final hold = server.holdCommands = Completer<void>();
+ await tester.tap(chatSession);
+ await tester.enterText(chatComposer, 'Private words');
+ await tester.pump();
+ await tester.tap(chatSend);
+ await tester.pump();
+ c.revokeAccess('You no longer have access to this Swarm.');
+ hold.complete();
+ server.holdCommands = null;
+ await tester.pumpAndSettle();
+ expect(c.openedThread, isNull);
+ expect(panel, findsNothing);
+ expect(chatSession, findsNothing);
+ expect(find.text('Private words'), findsNothing);
});
testSessions('Ending… cannot be pressed again while its end is on its way', (
diff --git a/desktop/test/super_tab_session_chips_shots_test.dart b/desktop/test/super_tab_session_chips_shots_test.dart
new file mode 100644
index 000000000..ec84a809c
--- /dev/null
+++ b/desktop/test/super_tab_session_chips_shots_test.dart
@@ -0,0 +1,165 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/view.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_SESSION_CHIPS_SHOTS'];
+
+/// A Buddy chat's thread box as the PR shows it, in both appearances: its
+/// choices at rest, with New session on, and with New session unavailable.
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+
+ /// The reader's own Buddy chat with its Buddy running and a thread open.
+ ConversationServer buddyChat({bool paused = false}) {
+ final server = ConversationServer()..threads = true;
+ server.state['threadSessions'] = true;
+ server.state['sessionsFromChat'] = true;
+ if (paused) server.state['paused'] = true;
+ final chat = (server.state['conversations'] as List)[1] as Map;
+ chat
+ ..['kind'] = 'buddy'
+ ..['buddyOwnerId'] = 'owner'
+ ..['title'] = 'Wren'
+ ..['agentIds'] = ['buddy-main'];
+ (server.state['agents'] as List).add({
+ 'id': 'buddy-main',
+ 'name': 'Wren',
+ 'displayName': 'Wren',
+ 'machineId': 'mac',
+ 'harnessId': 'h-main',
+ 'contributorId': 'owner',
+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},
+ 'configuration': {'engine': 'claude'},
+ });
+ server.append(
+ 'Two things today: measure prod CPU, and check the release notes.',
+ conversationId: 'offline',
+ );
+ server.append(
+ 'Measure prod CPU for the last day',
+ conversationId: 'offline',
+ );
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1';
+ return server;
+ }
+
+ for (final brightness in Brightness.values) {
+ for (final scene in [
+ 'rest',
+ 'on',
+ 'unavailable',
+ 'chat-off',
+ 'chat-on',
+ 'chat-unavailable',
+ 'chat-started',
+ 'chat-closed',
+ ]) {
+ final inChat = scene.startsWith('chat-');
+ testWidgets('screenshots for review ($scene, ${brightness.name})', (
+ tester,
+ ) async {
+ final picture = GlobalKey();
+ final server = buddyChat(paused: scene.endsWith('unavailable'));
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ await tester.binding.setSurfaceSize(const Size(1280, 720));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ RepaintBoundary(key: picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Mac Studio',
+ ),
+ ),
+ ),
+ );
+ c.select('offline');
+ await tester.pumpAndSettle();
+ final chip = find.byKey(
+ ValueKey(
+ inChat ? 'super-chat-new-session' : 'super-thread-new-session',
+ ),
+ );
+ if (!inChat) {
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ }
+ await tester.enterText(
+ find.byKey(
+ ValueKey(
+ inChat ? 'super-message-composer' : 'super-thread-composer',
+ ),
+ ),
+ inChat
+ ? 'Check the release notes for 1.3.80 against the merged PRs.'
+ : 'Measure it now, and compare with last week.',
+ );
+ await tester.pump();
+ if (const {
+ 'on',
+ 'chat-on',
+ 'chat-started',
+ 'chat-closed',
+ }.contains(scene)) {
+ await tester.tap(chip);
+ await tester.pump();
+ }
+ if (scene == 'chat-started' || scene == 'chat-closed') {
+ await tester.tap(find.byTooltip('Send message'));
+ await tester.pumpAndSettle();
+ }
+ if (scene == 'chat-closed') {
+ c.closeThread();
+ await tester.pumpAndSettle();
+ }
+ if (scene.endsWith('unavailable')) {
+ final gesture = await tester.createGesture(
+ kind: ui.PointerDeviceKind.mouse,
+ );
+ await gesture.addPointer(location: Offset.zero);
+ addTearDown(gesture.removePointer);
+ await gesture.moveTo(tester.getCenter(chip));
+ await tester.pump(const Duration(seconds: 2));
+ }
+ await tester.pumpAndSettle();
+
+ await tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/session-chips-$scene-${brightness.name}.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ }, skip: shots == null);
+ }
+ }
+}
diff --git a/desktop/test/super_tab_threads_test.dart b/desktop/test/super_tab_threads_test.dart
index c987f023b..4e512366f 100644
--- a/desktop/test/super_tab_threads_test.dart
+++ b/desktop/test/super_tab_threads_test.dart
@@ -514,7 +514,11 @@ void main() {
final c = await show(tester, server);
await tester.tap(line('message-1'));
await tester.pumpAndSettle();
- expect(inPanel(find.text('Also send to the project chat')), findsOneWidget);
+ expect(inPanel(find.text('Also send')), findsOneWidget);
+ expect(
+ inPanel(find.byTooltip('Also send to the project chat')),
+ findsOneWidget,
+ );
await tester.enterText(
find.byKey(const ValueKey('super-thread-composer')),
'In the thread only.',
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index c91156a47..72c04b3c5 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -88,6 +88,7 @@ class SwarmPartsBackend {
'threadMarks',
'teamAccounts',
'threadSessions',
+ 'sessionsFromChat',
}.contains(entry.key))
entry.key: entry.value,
};
@@ -168,6 +169,7 @@ class SwarmPartsBackend {
if (state['teamAccounts'] == false) 'teamAccounts': false,
// A server that takes a thread reply's New session (backend read/views.ts).
if (state['threadSessions'] == true) 'threadSessions': true,
+ if (state['sessionsFromChat'] == true) 'sessionsFromChat': true,
// The reader's own read marks alone, as backend readMarks.ts sends them.
if ((state['readMarks'] as Map?)?[reader ?? 'owner'] case final Map marks)
'readMarks': Map<String, dynamic>.from(marks),
@@ -988,6 +990,21 @@ class ConversationServer {
messages.last['id'] = id;
}
output['messageId'] = messages.last['id'];
+ // New session starts the thread's own session (backend commands.ts
+ // routeBuddySession): a top-level message roots its own thread.
+ if (command['newSession'] == true) {
+ final sent = messages.last;
+ final thread = (sent['thread'] ?? sent['id']) as String;
+ sent['buddySession'] = true;
+ final chat = (state['conversations'] as List).cast<Map>().firstWhere(
+ (c) => c['id'] == command['conversationId'],
+ );
+ chat['buddySessions'] = [
+ ...(chat['buddySessions'] as List? ?? const []),
+ {'thread': thread, 'startId': operationId, 'at': 1},
+ ];
+ output['startId'] = operationId;
+ }
} else if (command['type'] == 'member.status' ||
command['type'] == 'member.username' ||
command['type'] == 'member.avatar' ||