openclacky 1.5.25 → 1.5.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -0
  3. data/lib/clacky/agent/chunk_index.rb +2 -1
  4. data/lib/clacky/agent/message_compressor_helper.rb +20 -2
  5. data/lib/clacky/agent/session_serializer.rb +28 -1
  6. data/lib/clacky/agent/skill_manager.rb +2 -8
  7. data/lib/clacky/agent/time_machine.rb +108 -127
  8. data/lib/clacky/agent/tool_executor.rb +2 -11
  9. data/lib/clacky/agent.rb +15 -19
  10. data/lib/clacky/agent_config.rb +14 -4
  11. data/lib/clacky/billing/media_usage.rb +69 -0
  12. data/lib/clacky/billing/platform_billing.rb +5 -0
  13. data/lib/clacky/brand_config.rb +16 -215
  14. data/lib/clacky/default_extensions/ext-studio/agents/ext-developer/system_prompt.md +2 -80
  15. data/lib/clacky/default_extensions/ext-studio/panels/studio/view.js +1 -1
  16. data/lib/clacky/default_extensions/ext-studio/skills/ext-develop/SKILL.md +10 -96
  17. data/lib/clacky/default_extensions/git/panels/git/view.js +208 -69
  18. data/lib/clacky/default_extensions/knowledge/README.md +1 -1
  19. data/lib/clacky/default_extensions/knowledge/README.zh.md +1 -1
  20. data/lib/clacky/default_extensions/knowledge/lib/importer.rb +1 -1
  21. data/lib/clacky/default_extensions/knowledge/panels/kb/view.js +3 -3
  22. data/lib/clacky/default_extensions/meeting/api/handler.rb +23 -2
  23. data/lib/clacky/default_extensions/meeting/panels/meeting/view.js +194 -36
  24. data/lib/clacky/default_extensions/preview/icon.svg +3 -2
  25. data/lib/clacky/default_extensions/secretary/panels/work/view.js +108 -33
  26. data/lib/clacky/default_extensions/side-chat/README.md +40 -0
  27. data/lib/clacky/default_extensions/side-chat/README.zh.md +40 -0
  28. data/lib/clacky/default_extensions/side-chat/api/handler.rb +90 -0
  29. data/lib/clacky/default_extensions/side-chat/api/runtime.rb +411 -0
  30. data/lib/clacky/default_extensions/side-chat/ext.yml +16 -0
  31. data/lib/clacky/default_extensions/side-chat/icon.svg +14 -0
  32. data/lib/clacky/default_extensions/side-chat/panels/side-chat/view.js +779 -0
  33. data/lib/clacky/default_extensions/terminal/README.md +36 -0
  34. data/lib/clacky/default_extensions/terminal/README.zh.md +36 -0
  35. data/lib/clacky/default_extensions/terminal/api/handler.rb +121 -0
  36. data/lib/clacky/default_extensions/terminal/api/runtime.rb +397 -0
  37. data/lib/clacky/default_extensions/terminal/ext.yml +16 -0
  38. data/lib/clacky/default_extensions/terminal/icon.svg +13 -0
  39. data/lib/clacky/default_extensions/terminal/panels/terminal/view.js +351 -0
  40. data/lib/clacky/default_extensions/terminal/vendor/LICENSE +21 -0
  41. data/lib/clacky/default_extensions/terminal/vendor/addon-fit.js +2 -0
  42. data/lib/clacky/default_extensions/terminal/vendor/xterm.css +218 -0
  43. data/lib/clacky/default_extensions/terminal/vendor/xterm.js +2 -0
  44. data/lib/clacky/default_skills/media-gen/SKILL.md +30 -9
  45. data/lib/clacky/extension/api_extension.rb +12 -0
  46. data/lib/clacky/locales/en.rb +14 -11
  47. data/lib/clacky/locales/i18n.rb +25 -0
  48. data/lib/clacky/locales/zh.rb +14 -11
  49. data/lib/clacky/media/base.rb +11 -1
  50. data/lib/clacky/media/openai_compat.rb +271 -3
  51. data/lib/clacky/message_format/open_ai.rb +17 -0
  52. data/lib/clacky/prompts/base.md +3 -0
  53. data/lib/clacky/providers.rb +33 -20
  54. data/lib/clacky/reasoning_levels.rb +75 -0
  55. data/lib/clacky/server/channel/channel_ui_controller.rb +12 -5
  56. data/lib/clacky/server/git_panel.rb +40 -18
  57. data/lib/clacky/server/http_server.rb +62 -71
  58. data/lib/clacky/server/session_registry.rb +3 -0
  59. data/lib/clacky/ui2/markdown_renderer.rb +153 -0
  60. data/lib/clacky/ui2/strings_cjk_patch.rb +134 -124
  61. data/lib/clacky/utils/file_link_normalizer.rb +30 -3
  62. data/lib/clacky/utils/frontmatter.rb +63 -0
  63. data/lib/clacky/utils/model_pricing.rb +67 -9
  64. data/lib/clacky/version.rb +1 -1
  65. data/lib/clacky/web/app.css +722 -274
  66. data/lib/clacky/web/app.js +2 -0
  67. data/lib/clacky/web/components/chat-composer.js +504 -0
  68. data/lib/clacky/web/components/chat-navigator.js +1 -1
  69. data/lib/clacky/web/components/model-picker.js +319 -20
  70. data/lib/clacky/web/components/quote-select.js +97 -39
  71. data/lib/clacky/web/core/aside.js +137 -27
  72. data/lib/clacky/web/core/ext.js +658 -81
  73. data/lib/clacky/web/features/brand/store.js +0 -4
  74. data/lib/clacky/web/features/brand/view.js +2 -99
  75. data/lib/clacky/web/features/extensions/store.js +3 -1
  76. data/lib/clacky/web/features/extensions/view.js +14 -15
  77. data/lib/clacky/web/features/new-session/store.js +4 -0
  78. data/lib/clacky/web/features/new-session/view.js +27 -4
  79. data/lib/clacky/web/features/skills/store.js +7 -5
  80. data/lib/clacky/web/features/skills/view.js +65 -16
  81. data/lib/clacky/web/features/version/view.js +1 -1
  82. data/lib/clacky/web/features/workspace/store.js +7 -3
  83. data/lib/clacky/web/features/workspace/view.js +46 -5
  84. data/lib/clacky/web/i18n.js +104 -58
  85. data/lib/clacky/web/index.html +21 -22
  86. data/lib/clacky/web/lib/box-diagram.js +239 -0
  87. data/lib/clacky/web/sessions.js +117 -151
  88. data/lib/clacky/web/settings.js +23 -16
  89. data/lib/clacky/web/ws-dispatcher.js +4 -1
  90. data/lib/clacky.rb +2 -0
  91. metadata +24 -1
@@ -13,6 +13,13 @@ module Clacky
13
13
  module UI2
14
14
  # MarkdownRenderer handles rendering Markdown content with syntax highlighting
15
15
  module MarkdownRenderer
16
+ BOX_OPEN = /\A\s*┌.*┐\s*\z/.freeze
17
+ BOX_ROW_END = /[│┐┘┤]\z/.freeze
18
+ BOX_CHARS = "│┌┐└┘├┤┬┴┼"
19
+ BOX_CORNERS = "┌┐└┘"
20
+ # Frame followed by a floating label, e.g. `│ + │ ← tab bar`.
21
+ BOX_ANNOTATED = /\A(.*│)(\s{2,}[^\s│┌┐└┘├┤┬┴┼][^│┌┐└┘├┤┬┴┼]*)\z/.freeze
22
+
16
23
  class << self
17
24
  # Render markdown content with theme-aware colors
18
25
  # @param content [String] Markdown content to render
@@ -26,6 +33,8 @@ module Clacky
26
33
  # Tables need CJK-aware column widths before anything is rendered.
27
34
  require_relative "tty_markdown_cjk_table_patch" unless defined?(Clacky::UI2::TTYMarkdownCJKTablePatch)
28
35
 
36
+ content = align_box_diagrams(content)
37
+
29
38
  # Get current theme colors
30
39
  theme = ThemeManager.current_theme
31
40
 
@@ -191,6 +200,150 @@ module Clacky
191
200
  text.sub(/( +)((?:\e\[[0-9;]*m)+)\z/, '\2').sub(/ +\z/, "")
192
201
  end
193
202
 
203
+ # Models pad box rows by character count, so a CJK row comes out wider
204
+ # than the frame it sits in. Every frame in one diagram is given the
205
+ # same width, and cell separators follow the border row above them.
206
+ def align_box_diagrams(content)
207
+ return content unless content.include?("┌")
208
+
209
+ lines = content.lines
210
+ out = []
211
+ index = 0
212
+ while index < lines.size
213
+ if lines[index].chomp.match?(BOX_OPEN)
214
+ stop = index
215
+ stop += 1 while stop + 1 < lines.size && box_block_line?(lines[stop + 1])
216
+ out.concat(align_box_block(lines[index..stop]))
217
+ index = stop + 1
218
+ next
219
+ end
220
+ out << lines[index]
221
+ index += 1
222
+ end
223
+ out.join
224
+ end
225
+
226
+ def box_block_line?(line)
227
+ text = line.chomp
228
+ return false if text.strip.empty?
229
+
230
+ text.match?(BOX_ROW_END) || text.match?(/\A\s*│/)
231
+ end
232
+
233
+ # Frames grow to the widest row instead of cutting content.
234
+ def align_box_block(rows)
235
+ aligned = align_box_cells(rows)
236
+ target = aligned.map { |row| box_width(row.chomp) }.compact.max
237
+ aligned.map do |row|
238
+ ending = row.end_with?("\n") ? "\n" : ""
239
+ body, label = box_split_label(row.chomp)
240
+ # A connector carrying a label is not a frame row; padding it would
241
+ # shove the label past the frame it annotates.
242
+ resized = label && body.count(BOX_CHARS) < 2 ? body : box_resize(body, target)
243
+ resized = "#{resized} #{label}" if label
244
+ resized + ending
245
+ end
246
+ end
247
+
248
+ def box_split_label(text)
249
+ match = text.match(BOX_ANNOTATED)
250
+ return [text, nil] unless match
251
+
252
+ [match[1], match[2].strip]
253
+ end
254
+
255
+ def box_width(body)
256
+ text, = box_split_label(body.rstrip)
257
+ text.rstrip.match?(BOX_ROW_END) ? Unicode::DisplayWidth.of(text.rstrip) : nil
258
+ end
259
+
260
+ def align_box_cells(rows)
261
+ ref = nil
262
+ rows.map do |row|
263
+ text = row.chomp.rstrip
264
+ if box_grid_row?(text) || (text.match?(/[┬┼]/) && text.match?(/[┌├]/))
265
+ ref = box_bar_columns(text, BOX_CHARS)
266
+ row
267
+ elsif text.match?(/\A\s*[└┘]/)
268
+ ref = nil
269
+ row
270
+ elsif text.match?(/\A\s*│/) && text.match?(BOX_ROW_END)
271
+ bars = box_bar_columns(text, "│")
272
+ target = box_target_bars(ref, bars)
273
+ rebuilt = target && box_rebuild_row(text, target)
274
+ ref ||= bars if bars.size > 2
275
+ rebuilt ? rebuilt + (row.end_with?("\n") ? "\n" : "") : row
276
+ else
277
+ row
278
+ end
279
+ end
280
+ end
281
+
282
+ # A frame holding free-standing boxes (no ┬/┼ anywhere) is gridded by
283
+ # those boxes' own corners, e.g. `│ ┌──┐ ┌──┐ │`.
284
+ def box_grid_row?(text)
285
+ text.match?(/\A\s*│/) && text.count(BOX_CORNERS) >= 2
286
+ end
287
+
288
+ # A border row is the grid; a frame drawn without one falls back to its
289
+ # first content row, so the rest of the frame at least agrees with it.
290
+ def box_target_bars(ref, bars)
291
+ return nil if ref.nil?
292
+
293
+ inner = bars[1..-2] || []
294
+ target = ref.size == inner.size ? ref : (ref[1..-2] || [])
295
+ return nil if inner.empty? || target.size != inner.size
296
+
297
+ [bars.first] + target + [bars.last]
298
+ end
299
+
300
+ # A cell that cannot fit its column leaves the row alone rather than
301
+ # half-aligned; an exact fit closes the gap and keeps the bars lined up.
302
+ def box_rebuild_row(text, target_bars)
303
+ cells = text.split("│", -1)
304
+ return nil if cells.size != target_bars.size + 1
305
+
306
+ widths = (0...(target_bars.size - 1)).map do |i|
307
+ target_bars[i + 1] - target_bars[i] - 1
308
+ end
309
+ fitted = (0...widths.size).map { |i| box_fit(cells[i + 1], widths[i]) }
310
+ return nil if fitted.include?(nil)
311
+
312
+ out = +cells[0]
313
+ fitted.each { |cell| out << "│" << cell }
314
+ out << "│" << cells[-1]
315
+ end
316
+
317
+ def box_bar_columns(text, chars)
318
+ cols = []
319
+ width = 0
320
+ text.each_char do |char|
321
+ cols << width if chars.include?(char)
322
+ width += Unicode::DisplayWidth.of(char)
323
+ end
324
+ cols
325
+ end
326
+
327
+ def box_fit(cell, width)
328
+ text = cell.strip
329
+ pad = width - Unicode::DisplayWidth.of(text)
330
+ return nil if pad.negative?
331
+ return text if pad.zero?
332
+
333
+ " " + text + " " * (pad - 1)
334
+ end
335
+
336
+ def box_resize(body, target)
337
+ text = body.rstrip
338
+ return body unless text.match?(BOX_ROW_END)
339
+
340
+ diff = target - Unicode::DisplayWidth.of(text)
341
+ return text if diff <= 0
342
+
343
+ filler = text.lstrip.start_with?("┌", "└", "├") ? "─" : " "
344
+ text[0...-1] + filler * diff + text[-1]
345
+ end
346
+
194
347
  # Check if content looks like markdown
195
348
  # @param content [String] Content to check
196
349
  # @return [Boolean] true if content appears to be markdown
@@ -2,21 +2,23 @@
2
2
 
3
3
  require "strings"
4
4
 
5
- # strings 0.2.1 (latest release, 2021) tracks ANSI reinsertion offsets in
6
- # display width (CJK chars count as 2) but applies them as String character
7
- # indexes via String#insert, so any colored CJK content that needs wrapping
8
- # raises IndexError. These methods mirror upstream with offsets tracked in
9
- # character count instead of display width.
5
+ # strings 0.2.1 (latest release, 2021) re-wraps coloured text by remembering
6
+ # where every escape sequence started and inserting it back with
7
+ # String#insert. Three things go wrong with that:
10
8
  #
11
- # Two more places count the wrong thing once CJK is involved:
9
+ # - Offsets are tracked in display width (CJK counts as 2) but applied as
10
+ # character indexes, so coloured CJK content raises IndexError.
11
+ # - The offset stack is shared across lines, so a position recorded on one
12
+ # line lands inside another line's characters. "\e[38;5;230m" came out as
13
+ # "\e[38;5" plus a literal "230m" printed to the user.
14
+ # - The early bail-out compares the printable *character* count with wrap_at.
15
+ # Forty Chinese characters are eighty columns, so such a line is returned
16
+ # unwrapped and overflows the pane.
12
17
  #
13
- # - Upstream bails out early when the printable *character* count is below
14
- # wrap_at. Forty Chinese characters are eighty terminal columns, so such a
15
- # line is returned unwrapped and overflows the pane.
16
- # - Insertion offsets recorded on one line are meaningless on the next one,
17
- # yet they were kept in the stack and reused verbatim. A stale offset can
18
- # land inside an escape sequence, splitting "\e[38;5;230m" into "\e[38;5"
19
- # plus a literal ";230m" printed to the user.
18
+ # The wrapper below is token based instead: an escape sequence is a
19
+ # zero-width token that is always copied whole, and the colours still open at
20
+ # a break are replayed on the continuation line. Output offsets cannot drift
21
+ # because nothing is ever inserted at a remembered position.
20
22
  module Strings
21
23
  # Upstream ANSI_MATCHER ends with an optional `([\];])?` group, so a literal
22
24
  # ";" right after a color code is swallowed along with it: the text
@@ -25,7 +27,8 @@ module Strings
25
27
  # Strip well-formed CSI sequences first and only fall back to the loose
26
28
  # matcher for genuinely broken leftovers.
27
29
  module ANSI
28
- CSI_SEQUENCE = /\e\[[0-9:;<=>?]*[ -\/]*[@-~]/
30
+ CSI_SEQUENCE = /\e\[[0-9:;<=>?]*[ -\/]*[@-~]/.freeze
31
+ CSI_TOKEN = /\A\e\[[0-9:;<=>?]*[ -\/]*[@-~]\z/.freeze
29
32
  module_function
30
33
 
31
34
  def sanitize(string)
@@ -38,139 +41,146 @@ module Strings
38
41
  end
39
42
 
40
43
  module Wrap
44
+ # Codes that end whatever colour was open before them.
45
+ RESET_TOKENS = "\e[0m\e[m\e[39m\e[49m"
46
+ # A line with more open colours than this is replayed from the most
47
+ # recent ones only; keeps the prefix bounded on pathological input.
48
+ MAX_ACTIVE = 8
49
+
41
50
  module_function
42
51
 
43
52
  def wrap(text, wrap_at = DEFAULT_WIDTH, separator: NEWLINE)
44
53
  width = wrap_at.to_i
45
54
  return text if width.zero?
46
- return text if text.lines.all? { |line| display_width(line.chomp) <= width }
55
+ return text if text.lines.all? { |line| visible_width(line.chomp) <= width }
47
56
 
48
- ansi_stack = []
49
- text.lines.map do |line|
50
- format_line(line, width, ansi_stack).join(separator)
51
- end.join
57
+ text.lines.map { |line| wrap_line(line, width).join(separator) }.join
52
58
  end
53
59
 
54
- def format_line(text_line, wrap_at, ansi_stack)
55
- lines = []
56
- line = []
57
- word = []
58
- ansi = []
59
- ansi_matched = false
60
- word_length = 0
61
- line_length = 0
62
- word_chars = 0
63
- line_chars = 0
64
- char_length = 0
65
- text_length = display_width(text_line)
66
- total_length = 0
67
-
68
- UnicodeUtils.each_grapheme(text_line) do |char|
69
- if char == Strings::ANSI::CSI || ansi.length > 0
70
- ansi << char
71
- if Strings::ANSI.only_ansi?(ansi.join)
72
- ansi_matched = true
73
- elsif ansi_matched
74
- ansi_stack << [ansi[0...-1].join, line_chars + word_chars]
75
- ansi_matched = false
76
-
77
- if ansi.last == Strings::ANSI::CSI
78
- ansi = [ansi.last]
79
- else
80
- ansi = []
81
- end
82
- end
83
- next if ansi.length > 0
60
+ # Split one line (which may carry colour) into chunks of at most `width`
61
+ # display columns. Word boundaries are respected; a single word wider
62
+ # than the line – the normal case for Chinese, which has no spaces – is
63
+ # broken between graphemes instead of being emitted oversized.
64
+ def wrap_line(line, width)
65
+ ending = line.end_with?(NEWLINE) ? NEWLINE : ""
66
+ tokens = tokenize(ending.empty? ? line : line.chomp)
67
+
68
+ chunks = []
69
+ current = []
70
+ current_width = 0
71
+
72
+ words(tokens).each do |word|
73
+ word_width = word.sum { |token| token[1] }
74
+
75
+ if current_width + word_width <= width
76
+ current.concat(word)
77
+ current_width += word_width
78
+ next
84
79
  end
85
80
 
86
- char_length = display_width(char)
87
- total_length += char_length
88
- if line_length + word_length + char_length <= wrap_at
89
- if char == SPACE || total_length == text_length
90
- line << word.join + char
91
- line_length += word_length + char_length
92
- line_chars += word_chars + char.size
93
- word = []
94
- word_length = 0
95
- word_chars = 0
96
- else
97
- word << char
98
- word_length += char_length
99
- word_chars += char.size
100
- end
81
+ unless current.empty?
82
+ chunks << current
83
+ current = []
84
+ current_width = 0
85
+ end
86
+
87
+ if word_width <= width
88
+ current = word.dup
89
+ current_width = word_width
101
90
  next
102
91
  end
103
92
 
104
- if char == SPACE
105
- lines << insert_ansi(line.join, ansi_stack)
106
- line = []
107
- line_length = 0
108
- line_chars = 0
109
- word << char
110
- word_length += char_length
111
- word_chars += char.size
112
- elsif word_length + char_length <= wrap_at
113
- lines << insert_ansi(line.join, ansi_stack)
114
- line = [word.join + char]
115
- line_length = word_length + char_length
116
- line_chars = word_chars + char.size
117
- word = []
118
- word_length = 0
119
- word_chars = 0
120
- else # hyphenate word - too long to fit a line
121
- lines << insert_ansi(word.join, ansi_stack)
122
- line_length = 0
123
- line_chars = 0
124
- word = [char]
125
- word_length = char_length
126
- word_chars = char.size
93
+ word.each do |token|
94
+ if current_width.positive? && current_width + token[1] > width
95
+ chunks << current
96
+ current = []
97
+ current_width = 0
98
+ next if token[0] == SPACE
99
+ end
100
+ current << token
101
+ current_width += token[1]
127
102
  end
128
103
  end
129
- lines << insert_ansi(line.join, ansi_stack) unless line.empty?
130
- lines << insert_ansi(word.join, ansi_stack) unless word.empty?
131
- lines
104
+ chunks << current unless current.empty?
105
+
106
+ render_chunks(chunks, ending)
132
107
  end
133
108
 
134
- def insert_ansi(string, ansi_stack = [])
135
- return string if ansi_stack.empty?
136
- return string if string.empty?
137
-
138
- new_stack = []
139
- output = string.dup
140
- length = string.size
141
- matched_reset = false
142
- ansi_reset = Strings::ANSI::RESET
143
-
144
- ansi_stack.reverse_each do |ansi|
145
- pos = ansi[1]
146
- # Offsets carried over from a previous (longer) line can exceed this
147
- # line; such codes belong before the wrapped content.
148
- pos = 0 if pos > length
149
- if ansi[0] =~ /#{Regexp.quote(ansi_reset)}/
150
- matched_reset = true
151
- output.insert(pos, ansi_reset)
152
- next
153
- elsif !matched_reset # ansi without reset
154
- matched_reset = false
155
- new_stack << ansi # keep the ansi
156
- next if pos == length
157
- if output.end_with?(NEWLINE)
158
- output.insert(-2, ansi_reset)
159
- else
160
- output.insert(-1, ansi_reset)
109
+ # @return [Array<Array(String, Integer)>] graphemes paired with their
110
+ # display width, plus whole escape sequences paired with 0.
111
+ def tokenize(text)
112
+ tokens = []
113
+ escape = nil
114
+
115
+ UnicodeUtils.each_grapheme(text) do |char|
116
+ if escape
117
+ escape << char
118
+ if escape.match?(ANSI::CSI_TOKEN) || escape.size > 16
119
+ tokens << [escape, 0]
120
+ escape = nil
161
121
  end
122
+ next
123
+ end
124
+
125
+ if char == "\e"
126
+ escape = +"\e"
127
+ next
162
128
  end
163
129
 
164
- output.insert(pos, ansi[0])
130
+ tokens << [char, Unicode::DisplayWidth.of(char)]
131
+ end
132
+ tokens << [escape, 0] if escape
133
+
134
+ tokens
135
+ end
136
+
137
+ # Group tokens into words. A word keeps its trailing space, which is what
138
+ # makes the chunks add up to the original text.
139
+ def words(tokens)
140
+ result = []
141
+ word = []
142
+ tokens.each do |token|
143
+ word << token
144
+ next unless token[0] == SPACE
145
+
146
+ result << word
147
+ word = []
165
148
  end
149
+ result << word unless word.empty?
150
+
151
+ result
152
+ end
153
+
154
+ # Turn token chunks into strings, replaying the colour that is still open
155
+ # at the start of each chunk and closing every chunk that leaves one open.
156
+ def render_chunks(chunks, ending)
157
+ active = []
158
+ rendered = chunks.each_with_index.map do |chunk, index|
159
+ text = chunk.map { |token| token[0] }.join
160
+ body = active.empty? ? text : active.join + text
161
+ chunk.each { |token| track(active, token[0]) }
162
+ body += Strings::ANSI::RESET unless active.empty?
163
+ index == chunks.size - 1 ? body + ending : body
164
+ end
165
+
166
+ rendered.empty? ? [ending] : rendered
167
+ end
168
+
169
+ def track(active, text)
170
+ return unless text.getbyte(0) == 27
171
+
172
+ if RESET_TOKENS.include?(text)
173
+ active.clear
174
+ else
175
+ active << text
176
+ active.shift while active.size > MAX_ACTIVE
177
+ end
178
+ end
166
179
 
167
- ansi_stack.replace(new_stack)
168
- # Nothing recorded above survives this line: offsets are character
169
- # positions inside the line we just emitted. Whatever is still open has
170
- # to be reopened at the very start of the next line.
171
- ansi_stack.each { |ansi| ansi[1] = 0 }
180
+ def visible_width(text)
181
+ return 0 if text.empty?
172
182
 
173
- output
183
+ Unicode::DisplayWidth.of(Strings::ANSI.sanitize(text))
174
184
  end
175
185
  end
176
186
  end
@@ -8,6 +8,15 @@ module Clacky
8
8
  module FileLinkNormalizer
9
9
  SKIP_PREFIXES = %w[/api/ /preview/ /ext_ui/ /agent_ui/ http:// https:// mailto: #].freeze
10
10
 
11
+ # Link destination grammar, the single source for every Ruby-side matcher.
12
+ # Angle brackets are CommonMark's way of writing a path with spaces:
13
+ # `[x](</a b.pdf>)`. Unbracketed, the destination runs to the first
14
+ # unbalanced ")", so a paired "()" in a file name (备份(旧).pdf) belongs to
15
+ # the path rather than ending it.
16
+ DESTINATION = /<([^<>\n]+)>|((?:[^()\n]|\([^()\n]*\))+)/.freeze
17
+ LINK_TARGET = /\]\((?:#{DESTINATION})\)/.freeze
18
+ FILE_LINK = /(!?)\[[^\]]*\]\((?:#{DESTINATION})\)/.freeze
19
+
11
20
  # Models can emit local files as hosted-platform references
12
21
  # (`/workspace/projects/<base64url>` decoding to `cch1:file:///abs/path`) or
13
22
  # as bare absolute paths. Neither matches the `file://` handler in the Web UI
@@ -16,10 +25,28 @@ module Clacky
16
25
  def self.normalize(content)
17
26
  return content if content.nil? || content.empty?
18
27
 
19
- content.gsub(/\]\(([^)\s]+)\)/) do |match|
20
- path = local_file_path($1)
21
- path ? "](file://#{path})" : match
28
+ # Angle brackets are kept in the output (marked understands them) so only
29
+ # the scheme is added. Bare spaces are fine too: the Web UI percent-encodes
30
+ # them before marked parses the message, and IM clients keep the raw path.
31
+ content.gsub(LINK_TARGET) do |match|
32
+ path = local_file_path($1 || $2)
33
+ next match unless path
34
+
35
+ $1 ? "](<file://#{path}>)" : "](file://#{path})"
36
+ end
37
+ end
38
+
39
+ # Returns [{ inline:, path: }] for every `file://` link in content, in order;
40
+ # path is the raw text after the scheme, still percent-encoded if it was.
41
+ def self.extract_file_links(content)
42
+ return [] if content.nil? || content.empty?
43
+
44
+ links = []
45
+ content.scan(FILE_LINK) do
46
+ href = $2 || $3
47
+ links << { inline: $1 == "!", path: href.delete_prefix("file://") } if href.start_with?("file://")
22
48
  end
49
+ links
23
50
  end
24
51
 
25
52
  def self.local_file_path(href)
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Clacky
4
+ module Utils
5
+ # Parse the YAML frontmatter block at the top of a Markdown file.
6
+ #
7
+ # Frontmatter is authored by users and by the LLM, so it is not guaranteed
8
+ # to be valid YAML. Two failure modes must never cost the whole block:
9
+ #
10
+ # * Values YAML types itself — a bare `updated_at: 2026-05-07` becomes a
11
+ # Date, which `YAML.safe_load` rejects unless the class is permitted.
12
+ # Legacy memory files written before v1.5.24 still carry such fields.
13
+ # * Values that break the YAML grammar — an unquoted `description` that
14
+ # contains ": " is enough to raise.
15
+ #
16
+ # The first is handled by permitting Date/Time; the second degrades to a
17
+ # line-wise scan so `topic` / `description` survive a malformed neighbour.
18
+ module Frontmatter
19
+ # `---` fence, body, closing `---`. CRLF tolerated for files edited on
20
+ # Windows. Anchored so a horizontal rule mid-document is never matched.
21
+ PATTERN = /\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\z)/m.freeze
22
+
23
+ # Single `key: value` line. Indented lines are skipped on purpose so the
24
+ # fallback never picks up nested mappings or block-scalar content.
25
+ FIELD_LINE = /\A([A-Za-z_][A-Za-z0-9_-]*):[ \t]*(.*?)[ \t]*\z/.freeze
26
+
27
+ # @param content [String] full file content
28
+ # @return [Hash] frontmatter as a string-keyed hash; empty when absent
29
+ def self.parse(content)
30
+ match = content.to_s.match(PATTERN)
31
+ return {} unless match
32
+
33
+ body = match[1]
34
+ data = YAMLCompat.safe_load(body, permitted_classes: [::Date, ::Time])
35
+ data.is_a?(Hash) ? data : {}
36
+ rescue Psych::Exception
37
+ scan_fields(body)
38
+ end
39
+
40
+ # Line-wise `key: value` extraction used when the block is not valid YAML.
41
+ # First occurrence wins, matching how a YAML duplicate key would be read.
42
+ #
43
+ # @param body [String] raw frontmatter body
44
+ # @return [Hash]
45
+ def self.scan_fields(body)
46
+ fields = {}
47
+ body.each_line do |line|
48
+ m = line.chomp.match(FIELD_LINE)
49
+ next unless m
50
+ next if fields.key?(m[1])
51
+
52
+ fields[m[1]] = unquote(m[2])
53
+ end
54
+ fields
55
+ end
56
+
57
+ def self.unquote(value)
58
+ m = value.match(/\A(["'])(.*)\1\z/m)
59
+ m ? m[2] : value
60
+ end
61
+ end
62
+ end
63
+ end