-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcompat.go
More file actions
622 lines (546 loc) · 17.7 KB
/
compat.go
File metadata and controls
622 lines (546 loc) · 17.7 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
package slagent
import (
"fmt"
"io"
"strings"
"sync"
"time"
slackapi "github.com/slack-go/slack"
)
const (
maxBlockTextLen = 3000
maxDisplayLines = 6
compatThrottleMs = 1000
)
// compatTurn implements turnWriter using postMessage/update for session/user tokens.
// Thinking + tools + status share a single "activity" message (≤6 lines, updated in-place).
// Text streams in a separate message (last 6 lines while streaming, full text on finish).
// No messages are ever deleted.
type compatTurn struct {
api *slackapi.Client
channel string
threadTS string
blockID string // slagent block_id for message tagging
emoji string // identity emoji prefix for text messages
thinkingEmoji string // Slack shortcode for thinking/running indicator
slackLog io.Writer // optional Slack API logger
// Unified activity message (thinking + tools + status)
thinkBuf strings.Builder // accumulated thinking text
activities []string // discrete lines: tools, status
toolIndex map[string]int // tool ID → index in activities
activityTS string // single message timestamp
actUpdate time.Time // throttle
activityTimer *time.Timer // debounce timer for activity flush
activityDeleted bool // activity was deleted by text; don't recreate
// Text streaming — progressive message chain.
// Frozen messages contain finalized text with block_id.
// The last message shows a scrolling tail with streaming block_id (~).
textBuf strings.Builder
textFrozenLen int // bytes of textBuf in frozen (completed) messages
textPrefix string // prepended to next chunk (e.g. "```\n" to reopen a code fence)
textMsgs []string // timestamps: frozen messages + current streaming message
textUpdate time.Time
textTimer *time.Timer // debounce timer for text flush
question bool // replace trailing ? with ❓ on finish
qPrefix string // prepended to text on finish (e.g. "@user: ")
plainText bool // wrap text in code block instead of mrkdwn conversion
mu sync.Mutex
}
func newCompatTurn(api *slackapi.Client, channel, threadTS, blockID, emoji, thinkingEmoji string, slackLog io.Writer) *compatTurn {
return &compatTurn{
api: api,
channel: channel,
threadTS: threadTS,
blockID: blockID,
emoji: emoji,
thinkingEmoji: thinkingEmoji,
slackLog: slackLog,
toolIndex: make(map[string]int),
}
}
// logSlack writes a Slack API action to the log writer. Must be called with lock held.
func (c *compatTurn) logSlack(action, content string) {
if c.slackLog == nil {
return
}
fmt.Fprintf(c.slackLog, "[slack] %s: %s\n", action, content)
}
// renderActivity builds the activity message content from thinking + activity lines,
// keeping at most maxDisplayLines. Must be called with lock held.
func (c *compatTurn) renderActivity() string {
var lines []string
// Thinking indicator: only shown before tools appear.
// Once tools are active they carry their own :claude: spinner.
if c.thinkBuf.Len() > 0 && len(c.activities) == 0 {
lines = append(lines, c.emoji+c.thinkingEmoji)
thinkText := c.thinkBuf.String()
if len(thinkText) > 500 {
thinkText = "…" + thinkText[len(thinkText)-499:]
}
for _, l := range strings.Split(thinkText, "\n") {
lines = append(lines, " "+l)
}
}
// Activity lines (tools, status).
// Only one :claude: spinner visible at a time (the last running tool),
// unless in question mode where all spinners are shown.
if c.question {
lines = append(lines, c.activities...)
} else {
// Find the last line with a running spinner
lastSpinner := -1
for i := len(c.activities) - 1; i >= 0; i-- {
if strings.HasPrefix(c.activities[i], c.thinkingEmoji+" ") {
lastSpinner = i
break
}
}
for i, line := range c.activities {
// Demote earlier running spinners to "⋯"
if i != lastSpinner && strings.HasPrefix(line, c.thinkingEmoji+" ") {
lines = append(lines, "⋯"+line[len(c.thinkingEmoji):])
} else {
lines = append(lines, line)
}
}
}
// Keep last maxDisplayLines
if len(lines) > maxDisplayLines {
lines = lines[len(lines)-maxDisplayLines:]
}
return strings.Join(lines, "\n")
}
// flushActivity posts or updates the unified activity message. Must be called with lock held.
func (c *compatTurn) flushActivity() {
// Throttle to 1/sec
if c.activityTS != "" && time.Since(c.actUpdate) < time.Duration(compatThrottleMs)*time.Millisecond {
c.scheduleActivityFlush()
return
}
c.stopActivityTimer()
c.postActivity()
}
// postActivity posts or updates the activity message. Must be called with lock held.
func (c *compatTurn) postActivity() {
if c.activityDeleted {
return
}
display := c.renderActivity()
if display == "" {
return
}
// Activity messages use ~act suffix — always skipped by all pollers
actBlockID := c.blockID + "~act"
ctx := slackapi.NewContextBlock(actBlockID,
slackapi.NewTextBlockObject("mrkdwn", display, false, false),
)
if c.activityTS == "" {
c.logSlack("postMessage(activity)", display)
_, ts, err := c.api.PostMessage(
c.channel,
slackapi.MsgOptionBlocks(ctx),
slackapi.MsgOptionText("activity", false),
slackapi.MsgOptionTS(c.threadTS),
)
if err == nil {
c.activityTS = ts
}
} else {
c.logSlack("updateMessage(activity)", display)
c.api.UpdateMessage(
c.channel,
c.activityTS,
slackapi.MsgOptionBlocks(ctx),
slackapi.MsgOptionText("activity", false),
)
}
c.actUpdate = time.Now()
}
// scheduleActivityFlush starts a debounce timer for activity. Must be called with lock held.
func (c *compatTurn) scheduleActivityFlush() {
if c.activityTimer != nil {
return
}
c.activityTimer = time.AfterFunc(time.Duration(compatThrottleMs)*time.Millisecond, func() {
c.mu.Lock()
defer c.mu.Unlock()
c.activityTimer = nil
c.postActivity()
})
}
// stopActivityTimer cancels any pending activity debounce timer. Must be called with lock held.
func (c *compatTurn) stopActivityTimer() {
if c.activityTimer != nil {
c.activityTimer.Stop()
c.activityTimer = nil
}
}
// forceFlushText updates the text message with current buffer content,
// bypassing throttle. Must be called with lock held.
func (c *compatTurn) forceFlushText() {
c.stopTimer()
if c.textBuf.Len() == 0 {
return
}
c.postText()
}
// deleteActivity deletes the activity message and resets activity state.
// Acquires the lock.
func (c *compatTurn) deleteActivity() {
c.mu.Lock()
defer c.mu.Unlock()
c.deleteActivityLocked()
}
// deleteActivityLocked deletes the activity message. Must be called with lock held.
func (c *compatTurn) deleteActivityLocked() {
c.stopActivityTimer()
if c.activityTS == "" {
return
}
c.logSlack("deleteMessage(activity)", c.activityTS)
c.api.DeleteMessage(c.channel, c.activityTS)
c.activityTS = ""
c.activityDeleted = true
c.thinkBuf.Reset()
c.activities = nil
c.toolIndex = make(map[string]int)
}
func (c *compatTurn) writeThinking(text string) {
c.mu.Lock()
defer c.mu.Unlock()
// Flush any pending text before activity
c.forceFlushText()
c.activityDeleted = false // new thinking starts fresh activity
c.thinkBuf.WriteString(text)
c.flushActivity()
}
func (c *compatTurn) writeTool(id, name, status, detail string) {
c.mu.Lock()
defer c.mu.Unlock()
// Flush any pending text before activity
c.forceFlushText()
// New running tool (not a done/error update) starts fresh activity
if status == ToolRunning {
if _, exists := c.toolIndex[id]; !exists {
c.activityDeleted = false
}
}
summary := name
if detail != "" {
summary += ": " + detail
}
// :claude: while running, ✅ when done, ❌ on error
var icon string
switch status {
case ToolDone:
icon = "✓"
case ToolError:
icon = "❌"
default:
icon = c.thinkingEmoji
}
line := fmt.Sprintf("%s %s", icon, summary)
// Update existing line or append new one
if idx, ok := c.toolIndex[id]; ok {
c.activities[idx] = line
} else {
c.toolIndex[id] = len(c.activities)
c.activities = append(c.activities, line)
}
c.flushActivity()
}
func (c *compatTurn) markQuestion(prefix string) {
c.mu.Lock()
defer c.mu.Unlock()
c.question = true
c.qPrefix = prefix
}
func (c *compatTurn) setPlainText(on bool) {
c.mu.Lock()
defer c.mu.Unlock()
c.plainText = on
}
func (c *compatTurn) writeStatus(text string) {
c.mu.Lock()
defer c.mu.Unlock()
if text == "" {
return
}
c.activities = append(c.activities, fmt.Sprintf("⏳ %s", text))
c.flushActivity()
}
func (c *compatTurn) writeText(text string) {
c.mu.Lock()
defer c.mu.Unlock()
// Strip leading newlines from the first text content
if c.textBuf.Len() == 0 {
text = strings.TrimLeft(text, "\n")
if text == "" {
return
}
// Delete activity and post text immediately (same lock scope, minimal gap)
c.deleteActivityLocked()
}
c.textBuf.WriteString(text)
// Throttle updates to 1/sec
if len(c.textMsgs) > 0 && time.Since(c.textUpdate) < time.Duration(compatThrottleMs)*time.Millisecond {
// Schedule a debounce flush: if no further event within 1s, flush
c.scheduleFlush()
return
}
c.stopTimer()
c.postText()
}
// postText posts or updates the text message with current buffer content.
const (
// maxRawChunkLen is the raw text limit per message before formatting.
// Formatted text (with "> " prefix, emoji, fences) must fit in maxBlockTextLen (3000).
maxRawChunkLen = 2500
// streamingTailLines is how many lines to show in the scrolling tail.
streamingTailLines = 6
)
// postText progressively freezes text into messages and shows a scrolling tail.
// Each frozen message uses a section block with block_id for poller identification.
// Must be called with lock held.
func (c *compatTurn) postText() {
full := c.textBuf.String()
current := full[c.textFrozenLen:]
// Freeze chunks when current portion exceeds the raw limit.
// Track code fences: if we split inside a ``` block, close it in the
// frozen chunk and reopen in the next.
for len(current) > maxRawChunkLen {
cut := strings.LastIndex(current[:maxRawChunkLen], "\n")
if cut <= 0 {
cut = maxRawChunkLen
} else {
cut++
}
// Prepend reopening fence from previous split
frozen := c.textPrefix + current[:cut]
// Check if the frozen chunk has an unclosed code fence
if hasUnclosedFence(frozen) {
frozen += "```\n"
c.textPrefix = "```\n"
} else {
c.textPrefix = ""
}
c.freezeMessage(frozen)
c.textFrozenLen += cut
current = full[c.textFrozenLen:]
}
// Show the tail of the current (unfrozen) portion.
// Prepend code fence prefix if we split inside a code block.
// Append closing fence if the tail has an unclosed one.
lines := strings.Split(current, "\n")
display := current
if len(lines) > streamingTailLines {
display = strings.Join(lines[len(lines)-streamingTailLines:], "\n")
}
display = c.textPrefix + display
if hasUnclosedFence(display) {
display += "\n```"
}
converted := formatText(display, c.emoji, c.plainText)
streamBlockID := c.blockID + "~"
blocks := textBlocks(display, streamBlockID, c.emoji, c.plainText)
opts := []slackapi.MsgOption{
slackapi.MsgOptionBlocks(blocks...),
slackapi.MsgOptionText(converted, false),
}
lastTS := c.lastTextTS()
if lastTS == "" {
c.logSlack("postMessage(text)", converted[:min(60, len(converted))])
allOpts := append(opts, slackapi.MsgOptionTS(c.threadTS))
if _, ts, err := c.api.PostMessage(c.channel, allOpts...); err == nil {
c.textMsgs = append(c.textMsgs, ts)
}
} else {
c.logSlack("updateMessage(text)", converted[:min(60, len(converted))])
c.api.UpdateMessage(c.channel, lastTS, opts...)
}
c.textUpdate = time.Now()
}
// freezeMessage finalizes the current streaming message with the given text,
// then appends an empty slot so the next postText creates a new message.
func (c *compatTurn) freezeMessage(text string) {
converted := formatText(text, c.emoji, c.plainText)
frozenBlockID := fmt.Sprintf("%s-%d", c.blockID, len(c.textMsgs))
blocks := textBlocks(text, frozenBlockID, c.emoji, c.plainText)
opts := []slackapi.MsgOption{
slackapi.MsgOptionBlocks(blocks...),
slackapi.MsgOptionText(converted, false),
}
lastTS := c.lastTextTS()
if lastTS != "" {
c.logSlack("updateMessage(text/freeze)", converted[:min(60, len(converted))])
c.api.UpdateMessage(c.channel, lastTS, opts...)
} else {
c.logSlack("postMessage(text/freeze)", converted[:min(60, len(converted))])
allOpts := append(opts, slackapi.MsgOptionTS(c.threadTS))
if _, ts, err := c.api.PostMessage(c.channel, allOpts...); err == nil {
c.textMsgs = append(c.textMsgs, ts)
}
}
// Next postText will create a fresh message
c.textMsgs = append(c.textMsgs, "")
}
// lastTextTS returns the timestamp of the last text message, or "".
func (c *compatTurn) lastTextTS() string {
if len(c.textMsgs) == 0 {
return ""
}
return c.textMsgs[len(c.textMsgs)-1]
}
// formatText converts raw text to the slagent blockquote convention.
// Every line starts with "> "; first line is "> :emoji: ...".
// This convention is how the poller identifies slagent messages.
func formatText(display, emoji string, plainText bool) string {
if plainText {
// Plan mode: quoted header + code block. The > on the opening fence
// makes the code block appear inside a blockquote in Slack mrkdwn.
escaped := strings.ReplaceAll(display, "```", "'''")
return "> " + emoji + " 📋\n> ```\n" + escaped + "\n```"
}
body := MarkdownToMrkdwn(display)
lines := strings.Split(body, "\n")
// Blockquote all lines, but skip > inside code fences.
// Opening ``` gets >, content and closing ``` do not.
inCode := false
for i, line := range lines {
if strings.HasPrefix(line, "```") {
if !inCode {
// Opening fence: quote it, then enter code mode
if i == 0 {
lines[i] = "> " + emoji + " " + line
} else {
lines[i] = "> " + line
}
inCode = true
} else {
// Closing fence: no quote
inCode = false
}
continue
}
if inCode {
continue // no > prefix inside code block
}
if i == 0 {
lines[i] = "> " + emoji + " " + line
} else {
lines[i] = "> " + line
}
}
return strings.Join(lines, "\n")
}
// textBlocks returns the Slack block for a text message.
// Uses a section block with mrkdwn (both normal and plan mode).
func textBlocks(display, blockID, emoji string, plainText bool) []slackapi.Block {
converted := formatText(display, emoji, plainText)
section := slackapi.NewSectionBlock(
slackapi.NewTextBlockObject("mrkdwn", converted, false, false),
nil, nil,
)
section.BlockID = blockID
return []slackapi.Block{section}
}
// hasUnclosedFence returns true if the text has an odd number of ``` fences,
// meaning a code block is open and needs closing.
func hasUnclosedFence(text string) bool {
return strings.Count(text, "```")%2 != 0
}
// scheduleFlush starts a debounce timer that flushes text after 1s.
// Must be called with lock held.
func (c *compatTurn) scheduleFlush() {
if c.textTimer != nil {
return // already scheduled
}
c.textTimer = time.AfterFunc(time.Duration(compatThrottleMs)*time.Millisecond, func() {
c.mu.Lock()
defer c.mu.Unlock()
c.textTimer = nil
c.postText()
})
}
// stopTimer cancels any pending debounce timer. Must be called with lock held.
func (c *compatTurn) stopTimer() {
if c.textTimer != nil {
c.textTimer.Stop()
c.textTimer = nil
}
}
// finish freezes the activity message and updates the text message to the full final response.
func (c *compatTurn) finish() error {
c.mu.Lock()
defer c.mu.Unlock()
// Cancel debounce timers
c.stopTimer()
c.stopActivityTimer()
// If no text and no real activity, delete the activity message (e.g. early thinking indicator)
finalText := strings.TrimLeft(c.textBuf.String(), "\n")
if finalText == "" && len(c.activities) == 0 && strings.TrimSpace(c.thinkBuf.String()) == "" {
c.deleteActivityLocked()
return nil
}
// Final flush of activity (frozen as-is, no deletion)
c.postActivity()
if c.activityTS != "" {
display := c.renderActivity()
actBlockID := c.blockID + "~act"
ctx := slackapi.NewContextBlock(actBlockID,
slackapi.NewTextBlockObject("mrkdwn", display, false, false),
)
c.api.UpdateMessage(
c.channel,
c.activityTS,
slackapi.MsgOptionBlocks(ctx),
slackapi.MsgOptionText("activity", false),
)
}
// Update text message to full final response
if finalText == "" {
return nil
}
// Question turns: prepend @mention, replace trailing ? with ❓
if c.question {
if c.qPrefix != "" {
finalText = c.qPrefix + finalText
}
finalText = strings.TrimRight(finalText, "\n ")
if strings.HasSuffix(finalText, "?") {
finalText = finalText[:len(finalText)-1] + " ❓"
} else {
finalText += " ❓"
}
}
// Finalize the last streaming message with its remaining unfrozen content.
// Frozen messages are already posted with their final content.
// Prepend code fence prefix if we split inside a code block.
unfrozen := c.textPrefix + finalText[c.textFrozenLen:]
converted := formatText(unfrozen, c.emoji, c.plainText)
finalBlockID := c.blockID
blocks := textBlocks(unfrozen, finalBlockID, c.emoji, c.plainText)
opts := []slackapi.MsgOption{
slackapi.MsgOptionBlocks(blocks...),
slackapi.MsgOptionText(converted, false),
}
// If activity is below text, delete the first text message so it reposts after activity
if len(c.textMsgs) > 0 && c.textMsgs[0] != "" && c.activityTS != "" && c.textMsgs[0] < c.activityTS {
c.logSlack("deleteMessage(text/reorder)", c.textMsgs[0])
c.api.DeleteMessage(c.channel, c.textMsgs[0])
c.textMsgs[0] = ""
}
lastTS := c.lastTextTS()
if lastTS != "" {
c.logSlack("updateMessage(text/final)", converted[:min(60, len(converted))])
c.api.UpdateMessage(c.channel, lastTS, opts...)
} else {
c.logSlack("postMessage(text/final)", converted[:min(60, len(converted))])
allOpts := append(opts, slackapi.MsgOptionTS(c.threadTS))
_, _, err := c.api.PostMessage(c.channel, allOpts...)
if err != nil {
return err
}
}
return nil
}