Merge branch 'main' into run/artifacts-collapsed

This commit is contained in:
2026-10-31 00:22:14 +00:00
7 changed files with 328 additions and 8 deletions
@@ -20,6 +20,7 @@ import '../ui/sessions/chat_adaptive.dart';
import 'chat_command_actions.dart';
import 'chat_command_palette.dart';
import 'chat_composer_controller.dart';
import '../ui/transcript/chat_attachment_frame.dart';
/// The composer's placeholder when the chat names no working directory.
const String chatComposerPlaceholder = 'Message the agent';
@@ -801,8 +802,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
clipBehavior: Clip.none,
children: [
Positioned.fill(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: ChatAttachmentFrame(
radius: BorderRadius.circular(10),
child: Image.memory(
bytes,
key: ValueKey<String>('chat-composer-thumbnail-$index'),
@@ -0,0 +1,36 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../sessions/chat_adaptive.dart';
/// Rounds an attachment thumbnail and draws a subtle hairline around it, so a
/// dark screenshot on a dark page (or a light one on a light page) still reads
/// as a separate object. The line sits over the image's edge, in the host's
/// own outline role.
class ChatAttachmentFrame extends StatelessWidget {
const ChatAttachmentFrame({
super.key,
required this.radius,
required this.child,
});
final BorderRadius radius;
final Widget child;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final line = cupertino
? CupertinoColors.separator.resolveFrom(context)
: Theme.of(context).colorScheme.outlineVariant;
return Container(
key: const Key('chat-attachment-frame'),
foregroundDecoration: BoxDecoration(
borderRadius: radius,
border: Border.all(color: line.withValues(alpha: 0.8)),
),
child: ClipRRect(borderRadius: radius, child: child),
);
}
}
@@ -4,6 +4,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../data/chat_attachment_images.dart';
import 'chat_attachment_frame.dart';
import 'chat_image_viewer.dart';
/// The largest edge a sent image's thumbnail takes in the transcript.
@@ -105,8 +106,8 @@ class _ChatAttachmentThumbnailState extends State<ChatAttachmentThumbnail> {
Widget _thumbnail(BuildContext context, Uint8List bytes) {
final ratio = MediaQuery.devicePixelRatioOf(context);
final image = ClipRRect(
borderRadius: _radius,
final image = ChatAttachmentFrame(
radius: _radius,
child: Image(
key: const Key('chat-attachment-thumbnail-image'),
// Decode at the thumbnail's size, not the photo's, while scrolling.
@@ -90,6 +90,11 @@ void main() {
find.byKey(const Key('chat-attachment-thumbnail-image')),
findsOneWidget,
);
// A hairline frames the image so it reads against the page.
final frame = tester.widget<Container>(
find.byKey(const Key('chat-attachment-frame')),
);
expect((frame.foregroundDecoration as BoxDecoration).border, isNotNull);
// No paperclip row and no base64 shown as a file name.
expect(find.byIcon(Icons.attach_file), findsNothing);
expect(find.byIcon(CupertinoIcons.paperclip), findsNothing);
+36
View File
@@ -0,0 +1,36 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_turn_activity_view.dart';
const _style = String.fromEnvironment('PROBE_STYLE', defaultValue: 'material');
/// Visual check for the streaming activity line: the pending dots beside
/// "Responding Ns" at a few text sizes, in light and dark.
void main() {
Widget line(double scale) => MediaQuery.withClampedTextScaling(
minScaleFactor: scale,
maxScaleFactor: scale,
child: const Padding(
padding: EdgeInsets.all(8),
child: ChatTurnActivityView(
parts: [
{'type': 'text', 'text': 'Partial answer'},
],
streaming: true,
),
),
);
final body = ListView(children: [line(1), line(1.5), line(2)]);
runApp(
_style == 'cupertino'
? CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(child: SafeArea(child: body)),
)
: MaterialApp(
theme: ThemeData(brightness: Brightness.dark),
home: Scaffold(body: SafeArea(child: body)),
),
);
}
+120
View File
@@ -0,0 +1,120 @@
package claude
import (
"context"
"encoding/json"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func backgroundSession(t *testing.T) (*Chat, *session) {
t.Helper()
chat := New(context.Background())
return chat, chat.sessionFor("ses_bg", t.TempDir())
}
func line(t *testing.T, value any) []byte {
t.Helper()
raw, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
return raw
}
func toolUse(t *testing.T, id, name string, input map[string]any) []byte {
return line(t, map[string]any{
"type": "assistant",
"message": map[string]any{
"id": "msg_" + id, "role": "assistant",
"content": []any{map[string]any{"type": "tool_use", "id": id, "name": name, "input": input}},
},
})
}
func toolResult(t *testing.T, id, text string) []byte {
return line(t, map[string]any{
"type": "user",
"message": map[string]any{
"role": "user",
"content": []any{map[string]any{"type": "tool_result", "tool_use_id": id, "content": text}},
},
})
}
func running(t *testing.T, chat *Chat) []protocol.ChatShell {
t.Helper()
shells, err := chat.Shells(context.Background(), "ses_bg")
if err != nil {
t.Fatal(err)
}
return shells
}
func TestBackgroundBashStaysRunningUntilItsNotification(t *testing.T) {
chat, s := backgroundSession(t)
s.handleLine(nil, toolUse(t, "toolu_bg", "Bash", map[string]any{"command": "pipelines wait 191", "run_in_background": true}))
s.handleLine(nil, toolResult(t, "toolu_bg", "Command running in background with ID: b123. Output is being written to: /tmp/b123.output"))
shells := running(t, chat)
if len(shells) != 1 || shells[0].Command != "pipelines wait 191" {
t.Fatalf("a background command must stay listed while it runs, got %+v", shells)
}
s.handleLine(nil, line(t, map[string]any{
"type": "user",
"message": map[string]any{
"role": "user",
"content": "<task-notification>\n<task-id>b123</task-id>\n<tool-use-id>toolu_bg</tool-use-id>\n" +
"<status>completed</status>\n<summary>Background command \"Wait\" completed (exit code 3)</summary>\n</task-notification>",
},
}))
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("a notified task must leave the running list, got %+v", shells)
}
s.mu.Lock()
exit := s.shells["toolu_bg"].shell.Exit
s.mu.Unlock()
if exit == nil || *exit != 3 {
t.Fatalf("the notification's exit code is recorded, got %v", exit)
}
}
func TestBackgroundAgentFinishesFromTheStructuredNotice(t *testing.T) {
chat, s := backgroundSession(t)
s.handleLine(nil, toolUse(t, "toolu_agent", "Agent", map[string]any{"description": "Review the lists", "prompt": "…"}))
s.handleLine(nil, toolResult(t, "toolu_agent", "Async agent launched successfully."))
shells := running(t, chat)
if len(shells) != 1 || shells[0].Command != "Agent: Review the lists" {
t.Fatalf("a background agent is listed by its description, got %+v", shells)
}
s.handleLine(nil, line(t, map[string]any{
"type": "system", "subtype": "task_notification",
"task_id": "a1", "tool_use_id": "toolu_agent", "status": "completed", "summary": "Agent finished",
}))
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("the structured notice finishes the agent, got %+v", shells)
}
}
func TestForegroundCommandsAndAgentsFinishWithTheirResult(t *testing.T) {
chat, s := backgroundSession(t)
s.handleLine(nil, toolUse(t, "toolu_fg", "Bash", map[string]any{"command": "ls"}))
s.handleLine(nil, toolUse(t, "toolu_sync", "Agent", map[string]any{"description": "Quick look"}))
if shells := running(t, chat); len(shells) != 2 {
t.Fatalf("both are running while their calls are open, got %+v", shells)
}
s.handleLine(nil, toolResult(t, "toolu_fg", "file.txt"))
s.handleLine(nil, toolResult(t, "toolu_sync", "Here is what I found."))
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("a foreground command or agent finishes with its result, got %+v", shells)
}
// A stray notification for an unknown or finished task changes nothing.
s.finishBackgroundTasks("<task-notification><tool-use-id>toolu_fg</tool-use-id><status>completed</status></task-notification>")
s.finishBackgroundTasks("<task-notification><tool-use-id>toolu_unknown</tool-use-id></task-notification>")
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("stray notifications list nothing, got %+v", shells)
}
}
+125 -4
View File
@@ -109,6 +109,10 @@ func (s *session) handleLine(p *process, line []byte) {
case "result":
s.handleResult(envelope)
case "system":
if envelope.Subtype == "task_notification" {
s.finishNotifiedTask(line)
return
}
s.handleSystem(envelope)
}
}
@@ -377,10 +381,23 @@ func (s *session) handleAssistant(envelope lineEnvelope) {
},
},
})
if block.Name == "Bash" {
if shell := s.recordShellLocked(block.ID, bashCommand(input)); shell != nil {
frames = append(frames, protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: shell})
var shell *protocol.ChatShell
switch block.Name {
case "Bash":
shell = s.recordShellLocked(block.ID, bashCommand(input))
if shell != nil && backgroundRequested(input) {
s.shells[block.ID].background = true
}
case "Agent", "Task":
// A subagent usually runs in the background; its immediate
// result says so, and a foreground one simply finishes.
shell = s.recordShellLocked(block.ID, agentLabel(input))
if shell != nil {
s.shells[block.ID].background = true
}
}
if shell != nil {
frames = append(frames, protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: shell})
}
}
}
@@ -400,6 +417,11 @@ func (s *session) handleUser(envelope lineEnvelope) {
return
}
blocks := decodeBlocks(body.Content)
for _, block := range blocks {
if block.Type == "text" && strings.Contains(block.Text, "<task-notification>") {
s.finishBackgroundTasks(block.Text)
}
}
for _, block := range blocks {
if block.Type != "tool_result" || block.ToolUseID == "" {
continue
@@ -447,7 +469,12 @@ func (s *session) handleUser(envelope lineEnvelope) {
if shell != nil {
var frame *protocol.ChatShell
s.mu.Lock()
if snapshot, ok := s.shells[block.ToolUseID]; ok {
if snapshot, ok := s.shells[block.ToolUseID]; ok && snapshot.background && launchedInBackground(text) {
// Started, not finished: it stays running until Claude Code
// reports the task's completion.
snapshot.output = text
snapshot.size = int64(len(text))
} else if ok {
snapshot.shell.Status = protocol.ChatShellExited
snapshot.shell.Exit = exit
if text != "" && len(text) >= len(snapshot.output) {
@@ -630,6 +657,100 @@ type shellSnapshot struct {
output string
size int64
order uint64
// background marks a command or subagent that may outlive its tool call:
// its immediate result only says it started.
background bool
}
// backgroundRequested reports a Bash call asked to run in the background.
func backgroundRequested(input json.RawMessage) bool {
var parsed struct {
Background bool `json:"run_in_background"`
}
return json.Unmarshal(input, &parsed) == nil && parsed.Background
}
// agentLabel names a subagent the way the operator recognises it.
func agentLabel(input json.RawMessage) string {
var parsed struct {
Description string `json:"description"`
Type string `json:"subagent_type"`
}
_ = json.Unmarshal(input, &parsed)
label := strings.TrimSpace(parsed.Description)
if label == "" {
label = strings.TrimSpace(parsed.Type)
}
if label == "" {
return "Agent"
}
return "Agent: " + label
}
// launchedInBackground recognises Claude Code's immediate result for a task
// that keeps running after its tool call returns.
func launchedInBackground(text string) bool {
return strings.Contains(text, "running in background with ID") ||
strings.HasPrefix(strings.TrimSpace(text), "Async agent launched")
}
var (
taskNotificationPattern = regexp.MustCompile(`(?s)<task-notification>(.*?)</task-notification>`)
taskToolUsePattern = regexp.MustCompile(`<tool-use-id>\s*([^<\s]+)\s*</tool-use-id>`)
taskSummaryPattern = regexp.MustCompile(`(?s)<summary>(.*?)</summary>`)
taskExitPattern = regexp.MustCompile(`exit code (-?\d+)`)
)
// finishNotifiedTask handles the SDK's structured completion message for a
// background task, the counterpart of the <task-notification> text.
func (s *session) finishNotifiedTask(line []byte) {
var notice struct {
ToolUseID string `json:"tool_use_id"`
Status string `json:"status"`
Summary string `json:"summary"`
}
if json.Unmarshal(line, &notice) != nil || notice.ToolUseID == "" {
return
}
s.finishBackgroundTasks(fmt.Sprintf(
"<task-notification><tool-use-id>%s</tool-use-id><status>%s</status><summary>%s</summary></task-notification>",
notice.ToolUseID, notice.Status, notice.Summary,
))
}
// finishBackgroundTasks marks the tasks a Claude Code task notification
// reports as finished, and publishes each one's final state.
func (s *session) finishBackgroundTasks(text string) {
var frames []*protocol.ChatShell
s.mu.Lock()
for _, match := range taskNotificationPattern.FindAllStringSubmatch(text, -1) {
toolID := taskToolUsePattern.FindStringSubmatch(match[1])
if toolID == nil {
continue
}
snapshot, ok := s.shells[toolID[1]]
if !ok || snapshot.shell.Status != protocol.ChatShellRunning {
continue
}
snapshot.shell.Status = protocol.ChatShellExited
if summary := taskSummaryPattern.FindStringSubmatch(match[1]); summary != nil {
line := strings.TrimSpace(summary[1])
if code := taskExitPattern.FindStringSubmatch(line); code != nil {
if exit, err := strconv.Atoi(code[1]); err == nil {
snapshot.shell.Exit = &exit
}
}
if line != "" {
snapshot.output = strings.TrimRight(snapshot.output, "\n") + "\n" + line
snapshot.size = int64(len(snapshot.output))
}
}
frames = append(frames, &protocol.ChatShell{ID: snapshot.shell.ID, Status: snapshot.shell.Status, Command: snapshot.shell.Command, Exit: snapshot.shell.Exit})
}
s.mu.Unlock()
for _, frame := range frames {
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: frame})
}
}
func shellID(toolID string) string {