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
@@ -0,0 +1,36 @@
1
+ ## How to open
2
+
3
+ - Tab bar of the session side panel → **+** (new tab) → **Official › Terminal**.
4
+ - Status: off by default. Enable **Terminal** under **Extensions › All › Official** first.
5
+ - Requires: the app is opened on this machine; a LAN or remote address cannot use it.
6
+
7
+ ## How to use
8
+
9
+ ### Opening and closing
10
+
11
+ - One shell per session, started in that session's working directory — the folder the AI works in. Falls back to your home directory when the session has none.
12
+ - Switching to another tab or another session leaves the shell running. Come back and everything it printed meanwhile is replayed.
13
+ - Closing the tab with × does not kill the shell. Add **Terminal** again and you are back in the same one.
14
+ - Typing `exit` (or `Ctrl+D`) ends the shell, and the tab closes itself. Adding **Terminal** again gives you a fresh shell.
15
+
16
+ ### Everyday commands
17
+
18
+ | Goal | How |
19
+ |---|---|
20
+ | Run a command / install dependencies | Type it, same as your own terminal |
21
+ | Stop the running command | `Ctrl+C` |
22
+ | Suspend it to the background | `Ctrl+Z` |
23
+ | Clear the screen | `clear` or `Ctrl+L` |
24
+ | Change directory | `cd`. The session's working directory, the one the AI uses, does not follow |
25
+
26
+ ## Notes
27
+
28
+ - The terminal runs commands on the machine Clacky itself runs on, which is why it is off by default and answers local requests only.
29
+ - At most 6 shells at once across sessions. At the limit, the least recently used shell that no page is attached to is reaped.
30
+ - A shell with no page attached for over an hour is reaped the next time a terminal opens, so that open starts a new one.
31
+ - Shells live in the Clacky process: restarting Clacky ends them, and the tab closes itself instead of leaving a dead pane.
32
+ - Not available on Windows yet — the panel says it could not start a terminal.
33
+
34
+ ## Third-party
35
+
36
+ `vendor/` ships [xterm.js](https://github.com/xtermjs/xterm.js) 5.5.0 with its fit addon (0.10.0), MIT licensed — see `vendor/LICENSE`.
@@ -0,0 +1,36 @@
1
+ ## 入口
2
+
3
+ - 会话右侧面板的标签栏 → 点 **+(新标签页)** → **官方 › 终端**。
4
+ - 状态:默认关闭。先在 **扩展 › 全部 › 官方** 里启用「终端」。
5
+ - 前提:界面是从本机打开的;通过局域网/远程地址访问时用不了。
6
+
7
+ ## 怎么用
8
+
9
+ ### 打开与关闭
10
+
11
+ - 一个会话一个 shell,起始目录就是这个会话的工作目录(AI 干活的目录);没有会话目录时用用户主目录。
12
+ - 切到别的标签页或别的会话,shell 继续在后台跑;切回来时,期间打印的内容会补上。
13
+ - 用 × 关掉标签页不会杀掉进程;再添加「终端」就接回同一个 shell。
14
+ - 输入 `exit`(或 `Ctrl+D`)退出后,这个标签页会自动关掉;再添加「终端」得到一个新 shell。
15
+
16
+ ### 常用操作
17
+
18
+ | 想做什么 | 怎么做 |
19
+ |---|---|
20
+ | 跑命令 / 装依赖 | 直接输入,跟本机终端一样 |
21
+ | 停止正在跑的命令 | `Ctrl+C` |
22
+ | 挂到后台 | `Ctrl+Z` |
23
+ | 清屏 | `clear` 或 `Ctrl+L` |
24
+ | 换目录 | `cd`。会话的工作目录(AI 用的那个)不会跟着变 |
25
+
26
+ ## 注意事项
27
+
28
+ - 终端等于在跑 Clacky 的那台机器上执行命令,所以默认关闭,并且只接受本机请求。
29
+ - 跨会话最多同时 6 个 shell;到上限时会回收最久没用、且当前没被页面连着的那个。
30
+ - 关掉标签页后如果超过 1 小时没有页面连着它,下次打开终端时会被回收,再打开就是新的 shell。
31
+ - shell 活在 Clacky 进程里:重启 Clacky 后它们都没了,标签页会自动关掉,而不是留下一个死掉的窗格。
32
+ - Windows 暂不支持,面板会提示无法启动终端。
33
+
34
+ ## 第三方
35
+
36
+ `vendor/` 内置 [xterm.js](https://github.com/xtermjs/xterm.js) 5.5.0 和它的 fit 插件(0.10.0),MIT 许可,见 `vendor/LICENSE`。
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "runtime"
4
+
5
+ # Interactive shell for the right-hand panel.
6
+ #
7
+ # Split of responsibilities:
8
+ # - HTTP builds a shell: it is the only layer that can resolve a session's
9
+ # working directory through `session_manager`.
10
+ # - WebSocket carries the data plane (`ext.terminal.*` frames), because the
11
+ # PTY reader thread can push output to one connection without polling.
12
+ #
13
+ # Every route is localhost-only. A terminal is arbitrary command execution, and
14
+ # the server can be bound to a LAN/public address with an access key — the key
15
+ # protects the UI, not the machine behind it.
16
+ class TerminalExtension < Clacky::ApiExtension
17
+ LOOPBACK = %w[127.0.0.1 ::1 ::ffff:127.0.0.1 ::ffff:0:0:1].freeze
18
+ WS_PREFIX = "ext.terminal."
19
+
20
+ get "/info" do
21
+ json(
22
+ local: local_request?,
23
+ shell: Clacky::Extensions::Terminal::Runtime::Session.default_shell,
24
+ sessions: local_request? ? Clacky::Extensions::Terminal::Runtime.list : []
25
+ )
26
+ end
27
+
28
+ post "/open" do
29
+ error!("terminals are only available to clients on this machine", status: 403) unless local_request?
30
+
31
+ body = json_body
32
+ session = begin
33
+ Clacky::Extensions::Terminal::Runtime.open(
34
+ cwd: working_dir_for(body["session_id"]),
35
+ cols: clamp_int(body["cols"], 1, 1000, 80),
36
+ rows: clamp_int(body["rows"], 1, 500, 24)
37
+ )
38
+ rescue Clacky::Extensions::Terminal::Runtime::PlatformError => e
39
+ error!(e.message, status: 501)
40
+ rescue Clacky::Extensions::Terminal::Runtime::CapacityError => e
41
+ error!(e.message, status: 429)
42
+ end
43
+
44
+ json(term_id: session.id, cwd: session.cwd, shell: session.shell)
45
+ end
46
+
47
+ post "/close" do
48
+ error!("terminals are only available to clients on this machine", status: 403) unless local_request?
49
+
50
+ Clacky::Extensions::Terminal::Runtime.close(json_body["term_id"])
51
+ json(ok: true)
52
+ end
53
+
54
+ # Runs on the WebSocket reader thread: every branch must stay cheap. Anything
55
+ # that could block (spawning a shell, resolving a session) lives in a route.
56
+ def self.on_ws_event(conn, message)
57
+ type = message["type"].to_s
58
+ return false unless type.start_with?(WS_PREFIX)
59
+
60
+ runtime = Clacky::Extensions::Terminal::Runtime
61
+ term_id = message["term_id"].to_s
62
+
63
+ case type.delete_prefix(WS_PREFIX)
64
+ when "attach"
65
+ session = runtime.find(term_id)
66
+ # A restarted server has no shells, so the client would otherwise keep a
67
+ # pane that can never print again.
68
+ if session
69
+ session.attach(conn)
70
+ else
71
+ conn.send_json(type: "ext.terminal.gone", term_id: term_id)
72
+ end
73
+ when "input"
74
+ runtime.find(term_id)&.write(message["data"].to_s)
75
+ when "resize"
76
+ runtime.find(term_id)&.resize(message["cols"], message["rows"])
77
+ when "detach"
78
+ runtime.find(term_id)&.detach(conn)
79
+ when "close"
80
+ runtime.close(term_id)
81
+ else
82
+ return false
83
+ end
84
+ true
85
+ end
86
+
87
+ def self.on_ws_close(conn)
88
+ Clacky::Extensions::Terminal::Runtime.detach(conn)
89
+ end
90
+
91
+ private def local_request?
92
+ ip = begin
93
+ req.remote_ip
94
+ rescue StandardError
95
+ nil
96
+ end
97
+ ip ||= begin
98
+ peer = req.peeraddr
99
+ peer && peer[3]
100
+ rescue StandardError
101
+ nil
102
+ end
103
+ LOOPBACK.include?(ip.to_s)
104
+ end
105
+
106
+ private def working_dir_for(session_id)
107
+ id = session_id.to_s
108
+ data = id.empty? ? nil : session_manager&.load(id)
109
+ dir = data && data[:working_dir].to_s
110
+ return Dir.home if dir.nil? || dir.empty? || !Dir.exist?(dir)
111
+
112
+ dir
113
+ end
114
+
115
+ private def clamp_int(value, min, max, fallback)
116
+ number = value.to_i
117
+ return fallback unless number.positive?
118
+
119
+ [[number, min].max, max].min
120
+ end
121
+ end
@@ -0,0 +1,397 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "securerandom"
5
+
6
+ module Clacky
7
+ module Extensions
8
+ module Terminal
9
+ # In-process pool of interactive shells backing the terminal panel.
10
+ #
11
+ # This file is loaded once via `require_relative` from handler.rb on
12
+ # purpose: ApiExtensionLoader re-`load`s handler.rb whenever its mtime
13
+ # changes (`ensure_fresh`), which installs a brand-new class object. Live
14
+ # PTYs must survive that edit, so they are owned here, not by the handler.
15
+ #
16
+ # Wire format (all JSON, one frame per event):
17
+ # server → client ext.terminal.ready { term_id, cwd, shell, status,
18
+ # exit_code, seq, replay }
19
+ # ext.terminal.output { term_id, seq, data }
20
+ # ext.terminal.exit { term_id, exit_code }
21
+ # client → server ext.terminal.attach | input | resize | close
22
+ #
23
+ # Data travelling in both directions is base64: PTY output is raw bytes
24
+ # and routinely splits a multi-byte UTF-8 sequence across reads, which
25
+ # JSON would either mangle or reject.
26
+ class Runtime
27
+ MAX_SESSIONS = 6
28
+ RING_BYTES = 256 * 1024
29
+ BATCH_WINDOW = 0.016 # seconds of output coalesced into one frame
30
+ UNATTACHED_TTL = 60 * 60 # an unattached live shell is reaped after this
31
+ EXITED_RETENTION = 5 * 60 # an exited shell stays listed while its pane shows the result
32
+ MAX_INPUT_BYTES = 64 * 1024
33
+ READ_CHUNK = 65_536
34
+ KILL_AFTER = 0.8 # grace between SIGTERM and SIGKILL
35
+ EXIT_WAIT = 10 # hard stop for the post-mortem wait
36
+
37
+ class CapacityError < StandardError; end
38
+ class PlatformError < StandardError; end
39
+
40
+ class Session
41
+ attr_reader :id, :cwd, :shell, :pid
42
+
43
+ def self.default_shell
44
+ @default_shell ||= begin
45
+ candidates = [ENV["SHELL"], "/bin/zsh", "/bin/bash", "/bin/sh"]
46
+ candidates.map(&:to_s).find { |path| !path.empty? && File.executable?(path) } || "/bin/sh"
47
+ end
48
+ end
49
+
50
+ def initialize(cwd:, cols:, rows:)
51
+ @id = SecureRandom.hex(6)
52
+ @cwd = cwd
53
+ @shell = self.class.default_shell
54
+ @mutex = Mutex.new
55
+ @write_mutex = Mutex.new
56
+ @subscribers = {}
57
+ @ring = +"".b
58
+ @seq = 0
59
+ @status = "running"
60
+ @exit_code = nil
61
+ @reaper_started = false
62
+ @closing_since = nil
63
+ @last_seen = Runtime.now
64
+ spawn_pty(cols, rows)
65
+ start_reader
66
+ end
67
+
68
+ def running?
69
+ @mutex.synchronize { @status == "running" }
70
+ end
71
+
72
+ def attached?
73
+ @mutex.synchronize { !@subscribers.empty? }
74
+ end
75
+
76
+ def last_seen_at
77
+ @mutex.synchronize { @last_seen }
78
+ end
79
+
80
+ # Bind a client connection and hand it everything the shell has
81
+ # produced so far, so a page reload restores the visible screen.
82
+ # Snapshot and subscription happen under the same mutex as output
83
+ # delivery, otherwise a chunk could land twice or not at all.
84
+ def attach(conn)
85
+ @mutex.synchronize do
86
+ @subscribers[conn.object_id] = conn
87
+ @last_seen = Runtime.now
88
+ conn.send_json(
89
+ type: "ext.terminal.ready",
90
+ term_id: @id,
91
+ cwd: @cwd,
92
+ shell: @shell,
93
+ status: @status,
94
+ exit_code: @exit_code,
95
+ seq: @seq,
96
+ replay: Base64.strict_encode64(@ring)
97
+ )
98
+ end
99
+ self
100
+ end
101
+
102
+ def detach(conn)
103
+ @mutex.synchronize do
104
+ @subscribers.delete(conn.object_id)
105
+ @last_seen = Runtime.now
106
+ end
107
+ end
108
+
109
+ def write(data)
110
+ return false if data.nil? || data.empty?
111
+ return false if data.bytesize > MAX_INPUT_BYTES
112
+
113
+ @write_mutex.synchronize do
114
+ return false if @writer.nil? || @writer.closed?
115
+ @writer.write(data)
116
+ true
117
+ end
118
+ rescue Errno::EIO, Errno::EPIPE, IOError
119
+ false
120
+ end
121
+
122
+ def resize(cols, rows)
123
+ cols = cols.to_i
124
+ rows = rows.to_i
125
+ return false unless cols.positive? && rows.positive?
126
+
127
+ @write_mutex.synchronize do
128
+ return false if @writer.nil? || @writer.closed?
129
+ @writer.winsize = [rows, cols]
130
+ true
131
+ end
132
+ rescue Errno::EIO, Errno::ENOTTY, Errno::EPIPE, IOError, NoMethodError
133
+ false
134
+ end
135
+
136
+ def close!
137
+ pid = @pid
138
+ reaper = @mutex.synchronize do
139
+ return self unless @status == "running"
140
+ next false if @reaper_started
141
+
142
+ @status = "closing"
143
+ @closing_since = Runtime.now
144
+ @reaper_started = true
145
+ end
146
+
147
+ signal(pid, "TERM")
148
+ start_reaper(pid) if reaper
149
+ self
150
+ end
151
+
152
+ # Synchronous kill for process shutdown. During normal operation the
153
+ # reaper started by #close! escalates instead.
154
+ def kill!
155
+ signal(@pid, "KILL")
156
+ self
157
+ end
158
+
159
+ # SIGTERM is advisory: an interactive shell may ignore it, and the
160
+ # reader thread is parked in readpartial meanwhile — it only reaches
161
+ # #wait_exit_code once the shell is gone. So the escalation to SIGKILL
162
+ # has to run on its own thread, or a TERM-proof shell leaks the pty
163
+ # and never reports its exit.
164
+ private def start_reaper(pid)
165
+ Clacky::ThreadRegistry.spawn(name: "terminal-reaper-#{@id}", daemon: true) do
166
+ deadline = Runtime.now + EXIT_WAIT
167
+ while Runtime.now < deadline
168
+ sleep 0.05
169
+ break if @mutex.synchronize { @status == "exited" }
170
+ if Runtime.now - @closing_since.to_f >= KILL_AFTER
171
+ signal(pid, "KILL")
172
+ break
173
+ end
174
+ end
175
+ end
176
+ end
177
+
178
+ private def signal(pid, name)
179
+ return nil if pid.nil?
180
+
181
+ Process.kill(name, pid)
182
+ rescue Errno::ESRCH, Errno::EPERM
183
+ nil
184
+ end
185
+
186
+ private def spawn_pty(cols, rows)
187
+ begin
188
+ require "pty"
189
+ require "io/console"
190
+ rescue LoadError => e
191
+ raise PlatformError, "interactive terminals are not supported on this platform (#{e.message})"
192
+ end
193
+
194
+ env = { "TERM" => "xterm-256color", "COLORTERM" => "truecolor", "PWD" => @cwd }
195
+ @reader, @writer, @pid = PTY.spawn(env, @shell, "-l", chdir: @cwd)
196
+ begin
197
+ @writer.winsize = [rows, cols]
198
+ rescue Errno::ENOTTY, Errno::EIO, NoMethodError
199
+ nil
200
+ end
201
+ rescue SystemCallError => e
202
+ raise PlatformError, "could not start #{@shell}: #{e.message}"
203
+ end
204
+
205
+ private def start_reader
206
+ @reader_thread = Clacky::ThreadRegistry.spawn(name: "terminal-pty-#{@id}", daemon: true) do
207
+ read_loop
208
+ end
209
+ end
210
+
211
+ # A shell answers a keystroke with a handful of tiny writes; sending
212
+ # each as its own WebSocket frame would triple the frame count for no
213
+ # visible gain. Coalesce whatever is already buffered into one frame.
214
+ private def read_loop
215
+ loop do
216
+ batch = +"".b
217
+ batch << @reader.readpartial(READ_CHUNK)
218
+ deadline = Runtime.now + BATCH_WINDOW
219
+ loop do
220
+ break if Runtime.now >= deadline
221
+ more = @reader.read_nonblock(READ_CHUNK, exception: false)
222
+ break if more == :wait_readable || more.nil?
223
+ batch << more
224
+ end
225
+ deliver(batch)
226
+ end
227
+ rescue Errno::EIO, EOFError, IOError
228
+ nil
229
+ ensure
230
+ finish!
231
+ end
232
+
233
+ private def deliver(bytes)
234
+ @mutex.synchronize do
235
+ @seq += 1
236
+ @ring << bytes
237
+ @ring = @ring.byteslice(-RING_BYTES, RING_BYTES) if @ring.bytesize > RING_BYTES
238
+ next if @subscribers.empty?
239
+
240
+ encoded = Base64.strict_encode64(bytes)
241
+ @subscribers.each_value do |conn|
242
+ conn.send_json(type: "ext.terminal.output", term_id: @id, seq: @seq, data: encoded)
243
+ end
244
+ end
245
+ end
246
+
247
+ private def finish!
248
+ code = wait_exit_code
249
+ subscribers = @mutex.synchronize do
250
+ next nil if @status == "exited"
251
+ @status = "exited"
252
+ @exit_code = code
253
+ @last_seen = Runtime.now
254
+ @subscribers.dup
255
+ end
256
+ subscribers&.each_value do |conn|
257
+ conn.send_json(type: "ext.terminal.exit", term_id: @id, exit_code: code)
258
+ end
259
+ close_ios
260
+ end
261
+
262
+ # Runs on the reader thread, so it must never block: Ruby cannot
263
+ # interrupt a thread parked in waitpid and will wait for it forever
264
+ # when the process exits, which hangs the whole app. Poll instead.
265
+ # SIGKILL escalation lives in #start_reaper, not here — this method is
266
+ # only reached once the shell is already gone.
267
+ private def wait_exit_code
268
+ deadline = Runtime.now + EXIT_WAIT
269
+ loop do
270
+ pid, status = Process.waitpid2(@pid, Process::WNOHANG)
271
+ return status.exitstatus || (status.termsig && 128 + status.termsig) if pid
272
+ return nil if Runtime.now > deadline
273
+
274
+ sleep 0.02
275
+ end
276
+ rescue Errno::ECHILD
277
+ nil
278
+ end
279
+
280
+ private def close_ios
281
+ [@reader, @writer].each do |io|
282
+ io.close
283
+ rescue StandardError
284
+ nil
285
+ end
286
+ end
287
+ end
288
+
289
+ @sessions = {}
290
+ @mutex = Mutex.new
291
+
292
+ class << self
293
+ def now
294
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
295
+ end
296
+
297
+ def open(cwd:, cols: 32, rows: 120)
298
+ sweep!
299
+ @mutex.synchronize do
300
+ live = @sessions.each_value.select(&:running?)
301
+ evict_one!(live) if live.size >= MAX_SESSIONS
302
+ live = @sessions.each_value.select(&:running?)
303
+ raise CapacityError, "at most #{MAX_SESSIONS} terminal sessions can run at once" if live.size >= MAX_SESSIONS
304
+
305
+ session = Session.new(cwd: cwd, cols: cols, rows: rows)
306
+ @sessions[session.id] = session
307
+ session
308
+ end
309
+ end
310
+
311
+ def find(term_id)
312
+ @mutex.synchronize { @sessions[term_id.to_s] }
313
+ end
314
+
315
+ def close(term_id)
316
+ session = @mutex.synchronize { @sessions.delete(term_id.to_s) }
317
+ session&.close!
318
+ session
319
+ end
320
+
321
+ def detach(conn)
322
+ sessions_snapshot.each { |session| session.detach(conn) }
323
+ end
324
+
325
+ def list
326
+ sessions_snapshot.map do |session|
327
+ { term_id: session.id, cwd: session.cwd, shell: session.shell,
328
+ status: session.running? ? "running" : "exited", pid: session.pid }
329
+ end
330
+ end
331
+
332
+ # Reap shells nobody is looking at. Runs on open() and on close, so a
333
+ # long-idle browser tab cannot pin a PTY (and its fds) forever.
334
+ def sweep!
335
+ now = self.now
336
+ stale = @mutex.synchronize do
337
+ doomed = @sessions.each_value.select { |session| stale?(session, now) }
338
+ doomed.each { |session| @sessions.delete(session.id) }
339
+ doomed
340
+ end
341
+ stale.each { |session| session.close! if session.running? }
342
+ end
343
+
344
+ def close_all!
345
+ doomed = @mutex.synchronize do
346
+ list = @sessions.values
347
+ @sessions = {}
348
+ list
349
+ end
350
+ doomed.each(&:close!)
351
+ doomed
352
+ end
353
+
354
+ # Process exit path: no grace period, nothing may outlive the app.
355
+ def shutdown!
356
+ close_all!.each(&:kill!)
357
+ end
358
+
359
+ def reset!
360
+ shutdown!
361
+ end
362
+
363
+ private def sessions_snapshot
364
+ @mutex.synchronize { @sessions.values }
365
+ end
366
+
367
+ # Called with the registry mutex held. Closing the tab of an
368
+ # unattached shell must not permanently consume one of the slots, so
369
+ # the least recently used one makes room instead of failing the new
370
+ # request outright.
371
+ private def evict_one!(live)
372
+ victim = live.reject(&:attached?).min_by(&:last_seen_at)
373
+ return unless victim
374
+
375
+ @sessions.delete(victim.id)
376
+ victim.close!
377
+ end
378
+
379
+ private def stale?(session, now)
380
+ idle = now - session.last_seen_at
381
+ return idle > UNATTACHED_TTL if session.running? && !session.attached?
382
+ return false if session.running?
383
+ idle > EXITED_RETENTION
384
+ end
385
+ end
386
+ end
387
+ end
388
+ end
389
+ end
390
+
391
+ at_exit do
392
+ begin
393
+ Clacky::Extensions::Terminal::Runtime.shutdown!
394
+ rescue StandardError
395
+ nil
396
+ end
397
+ end
@@ -0,0 +1,16 @@
1
+ id: terminal
2
+ name: Terminal
3
+ display_name: Terminal
4
+ display_name_zh: 终端
5
+ description: Interactive shell in the session's working directory, in the right panel
6
+ description_zh: 在当前会话的工作目录打开交互式终端(右侧面板)
7
+ version: "0.1.0"
8
+ icon: icon.svg
9
+ author: OpenClacky
10
+ license: MIT
11
+ enabled_by_default: false
12
+ contributes:
13
+ api: api/handler.rb
14
+ panels:
15
+ - id: terminal
16
+ view: panels/terminal/view.js
@@ -0,0 +1,13 @@
1
+ <svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
2
+ <defs>
3
+ <linearGradient id="terminal-bg" x1="18" y1="0" x2="18" y2="36" gradientUnits="userSpaceOnUse">
4
+ <stop stop-color="#3F3F46"/>
5
+ <stop offset="1" stop-color="#18181B"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect width="36" height="36" fill="url(#terminal-bg)"/>
9
+ <g transform="translate(8 8) scale(0.8333)" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
10
+ <polyline points="5 7 10 12 5 17"/>
11
+ <line x1="13" y1="17" x2="20" y2="17"/>
12
+ </g>
13
+ </svg>