-
Notifications
You must be signed in to change notification settings - Fork 417
Expand file tree
/
Copy pathapp.go
More file actions
1702 lines (1505 loc) · 57 KB
/
Copy pathapp.go
File metadata and controls
1702 lines (1505 loc) · 57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package app
import (
"cmp"
"context"
"errors"
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
tea "charm.land/bubbletea/v2"
"github.com/docker/docker-agent/pkg/app/export"
"github.com/docker/docker-agent/pkg/app/transcript"
"github.com/docker/docker-agent/pkg/chat"
"github.com/docker/docker-agent/pkg/cli"
"github.com/docker/docker-agent/pkg/config/types"
"github.com/docker/docker-agent/pkg/effort"
"github.com/docker/docker-agent/pkg/hooks/builtins"
"github.com/docker/docker-agent/pkg/runtime"
"github.com/docker/docker-agent/pkg/session"
"github.com/docker/docker-agent/pkg/sessiontitle"
"github.com/docker/docker-agent/pkg/shellpath"
"github.com/docker/docker-agent/pkg/skills"
"github.com/docker/docker-agent/pkg/tools"
skillstool "github.com/docker/docker-agent/pkg/tools/builtin/skills"
mcptools "github.com/docker/docker-agent/pkg/tools/mcp"
"github.com/docker/docker-agent/pkg/tui/messages"
)
type App struct {
ctx func() context.Context
runtime runtime.Runtime
session *session.Session
firstMessage *string
firstMessageAttach string
queuedMessages []string
events chan tea.Msg
throttleDuration time.Duration
cancel context.CancelFunc
currentAgentModel string // Tracks the current agent's model ID from AgentInfoEvent
exitAfterFirstResponse bool // Exit TUI after first assistant response completes
readOnly bool // When true, no new messages can be sent to the LLM
titleGenerating atomic.Bool // True when title generation is in progress
titleGen *sessiontitle.Generator // Title generator for local runtime (nil for remote)
snapshotController builtins.SnapshotController // Drives /undo, /snapshots, /reset; nil for runtimes that don't capture snapshots
startOnce sync.Once
subsMu sync.Mutex
subs []chan tea.Msg
fanoutOnce sync.Once
}
// Opt is an option for creating a new App.
type Opt func(*App)
// WithFirstMessage sets the first message to send.
func WithFirstMessage(msg string) Opt {
return func(a *App) {
a.firstMessage = &msg
}
}
// WithFirstMessageAttachment sets the attachment path for the first message.
func WithFirstMessageAttachment(path string) Opt {
return func(a *App) {
a.firstMessageAttach = path
}
}
// WithExitAfterFirstResponse configures the app to exit after the first assistant response.
func WithExitAfterFirstResponse() Opt {
return func(a *App) {
a.exitAfterFirstResponse = true
}
}
// WithQueuedMessages sets messages to be queued after the first message is sent.
// These messages will be delivered to the TUI as SendMsg events, which the
// chat page will queue and process sequentially after each agent response.
func WithQueuedMessages(msgs []string) Opt {
return func(a *App) {
a.queuedMessages = msgs
}
}
// WithTitleGenerator sets the title generator for local title generation.
// If not set, title generation will be handled by the runtime (for remote) or skipped.
func WithTitleGenerator(gen *sessiontitle.Generator) Opt {
return func(a *App) {
a.titleGen = gen
}
}
// WithReadOnly marks the session as read-only: the conversation history
// is displayed but no new messages can be sent to the LLM.
func WithReadOnly() Opt {
return func(a *App) {
a.readOnly = true
}
}
// WithSnapshotController plumbs in the [builtins.SnapshotController]
// the App uses to drive /undo, /snapshots, /reset. Pass the same
// controller to the runtime via runtime.WithAutoInjector so the
// instance that captures the checkpoints is the one the TUI commands
// drive. Pass nil (or omit the option) for runtimes that don't capture
// snapshots; the App then reports SnapshotsEnabled()==false and the
// related commands silently no-op.
func WithSnapshotController(c builtins.SnapshotController) Opt {
return func(a *App) {
a.snapshotController = c
}
}
func New(ctx context.Context, rt runtime.Runtime, sess *session.Session, opts ...Opt) *App {
app := &App{
ctx: func() context.Context { return context.WithoutCancel(ctx) },
runtime: rt,
session: sess,
events: make(chan tea.Msg, 128),
throttleDuration: 50 * time.Millisecond, // Throttle rapid events
}
for _, opt := range opts {
opt(app)
}
return app
}
// Start begins App-owned background event producers. Construction stays cheap
// and side-effect free; embedders call Start when the App enters a managed
// lifecycle.
func (a *App) Start(ctx context.Context) {
a.startOnce.Do(func() {
// Emit startup info (agent, team, tools) through the events channel.
// This runs in the background so the TUI can start immediately while
// slow operations (like MCP tool loading) complete asynchronously.
go func() {
startupEvents := make(chan runtime.Event, 10)
go func() {
defer close(startupEvents)
a.runtime.EmitStartupInfo(ctx, a.session, runtime.NewChannelSink(startupEvents))
}()
for event := range startupEvents {
select {
case a.events <- event:
case <-ctx.Done():
return
}
}
}()
// Subscribe to tool list changes so the sidebar updates immediately
// when an MCP server adds or removes tools (outside of a RunStream).
a.runtime.OnToolsChanged(func(event runtime.Event) {
select {
case a.events <- event:
case <-ctx.Done():
}
})
// Forward events surfaced from detached background work (token usage
// from background agent tasks) so the sidebar and agent inspector can
// account for background agents' context usage.
a.runtime.OnBackgroundEvent(func(event runtime.Event) {
select {
case a.events <- event:
case <-ctx.Done():
}
})
})
}
func (a *App) SendFirstMessage() tea.Cmd {
if a.firstMessage == nil {
return nil
}
cmds := []tea.Cmd{
func() tea.Msg {
// Use the shared PrepareUserMessage function for consistent attachment handling
userMsg, attachedPath, err := cli.PrepareUserMessage(a.ctx(), a.runtime, *a.firstMessage, a.firstMessageAttach)
if err != nil {
slog.Error("Failed to prepare first message", "error", err)
return nil
}
if userMsg == nil {
// Agent-only command with no content - agent switched but no message to send
return nil
}
// Inherit the attachment in any sub-session created by this turn.
a.session.AddAttachedFile(attachedPath)
// If the message has multi-content (attachments), we need to handle it specially
if len(userMsg.Message.MultiContent) > 0 {
return messages.SendAttachmentMsg{
Content: userMsg,
}
}
return messages.SendMsg{
Content: userMsg.Message.Content,
}
},
}
// Queue additional messages to be sent after the first one.
// The TUI's message queue will hold them until the agent finishes
// processing the previous message.
for _, msg := range a.queuedMessages {
cmds = append(cmds, func() tea.Msg {
return messages.SendMsg{
Content: msg,
}
})
}
return tea.Sequence(cmds...)
}
// CurrentAgentTools returns the tools available to the current agent.
func (a *App) CurrentAgentTools(ctx context.Context) ([]tools.Tool, error) {
return a.runtime.CurrentAgentTools(ctx)
}
// agentConfigProvider is an optional runtime capability: exposing an agent's
// static configuration (toolsets, sub-agents, handoffs, fallbacks) by name.
// Only the local runtime (which holds the team) implements it; remote runtimes
// don't, so the agent-details config sections are simply omitted for them.
type agentConfigProvider interface {
AgentConfigInfo(ctx context.Context, agentName string) runtime.AgentConfigInfo
}
// AgentConfigInfo returns the named agent's static configuration for the
// read-only agent-details dialog, or the zero value when it can't be resolved
// (remote runtime or unknown agent). It reads resolved config only and starts
// no toolsets.
func (a *App) AgentConfigInfo(ctx context.Context, agentName string) runtime.AgentConfigInfo {
cp, ok := a.runtime.(agentConfigProvider)
if !ok {
return runtime.AgentConfigInfo{}
}
return cp.AgentConfigInfo(ctx, agentName)
}
// CurrentAgentToolsetStatuses returns lifecycle status for each toolset of
// the active agent.
func (a *App) CurrentAgentToolsetStatuses() []tools.ToolsetStatus {
return a.runtime.CurrentAgentToolsetStatuses()
}
// RestartToolset triggers a supervisor-driven restart of the named toolset.
func (a *App) RestartToolset(ctx context.Context, name string) error {
return a.runtime.RestartToolset(ctx, name)
}
// CurrentAgentCommands returns the commands for the active agent
func (a *App) CurrentAgentCommands(ctx context.Context) types.Commands {
return a.runtime.CurrentAgentInfo(ctx).Commands
}
// CurrentAgentSkills returns the available skills if skills are enabled for the current agent.
func (a *App) CurrentAgentSkills() []skills.Skill {
st := a.runtime.CurrentAgentSkillsToolset()
if st == nil {
return nil
}
return st.Skills()
}
// ResolveSkillCommand checks if the input matches a skill slash command (e.g. /skill-name args).
// If matched, it reads the skill content and returns the resolved prompt. Otherwise returns "".
//
// Fork-mode skills are NOT resolved here; chat dispatches them via
// SkillCommandFork + RunSkillFork to keep the parent transcript clean.
func (a *App) ResolveSkillCommand(ctx context.Context, input string) (string, error) {
if !strings.HasPrefix(input, "/") {
return "", nil
}
st := a.runtime.CurrentAgentSkillsToolset()
if st == nil {
return "", nil
}
cmd, arg, _ := strings.Cut(input[1:], " ")
arg = strings.TrimSpace(arg)
for _, skill := range st.Skills() {
if skill.Name != cmd {
continue
}
if skill.IsFork() {
// Fall through to ResolveCommand for non-chat callers; the
// chat layer already routed fork-mode skills via
// SkillCommandFork before reaching this point.
return "", nil
}
content, err := st.ReadSkillContent(ctx, skill.Name)
if err != nil {
return "", fmt.Errorf("reading skill %q: %w", skill.Name, err)
}
if arg != "" {
return fmt.Sprintf("Use the following skill.\n\nUser's request: %s\n\n<skill name=%q>\n%s\n</skill>", arg, skill.Name, content), nil
}
return fmt.Sprintf("Use the following skill.\n\n<skill name=%q>\n%s\n</skill>", skill.Name, content), nil
}
return "", nil
}
// SkillCommandFork returns (skillName, task, true) when input is a slash
// command for a `context: fork` skill, otherwise (_, _, false). Chat layers
// must call this before ResolveInput and route to RunSkillFork on a hit.
func (a *App) SkillCommandFork(_ context.Context, input string) (skillName, task string, ok bool) {
if !strings.HasPrefix(input, "/") {
return "", "", false
}
st := a.runtime.CurrentAgentSkillsToolset()
if st == nil {
return "", "", false
}
cmd, arg, _ := strings.Cut(input[1:], " ")
arg = strings.TrimSpace(arg)
for _, skill := range st.Skills() {
if skill.Name != cmd {
continue
}
if !skill.IsFork() {
return "", "", false
}
return skill.Name, arg, true
}
return "", "", false
}
// RunSkillFork dispatches a fork-mode skill in an isolated sub-session of
// the current parent. The parent gains a SubSession item once the runtime
// opens the child; the sub-session's first user message is the expanded
// SKILL.md body. Companion of SkillCommandFork.
func (a *App) RunSkillFork(ctx context.Context, cancel context.CancelFunc, skillName, task string, _ []messages.Attachment) {
a.cancel = cancel
// Mirrors App.Run's drain loop: forward events to the App bus and
// always let StreamStoppedEvent through, even after ctx cancellation,
// so the supervisor marks the session idle.
go func() {
events := make(chan runtime.Event, defaultRuntimeEventBuffer)
go func() {
defer close(events)
result, err := a.runtime.RunSkillFork(ctx, a.session, skillstool.RunSkillArgs{
Name: skillName,
Task: task,
}, runtime.NewChannelSink(events))
switch {
case errors.Is(err, runtime.ErrUnsupported):
slog.WarnContext(ctx, "Runtime does not support fork-mode skills; skill not executed", "skill", skillName)
a.sendEvent(ctx, runtime.Error(fmt.Sprintf("Skill %q cannot run: this runtime does not support fork-mode skills.", skillName)))
case err != nil:
slog.ErrorContext(ctx, "Failed to run fork-mode skill", "skill", skillName, "error", err)
a.sendEvent(ctx, runtime.Error(fmt.Sprintf("Skill %q failed: %v", skillName, err)))
case result != nil && result.IsError:
a.sendEvent(ctx, runtime.Error(result.Output))
}
}()
for event := range events {
if ctx.Err() != nil {
if _, ok := event.(*runtime.StreamStoppedEvent); ok {
// ctx is cancelled; detach cancellation but keep its trace
// context so the stop event still reaches subscribers.
a.sendEvent(context.WithoutCancel(ctx), event)
}
continue
}
a.sendEvent(ctx, event)
}
}()
}
// defaultRuntimeEventBuffer matches Summarize and Runtime.RunStream;
// wide enough that a fork-skill sub-session won't block the producer.
const defaultRuntimeEventBuffer = 100
// ResolveInput resolves the user input by trying skill commands first,
// then agent commands. Returns the resolved content ready to send to the agent.
func (a *App) ResolveInput(ctx context.Context, input string) string {
if resolved, err := a.ResolveSkillCommand(ctx, input); err != nil {
return fmt.Sprintf("Error loading skill: %v", err)
} else if resolved != "" {
return resolved
}
return a.ResolveCommand(ctx, input)
}
// CurrentAgentModel returns the model ID for the current agent.
// Returns the tracked model from AgentInfoEvent, or falls back to session overrides.
// Returns empty string if no model information is available (fail-open scenario).
func (a *App) CurrentAgentModel(ctx context.Context) string {
if a.currentAgentModel != "" {
return a.currentAgentModel
}
// Fallback to session overrides
if a.session != nil && a.session.AgentModelOverrides != nil {
agentName := a.runtime.CurrentAgentName(ctx)
if modelRef, ok := a.session.AgentModelOverrides[agentName]; ok {
return modelRef
}
}
return ""
}
// TrackCurrentAgentModel updates the tracked model ID for the current agent.
// This is called when AgentInfoEvent is received from the runtime.
func (a *App) TrackCurrentAgentModel(model string) {
a.currentAgentModel = model
}
// CurrentMCPPrompts returns the available MCP prompts for the active agent
func (a *App) CurrentMCPPrompts(ctx context.Context) map[string]mcptools.PromptInfo {
return a.runtime.CurrentMCPPrompts(ctx)
}
// ExecuteMCPPrompt executes an MCP prompt with provided arguments and returns the content
func (a *App) ExecuteMCPPrompt(ctx context.Context, promptName string, arguments map[string]string) (string, error) {
return a.runtime.ExecuteMCPPrompt(ctx, promptName, arguments)
}
// ResolveCommand converts /command to its prompt text
func (a *App) ResolveCommand(ctx context.Context, userInput string) string {
return runtime.ResolveCommand(ctx, a.runtime, userInput)
}
// LookupCommand parses userInput as a /command invocation and returns the
// matching command, the trailing arguments, and whether a match was found.
// Callers that want to act on command metadata (for example switching to a
// sub-agent declared via the `agent:` field) should call this before
// ResolveCommand to inspect the raw command.
func (a *App) LookupCommand(ctx context.Context, userInput string) (types.Command, string, bool) {
return runtime.LookupCommand(ctx, a.runtime, userInput)
}
// EmitStartupInfo emits initial agent, team, and toolset information to the provided channel
func (a *App) EmitStartupInfo(ctx context.Context, events chan runtime.Event) {
a.runtime.EmitStartupInfo(ctx, a.session, runtime.NewChannelSink(events))
}
// Run one agent loop
func (a *App) Run(ctx context.Context, cancel context.CancelFunc, message string, attachments []messages.Attachment) {
a.cancel = cancel
// If this is the first message and no title exists, start local title generation
if a.session.Title == "" && a.titleGen != nil {
a.titleGenerating.Store(true)
go a.generateTitle(ctx, []string{message})
}
go func() {
if len(attachments) > 0 {
// Build a single text string with the user's message and inlined text files.
// Keeping everything in one text block ensures the model sees file content
// together with the message, rather than as separate content blocks.
var textBuilder strings.Builder
textBuilder.WriteString(message)
// binaryParts holds non-text file parts (images, PDFs, etc.)
var binaryParts []chat.MessagePart
for _, att := range attachments {
switch {
case att.FilePath != "":
// File-reference attachment: read and classify from disk.
// Only remember the path on the session when the file actually
// exists as a regular file — we don't want sub-agents to inherit
// dangling references to directories or missing paths. The editor
// resolves @-mentions to absolute paths before this point.
if a.processFileAttachment(ctx, att, &textBuilder, &binaryParts) {
a.session.AddAttachedFile(att.FilePath)
}
case att.Content != "":
// Inline content attachment (e.g. pasted text).
a.processInlineAttachment(att, &textBuilder)
default:
slog.DebugContext(ctx, "skipping attachment with no file path or content", "name", att.Name)
}
}
multiContent := []chat.MessagePart{
{Type: chat.MessagePartTypeText, Text: textBuilder.String()},
}
multiContent = append(multiContent, binaryParts...)
a.session.AddMessage(session.UserMessage(message, multiContent...))
} else {
a.session.AddMessage(session.UserMessage(message))
}
for event := range a.runtime.RunStream(ctx, a.session) {
// If context is cancelled, continue draining but don't forward events
// — except StreamStoppedEvent, which must always propagate so the
// supervisor can mark the session as no longer running.
if ctx.Err() != nil {
if _, ok := event.(*runtime.StreamStoppedEvent); ok {
// ctx is cancelled; detach cancellation but keep its trace
// context so the stop event still reaches subscribers.
a.sendEvent(context.WithoutCancel(ctx), event)
}
continue
}
// Clear titleGenerating flag when title is generated (from server for remote runtime)
if _, ok := event.(*runtime.SessionTitleEvent); ok {
a.titleGenerating.Store(false)
}
a.sendEvent(ctx, event)
}
}()
}
// processFileAttachment reads a file from disk, classifies it, and either
// appends its text content to textBuilder or adds a binary part to binaryParts.
// Returns true when the path resolved to a real, regular file that we attempted
// to surface to the model — even if the content itself was rejected (too
// large, unsupported MIME, transient read error, etc.). The boolean is meant
// for callers that want to record the path on the session for later reuse by
// sub-agents; we don't want those references to point at directories or
// missing files, but we do want them to cover "the agent has bigger tools
// than us" cases.
func (a *App) processFileAttachment(ctx context.Context, att messages.Attachment, textBuilder *strings.Builder, binaryParts *[]chat.MessagePart) bool {
absPath := att.FilePath
fi, err := os.Stat(absPath)
if err != nil {
var reason string
switch {
case os.IsNotExist(err):
reason = "file does not exist"
case os.IsPermission(err):
reason = "permission denied"
default:
reason = fmt.Sprintf("cannot access file: %v", err)
}
slog.WarnContext(ctx, "skipping attachment", "path", absPath, "reason", reason)
a.sendEvent(ctx, runtime.Warning(fmt.Sprintf("Skipped attachment %s: %s", att.Name, reason), ""))
return false
}
if !fi.Mode().IsRegular() {
slog.WarnContext(ctx, "skipping attachment: not a regular file", "path", absPath, "mode", fi.Mode().String())
a.sendEvent(ctx, runtime.Warning(fmt.Sprintf("Skipped attachment %s: not a regular file", att.Name), ""))
return false
}
const maxAttachmentSize = 100 * 1024 * 1024 // 100MB
if fi.Size() > maxAttachmentSize {
slog.WarnContext(ctx, "skipping attachment: file too large", "path", absPath, "size", fi.Size(), "max", maxAttachmentSize)
a.sendEvent(ctx, runtime.Warning(fmt.Sprintf("Skipped attachment %s: file too large (max 100MB)", att.Name), ""))
return true
}
mimeType := chat.DetectMimeType(absPath)
switch {
case chat.IsTextFile(absPath):
if fi.Size() > chat.MaxInlineFileSize {
slog.WarnContext(ctx, "skipping attachment: text file too large to inline", "path", absPath, "size", fi.Size(), "max", chat.MaxInlineFileSize)
a.sendEvent(ctx, runtime.Warning(fmt.Sprintf("Skipped attachment %s: text file too large to inline (max 5MB)", att.Name), ""))
return true
}
content, err := chat.ReadFileForInline(absPath)
if err != nil {
slog.WarnContext(ctx, "skipping attachment: failed to read file", "path", absPath, "error", err)
a.sendEvent(ctx, runtime.Warning(fmt.Sprintf("Skipped attachment %s: failed to read file", att.Name), ""))
return true
}
textBuilder.WriteString("\n\n")
textBuilder.WriteString(content)
case chat.IsSupportedMimeType(mimeType):
// Route through ProcessAttachmentWithMetadata for normalised Document output.
// For images this also returns resize metadata used to emit a dimension note.
doc, resizeMeta, procErr := chat.ProcessAttachmentWithMetadata(chat.MessagePart{
Type: chat.MessagePartTypeFile,
File: &chat.MessageFile{Path: absPath, MimeType: mimeType},
})
if procErr != nil {
slog.WarnContext(ctx, "skipping attachment: processing failed", "path", absPath, "error", procErr)
a.sendEvent(ctx, runtime.Warning(fmt.Sprintf("Skipped attachment %s: %s", att.Name, procErr), ""))
return true
}
// For images, emit a dimension note so the model can map coordinates back to the original.
if resizeMeta != nil {
if note := chat.FormatDimensionNote(resizeMeta); note != "" {
textBuilder.WriteString("\n" + note)
}
}
*binaryParts = append(*binaryParts, chat.MessagePart{
Type: chat.MessagePartTypeDocument,
Document: &doc,
})
default:
slog.WarnContext(ctx, "skipping attachment: unsupported file type", "path", absPath, "mime_type", mimeType)
a.sendEvent(ctx, runtime.Warning(fmt.Sprintf("Skipped attachment %s: unsupported file type", att.Name), ""))
}
return true
}
// sendEvent sends an event to the TUI, respecting context cancellation to
// avoid blocking on the channel when the consumer has stopped reading.
func (a *App) sendEvent(ctx context.Context, event tea.Msg) {
select {
case a.events <- event:
case <-ctx.Done():
}
}
// processInlineAttachment handles content that is already in memory (e.g. pasted
// text). The content is appended to textBuilder wrapped in an XML tag for context.
func (a *App) processInlineAttachment(att messages.Attachment, textBuilder *strings.Builder) {
textBuilder.WriteString("\n\n")
fmt.Fprintf(textBuilder, "<attached_file path=%q>\n%s\n</attached_file>", att.Name, att.Content)
}
// Retry re-runs the agent loop on the current session without adding a new
// user message. It is used to resume the conversation after an error: the
// session already holds the messages exchanged so far, so RunStream picks up
// from where it left off.
//
// RunStream re-emits a UserMessageEvent for the trailing session message at
// startup (before StreamStarted) whenever SendUserMessage is set. On retry
// that message is already displayed, so forwarding the re-emission would
// duplicate the user bubble — or, when the tail is a tool/assistant message,
// render non-user content inside a spurious user bubble. We suppress any
// UserMessageEvent observed before StreamStarted to drop exactly that
// re-emission; genuine user messages injected mid-run (steer / follow-up)
// arrive after StreamStarted and are forwarded normally.
func (a *App) Retry(ctx context.Context, cancel context.CancelFunc) {
a.cancel = cancel
go func() {
streamStarted := false
for event := range a.runtime.RunStream(ctx, a.session) {
// If context is cancelled, continue draining but don't forward events
// — except StreamStoppedEvent, which must always propagate so the
// supervisor can mark the session as no longer running.
if ctx.Err() != nil {
if _, ok := event.(*runtime.StreamStoppedEvent); ok {
a.sendEvent(context.WithoutCancel(ctx), event)
}
continue
}
switch event.(type) {
case *runtime.StreamStartedEvent:
streamStarted = true
case *runtime.UserMessageEvent:
if !streamStarted {
continue
}
}
if _, ok := event.(*runtime.SessionTitleEvent); ok {
a.titleGenerating.Store(false)
}
a.sendEvent(ctx, event)
}
}()
}
// RunWithMessage runs the agent loop with a pre-constructed message.
// This is used for special cases like image attachments.
func (a *App) RunWithMessage(ctx context.Context, cancel context.CancelFunc, msg *session.Message) {
a.cancel = cancel
// If this is the first message and no title exists, start local title generation
if a.session.Title == "" && a.titleGen != nil {
a.titleGenerating.Store(true)
// Extract text content from the message for title generation
userMessage := msg.Message.Content
if userMessage == "" && len(msg.Message.MultiContent) > 0 {
for _, part := range msg.Message.MultiContent {
if part.Type == chat.MessagePartTypeText {
userMessage = part.Text
break
}
}
}
go a.generateTitle(ctx, []string{userMessage})
}
go func() {
a.session.AddMessage(msg)
for event := range a.runtime.RunStream(ctx, a.session) {
// If context is cancelled, continue draining but don't forward events
// — except StreamStoppedEvent, which must always propagate so the
// supervisor can mark the session as no longer running.
if ctx.Err() != nil {
if _, ok := event.(*runtime.StreamStoppedEvent); ok {
// ctx is cancelled; detach cancellation but keep its trace
// context so the stop event still reaches subscribers.
a.sendEvent(context.WithoutCancel(ctx), event)
}
continue
}
// Clear titleGenerating flag when title is generated (from server for remote runtime)
if _, ok := event.(*runtime.SessionTitleEvent); ok {
a.titleGenerating.Store(false)
}
a.sendEvent(ctx, event)
}
}()
}
func (a *App) RunBangCommand(ctx context.Context, command string) {
command = strings.TrimSpace(command)
if command == "" {
a.events <- runtime.ShellOutput("Error: empty command")
return
}
shell, argsPrefix := shellpath.DetectShell()
out, err := exec.CommandContext(ctx, shell, append(argsPrefix, command)...).CombinedOutput()
output := "$ " + command + "\n" + string(out)
if err != nil && len(out) == 0 {
output = "$ " + command + "\nError: " + err.Error()
}
a.events <- runtime.ShellOutput(output)
}
// InjectUserMessage feeds content into the app exactly as if the user had
// typed and submitted it in the TUI. It is the entry point external drivers
// (the --listen control plane) use to send follow-up prompts: routing through
// the normal SendMsg path means the message is queued when the agent is busy,
// triggers title generation on the first turn, and — crucially — starts a
// RunStream whose events flow through a.events to every subscriber (the TUI
// and any SSE consumer). Enqueuing into the runtime's follow-up queue instead
// would do nothing while the agent is idle, since that queue is only drained
// mid-stream.
//
// SendMsg is a TUI message, not a runtime.Event, so SSE subscribers (which
// forward only runtime.Events) ignore it; it reaches the TUI program alone.
func (a *App) InjectUserMessage(ctx context.Context, content string) {
a.sendEvent(ctx, messages.SendMsg{Content: content})
}
// SubscribeWith subscribes to app events using a custom send function.
// Multiple concurrent subscribers are supported: a single fan-out goroutine
// drains the throttled event stream and dispatches a copy to each one.
// Slow subscribers drop events rather than block the bus.
func (a *App) SubscribeWith(ctx context.Context, send func(tea.Msg)) {
ch := make(chan tea.Msg, subscriberBufferSize)
a.addSubscriber(ch)
defer a.removeSubscriber(ch)
a.fanoutOnce.Do(a.startFanOut)
for {
select {
case <-ctx.Done():
return
case msg := <-ch:
send(msg)
}
}
}
const subscriberBufferSize = 1024
func (a *App) addSubscriber(ch chan tea.Msg) {
a.subsMu.Lock()
defer a.subsMu.Unlock()
a.subs = append(a.subs, ch)
}
func (a *App) removeSubscriber(ch chan tea.Msg) {
a.subsMu.Lock()
defer a.subsMu.Unlock()
a.subs = slices.DeleteFunc(a.subs, func(c chan tea.Msg) bool { return c == ch })
}
// startFanOut runs once per App. It throttles the raw events channel and
// scatters every message to all currently-registered subscribers. Sends are
// non-blocking; if a subscriber's buffer is full the event is dropped for
// that subscriber so one slow consumer cannot stall the others.
//
// Turn-boundary events are the exception: dropping a stream_started or
// stream_stopped skews a consumer's turn accounting for good (the SSE replay
// buffer never sees the event, so reconnecting cannot recover it). For those,
// the oldest pending message — almost always a content delta, which the next
// delta supersedes — is evicted to make room instead.
func (a *App) startFanOut() {
throttled := a.throttleEvents(a.ctx(), a.events)
go func() {
for msg := range throttled {
a.subsMu.Lock()
subs := slices.Clone(a.subs)
a.subsMu.Unlock()
for _, ch := range subs {
select {
case ch <- msg:
default:
if !isTurnBoundaryEvent(msg) {
slog.Warn("app: subscriber buffer full, dropping event")
continue
}
// Evict the oldest pending message (racing the subscriber's
// own receive is fine: either way a slot frees up), then
// retry once. Still full means the subscriber is wedged;
// drop as before rather than block the fan-out.
select {
case <-ch:
default:
}
select {
case ch <- msg:
default:
slog.Warn("app: subscriber buffer full, dropping turn-boundary event")
}
}
}
}
}()
}
// isTurnBoundaryEvent reports whether msg is one of the events consumers use
// to track turn state (running/waiting/failed/paused) and identity (title).
// These are low-frequency and irrecoverable when lost, unlike the content
// deltas that dominate the stream, so the fan-out prefers them on overflow.
func isTurnBoundaryEvent(msg tea.Msg) bool {
switch msg.(type) {
case *runtime.StreamStartedEvent,
*runtime.StreamStoppedEvent,
*runtime.UserMessageEvent,
*runtime.ErrorEvent,
*runtime.PausedEvent,
*runtime.SessionTitleEvent:
return true
default:
return false
}
}
// Resume resumes the runtime with the given confirmation request
func (a *App) Resume(req runtime.ResumeRequest) {
a.runtime.Resume(a.ctx(), req)
}
// Steer queues a user message for mid-turn injection into the running agent.
func (a *App) Steer(ctx context.Context, msg runtime.QueuedMessage) error {
return a.runtime.Steer(ctx, msg)
}
// TogglePause toggles whether the runtime loop is paused at iteration
// boundaries. The second return value is false if the underlying runtime
// doesn't support pausing (e.g. remote runtimes), in which case the first
// return value is meaningless.
func (a *App) TogglePause() (paused, supported bool) {
p, err := a.runtime.TogglePause(a.ctx())
if errors.Is(err, runtime.ErrUnsupported) {
return false, false
}
if err != nil {
slog.Error("Failed to toggle pause", "error", err)
return false, false
}
return p, true
}
// ResumeElicitation resumes an elicitation request with the given action and content
func (a *App) ResumeElicitation(ctx context.Context, action tools.ElicitationAction, content map[string]any) error {
return a.runtime.ResumeElicitation(ctx, action, content)
}
func (a *App) NewSession() {
if a.cancel != nil {
a.cancel()
a.cancel = nil
}
// Preserve user-controlled session flags
// so they don't reset to default on /new
var opts []session.Opt
if a.session != nil {
opts = append(opts,
session.WithToolsApproved(a.session.ToolsApproved),
session.WithHideToolResults(a.session.HideToolResults),
session.WithWorkingDir(a.session.WorkingDir),
)
}
a.session = session.New(opts...)
// Clear first message so it won't be re-sent on re-init
a.firstMessage = nil
a.firstMessageAttach = ""
// Re-emit startup info so the sidebar shows agent/tools info in the new session
a.reEmitStartupInfo(a.ctx())
}
// reEmitStartupInfo resets and re-emits startup info (agent, team, tools)
// through the events channel so the sidebar updates.
func (a *App) reEmitStartupInfo(ctx context.Context) {
a.runtime.ResetStartupInfo()
a.pumpToEvents(ctx, func(sink runtime.EventSink) {
a.runtime.EmitStartupInfo(ctx, a.session, sink)
})
}
// pumpToEvents runs emit (which produces events into the supplied sink) in a
// background goroutine and forwards everything it emits to the app's events
// channel, without blocking the caller.
func (a *App) pumpToEvents(ctx context.Context, emit func(runtime.EventSink)) {
go func() {
ch := make(chan runtime.Event, 10)
go func() {
defer close(ch)
emit(runtime.NewChannelSink(ch))
}()
for event := range ch {
select {
case a.events <- event:
case <-ctx.Done():
return
default:
}
}
}()
}
func (a *App) Session() *session.Session {
return a.session
}
// contextBreakdownProvider is an optional runtime capability: computing the
// estimated context-window composition for a session. Only the local runtime
// (which holds the agent and its tools) implements it; remote runtimes
// don't, so the /context dialog reports the feature as unavailable.
type contextBreakdownProvider interface {
ContextBreakdown(ctx context.Context, sess *session.Session) (*runtime.ContextBreakdown, error)
}
// ContextBreakdown returns the estimated context-window composition for the
// current session. Returns an error wrapping [runtime.ErrUnsupported] when
// the runtime cannot compute it (e.g. remote runtimes).
func (a *App) ContextBreakdown(ctx context.Context) (*runtime.ContextBreakdown, error) {
cp, ok := a.runtime.(contextBreakdownProvider)
if !ok {
return nil, fmt.Errorf("context breakdown: %w", runtime.ErrUnsupported)
}
return cp.ContextBreakdown(ctx, a.Session())
}
// DropAttachedFile removes a file from the current session's attached files
// and returns the absolute path that was dropped. The path is resolved
// against the session's attachment list: exact match first, then the
// absolute form of a relative path, then a unique base-name match. Dropping
// stops the file from being propagated to future sub-agent delegations and
// skill prompts; content already inlined in past messages is unaffected.
//
// Attached files are in-memory session state (recording them never touches
// the store either), so the store sync afterwards is best-effort: it only
// refreshes stores that snapshot the attachment list and a failure does not
// undo the drop.
func (a *App) DropAttachedFile(ctx context.Context, path string) (string, error) {
sess := a.Session()
if sess == nil {
return "", errors.New("no active session")
}
resolved, err := resolveAttachedFile(sess.AttachedFilesSnapshot(), path)
if err != nil {
return "", err
}
if !sess.RemoveAttachedFile(resolved) {
return "", fmt.Errorf("file is not attached to this session: %s", resolved)
}
if store := a.runtime.SessionStore(); store != nil {
if err := store.UpdateSession(ctx, sess); err != nil {
slog.WarnContext(ctx, "Failed to sync session store after dropping attachment", "session_id", sess.ID, "path", resolved, "error", err)
}