Merge: chat session info, copy and export
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../artifacts/actions/artifact_file.dart';
|
||||
import '../../artifacts/actions/artifact_file_bridge.dart';
|
||||
import '../../artifacts/actions/artifact_transfer.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import '../domain/chat_session_handoff.dart';
|
||||
|
||||
/// Exports one chat through `chat_export` and hands the file to the host the
|
||||
/// same way the artifact viewer does: a browser download on the web, the share
|
||||
/// sheet (which offers saving) on phones. One export runs at a time.
|
||||
class ChatExportController extends ChangeNotifier {
|
||||
ChatExportController({
|
||||
required this.repository,
|
||||
required this.sessionId,
|
||||
this.bridge = const ArtifactFileBridge(),
|
||||
bool? share,
|
||||
}) : share = share ?? !kIsWeb;
|
||||
|
||||
final ChatRepository repository;
|
||||
final String sessionId;
|
||||
final ArtifactFileBridge bridge;
|
||||
|
||||
/// True hands the file to the share sheet; false downloads/saves it.
|
||||
final bool share;
|
||||
|
||||
ChatExportFormat? _active;
|
||||
String? _status;
|
||||
bool _disposed = false;
|
||||
|
||||
ChatExportFormat? get active => _active;
|
||||
bool get busy => _active != null;
|
||||
String? get status => _status;
|
||||
|
||||
Future<void> export(ChatExportFormat format) async {
|
||||
if (busy) return;
|
||||
final useShare = share && bridge.canShare;
|
||||
if (!useShare && !bridge.canDownload) {
|
||||
_set(null, bridge.downloadUnavailableMessage);
|
||||
return;
|
||||
}
|
||||
_set(format, 'Preparing export…');
|
||||
final JsonMap file;
|
||||
try {
|
||||
file = await repository.export(sessionId, format.wire);
|
||||
} catch (error) {
|
||||
_set(null, 'Could not export the chat: $error');
|
||||
return;
|
||||
}
|
||||
final artifact = ArtifactFile(
|
||||
name: '${file['name']}',
|
||||
mimeType: '${file['mime'] ?? ''}'.isEmpty
|
||||
? 'text/plain'
|
||||
: '${file['mime']}',
|
||||
bytes: Uint8List.fromList(utf8.encode('${file['content'] ?? ''}')),
|
||||
);
|
||||
ArtifactTransferResult result;
|
||||
try {
|
||||
result = useShare
|
||||
? await bridge.shareFile(artifact)
|
||||
: await bridge.saveFile(artifact);
|
||||
} catch (error) {
|
||||
_set(null, 'Could not save ${artifact.name}: $error');
|
||||
return;
|
||||
}
|
||||
final truncated = file['truncated'] == true
|
||||
? ' Older messages were left out to fit the size limit.'
|
||||
: '';
|
||||
final message = switch (result.state) {
|
||||
ArtifactTransferState.saved => 'Exported ${artifact.name}.$truncated',
|
||||
ArtifactTransferState.shared => 'Shared ${artifact.name}.$truncated',
|
||||
ArtifactTransferState.canceled => 'Export canceled.',
|
||||
_ => result.message.isEmpty ? 'Export failed.' : result.message,
|
||||
};
|
||||
_set(null, message);
|
||||
}
|
||||
|
||||
void _set(ChatExportFormat? active, String? status) {
|
||||
_active = active;
|
||||
_status = status;
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../../ui/text/monospace.dart';
|
||||
import '../domain/chat_session_handoff.dart';
|
||||
import '../ui/sessions/chat_create_fields.dart';
|
||||
import 'chat_export_controller.dart';
|
||||
|
||||
/// The info sheet's "Session" section: the harness's native session id with a
|
||||
/// copy control, the harness and the working directory, the verified terminal
|
||||
/// command that resumes the session, and the export actions.
|
||||
class ChatSessionSection extends StatefulWidget {
|
||||
const ChatSessionSection({
|
||||
super.key,
|
||||
required this.handoff,
|
||||
required this.exporter,
|
||||
required this.cupertino,
|
||||
});
|
||||
|
||||
final ChatSessionHandoff handoff;
|
||||
final ChatExportController exporter;
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
State<ChatSessionSection> createState() => _ChatSessionSectionState();
|
||||
}
|
||||
|
||||
class _ChatSessionSectionState extends State<ChatSessionSection> {
|
||||
/// Which copy control last succeeded, shown as "Copied" for a moment.
|
||||
String? _copied;
|
||||
Timer? _reset;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_reset?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _copy(String key, String text) async {
|
||||
await Clipboard.setData(ClipboardData(text: text));
|
||||
if (!mounted) return;
|
||||
setState(() => _copied = key);
|
||||
_reset?.cancel();
|
||||
_reset = Timer(const Duration(seconds: 2), () {
|
||||
if (mounted) setState(() => _copied = null);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = widget.cupertino;
|
||||
final handoff = widget.handoff;
|
||||
final secondary = cupertino
|
||||
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
final body = cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.bodyLarge;
|
||||
final title = cupertino
|
||||
? CupertinoTheme.of(
|
||||
context,
|
||||
).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600)
|
||||
: Theme.of(context).textTheme.titleSmall;
|
||||
final label =
|
||||
(cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.bodySmall)
|
||||
?.copyWith(color: secondary);
|
||||
final mono = body?.copyWith(fontFamily: appMonospaceFamily);
|
||||
final muted = body?.copyWith(color: secondary);
|
||||
|
||||
Widget fact(String key, String name, String value, {bool code = false}) {
|
||||
final known = value.isNotEmpty;
|
||||
return Padding(
|
||||
key: Key('chat-session-$key'),
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(name, style: label),
|
||||
Text(
|
||||
known ? value : 'Unavailable',
|
||||
key: Key('chat-session-value-$key'),
|
||||
style: !known ? muted : (code ? mono : body),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return AnimatedBuilder(
|
||||
animation: widget.exporter,
|
||||
builder: (context, _) {
|
||||
final exporter = widget.exporter;
|
||||
final status = exporter.status;
|
||||
return Padding(
|
||||
key: const Key('chat-session-section'),
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(24, 12, 24, 6),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text('Session', style: title),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Expanded(
|
||||
child: fact('id', 'Session ID', handoff.id, code: true),
|
||||
),
|
||||
_ActionButton(
|
||||
key: const Key('chat-session-copy-id'),
|
||||
cupertino: cupertino,
|
||||
label: _copied == 'id' ? 'Copied' : 'Copy',
|
||||
semanticsLabel: _copied == 'id'
|
||||
? 'Copied'
|
||||
: 'Copy session ID',
|
||||
icon: _copied == 'id'
|
||||
? (cupertino ? CupertinoIcons.checkmark : Icons.check)
|
||||
: (cupertino
|
||||
? CupertinoIcons.doc_on_doc
|
||||
: Icons.copy_outlined),
|
||||
onPressed: handoff.id.isEmpty
|
||||
? null
|
||||
: () => _copy('id', handoff.id),
|
||||
),
|
||||
],
|
||||
),
|
||||
fact('harness', 'Harness', chatBackendLabel(handoff.backend)),
|
||||
fact('directory', 'Directory', handoff.directory, code: true),
|
||||
if (handoff.resumeCommand.isNotEmpty)
|
||||
fact(
|
||||
'resume',
|
||||
'Resume in a terminal',
|
||||
handoff.resumeCommand,
|
||||
code: true,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
if (handoff.resumeCommand.isNotEmpty)
|
||||
_ActionButton(
|
||||
key: const Key('chat-session-copy-resume'),
|
||||
cupertino: cupertino,
|
||||
label: _copied == 'resume'
|
||||
? 'Copied'
|
||||
: 'Copy resume command',
|
||||
icon: _copied == 'resume'
|
||||
? (cupertino ? CupertinoIcons.checkmark : Icons.check)
|
||||
: (cupertino
|
||||
? CupertinoIcons
|
||||
.chevron_left_slash_chevron_right
|
||||
: Icons.terminal),
|
||||
onPressed: () => _copy('resume', handoff.resumeCommand),
|
||||
),
|
||||
_exportButton(
|
||||
ChatExportFormat.markdown,
|
||||
'Export conversation',
|
||||
cupertino
|
||||
? CupertinoIcons.square_arrow_up
|
||||
: Icons.ios_share,
|
||||
),
|
||||
_exportButton(
|
||||
ChatExportFormat.json,
|
||||
'Export JSON',
|
||||
cupertino ? CupertinoIcons.doc_text : Icons.data_object,
|
||||
),
|
||||
if (handoff.nativeExport)
|
||||
_exportButton(
|
||||
ChatExportFormat.native,
|
||||
'Export native session',
|
||||
cupertino
|
||||
? CupertinoIcons.doc
|
||||
: Icons.description_outlined,
|
||||
),
|
||||
],
|
||||
),
|
||||
if (status != null && status.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
status,
|
||||
key: const Key('chat-session-export-status'),
|
||||
style: label,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _exportButton(ChatExportFormat format, String label, IconData icon) {
|
||||
final exporter = widget.exporter;
|
||||
return _ActionButton(
|
||||
key: Key('chat-session-export-${format.wire}'),
|
||||
cupertino: widget.cupertino,
|
||||
label: label,
|
||||
icon: icon,
|
||||
busy: exporter.active == format,
|
||||
onPressed: exporter.busy ? null : () => exporter.export(format),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A standard text button with a leading icon, in the host's style.
|
||||
class _ActionButton extends StatelessWidget {
|
||||
const _ActionButton({
|
||||
super.key,
|
||||
required this.cupertino,
|
||||
required this.label,
|
||||
required this.icon,
|
||||
required this.onPressed,
|
||||
this.semanticsLabel,
|
||||
this.busy = false,
|
||||
});
|
||||
|
||||
final bool cupertino;
|
||||
final String label;
|
||||
final String? semanticsLabel;
|
||||
final IconData icon;
|
||||
final VoidCallback? onPressed;
|
||||
final bool busy;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Widget leading = busy
|
||||
? (cupertino
|
||||
? const CupertinoActivityIndicator()
|
||||
: const SizedBox.square(
|
||||
dimension: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
))
|
||||
: Icon(icon, size: 18);
|
||||
final child = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
leading,
|
||||
const SizedBox(width: 6),
|
||||
Flexible(child: Text(label, semanticsLabel: semanticsLabel)),
|
||||
],
|
||||
);
|
||||
final button = cupertino
|
||||
? CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
||||
onPressed: onPressed,
|
||||
child: child,
|
||||
)
|
||||
: TextButton(onPressed: onPressed, child: child);
|
||||
return button;
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,11 @@ import '../ui/sessions/session_actions.dart';
|
||||
import '../ui/transcript/chat_markdown_view.dart';
|
||||
import '../ui/transcript/chat_message_view.dart';
|
||||
import '../ui/transcript/chat_injected_rows.dart';
|
||||
import '../../artifacts/actions/artifact_file_bridge.dart';
|
||||
import '../domain/chat_session_handoff.dart';
|
||||
import 'chat_account_usage_section.dart';
|
||||
import 'chat_export_controller.dart';
|
||||
import 'chat_session_section.dart';
|
||||
import 'chat_background_tasks.dart';
|
||||
import 'chat_command_actions.dart';
|
||||
import 'chat_composer_bar.dart';
|
||||
@@ -75,6 +79,7 @@ class ChatThreadView extends StatefulWidget {
|
||||
this.onCreatedSession,
|
||||
this.onSessionRenamed,
|
||||
this.onSessionClosed,
|
||||
this.fileBridge = const ArtifactFileBridge(),
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
@@ -96,6 +101,9 @@ class ChatThreadView extends StatefulWidget {
|
||||
/// `/close` was accepted: the conversation is finished here as on the web.
|
||||
final VoidCallback? onSessionClosed;
|
||||
|
||||
/// The host file actions the info sheet's export uses; tests inject one.
|
||||
final ArtifactFileBridge fileBridge;
|
||||
|
||||
/// The list row's title when this visit knows it; a deep link may not.
|
||||
final String title;
|
||||
|
||||
@@ -344,16 +352,31 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
Future<void> _openInfo() async {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final exporter = ChatExportController(
|
||||
repository: ChatRepository(widget.gateway),
|
||||
sessionId: widget.sessionId,
|
||||
bridge: widget.fileBridge,
|
||||
);
|
||||
try {
|
||||
await _showInfo(cupertino, exporter);
|
||||
} finally {
|
||||
exporter.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showInfo(bool cupertino, ChatExportController exporter) async {
|
||||
final handoff = ChatSessionHandoff.from(widget.sessionId, widget.session);
|
||||
Widget sheet() => _ChatInfoSheet(
|
||||
controller: _controller,
|
||||
handoff: handoff,
|
||||
exporter: exporter,
|
||||
);
|
||||
if (cupertino) {
|
||||
await showCupertinoModalPopup<void>(
|
||||
context: context,
|
||||
builder: (sheetContext) => Align(
|
||||
alignment: Alignment.bottomCenter,
|
||||
child: SafeArea(
|
||||
child: CupertinoPopupSurface(
|
||||
child: _ChatInfoSheet(controller: _controller),
|
||||
),
|
||||
),
|
||||
child: SafeArea(child: CupertinoPopupSurface(child: sheet())),
|
||||
),
|
||||
);
|
||||
return;
|
||||
@@ -363,7 +386,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
showDragHandle: true,
|
||||
isScrollControlled: true,
|
||||
useSafeArea: true,
|
||||
builder: (sheetContext) => _ChatInfoSheet(controller: _controller),
|
||||
builder: (sheetContext) => sheet(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1553,9 +1576,15 @@ String _chatInfoDollars(num value) {
|
||||
/// The "Chat information" panel. It rebuilds from the controller, so metrics
|
||||
/// that arrive while it is open replace the displayed snapshot.
|
||||
class _ChatInfoSheet extends StatelessWidget {
|
||||
const _ChatInfoSheet({required this.controller});
|
||||
const _ChatInfoSheet({
|
||||
required this.controller,
|
||||
required this.handoff,
|
||||
required this.exporter,
|
||||
});
|
||||
|
||||
final ChatThreadController controller;
|
||||
final ChatSessionHandoff handoff;
|
||||
final ChatExportController exporter;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -1598,6 +1627,12 @@ class _ChatInfoSheet extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
ChatSessionSection(
|
||||
handoff: handoff,
|
||||
exporter: exporter,
|
||||
cupertino: cupertino,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
);
|
||||
if (!cupertino) return SingleChildScrollView(child: content);
|
||||
|
||||
@@ -178,6 +178,20 @@ class ChatRepository {
|
||||
gateway.call('chat_rename', {
|
||||
'chat_rename': {'session_id': sessionId, 'title': title.trim()},
|
||||
});
|
||||
|
||||
/// The chat as one file: `chat_export_file` with name, mime and content.
|
||||
/// A reply without a file is refused rather than saved as an empty file.
|
||||
Future<JsonMap> export(String sessionId, String format) async {
|
||||
final reply = await gateway.call('chat_export', {
|
||||
'chat_export': {'session_id': sessionId, 'format': format},
|
||||
});
|
||||
final file = reply['chat_export_file'];
|
||||
if (file is! Map || '${file['name'] ?? ''}'.trim().isEmpty) {
|
||||
throw StateError('The server did not return an export file.');
|
||||
}
|
||||
return file.cast<String, dynamic>();
|
||||
}
|
||||
|
||||
Future<JsonMap> star(String sessionId, bool starred) =>
|
||||
gateway.call('chat_star', {
|
||||
'chat_query': {'session_id': sessionId, 'starred': starred},
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// The facts the info sheet's "Session" section shows, read from the chat's
|
||||
/// `chat_sessions` row.
|
||||
///
|
||||
/// The chat id is the harness's native session id (Claude Code session UUID,
|
||||
/// Codex thread id, OpenCode `ses_` id). The resume command and native export
|
||||
/// flag come from the server, which checked each form against the harness
|
||||
/// CLI; an older server sends neither, and nothing is invented here.
|
||||
class ChatSessionHandoff {
|
||||
const ChatSessionHandoff({
|
||||
required this.id,
|
||||
required this.backend,
|
||||
required this.directory,
|
||||
required this.resumeCommand,
|
||||
required this.nativeExport,
|
||||
});
|
||||
|
||||
/// [row] may be null when the conversation was opened by id alone.
|
||||
factory ChatSessionHandoff.from(String sessionId, JsonMap? row) {
|
||||
String text(String key) => '${row?[key] ?? ''}'.trim();
|
||||
final id = text('id');
|
||||
return ChatSessionHandoff(
|
||||
id: id.isEmpty ? sessionId.trim() : id,
|
||||
backend: row == null
|
||||
? ''
|
||||
: (text('backend').isEmpty ? 'opencode' : text('backend')),
|
||||
directory: text('directory'),
|
||||
resumeCommand: text('resume_command'),
|
||||
nativeExport: row?['native_export'] == true,
|
||||
);
|
||||
}
|
||||
|
||||
final String id;
|
||||
|
||||
/// Empty when the row is unknown; a row without a backend is OpenCode.
|
||||
final String backend;
|
||||
final String directory;
|
||||
final String resumeCommand;
|
||||
final bool nativeExport;
|
||||
}
|
||||
|
||||
/// The formats `chat_export` accepts.
|
||||
enum ChatExportFormat {
|
||||
markdown('markdown'),
|
||||
json('json'),
|
||||
native('native');
|
||||
|
||||
const ChatExportFormat(this.wire);
|
||||
final String wire;
|
||||
}
|
||||
@@ -39,6 +39,17 @@ Future<FakeChatGateway> _thread(
|
||||
return gateway;
|
||||
}
|
||||
|
||||
/// "Unavailable" inside the usage metric rows only; the Session section says
|
||||
/// it too for a conversation opened without its list row.
|
||||
final _metricUnavailable = find.descendant(
|
||||
of: find.byWidgetPredicate(
|
||||
(widget) =>
|
||||
widget.key is ValueKey<String> &&
|
||||
(widget.key! as ValueKey<String>).value.startsWith('chat-info-metric-'),
|
||||
),
|
||||
matching: find.text('Unavailable'),
|
||||
);
|
||||
|
||||
Future<void> _openInfo(WidgetTester tester) async {
|
||||
await tester.tap(find.byKey(const Key('chat-info')));
|
||||
await tester.pumpAndSettle();
|
||||
@@ -109,7 +120,7 @@ void main() {
|
||||
|
||||
await _openInfo(tester);
|
||||
|
||||
expect(find.text('Unavailable'), findsNWidgets(4));
|
||||
expect(_metricUnavailable, findsNWidgets(4));
|
||||
expect(find.text('0'), findsNothing);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-info-close')));
|
||||
@@ -128,7 +139,7 @@ void main() {
|
||||
await tester.pump();
|
||||
await _openInfo(tester);
|
||||
|
||||
expect(find.text('Unavailable'), findsNothing);
|
||||
expect(_metricUnavailable, findsNothing);
|
||||
expect(find.text('0 tok/s'), findsOneWidget);
|
||||
expect(find.text('0'), findsOneWidget);
|
||||
expect(find.text('0 / 1,000'), findsOneWidget);
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
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/artifacts/actions/artifact_file.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_file_bridge.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_transfer.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_session_handoff.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
const _id = '0b6f1c2e-1111-4222-8333-444455556666';
|
||||
const _resume = 'cd /work/app && claude --resume $_id';
|
||||
|
||||
JsonMap _row({String backend = 'claude', bool native = true}) => {
|
||||
'id': _id,
|
||||
'title': 'Fix tests',
|
||||
'backend': backend,
|
||||
'directory': '/work/app',
|
||||
'resume_command': _resume,
|
||||
'native_export': native,
|
||||
};
|
||||
|
||||
/// Answers chat_export with a fixed file; everything else as the thread fake.
|
||||
class _ExportGateway extends FakeChatGateway {
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (type != 'chat_export') return super.call(type, fields);
|
||||
calls.add((type: type, fields: fields));
|
||||
final format = fields['chat_export']['format'];
|
||||
return {
|
||||
'type': 'chat_export',
|
||||
'chat_export_file': {
|
||||
'session_id': _id,
|
||||
'format': format,
|
||||
'name': format == 'json' ? 'Fix-tests.json' : 'Fix-tests.md',
|
||||
'mime': format == 'json' ? 'application/json' : 'text/markdown',
|
||||
'content': '# Fix tests\n',
|
||||
'messages': 1,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Widget _host(Widget child, bool cupertino) => cupertino
|
||||
? CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.light),
|
||||
home: CupertinoPageScaffold(child: child),
|
||||
)
|
||||
: MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
home: Scaffold(body: child),
|
||||
);
|
||||
|
||||
Future<
|
||||
({_ExportGateway gateway, List<ArtifactFile> shared, List<String> clipboard})
|
||||
>
|
||||
_open(WidgetTester tester, {required bool cupertino, JsonMap? row}) async {
|
||||
tester.view.physicalSize = const Size(800, 2400);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final clipboard = <String>[];
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
||||
if (call.method == 'Clipboard.setData') {
|
||||
clipboard.add('${(call.arguments as Map)['text']}');
|
||||
}
|
||||
return null;
|
||||
});
|
||||
addTearDown(
|
||||
() => messenger.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||
);
|
||||
final gateway = _ExportGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => chatPage([]);
|
||||
final shared = <ArtifactFile>[];
|
||||
final bridge = ArtifactFileBridge(
|
||||
shareSupported: true,
|
||||
downloadSupported: true,
|
||||
share: (file) async {
|
||||
shared.add(file);
|
||||
return const ArtifactTransferResult(ArtifactTransferState.shared, '');
|
||||
},
|
||||
download: (file) async {
|
||||
shared.add(file);
|
||||
return const ArtifactTransferResult(ArtifactTransferState.saved, '');
|
||||
},
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
_host(
|
||||
ChatThreadView(
|
||||
gateway: gateway,
|
||||
sessionId: _id,
|
||||
session: row ?? _row(),
|
||||
onBack: () {},
|
||||
fileBridge: bridge,
|
||||
),
|
||||
cupertino,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('chat-info')));
|
||||
await tester.pumpAndSettle();
|
||||
return (gateway: gateway, shared: shared, clipboard: clipboard);
|
||||
}
|
||||
|
||||
Future<void> _tap(WidgetTester tester, Key key) async {
|
||||
await tester.ensureVisible(find.byKey(key));
|
||||
await tester.tap(find.byKey(key));
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void main() {
|
||||
for (final cupertino in [false, true]) {
|
||||
final host = cupertino ? 'cupertino' : 'material';
|
||||
|
||||
testWidgets('$host: shows the native id, harness and directory', (
|
||||
tester,
|
||||
) async {
|
||||
await _open(tester, cupertino: cupertino);
|
||||
expect(find.text('Session'), findsOneWidget);
|
||||
expect(find.text('Session ID'), findsOneWidget);
|
||||
expect(find.text(_id), findsOneWidget);
|
||||
expect(find.text('Claude'), findsOneWidget);
|
||||
expect(find.text('/work/app'), findsOneWidget);
|
||||
expect(find.text(_resume), findsOneWidget);
|
||||
expect(find.text('Export native session'), findsOneWidget);
|
||||
expect(find.bySemanticsLabel('Copy session ID'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('$host: copies the id and the resume command', (tester) async {
|
||||
final opened = await _open(tester, cupertino: cupertino);
|
||||
await _tap(tester, const Key('chat-session-copy-id'));
|
||||
expect(opened.clipboard, [_id]);
|
||||
expect(find.text('Copied'), findsOneWidget);
|
||||
await _tap(tester, const Key('chat-session-copy-resume'));
|
||||
expect(opened.clipboard, [_id, _resume]);
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
expect(find.text('Copied'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('$host: export hands the server file to the file action', (
|
||||
tester,
|
||||
) async {
|
||||
final opened = await _open(tester, cupertino: cupertino);
|
||||
await _tap(tester, const Key('chat-session-export-markdown'));
|
||||
await tester.pumpAndSettle();
|
||||
final request = opened.gateway.calls.lastWhere(
|
||||
(call) => call.type == 'chat_export',
|
||||
);
|
||||
expect(request.fields['chat_export'], {
|
||||
'session_id': _id,
|
||||
'format': 'markdown',
|
||||
});
|
||||
expect(opened.shared, hasLength(1));
|
||||
final file = opened.shared.single;
|
||||
expect(file.name, 'Fix-tests.md');
|
||||
expect(file.mimeType, 'text/markdown');
|
||||
expect(utf8.decode(file.bytes), '# Fix tests\n');
|
||||
expect(find.text('Shared Fix-tests.md.'), findsOneWidget);
|
||||
|
||||
await _tap(tester, const Key('chat-session-export-json'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(opened.shared.last.name, 'Fix-tests.json');
|
||||
});
|
||||
}
|
||||
|
||||
testWidgets('no native export or resume command when the row has none', (
|
||||
tester,
|
||||
) async {
|
||||
await _open(
|
||||
tester,
|
||||
cupertino: false,
|
||||
row: {'id': _id, 'directory': '/work/app'},
|
||||
);
|
||||
expect(find.text('OpenCode'), findsOneWidget);
|
||||
expect(find.text('Export native session'), findsNothing);
|
||||
expect(find.text('Copy resume command'), findsNothing);
|
||||
expect(find.text('Export conversation'), findsOneWidget);
|
||||
});
|
||||
|
||||
test('a conversation opened by id alone keeps the id', () {
|
||||
final handoff = ChatSessionHandoff.from('ses_abc', null);
|
||||
expect(handoff.id, 'ses_abc');
|
||||
expect(handoff.backend, '');
|
||||
expect(handoff.resumeCommand, '');
|
||||
});
|
||||
}
|
||||
@@ -26,6 +26,16 @@ int get _hits => int.tryParse(_params['hits'] ?? '') ?? 0;
|
||||
int get _chats => int.tryParse(_params['chats'] ?? '') ?? 0;
|
||||
bool get perfRunGraph => _params['graph'] == '1';
|
||||
|
||||
/// `?harness=claude|codex` makes the chats that harness's (default OpenCode),
|
||||
/// with the resume command the server would send for it.
|
||||
String get _harness => _params['harness'] ?? 'opencode';
|
||||
|
||||
String _resumeCommand(String id) => switch (_harness) {
|
||||
'claude' => 'cd /workspace/demo && claude --resume $id',
|
||||
'codex' => 'cd /workspace/demo && codex resume $id',
|
||||
_ => 'cd /workspace/demo && opencode --session $id',
|
||||
};
|
||||
|
||||
/// Whether a chat scroll option (tool/perf/chat_scroll_fixture.dart) shapes
|
||||
/// the transcripts instead of the bench's short markdown history.
|
||||
bool get _scrollVariety => ['msgs', 'rich', 'older'].any(_params.containsKey);
|
||||
@@ -142,9 +152,28 @@ JsonMap? perfChatReply(JsonMap request) {
|
||||
'id': 'perf-chat-$i',
|
||||
'title': 'Fixture chat ${i + 1}',
|
||||
'directory': '/workspace/demo',
|
||||
// Server-shaped handoff facts (chat_sessions rows carry them).
|
||||
if (_harness != 'opencode') 'backend': _harness,
|
||||
'resume_command': _resumeCommand('perf-chat-$i'),
|
||||
'native_export': _harness == 'claude',
|
||||
},
|
||||
],
|
||||
};
|
||||
case 'chat_export':
|
||||
final body = request['chat_export'];
|
||||
final format = body is Map ? '${body['format'] ?? ''}' : '';
|
||||
final json = format == 'json';
|
||||
return {
|
||||
'id': id,
|
||||
'type': 'chat_export',
|
||||
'chat_export_file': {
|
||||
'session_id': body is Map ? body['session_id'] : '',
|
||||
'format': format,
|
||||
'name': json ? 'Fixture-chat.json' : 'Fixture-chat.md',
|
||||
'mime': json ? 'application/json' : 'text/markdown',
|
||||
'content': json ? '{"messages":[]}\n' : '# Fixture chat\n',
|
||||
},
|
||||
};
|
||||
case 'chat_subscribe':
|
||||
return {'id': id, 'type': 'chat_subscribed'};
|
||||
case 'chat_shells':
|
||||
|
||||
@@ -294,6 +294,31 @@ pipelines chat-adopt <session-id> [--harness opencode|claude|codex] [--title TEX
|
||||
Without `--harness`, each available harness is asked. Stop using the session
|
||||
elsewhere once you continue it in Pipelines.
|
||||
|
||||
## Continuing or exporting a chat
|
||||
|
||||
A chat's id is the harness's own session id (Claude Code session UUID, Codex
|
||||
thread id, OpenCode `ses_…`). The app's chat information sheet shows it with
|
||||
the harness and directory, and copies a command that continues the session in
|
||||
a terminal on the server machine:
|
||||
|
||||
| Harness | Resume command |
|
||||
| --- | --- |
|
||||
| Claude Code | `cd <dir> && claude --resume <id>` |
|
||||
| Codex | `cd <dir> && codex resume <id>` |
|
||||
| OpenCode | `cd <dir> && opencode --session <id>` |
|
||||
|
||||
Each `chat_sessions` row carries this as `resume_command`. Stop the turn in
|
||||
Pipelines before continuing the session elsewhere.
|
||||
|
||||
`chat_export` (`{"chat_export": {"session_id", "format"}}`) returns
|
||||
`chat_export_file` (`name`, `mime`, `content`, `messages`, `truncated`):
|
||||
`markdown` is a transcript of user and assistant messages and agent reports
|
||||
with timestamps and one line per tool call; `json` is the same as data.
|
||||
Reasoning and full tool output are left out, and an export is bounded at
|
||||
8 MiB (older pages are dropped and `truncated` is set). `native` returns
|
||||
Claude Code's own JSONL transcript, offered when a row has `native_export`.
|
||||
Only operator chats are exported.
|
||||
|
||||
## Limits
|
||||
|
||||
- Stage session exports: the native session read is capped at 8 MiB and the
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// NativeExportLimit bounds the Claude Code session file chat_export returns.
|
||||
const NativeExportLimit = 8 << 20
|
||||
|
||||
// NativeExport returns Claude Code's own JSONL transcript for one session, the
|
||||
// file `claude --resume` reads. It is a plain read of the retained file; no CLI
|
||||
// process is started.
|
||||
func (c *Chat) NativeExport(ctx context.Context, id string) (protocol.ChatExportFile, error) {
|
||||
path := findTranscriptFile(id)
|
||||
if path == "" {
|
||||
return protocol.ChatExportFile{}, errors.New("Claude Code has not written a transcript for session " + id + " yet")
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
defer file.Close()
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return protocol.ChatExportFile{}, errors.New("the Claude Code transcript is not a regular file")
|
||||
}
|
||||
if info.Size() > NativeExportLimit {
|
||||
return protocol.ChatExportFile{}, fmt.Errorf("the Claude Code transcript is %d bytes, over the %d byte export limit; it is at %s on the server", info.Size(), NativeExportLimit, path)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(file, NativeExportLimit+1))
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
if len(data) > NativeExportLimit {
|
||||
return protocol.ChatExportFile{}, fmt.Errorf("the Claude Code transcript grew past the %d byte export limit", NativeExportLimit)
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
return protocol.ChatExportFile{}, errors.New("the Claude Code transcript is not valid UTF-8")
|
||||
}
|
||||
return protocol.ChatExportFile{
|
||||
SessionID: id,
|
||||
Format: protocol.ChatExportNative,
|
||||
Name: id + ".jsonl",
|
||||
Mime: "application/x-ndjson",
|
||||
Content: string(data),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestNativeExportReturnsTheSessionJSONL(t *testing.T) {
|
||||
config := t.TempDir()
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", config)
|
||||
id := "0b6f1c2e-1111-4222-8333-444455556666"
|
||||
project := filepath.Join(config, "projects", "-work-a")
|
||||
if err := os.MkdirAll(project, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := `{"type":"user","uuid":"u1"}` + "\n" + `{"type":"assistant","uuid":"a1"}` + "\n"
|
||||
if err := os.WriteFile(filepath.Join(project, id+".jsonl"), []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat := New(context.Background())
|
||||
defer chat.Close()
|
||||
file, err := chat.NativeExport(context.Background(), id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if file.Name != id+".jsonl" || file.Mime != "application/x-ndjson" || file.Content != body || file.Format != protocol.ChatExportNative {
|
||||
t.Fatalf("native export = %+v", file)
|
||||
}
|
||||
if _, err := chat.NativeExport(context.Background(), "0b6f1c2e-1111-4222-8333-000000000000"); err == nil || !strings.Contains(err.Error(), "has not written a transcript") {
|
||||
t.Fatalf("missing transcript error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,12 @@ 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"
|
||||
// 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
|
||||
// chat_messages serves, or the harness's own session file where one exists
|
||||
// (ChatSession.NativeExport).
|
||||
ChatExport = "chat_export"
|
||||
// ChatBackends lists the installed chat harnesses the server can create a
|
||||
// session on. The reply is a bounded array of backend names.
|
||||
ChatBackends = "chat_backends"
|
||||
@@ -280,6 +286,41 @@ type ChatSession struct {
|
||||
// epoch-millisecond time it was set, 0 while unstarred.
|
||||
Starred bool `json:"starred,omitempty"`
|
||||
StarredAt int64 `json:"starred_at,omitempty"`
|
||||
// ResumeCommand is the shell command that continues this session in a
|
||||
// terminal on the server machine with the harness's own CLI, run in the
|
||||
// session's directory. ID is the harness's native session id (Claude Code
|
||||
// session UUID, Codex thread id, OpenCode ses_ id). Empty when the harness
|
||||
// has no verified resume option.
|
||||
ResumeCommand string `json:"resume_command,omitempty"`
|
||||
// NativeExport says chat_export with format "native" can return the
|
||||
// harness's own session file (today: Claude Code's JSONL transcript).
|
||||
NativeExport bool `json:"native_export,omitempty"`
|
||||
}
|
||||
|
||||
// Chat export formats accepted by chat_export.
|
||||
const (
|
||||
ChatExportMarkdown = "markdown"
|
||||
ChatExportJSON = "json"
|
||||
ChatExportNative = "native"
|
||||
)
|
||||
|
||||
// ChatExportRequest is the chat_export body.
|
||||
type ChatExportRequest struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Format string `json:"format"`
|
||||
}
|
||||
|
||||
// ChatExportFile is the chat_export reply: one named, typed text file. Messages
|
||||
// counts the transcript messages included (0 for a native file). Truncated says
|
||||
// older history was left out to keep the file within the server's bound.
|
||||
type ChatExportFile struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Format string `json:"format"`
|
||||
Name string `json:"name"`
|
||||
Mime string `json:"mime"`
|
||||
Content string `json:"content"`
|
||||
Messages int `json:"messages,omitempty"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
}
|
||||
|
||||
// ChatCloseResult reports the outcome of a chat_close: the session id, the
|
||||
|
||||
@@ -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"`
|
||||
// ChatExport is the chat_export body and ChatExportFile its reply.
|
||||
ChatExport *ChatExportRequest `json:"chat_export,omitempty"`
|
||||
ChatExportFile *ChatExportFile `json:"chat_export_file,omitempty"`
|
||||
// ChatBackends is the chat_backends reply: the installed harnesses a new
|
||||
// chat can use.
|
||||
ChatBackends []string `json:"chat_backends,omitempty"`
|
||||
|
||||
@@ -206,6 +206,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatRename:
|
||||
handleChatRename(ctx, request, registry, write)
|
||||
return true
|
||||
case protocol.ChatExport:
|
||||
handleChatExport(ctx, request, broker, registry, write)
|
||||
return true
|
||||
case protocol.ChatBackends:
|
||||
handleChatBackends(request, broker, write)
|
||||
return true
|
||||
|
||||
@@ -148,5 +148,5 @@ func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSess
|
||||
out.Starred = true
|
||||
out.StarredAt = session.StarredAt
|
||||
}
|
||||
return out
|
||||
return withChatHandoff(out)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claude"
|
||||
"git.a-wan.net/alan/pipelines/internal/codex"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatExportLimit bounds an exported transcript. Older pages stop being read
|
||||
// once the newest history already fills it, and the file says so.
|
||||
const chatExportLimit = 8 << 20
|
||||
|
||||
// chatExportPageLimit bounds how many history pages one export reads.
|
||||
const chatExportPageLimit = 500
|
||||
|
||||
// chatNativeExporter is a harness that can hand back its own session file
|
||||
// cheaply (Claude Code's JSONL transcript).
|
||||
type chatNativeExporter interface {
|
||||
NativeExport(ctx context.Context, sessionID string) (protocol.ChatExportFile, error)
|
||||
}
|
||||
|
||||
// NativeExport routes to the session's harness; only harnesses with a cheap
|
||||
// native file implement it.
|
||||
func (m *chatManager) NativeExport(ctx context.Context, sessionID string) (protocol.ChatExportFile, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
exporter, ok := adapter.(chatNativeExporter)
|
||||
if !ok {
|
||||
return protocol.ChatExportFile{}, errors.New("this chat's harness has no native session export")
|
||||
}
|
||||
return exporter.NativeExport(ctx, sessionID)
|
||||
}
|
||||
|
||||
// chatBackendName is the harness's display name.
|
||||
func chatBackendName(backend string) string {
|
||||
switch backend {
|
||||
case claude.Backend:
|
||||
return "Claude Code"
|
||||
case codex.Backend:
|
||||
return "Codex"
|
||||
case "", "opencode":
|
||||
return "OpenCode"
|
||||
default:
|
||||
return backend
|
||||
}
|
||||
}
|
||||
|
||||
// chatResumeCommand is the terminal command that continues a session with the
|
||||
// harness's own CLI in its directory. Each form was checked against the CLI's
|
||||
// --help: `claude --resume <id>` (Claude Code 2.1), `codex resume <id>` (Codex
|
||||
// CLI 0.164) and `opencode --session <id>` (OpenCode 2.0).
|
||||
func chatResumeCommand(backend, sessionID, directory string) string {
|
||||
if !validChatSessionID(sessionID) {
|
||||
return ""
|
||||
}
|
||||
var command string
|
||||
switch backend {
|
||||
case claude.Backend:
|
||||
command = "claude --resume " + sessionID
|
||||
case codex.Backend:
|
||||
command = "codex resume " + sessionID
|
||||
case "", "opencode":
|
||||
command = "opencode --session " + sessionID
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
if strings.TrimSpace(directory) == "" {
|
||||
return command
|
||||
}
|
||||
return "cd " + shellQuote(directory) + " && " + command
|
||||
}
|
||||
|
||||
// chatNativeExportAvailable says chat_export format=native is offered.
|
||||
func chatNativeExportAvailable(backend string) bool { return backend == claude.Backend }
|
||||
|
||||
// withChatHandoff fills the session's resume command and native export flag.
|
||||
func withChatHandoff(session protocol.ChatSession) protocol.ChatSession {
|
||||
session.ResumeCommand = chatResumeCommand(session.Backend, session.ID, session.Directory)
|
||||
session.NativeExport = chatNativeExportAvailable(session.Backend)
|
||||
return session
|
||||
}
|
||||
|
||||
// shellQuote leaves a plain path as it is and single-quotes anything else.
|
||||
func shellQuote(value string) string {
|
||||
plain := value != ""
|
||||
for _, r := range value {
|
||||
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("/._-+,:@%=", r)) {
|
||||
plain = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if plain {
|
||||
return value
|
||||
}
|
||||
return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'"
|
||||
}
|
||||
|
||||
// handleChatExport answers chat_export for one recorded operator session.
|
||||
func handleChatExport(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, 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
|
||||
}
|
||||
if registry == nil {
|
||||
fail("operator session registry is not configured on this server")
|
||||
return
|
||||
}
|
||||
body := request.ChatExport
|
||||
if body == nil || !validChatSessionID(body.SessionID) {
|
||||
fail("a valid chat session id is required")
|
||||
return
|
||||
}
|
||||
format := strings.TrimSpace(body.Format)
|
||||
if format == "" {
|
||||
format = protocol.ChatExportMarkdown
|
||||
}
|
||||
switch format {
|
||||
case protocol.ChatExportMarkdown, protocol.ChatExportJSON, protocol.ChatExportNative:
|
||||
default:
|
||||
fail("chat export format must be markdown, json or native")
|
||||
return
|
||||
}
|
||||
row, found, err := registry.OperatorSession(ctx, body.SessionID)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
fail("session " + body.SessionID + " is not an operator chat session")
|
||||
return
|
||||
}
|
||||
session := withChatHandoff(chatSessionFromOperator(row))
|
||||
var file protocol.ChatExportFile
|
||||
if format == protocol.ChatExportNative {
|
||||
if !session.NativeExport {
|
||||
fail(chatBackendName(session.Backend) + " has no native session export")
|
||||
return
|
||||
}
|
||||
exporter, ok := broker.(chatNativeExporter)
|
||||
if !ok {
|
||||
fail("native session export is not available on this server")
|
||||
return
|
||||
}
|
||||
file, err = exporter.NativeExport(ctx, body.SessionID)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
} else {
|
||||
messages, truncated, err := chatExportHistory(ctx, broker, body.SessionID)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
transcript := chatExportTranscript{Session: session, Messages: messages, Truncated: truncated, ExportedAt: time.Now().UTC()}
|
||||
file, err = transcript.file(format)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
file.SessionID = body.SessionID
|
||||
file.Format = format
|
||||
_ = write(protocol.Message{Type: protocol.ChatExport, ID: request.ID, ChatExportFile: &file})
|
||||
}
|
||||
|
||||
// chatExportHistory reads the session's whole history, newest page first as
|
||||
// chat_messages serves it, and returns it oldest first. It stops reading older
|
||||
// pages once the bound is reached and reports that older turns were left out.
|
||||
func chatExportHistory(ctx context.Context, broker chatBroker, sessionID string) ([]protocol.ChatMessage, bool, error) {
|
||||
var pages [][]protocol.ChatMessage
|
||||
seen := map[string]bool{}
|
||||
size := 0
|
||||
cursor := ""
|
||||
for page := 0; page < chatExportPageLimit; page++ {
|
||||
history, err := broker.Messages(ctx, sessionID, 100, cursor)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
kept := make([]protocol.ChatMessage, 0, len(history.Messages))
|
||||
for _, message := range history.Messages {
|
||||
if message.ID != "" && seen[message.ID] {
|
||||
continue
|
||||
}
|
||||
seen[message.ID] = true
|
||||
kept = append(kept, message)
|
||||
size += chatMessageSize(message)
|
||||
}
|
||||
pages = append(pages, kept)
|
||||
next := history.NextCursor
|
||||
if next == "" || next == cursor {
|
||||
return flattenChatPages(pages), false, nil
|
||||
}
|
||||
if size >= chatExportLimit {
|
||||
return flattenChatPages(pages), true, nil
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
return flattenChatPages(pages), true, nil
|
||||
}
|
||||
|
||||
func flattenChatPages(pages [][]protocol.ChatMessage) []protocol.ChatMessage {
|
||||
out := []protocol.ChatMessage{}
|
||||
for index := len(pages) - 1; index >= 0; index-- {
|
||||
out = append(out, pages[index]...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func chatMessageSize(message protocol.ChatMessage) int {
|
||||
size := 0
|
||||
for _, part := range message.Parts {
|
||||
size += len(part.Text) + len(part.Name) + 64
|
||||
}
|
||||
return size
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatExportTranscript is one session's history ready to be written as a file.
|
||||
type chatExportTranscript struct {
|
||||
Session protocol.ChatSession
|
||||
Messages []protocol.ChatMessage
|
||||
Truncated bool
|
||||
ExportedAt time.Time
|
||||
}
|
||||
|
||||
// chatExportEntry is one message as both formats describe it: the visible
|
||||
// text, attachments by name and each tool call summarised to one line.
|
||||
// Reasoning and full tool output are left out.
|
||||
type chatExportEntry struct {
|
||||
ID string `json:"id"`
|
||||
Role string `json:"role"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
CreatedAt string `json:"created_at,omitempty"`
|
||||
Client string `json:"client,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Attachments []string `json:"attachments,omitempty"`
|
||||
Tools []chatExportTool `json:"tools,omitempty"`
|
||||
}
|
||||
|
||||
type chatExportTool struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type chatExportSession struct {
|
||||
ID string `json:"id"`
|
||||
Backend string `json:"backend"`
|
||||
Harness string `json:"harness"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Directory string `json:"directory,omitempty"`
|
||||
ResumeCommand string `json:"resume_command,omitempty"`
|
||||
}
|
||||
|
||||
type chatExportDocument struct {
|
||||
Session chatExportSession `json:"session"`
|
||||
ExportedAt string `json:"exported_at"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
Messages []chatExportEntry `json:"messages"`
|
||||
}
|
||||
|
||||
func (t chatExportTranscript) entries() []chatExportEntry {
|
||||
out := make([]chatExportEntry, 0, len(t.Messages))
|
||||
for _, message := range t.Messages {
|
||||
entry := chatExportEntry{
|
||||
ID: message.ID, Role: message.Role, Kind: message.Kind,
|
||||
CreatedAt: chatExportTime(message.CreatedAt), Client: message.Client, Model: message.Model,
|
||||
}
|
||||
var text []string
|
||||
for _, part := range message.Parts {
|
||||
switch part.Type {
|
||||
case protocol.ChatPartText:
|
||||
if strings.TrimSpace(part.Text) != "" {
|
||||
text = append(text, strings.TrimRight(part.Text, "\n"))
|
||||
}
|
||||
case protocol.ChatPartFile:
|
||||
name := strings.TrimSpace(part.Name)
|
||||
if name == "" {
|
||||
name = "attachment"
|
||||
}
|
||||
entry.Attachments = append(entry.Attachments, name)
|
||||
case protocol.ChatPartTool:
|
||||
entry.Tools = append(entry.Tools, chatExportToolFor(part))
|
||||
}
|
||||
}
|
||||
entry.Text = strings.Join(text, "\n\n")
|
||||
if entry.Text == "" && len(entry.Attachments) == 0 && len(entry.Tools) == 0 {
|
||||
continue
|
||||
}
|
||||
out = append(out, entry)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (t chatExportTranscript) session() chatExportSession {
|
||||
backend := t.Session.Backend
|
||||
if backend == "" {
|
||||
backend = "opencode"
|
||||
}
|
||||
return chatExportSession{
|
||||
ID: t.Session.ID, Backend: backend, Harness: chatBackendName(backend),
|
||||
Title: t.Session.Title, Directory: t.Session.Directory, ResumeCommand: t.Session.ResumeCommand,
|
||||
}
|
||||
}
|
||||
|
||||
// file writes the transcript in one of the two transcript formats.
|
||||
func (t chatExportTranscript) file(format string) (protocol.ChatExportFile, error) {
|
||||
entries := t.entries()
|
||||
base := chatExportBaseName(t.Session)
|
||||
if format == protocol.ChatExportJSON {
|
||||
document := chatExportDocument{Session: t.session(), ExportedAt: t.ExportedAt.Format(time.RFC3339), Truncated: t.Truncated, Messages: entries}
|
||||
data, err := json.MarshalIndent(document, "", " ")
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
return protocol.ChatExportFile{Name: base + ".json", Mime: "application/json", Content: string(data) + "\n", Messages: len(entries), Truncated: t.Truncated}, nil
|
||||
}
|
||||
return protocol.ChatExportFile{Name: base + ".md", Mime: "text/markdown", Content: t.markdown(entries), Messages: len(entries), Truncated: t.Truncated}, nil
|
||||
}
|
||||
|
||||
func (t chatExportTranscript) markdown(entries []chatExportEntry) string {
|
||||
session := t.session()
|
||||
var b strings.Builder
|
||||
title := strings.TrimSpace(session.Title)
|
||||
if title == "" {
|
||||
title = "Chat"
|
||||
}
|
||||
fmt.Fprintf(&b, "# %s\n\n", exportOneLine(title))
|
||||
fmt.Fprintf(&b, "- Session ID: `%s`\n", session.ID)
|
||||
fmt.Fprintf(&b, "- Harness: %s\n", session.Harness)
|
||||
if session.Directory != "" {
|
||||
fmt.Fprintf(&b, "- Directory: `%s`\n", session.Directory)
|
||||
}
|
||||
if session.ResumeCommand != "" {
|
||||
fmt.Fprintf(&b, "- Resume: `%s`\n", session.ResumeCommand)
|
||||
}
|
||||
fmt.Fprintf(&b, "- Exported: %s\n", t.ExportedAt.Format("2006-01-02 15:04:05 UTC"))
|
||||
if t.Truncated {
|
||||
b.WriteString("\n> Older messages were left out to keep this export within the server's size limit.\n")
|
||||
}
|
||||
previous := ""
|
||||
for _, entry := range entries {
|
||||
heading := chatExportHeading(entry)
|
||||
group := heading + "\x00" + entry.Client
|
||||
if group != previous {
|
||||
b.WriteString("\n## " + heading)
|
||||
if entry.CreatedAt != "" {
|
||||
b.WriteString(" · " + strings.Replace(strings.TrimSuffix(entry.CreatedAt, "Z"), "T", " ", 1) + " UTC")
|
||||
}
|
||||
if entry.Client != "" {
|
||||
b.WriteString(" · " + exportOneLine(entry.Client))
|
||||
}
|
||||
b.WriteString("\n")
|
||||
previous = group
|
||||
}
|
||||
if entry.Text != "" {
|
||||
b.WriteString("\n" + entry.Text + "\n")
|
||||
}
|
||||
for _, name := range entry.Attachments {
|
||||
b.WriteString("\n- Attachment: " + exportOneLine(name) + "\n")
|
||||
}
|
||||
if len(entry.Tools) > 0 {
|
||||
b.WriteString("\n")
|
||||
for _, tool := range entry.Tools {
|
||||
b.WriteString(chatExportToolLine(tool) + "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func chatExportHeading(entry chatExportEntry) string {
|
||||
switch {
|
||||
case entry.Kind == protocol.ChatMessageKindAgentReport:
|
||||
return "Agent report"
|
||||
case entry.Kind == protocol.ChatMessageKindNotice:
|
||||
return "Notice"
|
||||
case entry.Role == protocol.ChatRoleUser:
|
||||
return "User"
|
||||
default:
|
||||
return "Assistant"
|
||||
}
|
||||
}
|
||||
|
||||
func chatExportToolLine(tool chatExportTool) string {
|
||||
line := "- Tool `" + tool.Name + "`"
|
||||
if tool.Status != "" {
|
||||
line += " (" + tool.Status + ")"
|
||||
}
|
||||
if tool.Summary != "" {
|
||||
line += ": " + tool.Summary
|
||||
}
|
||||
if tool.Error != "" {
|
||||
line += " — error: " + tool.Error
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
// chatExportToolSummaryKeys are the input fields that name what a tool call
|
||||
// did, in preference order.
|
||||
var chatExportToolSummaryKeys = []string{"description", "command", "file_path", "filePath", "path", "pattern", "query", "url", "subagent_type", "prompt"}
|
||||
|
||||
func chatExportToolFor(part protocol.ChatPart) chatExportTool {
|
||||
name := strings.TrimSpace(part.Name)
|
||||
if name == "" {
|
||||
name = "tool"
|
||||
}
|
||||
tool := chatExportTool{Name: exportOneLine(name)}
|
||||
if part.State == nil {
|
||||
return tool
|
||||
}
|
||||
tool.Status = part.State.Status
|
||||
if part.State.Error != nil {
|
||||
tool.Error = exportClip(exportOneLine(part.State.Error.Message), 200)
|
||||
}
|
||||
var input map[string]any
|
||||
if json.Unmarshal(part.State.Input, &input) == nil {
|
||||
for _, key := range chatExportToolSummaryKeys {
|
||||
if value, ok := input[key].(string); ok && strings.TrimSpace(value) != "" {
|
||||
tool.Summary = exportClip(exportOneLine(value), 160)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return tool
|
||||
}
|
||||
|
||||
func chatExportTime(ms int64) string {
|
||||
if ms <= 0 {
|
||||
return ""
|
||||
}
|
||||
return time.UnixMilli(ms).UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
var chatExportUnsafeName = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
|
||||
|
||||
// chatExportBaseName is a portable file name from the title and session id.
|
||||
func chatExportBaseName(session protocol.ChatSession) string {
|
||||
title := strings.Trim(chatExportUnsafeName.ReplaceAllString(strings.TrimSpace(session.Title), "-"), "-.")
|
||||
title = exportClip(title, 60)
|
||||
if title == "" {
|
||||
return "chat-" + session.ID
|
||||
}
|
||||
return title + "-" + session.ID
|
||||
}
|
||||
|
||||
var exportWhitespace = regexp.MustCompile(`\s+`)
|
||||
|
||||
func exportOneLine(value string) string {
|
||||
return strings.TrimSpace(exportWhitespace.ReplaceAllString(value, " "))
|
||||
}
|
||||
|
||||
func exportClip(value string, limit int) string {
|
||||
if utf8.RuneCountInString(value) <= limit {
|
||||
return value
|
||||
}
|
||||
runes := []rune(value)
|
||||
return string(runes[:limit-1]) + "…"
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// pagedChat serves a fixed history in chat_messages pages, newest first like
|
||||
// every harness adapter, and a native file for the native-export path.
|
||||
type pagedChat struct {
|
||||
*fakeChat
|
||||
pages map[string]protocol.ChatHistoryPage // cursor -> page
|
||||
native protocol.ChatExportFile
|
||||
}
|
||||
|
||||
func (p *pagedChat) Messages(_ context.Context, _ string, _ int, cursor string) (protocol.ChatHistoryPage, error) {
|
||||
return p.pages[cursor], nil
|
||||
}
|
||||
|
||||
func (p *pagedChat) NativeExport(_ context.Context, sessionID string) (protocol.ChatExportFile, error) {
|
||||
file := p.native
|
||||
file.SessionID = sessionID
|
||||
return file, nil
|
||||
}
|
||||
|
||||
const exportClaudeID = "0b6f1c2e-1111-4222-8333-444455556666"
|
||||
|
||||
func exportFixture(t *testing.T, backend string) (*pagedChat, context.Context, func(protocol.Message) protocol.Message) {
|
||||
t.Helper()
|
||||
store := newOperatorStore(t)
|
||||
broker := &pagedChat{fakeChat: scriptedChat(), pages: map[string]protocol.ChatHistoryPage{
|
||||
"": {HasMore: true, NextCursor: "older", Messages: []protocol.ChatMessage{
|
||||
{ID: "m3", Role: protocol.ChatRoleAssistant, CreatedAt: 1_700_000_060_000, Parts: []protocol.ChatPart{
|
||||
{Type: protocol.ChatPartReasoning, Text: "secret thinking"},
|
||||
{Type: protocol.ChatPartTool, Name: "Bash", State: &protocol.ChatToolState{Status: protocol.ChatToolCompleted, Input: json.RawMessage(`{"command":"go test ./...","description":"Run the tests"}`), Content: []protocol.ChatToolContent{{Type: "text", Text: "huge tool output"}}}},
|
||||
{Type: protocol.ChatPartText, Text: "All tests pass."},
|
||||
}},
|
||||
{ID: "m4", Role: protocol.ChatRoleUser, Kind: protocol.ChatMessageKindAgentReport, CreatedAt: 1_700_000_090_000, Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: "Subagent found two files."}}},
|
||||
}},
|
||||
"older": {Messages: []protocol.ChatMessage{
|
||||
{ID: "m1", Role: protocol.ChatRoleUser, Client: "Pixel", CreatedAt: 1_700_000_000_000, Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: "Run the tests"}, {Type: protocol.ChatPartFile, Name: "notes.txt"}}},
|
||||
{ID: "m2", Role: protocol.ChatRoleAssistant, CreatedAt: 1_700_000_030_000, Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: "Running them now."}}},
|
||||
}},
|
||||
}, native: protocol.ChatExportFile{Name: exportClaudeID + ".jsonl", Mime: "application/x-ndjson", Content: "{}\n"}}
|
||||
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
||||
if err := store.RecordOperatorSession(ctx, exportClaudeID, "/work/my repo", "Fix tests", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetOperatorSessionBackend(ctx, exportClaudeID, backend); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
send := func(message protocol.Message) protocol.Message {
|
||||
writeChat(t, ctx, conn, message)
|
||||
for {
|
||||
var reply protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &reply); err != nil {
|
||||
t.Fatalf("read reply to %s: %v", message.ID, err)
|
||||
}
|
||||
if reply.ID == message.ID {
|
||||
return reply
|
||||
}
|
||||
}
|
||||
}
|
||||
return broker, ctx, send
|
||||
}
|
||||
|
||||
func TestChatExportMarkdownFromHistory(t *testing.T) {
|
||||
_, _, send := exportFixture(t, "claude")
|
||||
reply := send(protocol.Message{Type: protocol.ChatExport, ID: "x1", ChatExport: &protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "markdown"}})
|
||||
if reply.Type != protocol.ChatExport || reply.ChatExportFile == nil {
|
||||
t.Fatalf("reply = %+v", reply)
|
||||
}
|
||||
file := reply.ChatExportFile
|
||||
if file.Name != "Fix-tests-"+exportClaudeID+".md" || file.Mime != "text/markdown" || file.Format != "markdown" || file.Messages != 4 || file.Truncated {
|
||||
t.Fatalf("file = %+v", file)
|
||||
}
|
||||
md := file.Content
|
||||
for _, want := range []string{
|
||||
"# Fix tests\n",
|
||||
"- Session ID: `" + exportClaudeID + "`\n",
|
||||
"- Harness: Claude Code\n",
|
||||
"- Directory: `/work/my repo`\n",
|
||||
"- Resume: `cd '/work/my repo' && claude --resume " + exportClaudeID + "`\n",
|
||||
"## User · 2023-11-14 22:13:20 UTC · Pixel\n\nRun the tests\n",
|
||||
"- Attachment: notes.txt",
|
||||
"## Assistant · 2023-11-14 22:13:50 UTC\n\nRunning them now.\n\nAll tests pass.\n",
|
||||
"- Tool `Bash` (completed): Run the tests",
|
||||
"## Agent report · 2023-11-14 22:14:50 UTC\n\nSubagent found two files.\n",
|
||||
} {
|
||||
if !strings.Contains(md, want) {
|
||||
t.Fatalf("markdown lacks %q:\n%s", want, md)
|
||||
}
|
||||
}
|
||||
if strings.Index(md, "Run the tests\n") > strings.Index(md, "Running them now.") || strings.Index(md, "All tests pass.") > strings.Index(md, "Subagent found") {
|
||||
t.Fatalf("markdown is not oldest first:\n%s", md)
|
||||
}
|
||||
for _, absent := range []string{"secret thinking", "huge tool output"} {
|
||||
if strings.Contains(md, absent) {
|
||||
t.Fatalf("markdown includes %q", absent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatExportJSONStructure(t *testing.T) {
|
||||
_, _, send := exportFixture(t, "codex")
|
||||
reply := send(protocol.Message{Type: protocol.ChatExport, ID: "x2", ChatExport: &protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "json"}})
|
||||
if reply.ChatExportFile == nil || reply.ChatExportFile.Mime != "application/json" || !strings.HasSuffix(reply.ChatExportFile.Name, ".json") {
|
||||
t.Fatalf("reply = %+v", reply)
|
||||
}
|
||||
var document chatExportDocument
|
||||
if err := json.Unmarshal([]byte(reply.ChatExportFile.Content), &document); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if document.Session.ID != exportClaudeID || document.Session.Backend != "codex" || document.Session.Harness != "Codex" || document.Session.ResumeCommand != "cd '/work/my repo' && codex resume "+exportClaudeID {
|
||||
t.Fatalf("session = %+v", document.Session)
|
||||
}
|
||||
if document.ExportedAt == "" || len(document.Messages) != 4 {
|
||||
t.Fatalf("document = %+v", document)
|
||||
}
|
||||
ids := []string{}
|
||||
for _, message := range document.Messages {
|
||||
ids = append(ids, message.ID)
|
||||
}
|
||||
if strings.Join(ids, ",") != "m1,m2,m3,m4" {
|
||||
t.Fatalf("order = %v", ids)
|
||||
}
|
||||
tool := document.Messages[2].Tools
|
||||
if len(tool) != 1 || tool[0].Name != "Bash" || tool[0].Status != "completed" || tool[0].Summary != "Run the tests" {
|
||||
t.Fatalf("tools = %+v", tool)
|
||||
}
|
||||
if document.Messages[3].Kind != protocol.ChatMessageKindAgentReport || document.Messages[0].CreatedAt != "2023-11-14T22:13:20Z" || document.Messages[0].Attachments[0] != "notes.txt" {
|
||||
t.Fatalf("messages = %+v", document.Messages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatExportRefusals(t *testing.T) {
|
||||
_, _, send := exportFixture(t, "opencode")
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
request protocol.ChatExportRequest
|
||||
want string
|
||||
}{
|
||||
{"unknown session", protocol.ChatExportRequest{SessionID: "ses_unknown", Format: "markdown"}, "is not an operator chat session"},
|
||||
{"invalid id", protocol.ChatExportRequest{SessionID: "../etc", Format: "markdown"}, "a valid chat session id is required"},
|
||||
{"bad format", protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "pdf"}, "must be markdown, json or native"},
|
||||
{"no native export", protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "native"}, "OpenCode has no native session export"},
|
||||
} {
|
||||
request := c.request
|
||||
reply := send(protocol.Message{Type: protocol.ChatExport, ID: "r-" + c.name, ChatExport: &request})
|
||||
if reply.Type != protocol.Error || !strings.Contains(reply.Error, c.want) {
|
||||
t.Fatalf("%s: reply = %+v", c.name, reply)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatExportNativeForClaude(t *testing.T) {
|
||||
_, _, send := exportFixture(t, "claude")
|
||||
reply := send(protocol.Message{Type: protocol.ChatExport, ID: "n1", ChatExport: &protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "native"}})
|
||||
file := reply.ChatExportFile
|
||||
if file == nil || file.Format != "native" || file.Name != exportClaudeID+".jsonl" || file.Content != "{}\n" || file.SessionID != exportClaudeID {
|
||||
t.Fatalf("reply = %+v", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatResumeCommandPerBackend(t *testing.T) {
|
||||
const uuid = "0b6f1c2e-1111-4222-8333-444455556666"
|
||||
for _, c := range []struct{ backend, id, dir, want string }{
|
||||
{"claude", uuid, "/work/a", "cd /work/a && claude --resume " + uuid},
|
||||
{"codex", uuid, "/work/a", "cd /work/a && codex resume " + uuid},
|
||||
{"opencode", "ses_abc123", "/work/a", "cd /work/a && opencode --session ses_abc123"},
|
||||
{"", "ses_abc123", "", "opencode --session ses_abc123"},
|
||||
{"claude", uuid, "/work/it's here", `cd '/work/it'\''s here' && claude --resume ` + uuid},
|
||||
{"pi", uuid, "/work/a", ""},
|
||||
{"claude", "not an id; rm -rf /", "/work/a", ""},
|
||||
} {
|
||||
if got := chatResumeCommand(c.backend, c.id, c.dir); got != c.want {
|
||||
t.Fatalf("%s %q: got %q want %q", c.backend, c.dir, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatSessionsCarryResumeCommand(t *testing.T) {
|
||||
store := newOperatorStore(t)
|
||||
broker := scriptedChat()
|
||||
broker.sessions = []protocol.ChatSession{{ID: exportClaudeID, Directory: "/work/a"}}
|
||||
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
||||
if err := store.RecordOperatorSession(ctx, exportClaudeID, "/work/a", "A", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetOperatorSessionBackend(ctx, exportClaudeID, "claude"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "l1"})
|
||||
reply := readUntil(t, ctx, conn, protocol.ChatSessions)
|
||||
if len(reply.ChatSessions) != 1 {
|
||||
t.Fatalf("sessions = %+v", reply.ChatSessions)
|
||||
}
|
||||
row := reply.ChatSessions[0]
|
||||
if row.ResumeCommand != "cd /work/a && claude --resume "+exportClaudeID || !row.NativeExport {
|
||||
t.Fatalf("row = %+v", row)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,7 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
|
||||
session.ClosedAt = operator.ClosedAt
|
||||
session.Starred = operator.StarredAt > 0
|
||||
session.StarredAt = operator.StarredAt
|
||||
session = withChatHandoff(session)
|
||||
response.ChatSessions = append(response.ChatSessions, session)
|
||||
}
|
||||
_ = write(response)
|
||||
|
||||
Reference in New Issue
Block a user