32 Commits
Author SHA1 Message Date
nianyucatfish e86ca723a9 fix(tui): polish rendering, history preview, and copy behavior (#816)
* fix(tui): repaint composer after macOS input

* feat(tui): add compact conversation history

* fix(tui): repaint messages after streaming and scroll

* fix(tui): polish history focus and scrollbar styling
2026-09-22 23:42:24 +08:00
nianyucatfish f6e5657fbe docs(ganet): cover macOS in the PC device-link setup SOP (#791)
GAnet 0.5.0 ships macOS sidecars, so the SOP no longer stops on non-Windows
desktops. The flow itself is unchanged; the edits are the platform facts GA
needs to follow it on a Mac:

- default component location moves to ~/.genericagent/components/GAnet on
  every platform; a checkout under the GA root's temp/ is wiped by the temp
  rewind mechanism
- launcher is ganet.cmd on Windows and ganet.sh on macOS; the bound Python
  shim is ga_python.cmd / ga_python.sh
- sidecar data lives in %LOCALAPPDATA%\GenericAgent\GAnet or
  ~/Library/Application Support/GenericAgent/GAnet; login autostart is the
  HKCU Run entry or a LaunchAgent; both are removed by remove_environment()
- release entries for macOS use platform "darwin", and verify_release checks
  Mach-O as well as PE
- on macOS, setup and upgrades request the screen-recording permission at the
  end and report it in screen_access; it is advisory and never blocks
- macOS needs no sudo; git/python placeholders without Xcode CLT must not be
  invoked
2026-09-03 14:37:00 +08:00
nianyucatfish 7ad2162f30 docs(ganet): add PC device-link setup SOP (#786)
Adds the standalone Windows GAnet device-link setup and removal SOP.

Known review risks accepted by maintainer.
2026-08-28 22:18:18 +08:00
nianyucatfish be90c8d2d3 fix(tui-v2): detach tool subprocess stdin (#678) 2026-07-10 22:25:54 +08:00
nianyucatfish cdc2a3abeb fix(continue): hide archived orphan worldlines (#677) 2026-07-10 22:25:11 +08:00
nianyucatfish 14d8df3ddd feat(worldline): persistent checkpoint-tree rewind for tui_v2 (/rewind + /worldline) (#667)
* feat(worldline): integrate checkpoint-tree rewind into tui_v2

- tuiapp_v2.py: /rewind durable inline picker + /worldline three-pane
  checkpoint tree (tree UI inlined; colors follow the v2 theme) with a
  per-node diff viewport; conv-only /rewind restores via the persistent store.
- worldline.py (new): UI-agnostic backend — RewindStore (persistent
  checkpoint tree + content-addressed blobs), reconcile, restore_plan,
  node_diff, native-log projection.
- continue_cmd.py: gated worldline support — list_sessions(rewind_root=),
  continue_inplace/copy(allow_empty=); default-off, other UIs byte-identical.
- tui_v3.py: status line shows concrete model id (unrelated minor tweak).

* feat(worldline): /rewind reuses the restore-mode picker (conv/code/both)

After picking a turn, /rewind now opens the same RestoreModeScreen as
/worldline to choose conversation / code / both, then restores via the
persistent store — making /rewind a true lite view of /worldline (linear
list, no tree/diff) over the identical restore backend.

* feat(worldline): sync working memory (history_info/key_info) on rewind

树节点除 conv 外,再存 history_info 增量(与 conv 同构)+ key_info 快照。
restore_plan 重建二者,_rw_sync_working_memory 在 rewind 时就地写回
handler.history_info / working['key_info'],使注入的 WORKING MEMORY 与
回退后的对话一致,消除旧 rewind「历史回退、纪要串味」缺陷。

向后兼容:老树无 WM 记录 → path_has_wm=False → 恢复时跳过 WM 同步,
不动现场纪要。单测 21/21 + 真机(363580)端到端验证(call_013→014
v2 痕迹 ×3→×0)通过。

* fix(worldline): reconcile against the log, only on /continue; rebuild working memory on absorb

- reconcile now takes the log-parsed full history, never the compressed
  backend.history. Compressed memory is a lossy derivative; reconciling the
  full tree against it made the tree adopt a front-trimmed suffix as a new
  trunk (false divergence). Contract pinned in the docstring.
- drop in-session reconcile from /rewind and /worldline: the tree is kept
  current every turn by _rw_commit, and live history there is compressed.
  reconcile now runs only on /continue, where backend.history is the freshly
  loaded full log.
- reconcile rebuilds history_info/key_info from the absorbed log so resumed
  and external-UI sessions also carry working memory on rewind.

* fix(worldline): feed commit the full log; derive deltas from the tree's real length

_rw_commit fed the compressed backend.history, so once a long session front-trims,
commit's absolute hist_len delta drops turns. Now:
- _rw_commit feeds the log-parsed full history (fallback to backend.history).
- commit derives the delta start from len(rebuild_history(parent)) /
  len(rebuild_hist_info(parent)) instead of the stored hist_len, so a poisoned
  count can't drop turns and a previously-lost turn self-heals on the next commit
  (the log is append-only, always a superset of the tree).

* chore(worldline): mark in-memory _do_rewind as the non-persistent degraded fallback

It chops the compressed live history (can't reach front-trimmed turns, keeps
truncated remnants, restores neither files nor working memory). Only used when
there is no checkpoint tree; the durable tree-rebuild path is always preferred.

* fix(worldline): derive tree working memory from the log, not live handler state

/continue resets agent.history (handler.history_info) to empty. _rw_commit
previously fed that live list as hist_info, so after a continue the per-turn WM
delta misaligned with the tree's log-derived WM and new turns' summaries were
dropped. commit now derives hist_info/key_info from the history it stores (the
full log) when not given, matching reconcile; _rw_commit stops passing the live
list. Tree WM is uniformly log-derived and survives the continue reset.

* feat(worldline): restore working memory on /continue (TUI-only, derived from the log)

continue_cmd clears handler.history_info on restore; the TUI's continue path now
derives history_info from the loaded log (same _derive_hist_info as the tree) and
writes it back to agent.history, so a continued session keeps its working memory,
consistent with the tree and live sessions. Scoped to tuiapp_v2 only — shared
continue_cmd is untouched, so telegram/discord/streamlit frontends are unaffected.

* refactor(continue): restore working memory on /continue via opt-in restore_wm

Move the WM restore from the TUI into continue_cmd as an opt-in. _load_history_into
derives history_info from the loaded log and writes it back to agent.history when
restore_wm=True; continue_inplace/continue_copy thread the flag and the worldline
TUI passes True. Default False keeps every other frontend (telegram/discord/
streamlit/shared chat) byte-for-byte unchanged. _derive_hist_info is self-contained
(no worldline dependency), same extraction口径 as the tree.

* perf(worldline): only re-parse the log in _rw_commit when front-trim is detected

_rw_commit re-parsed the whole log every segment to feed commit a full history;
for very long sessions (multi-MB logs) that adds a multi-second lag per turn. Now
it uses the fast in-memory backend.history by default and only falls back to
parsing the log when front-trim is detected — RewindStore.first_question() vs the
live history's first question (front-trim pops the first question, so they diverge).
Common case (no trim) pays nothing; correctness under trim is preserved.

* feat(worldline): conv/code bridge nodes + align _rw_commit to native log

- worldline: commit_bridge() + restore_plan() three-way (both/conv/code) with a new rw_tag field. conv bridges fork at parent(target); code bridges mount at parent(old_head) as a sibling of the current conversation node (same conversation, older code).

- tuiapp_v2: _rw_commit now reads the native log (parse_native_log) instead of the compressible live backend.history; stat-cached _rw_log_history; title from the real log delta; skip commit when there is no new complete pair. Cursor points at the bridge for conv/code; rw_tag rendered after the title.

- continue_cmd: add parse_native_log() public wrapper (complete Prompt->Response pairs only; [] for native-but-empty, None for non-native).

* fix(worldline): realpath 去重 key + 节点行数增删 + 剥离 project-mode

- key()/cwd 改用 realpath 解析 junction/symlink,同一物理文件只产生一个 tracked
  key(修 workspace 下 @提及绝对路径与相对写入产生双 key、回退误覆写当前内容)
- 新增 node_line_delta:按 node_diff 计每节点相对父节点的 +新增/-删除 行数,
  供 /rewind、worldline 显示代码变动量
- 重建历史时剥离 project-mode 注入块与自动注入标记(worldline._msg_user_text +
  continue_cmd._derive_hist_info),标题/提问只留用户原话

* feat(worldline/rewind): 面板与 rewind UI 精简重设计

worldline 面板:
- 右栏改用原生 OptionList(整项高亮/滑窗跟踪/点击映射,取代手写 ClickableList)
- 左右栏比例 3:2;详情面板精简(删掉与状态条/diff 重复的操作提示、时间、回退说明)
- 状态条重写为完整动宾短语,Enter 随聚焦切文案;右栏聚焦高亮改用更亮的 alt_bg
  (对齐左树,修此前聚焦态反而更淡的问题)

/rewind:
- 三列:用户 prompt · 上次时间 · 代码 +新增/-删除(绿/红,无改动显示「(无改动)」);
  倒序、聚焦底部、超长 prompt 省略号截断
- 延迟折叠(defer_collapse):选中先弹模式窗,确认才回退并清卡片;Esc 取消保留列表、
  焦点回到列表,不再留误导性「✓ 已选中」

其他:
- Ctrl+D 关会话时释放日志锁(abort + release_current),之后可原地 /continue

* fix(worldline): 回填输入框的 prefill 剥离 project-mode 注入

restore_plan 的 prefill/_prompt_of 走未清洗的 user_msg_text(树里的 user 消息取自
含注入的 native 日志),把 --- [PROJECT MODE:...] --- 一起塞进输入框。统一过
_strip_project_mode(幂等)。回归:temp/test_rewind_prefill_no_projectmode.py 9/9。

* refactor(tui): 删除被取代的旧 rewind 面板与死代码

- 删旧 /rewind 整簇:RewindScreen 类 + _on_rewind_pick + _rw_* 9 个 helper
  (已被内联 choice 卡 + RestoreModeScreen / RewindTreeScreen 取代,无 live 入口)
- 删未用 import next_same_depth/CheckpointTree、只写不读的 _diff_for/assistant_len
- 净 -276 行;import tuiapp_v2 通过、worldline 回归全绿

* fix(worldline): apply_code 回退失败不再静默,回传错误由 UI 提示

apply_code 直接写用户工作区文件,中途失败(权限/磁盘)会留下半回退状态。原先
restore_plan 吞成 changed=[],UI 显示「无变更」,用户毫不知情——全 PR 里失败半径
最大却唯一被静默的点。改为 _apply_code_safe 回传 (changed, code_error),
_rw_restore_node 据此追加「⚠️ 代码回退未完成…请检查」告警。
2026-07-07 08:36:28 +08:00
nianyucatfish 42804b5312 Merge pull request #17 from dd3xp/fix/bridge-takeover
便携包可移动 + bridge 接管 + 常驻后端
2026-06-19 06:12:18 +08:00
nianyucatfish 90078ea68d Merge pull request #16 from dd3xp/fix/service-process-lifecycle
端口占用拒绝启动与退出清理
2026-06-19 04:56:27 +08:00
nianyucatfish 774000f591 feat(worldline): checkpoint-tree rewind for tui_v2 (#625)
* fix(continue): preserve session workspace on in-place restore

In-place /continue retargets agent.log_path to the restored file, so the
reset bind `_bind_workspace(None)` ran during restore was persisting
session_ws_set(path, "") — erasing that session's own workspace mapping to
"" (read back as "explicitly off") before we read it, which also short-
circuited the log-scan fallback. The continued session never re-entered its
workspace.

Add a `persist` flag to `_bind_workspace`; the restore-time reset passes
persist=False so it only refreshes in-memory state. The session→workspace
map is now written solely by explicit /workspace, /workspace off, and a
successful restore.

* fix(tui_v3): support Home/End keys for line start/end

PTK delivers Home/End as raw VT sequences in KeyPress.data, which
_esc_repl swallowed (only arrows were decoded). Map \x1b[H/[F/[1~/[4~
and SS3 \x1bOH/\x1bOF to internal bytes 0x07/0x14, extend _ESC_RE to
match SS3 as whole sequences, and add jump-to-line-start/end handlers
in _keys. Home no longer collides with Ctrl+A select-all.

* feat(worldline): integrate checkpoint-tree rewind into tui_v2

- tuiapp_v2.py: /rewind durable inline picker + /worldline three-pane
  checkpoint tree (tree UI inlined; colors follow the v2 theme) with a
  per-node diff viewport; conv-only /rewind restores via the persistent store.
- worldline.py (new): UI-agnostic backend — RewindStore (persistent
  checkpoint tree + content-addressed blobs), reconcile, restore_plan,
  node_diff, native-log projection.
- continue_cmd.py: gated worldline support — list_sessions(rewind_root=),
  continue_inplace/copy(allow_empty=); default-off, other UIs byte-identical.
- tui_v3.py: status line shows concrete model id (unrelated minor tweak).

* feat(worldline): /rewind reuses the restore-mode picker (conv/code/both)

After picking a turn, /rewind now opens the same RestoreModeScreen as
/worldline to choose conversation / code / both, then restores via the
persistent store — making /rewind a true lite view of /worldline (linear
list, no tree/diff) over the identical restore backend.
2026-06-18 08:40:42 +08:00
nianyucatfish 1f2e38c6e3 fix(continue): preserve session workspace on in-place restore (#621)
In-place /continue retargets agent.log_path to the restored file, so the
reset bind `_bind_workspace(None)` ran during restore was persisting
session_ws_set(path, "") — erasing that session's own workspace mapping to
"" (read back as "explicitly off") before we read it, which also short-
circuited the log-scan fallback. The continued session never re-entered its
workspace.

Add a `persist` flag to `_bind_workspace`; the restore-time reset passes
persist=False so it only refreshes in-memory state. The session→workspace
map is now written solely by explicit /workspace, /workspace off, and a
successful restore.
2026-06-16 21:38:01 +08:00
nianyucatfish 6aecec1431 feat(continue): default in-place restore + per-session lock (copy-on-conflict) (#617)
/continue N 默认改为「原地续」:接管原会话日志、后续轮次写回同一文件,取代旧的
镜像复制(supersedes b4356c7 的 mirror 方案),不再每次续接都 fork 新会话、日志增殖。

- 空闲会话 → 直接原地接管;被活进程占用 → 弹窗确认后才复制一份续。
- 每会话出生持锁(temp/model_responses/.locks/<logid>.lock),整进程共用一个心跳
  线程每 5s touch mtime、30s 无心跳判死可接管;atexit 干净释放,崩溃/强杀靠超时兜底。
- 切走/新对话不再「快照+清空」(原 _snapshot_current_log 因 logid≠pid 实为死代码,
  从未生成过快照),旧日志原样留作空闲会话,新对话铸新 logid。
- list_sessions 新增 exclude_log,修正 exclude_pid=getpid 失效导致当前会话出现在
  自己列表里的问题。
- continue_cmd 仅新增函数,reset_conversation/restore/handle 未改动 → 其他前端
  (IM/qt/streamlit 等)行为完全不变。
- 改动仅限 continue_cmd.py + tui_v3.py + tuiapp_v2.py;rewind/worldline 逻辑不在本 PR。
2026-06-15 21:20:20 +08:00
nianyucatfish 1d976dd40f fix(tui-v3): /continue 恢复后镜像源日志,避免续聊丢失旧历史 (#612)
v3 的 _do_restore 此前只把历史载入内存 backend.history,不碰当前进程日志。native 后端逐轮只把新增消息 append 到 model_responses_{pid}.txt,恢复出的旧历史从不写入当前日志——续聊只追加增量,下次 /continue 扫到的本进程文件就只剩续聊部分,旧历史丢失。

对齐 v2 _do_continue_restore:恢复前 reset_conversation(快照+清空当前日志),恢复后 copyfile(源日志 → 当前日志),续聊便接在完整历史之后。
2026-06-15 08:59:37 +08:00
nianyucatfish 84254ad762 feat(tui): workspace 项目模式 + @ 文件引用补全(v2/v3) (#607)
* feat(tui): workspace 项目模式 + @ 文件引用补全(v2/v3)

- workspace: /workspace 设/off/picker、junction 复用 project_mode 记忆、
  per-session(v2)/进程级(v3)、/continue 恢复、session map 持久化绑定状态
- @ 补全(completion-only): 子序列模糊 + path-like 目录补全(~/ / ./ C:\)、
  提交期 @路径作为普通文本交 agent
- v3 filterable 焦点链 picker(输入框作焦点环对象、free_input)
- 新增共享模块 at_complete.py / workspace_cmd.py;核心零改动

* feat(tui): @ 路径绝对化 + 默认根=temp + 未绑显示完整路径

- 默认根 os.getcwd() → agent 工作目录 <GA根>/temp(与 file_read/code_run 一致、不随启动 cwd 飘)
- 提交期 @相对 → @绝对(display 保留相对短路径),让 agent file_read(相对自身 cwd)找得到
- 未绑 workspace 时候选显示完整路径(根不直观);索引忽略 model_responses 会话日志噪音
- 启动预热 temp 索引 + candidates_for 惰性兜底(任何根首次访问自动建)
2026-06-14 09:10:04 +08:00
nianyucatfish 262614cafd fix(tui-v2): restore CJK table copy alignment (#600)
The tool-cards change (#593) tightened _md_line_has_box_drawing to exempt
pure-horizontal '─' runs as markdown hr. But a SIMPLE-box Markdown table's
only box glyph is its header rule, so that exemption dropped whole tables
out of the passthrough copy path and into the wide-render aligner, which
maps selection cell-columns to character indices — misaligning copy of any
table with CJK (wide) cells.

Remove the pure-horizontal exemption so a table's header rule is detected
again and the table run stays passthrough. Card gutters (└─ / │ / └) keep
their own prefix-based exemptions, so tool cards are unaffected. The only
cost is a real markdown hr copying as a dash run — the pre-#593 behavior.
2026-06-12 13:15:34 +08:00
nianyucatfish 5b43813814 feat(tui): plan 卡片 /continue 恢复 + 可滚动 4 行窗口 + Ctrl+S/Ctrl+C 修复 (#599)
* feat(tui): /continue 恢复 plan 卡片 + Ctrl+S/Ctrl+C 路由修复

plan-card 恢复:plan 模式判定改用日志中结构化的 enter_plan_mode
tool_use(continue_cmd.find_plan_entry),不再扫聊天文本——用户打字
伪造不出。is_active/resolve_path 新增 restored_path 信号,AgentSession
新增 restored_plan_path 字段,plan_scan_baseline 退化为仅供 current_step
的 📌 扫描用。

Ctrl+S restore 卡死:_stash_cleanup_restore 由 self.text= 改为
clear()+_insert_via_keyboard,走编辑管线避免长会话全屏 relayout,与
stash 清空路径对称。

Ctrl+C 弹回收紧:_cmd_stop 仅在该轮未被消费(agent 尚未产出回复)时
才把 user 文本弹回输入框,避免已答轮次污染输入框 / 重发导致历史重复。

* feat(tui): plan 卡片可滚动(4 行任务窗口)+ TODO 渲染为 [ ]/[x]

planbar 拆为固定表头/步骤行(#planbar-head)+ 任务滚动区
(#planbar-tasks,max-height:4)。最多露 4 个 TODO,其余滚轮/PageUp
翻看,去掉旧的 5 行预算与 ⋮ +N more 截断;表头与当前步骤行固定不滚。

任务标记 ☐/✔ → [ ]/[x],与 plan.md 源文件写法对齐。
2026-06-11 21:11:25 +08:00
nianyucatfish 9badef879d feat(tui): 工具显示卡片 + /model 与 /effort 运行时切换 (#593)
tuiapp_v2 的两项增强,拆成两个 commit。

## 1. 工具显示卡片(file_write / file_patch / file_read / code_run)
把 agent_loop verbose 的 `🛠️ Tool` 块替换为紧凑卡片:
- **file_write / file_patch**:行号 + 上下文的主题化 diff;append/prepend 走整文件 diff 拿真实上下文。
- **file_read**:读到的内容带行号 gutter,剥离 LLM-facing 噪音(`[FILE]`/show_linenos 前言/截断提示),超长折叠;行号在不可知处(keyword 窗口 / 挖洞后)留空。
- **code_run**:参考 Claude Code / Codex 的 exec 渲染,无边框、`│` 命令 gutter + `└` 输出 gutter,输出 dim、**保尾截断**(traceback 关键在末尾);代码来自正文 ```块``` 时不重复展示。
- 三卡共用 `_CardWriter` / `_card_status_row` / `_emit_gutter`;2 格左 margin 只进显示流、不进复制源。
- capture 机制:live 走 `tool_before/after` 钩子,`/continue` 走 `iter_write_captures` 从历史 tool_result 重建,按 `hash(get_pretty_json(args))` 内容寻址。
- 双流渲染对齐(`_align_md_renders`)支持 margin 映射,鼠标复制不含视觉缩进。

## 2. /model 与 /effort 渠道内运行时切换
- **/model**:在线拉模型列表的 searchable picker;搜索框兼作自定义模型名输入(无匹配时 Enter 直设)。
- **/effort**:reasoning effort 档位切换,协议差异在 `effort_note` 单点编码——Claude(`output_config.effort`) low/med/high 原样、xhigh→max、none/minimal 忽略;OpenAI(`reasoning_effort` / `reasoning.effort`) 透传;mixin 经 `_BROADCAST_ATTRS` 广播到全部子渠道。
- 逻辑收在 `frontends/model_cmd.py`(agent 无关、可单测)。

## 测试
- 卡片:两份真实会话日志全链路重放,51 个 code_run + 23 read + 20 write 全部渲染、双流 parity、复制不含 margin。
- /model /effort:拦截真实 llmcore 请求构造验证 effort 进 payload(含 mixin 广播、各协议字段);picker 自定义输入走 Textual pilot 端到端。
2026-06-11 09:19:09 +08:00
nianyucatfish da6a4ba558 fix(tui-v2): copy via native clipboard, OSC 52 only over SSH (#581)
Ctrl+C / selection copy fell back to Textual's OSC 52 escape on Windows/Linux.
Some terminals (notably VSCode's integrated terminal) decode the OSC 52 base64
payload as latin-1 instead of UTF-8, so non-ASCII copied text lands in the
clipboard as mojibake (e.g. 需要 -> éè¦). Classic Windows conhost ignores
OSC 52 clipboard writes entirely, so copy was a silent no-op there (incl.
Windows Server).

Prefer the OS-native clipboard (_copy_to_clipboard: win32 CF_UNICODETEXT /
pbcopy / wl-copy / xclip), which writes real Unicode and bypasses the terminal.
Keep OSC 52 only as a fallback, and force it under SSH (SSH_CONNECTION /
SSH_TTY) where the native call would write the remote host's clipboard instead
of the user's local one.
2026-06-08 10:47:29 +08:00
nianyucatfish 607cbdaf13 fix(tui v2): serialize terminal escapes via driver + scrollable sidebar (#572)
- _term_write(): route OSC/control sequences through Textual's driver writer
  queue instead of direct sys.__stdout__. A title/OSC write landing mid-frame
  during streaming used to split Textual's own escape sequences, rendering as
  flashing ANSI garbage; serializing on the same writer queue lands it cleanly.
- sidebar: wrap the session list in a VerticalScroll (#sidebar-scroll) so it
  scrolls when overflowing (scrollbar-gutter reserved to avoid row reflow);
  inner #sidebar Static keeps padding so the click hit-test math is unchanged.
  Keyboard session-switch scrolls the active session into view.
2026-06-05 18:44:01 +08:00
nianyucatfish c9c3dbc58e fix(tui): stdout blank lines, leaked task_dir folders, and /continue search nav (#554)
* fix(tui): stop CRLF stdout rendering as blank lines (v2)

Windows child stdout is `\r\n`; the streaming path fed it straight to
`Text.from_ansi`, which treats `\r` as a carriage return and erases each
line's text, so a `[Stdout]` block rendered as a run of blank lines until
the turn finished (the done-state Markdown render strips `\r`). Normalise
`\r\n` -> `\n` before `from_ansi`; lone `\r` is kept so progress-bar
overwrites still work.

* fix(tui): stop leaking empty per-session task_dir signal folders

Both v2 and v3 eagerly `os.makedirs` the per-session `_intervene` /
`_keyinfo` signal dir, but the only writer (`_intervene`) already creates
it lazily — so every session that never used intervene left a stale empty
`temp/_tui_v2_<pid>_<id>` / `temp/_tui_v3_<pid>` behind (85+ accumulated).
`consume_file` tolerates a missing dir, so the eager create is redundant.

- Set only the task_dir *path*; let the writer create it on first inject.
- Remove empty dirs on session close (v2 `_cmd_close`), on graceful exit
  (v2 `on_unmount`, v3 `_cleanup`), and sweep stale ones left by crashes
  at startup (v2 `on_mount`, v3 `main`). `os.rmdir` only removes empty
  dirs, so a still-pending `_intervene` is never clobbered.

* fix(tui): repair /continue search box cursor & up-nav loop (v2)

The SearchablePicker swallowed Right while the search Input had focus
(always treating it as "select"), so the caret could never move right in
the query. And Up could leave the list but never return: from the search
box Down entered the list, yet Up at the top row was stuck.

- Right commits the highlight only when the caret is already at end of the
  query; otherwise it moves the caret within the search text.
- Up on the first list row returns focus to the search box (scoped to
  /continue — no-op for ChoiceLists outside a SearchablePicker), clearing
  the highlight so the next Down re-enters at the first row, not the second.
- Up from the search box wraps around to the bottom of the list.
2026-06-01 23:07:28 +08:00
nianyucatfish e40c0f19cb fix(tui): drain exit-boundary intervened replay (#533)
* fix(tui): drain exit-boundary intervened replay

* refine(tui): soften intervened message prompt
2026-05-29 21:55:50 +08:00
nianyucatfish 7d001ca8a7 fix(tui_v2): /continue resumes unfinished plan + /stop refills input (#508)
/continue previously pushed plan_scan_baseline past every restored
message, so plan_state.is_active() saw an empty slice and hid the card —
even when the prior session's plan.md still had `[ ]` items the user
wanted to keep working on. `working['in_plan_mode']` isn't replayed by
the log restore either, so the card never came back.

Make the baseline conditional: default to 0 so the scanner walks the
full restored history; only push past it when the restored plan.md is
already all-done, suppressing the stale ✓ card. Resolved-path missing
or empty items naturally fall back to "no card".

/stop now also refills the input box with the just-sent user message,
so an interrupted send is one keystroke from edit-and-resend. Only
when the box is empty (don't clobber a half-typed follow-up). Agent
history is untouched — a resend duplicates the turn in LLM context;
/rewind 1 is the manual escape.

Behaviour matrix (/continue):
  unfinished plan  → baseline=0, scanner finds path, card resumes
  completed plan   → baseline=len(msgs), card stays hidden
  plan.md deleted  → resolve_path None, card stays hidden
  fresh enter_plan_mode after continue → working flag re-arms, normal
2026-05-27 22:05:00 +08:00
nianyucatfish b5f094baab feat(tui v2): selection/paste/scroll/reload polish (#424)
Eight independent fixes accumulated since the last batch, all landing in
tuiapp_v2.py:

1. Code-block selection offset: _align_md_renders's is_centered heuristic
   tripped on any code line indented >=4 spaces (Python's default), stripping
   the indent from the source string so the visible selection and the copied
   text disagreed. Add wide_lead >= 2*nt0_lead guard — only Rich's H1 centering
   (wide_lead ~ width/2) crosses it, code lines never do.

2. Blockquote-continuation selection offset: Rich re-emits `▌ ` on every
   wrapped visual line of a quote, but the wide-render carries the marker
   only once. Strip the marker as a decoration prefix (counts as indent, not
   content) and switch the wrap-accumulator to account for the per-break
   eaten space — both pre-existing code-block wraps and blockquotes now map
   correctly.

3. Streaming ANSI garbage: while a turn is streaming, the tail text segment
   was rendered with `Text(content, style=C_FG)` instead of `Text.from_ansi`.
   SGR codes from the model/tool output would render as literal `[31m`
   glyphs and only resolve after `m.done` flipped or a resize forced a
   remount via the Markdown path. Switch the two streaming fast paths to
   Text.from_ansi — O(n) scan, no Markdown parse, colors honored live.

4. continue picker LIMIT removed: tuiapp's own `LIMIT = 20` truncated the
   /continue picker even though list_sessions() always builds the full list.
   Show everything; header now reads "选择要恢复的会话 (N 条)".

5. Long-paste rescue + user echo elision: Windows Terminal yanks window
   focus when its >=5KiB paste-warning dialog pops, leaving focused=None
   after the user confirms; Textual then routes the Paste event to the App
   bubble instead of InputArea, and the paste appears to do nothing. Add a
   GenericAgentTUI._on_paste forwarder that refocuses #input and replays the
   event into InputArea._on_paste. Separately, on submit, elide user-side
   display of very long pastes (head 10 / tail 5 / `⋯ 省略 N 行 ⋯`); the
   agent still receives the full content via expand_placeholders.

6. mykey.py hot reload: load_llm_sessions() already had mtime-gated reload
   plumbing, but it only ran on Agent.__init__ / next_llm / list_llms — so
   editing mykey.py mid-session required restart. Two triggers added:
   on_input_area_submitted now calls load_llm_sessions() before sending
   (cheap mtime check; rebuilds on change), and a new /reload-keys command
   forces a sweep across every session (resetting llmcore._mykey_mtime
   per-iteration so the cache doesn't short-circuit later sessions).

7. Resize / sidebar toggle no longer jumps to bottom: _remount_current_session
   used to unconditionally scroll_end after rebuilding. Capture scroll_y +
   "was at bottom?" first; stick to bottom only if the user was already there,
   otherwise restore the prior scroll_y so resizes don't yank the user away
   from what they were reading.

8. Markdown table cells wrap instead of ellipsizing: Rich's Markdown
   TableElement passes no `overflow` to Table.add_column, so the default
   "ellipsis" hides long cell content with `…` on narrow widths. Patch
   TableElement.__rich_console__ on import to pass overflow="fold".
2026-05-19 09:30:16 +08:00
nianyucatfish eb7c84cf78 feat(tui): improve message scrolling and rewind picker (#392)
* feat(tui): improve message scrolling and rewind picker

* feat(tui): add double-escape rewind shortcut
2026-05-16 08:10:09 +08:00
nianyucatfish 85d2c4809d feat(tui): click-to-expand folds, streaming spinner, layout polish (#390)
- Per-fold click-to-expand: assistant messages render as a sequence of
  text/fold-header/fold-body widgets; FoldHeader is a clickable Static
  that toggles m._toggled_folds and remounts just that message
- Ctrl+O is authoritative: clears all per-fold overrides so the state
  is uniformly all-collapsed or all-expanded
- Streaming spinner: dedicated tiny Static (`m._spinner_widget`) after
  segment widgets, driven by an independent 100ms timer. Bypasses
  Markdown completely so unclosed code fences / paragraph whitespace
  trimming can't eat it
- Hide `**LLM Running (Turn N) ...**` markers at render time only;
  fold_turns still uses them for splitting
- Ctrl+B sidebar toggle: invalidate width-keyed cache and reuse the
  resize debounce path so the chat reflows reliably after toggling
- #input min-width: 10 — guards Textual TextArea.render_lines against
  `range() arg 3 must not be zero` when sidebar is shown on a very
  narrow window and #main collapses to ≤ 0 cols
2026-05-15 18:19:29 +08:00
nianyucatfish dfac66d972 fix(tui): file paste, block-delete, ctrl+c copy, per-session input (#389)
- Pasting non-image files (.docx/.pdf/.py …) was folded as `[Image #N]`
  because clipboard helper returned any file path. Split into image vs
  file by extension; non-images now fold as `[File #N]` and expand to
  the path on submit, same flow as images.
- Backspace/Delete used to nibble placeholders one char at a time.
  Override `action_delete_left/right`: when the caret sits flush against
  a `[Pasted text #N +X lines]` / `[Image #N]` / `[File #N]` placeholder
  on the matching side, remove the whole span and drop its dict entry.
- Ctrl+C inside the input was clearing the whole field. Root cause:
  `screen.get_selected_text()` doesn't see TextArea's internal selection,
  so the handler fell through to the input-reset branch. Fixed by
  preferring the focused InputArea's `selected_text` before screen-level
  drag selection.
- Input text/history/pastes were globally shared across agent sessions
  (single InputArea widget). Moved the four state slots
  (text/history/pastes/paste_counter) onto `AgentSession`, with a
  `_swap_input_for_session` snapshot/restore on session switch.
2026-05-15 15:38:53 +08:00
nianyucatfish b4f0763cc8 feat&fix(tui): paste/scroll polish, /continue & /export pickers, mac aliases (#379)
* fix(tui): compat _select_state for textual 8.2.6 (was _select_start)

* feat(tui): right-click paste, sticky scroll, /continue & /export pickers, mac aliases

- InputArea 右键粘贴:复用 _insert_paste_text 多行折叠,统一文本/图片/Ctrl+V 三条粘贴路径
- action_paste 兜底通过 tkinter 读 OS 剪贴板,修复 Ctrl+V 在非 bracketed-paste 终端拿不到外部内容
- 消息区 sticky-bottom 跟随:用户上滚自动取消跟随;提交消息或斜杠命令完成后强制 scroll_end
- /continue 无参打开 ChoiceList(上限 20 项,超出标注 [仅显示最近 N/M]);恢复操作通过 call_after_refresh 推迟,避免折叠 widget 引用失效
- /export 选 "file" 改为预填可编辑文件名:/export <timestamp>.md,可改名/改后缀后回车
- macOS 防御性 Cmd 别名:cmd+c / cmd+v / cmd+n / cmd+/ 镜像对应 Ctrl 绑定;on_key disarm 兼容
- 顺手清理:_handlers dict 取代手写 if-elif 链;注释精简;修复 /branch deepcopy crash、/clear+/rewind DOM 未清的 bug;sidebar 末次提问解耦 sess.messages,改读 LLM 端 history 以保持 /clear 后预览不变
2026-05-14 22:48:10 +08:00
nianyucatfish 9bef576b36 Feat/v2 keybindings (#365)
* fix(tui): debounce v2 layout reflow on resize

Same-size resize events are deduped, layout reflow is debounced to 80ms,
and message remount is deferred to the next frame so #messages.content_region
reports the post-resize width instead of the pre-resize one.

* feat(tui): rebind v2 keys (Ctrl+C dual, Ctrl+↑↓ sessions, Ctrl+O fold) + help overlay

- Ctrl+C is the single stop/quit key: stops a running task; otherwise
  clears non-empty input; otherwise arms quit (press again within 2s to
  exit). Removes Ctrl+S, Ctrl+Q, and InputArea's prior Ctrl+C
  copy-or-clear binding. Any non-Ctrl+C key disarms the pending quit.
- Ctrl+O toggles turn fold (was Ctrl+F, which collides with terminal
  app search shortcuts on macOS). Topbar gains a small "▾ fold"
  indicator when fold mode is on.
- Ctrl+Up / Ctrl+Down switches sessions (was Ctrl+Left / Ctrl+Right)
  to match the vertical session-list mental model.
- Esc is the single one-press cancel for ChoiceList — drops the prior
  two-step "Left to leave, Left to cancel" flow. Esc also continues to
  close the command palette and now closes the help overlay.
- Adds a Ctrl+? help overlay listing every keybinding. Bound on both
  ctrl+? and ctrl+question_mark to survive terminal reporting quirks.
- Newline keeps Ctrl+J / Ctrl+Enter / Shift+Enter as cross-terminal
  fallbacks (Ctrl+J is the portable one for macOS Terminal.app); drops
  Alt+Enter.
- Bottom bar simplifies to four essentials + Ctrl+? and / hints, and
  shows a transient "再按 Ctrl+C 退出" while quit is armed.

* fix(tui): switch help shortcut from Ctrl+? to Ctrl+/

Ctrl+? (= Ctrl+Shift+/) is unreliable across terminals — many emulators
either swallow it or report it as something Textual can't parse. Ctrl+/
is the conventional VS Code / command-line help shortcut and ships with
the legacy Ctrl+_ fallback (ASCII 0x1F is what older terminals send for
Ctrl+/). All three forms are bound (ctrl+slash, ctrl+/, ctrl+underscore)
so the binding survives terminal-reporting differences.

Bottom hint bar collapses to a single left-aligned line carrying the
command-palette and help hints alongside the action keys, since the
prior right column repeated information the left column already had room
for. The help overlay header reads "快捷键帮助" instead of "快捷键".

* fix(tui): ctrl+c dual-press with non-empty input, centered help modal

- Ctrl+C with non-empty input now clears AND arms quit; a second Ctrl+C
  within 2s exits. Previously typing in the input let one Ctrl+C exit
  silently after the clear, which was easy to trigger by accident.
- Help is now a ModalScreen pushed over the main screen so opening it
  no longer shifts the input box. Centered with a lighter background
  (#21262d on #30363d border) to read as a lifted panel.
- Esc-cancelling a ChoiceList removes the prompt cleanly with no
  "已取消" output — the canceled prompt simply disappears from the
  chat, matching expectations for in-flight tool prompts.

* fix(tui): keep Ctrl+C copy semantics and update choice hints

When there is selected text, Ctrl+C now copies the selection and returns
without triggering stop, input clear, or quit-arming. This preserves the
TUI selection/copy path after Ctrl+C became the global stop/quit key.

Choice prompts now advertise the current Esc-cancel behavior instead of
the removed Left-arrow flow, and stale comments/docs mentioning the old
left-arrow return path were cleaned up.
2026-05-13 23:04:23 +08:00
nianyucatfish 1767ee1332 fix(tui): restore wheel scroll on macOS in tuiapp_v2 (#361)
PR #360 disabled Textual mouse support on darwin (run(mouse=False)) to
keep terminal-native selection working. Side effect: ?1006 SGR mouse was
never enabled, while macOS Terminal.app / iTerm2 default ?1007 (alternate
scroll mode) translated wheel events into Up/Down keys — which then
triggered the newly added input-history navigation.

Re-enable mouse globally and explicitly disable ?1007 on mount so wheel
events flow through the SGR channel without spawning duplicate arrow
keys. Keyboard Up/Down history navigation is unaffected. The ?1007
disable is a no-op on Linux / Windows Terminal where it defaults off.
2026-05-13 18:58:58 +08:00
nianyucatfish 0fb3cfb6af fix(tui): keep v2 output scrolled during stream updates (#356)
When an assistant message already has a mounted body widget, streaming updates only refreshed the widget content. Scroll the messages container after those in-place updates so both streaming chunks and final responses remain visible at the bottom.
2026-05-13 10:56:26 +08:00
nianyucatfish 3cb5ccaa09 fix(tui): avoid duplicate paste in tuiapp_v2 (#352)
Handle paste events directly for both short and multi-line input instead of mixing TextArea's default paste path with the custom placeholder path. This keeps single-line paste from being inserted twice while preserving the existing multi-line placeholder behavior.
2026-05-13 10:34:32 +08:00
nianyucatfish d40f76d7b1 feat(tui): add tuiapp_v2.py — refined Textual frontend (#350)
新版 TUI 与 tuiapp.py 并存,共享 GenericAgent 调度/队列/线程协议,
重做视觉与交互:
- 多行 InputArea:≤3 行自适应、>3 行三行滑动窗口、粘贴占位符
- 命令面板(OptionList + 模糊匹配 + Tab 补全)
- /llm、command 选择走 ChoiceList,选完区域收缩
- Markdown HardBreak 渲染 + ANSI 缓存
- 响应式布局(窄屏隐藏侧栏 / 宽屏按比例放大)
- selection-aware 自动滚动(选文本时不抢滚动)
- 新增 /btw、/continue、/export、/restore

不改 cli / hub / README / tuiapp.py 入口。
2026-05-12 22:26:35 +08:00
nianyucatfish 2d848e9a4e feat(stapp): add /export command (clip/file/all) (#322) 2026-05-09 23:08:20 +08:00