Skip to content

Commit b99d4dc

Browse files
authored
Merge pull request #584 from OpenCoven/fix/573-session-id-char-slice
fix: shorten session ids by characters, not bytes
2 parents 2326ee3 + 1652bcc commit b99d4dc

6 files changed

Lines changed: 153 additions & 4 deletions

File tree

‎scripts/tui-tests/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ lands on the main screen. No secrets or network access required.
181181
| `cases/32_one_runtime.sh` | One runtime per renderer (#408) | In Classic (`COVEN_CODE_UI` unset) and Next, `fake_anthropic.py` drives two real turns, an approved Bash call and then a text answer. Between them the window grows by 20 columns and 5 rows until the app draws a rule that wide, then goes back. There is one session file after the first turn, and after the second turn and the exit it is still that one file with that id; under the home and the project, the only session file (`sessions/*.json`) and session index (`sessions.db`) are that file and that index, which holds that one session. The fake saw three streamed requests, each carrying the one before it, its reply and the next user message, and the request of the second turn came on a TCP connection the first turn used (the fake numbers connections in a log of its own), so it came from the same HTTP connection pool. The saved session is the last request's conversation plus its answer, and every indexed message is that session's. A user message has no uuid, so the index keeps only the first one ever (current behaviour); the check uses the answers. The tool-result request inside the first turn is not checked on its own. Not shown: anything built but never used to send or save; clients that share one pool; and the other clients the process builds the same way in both renderers (the registry's Anthropic provider, the per-goal-turn wrapper, Agent sub-agents, memory extraction, which starts at 20 messages and which `fake_anthropic.py` answers and keeps out of its request logs, and the replacements made by `/refresh` and an in-session login); one store object, since the index is opened at every save; the scheduler and memory authority; relaunching the other renderer on the same session, `/resume` and `/clear`; any transport but the direct API-key one; needs `python3` |
182182
| `cases/33_daemon_restart_unknown.sh` | Restarted Coven daemon (#412) | In Classic (`COVEN_CODE_UI` unset) and Next, with `daemonLedger` on, a fake daemon on `coven.sock` in a disposable `COVEN_HOME` answers health with its own pid and start time and logs every request. The session registers with it once. The fake is stopped and a second one, a new process, starts on the same path: within 30 s, with no input, Next's header reads `ledger unknown` instead of `ledger-registered`, and Classic's footer shows `◌ coven (unknown)` and its welcome line `unknown` instead of `online`. Across two more probes and one turn against `fake_anthropic.py`, the new daemon receives no registration. `/session resume <id>` then registers that session with it exactly once, and the state reads registered and online again (Classic's online glyph returns only once the new daemon has accepted the registration); needs `python3` |
183183
| `cases/34_command_error_clears.sh` | A command error leaves the status row (#529) | In Classic (`COVEN_CODE_UI` unset, before its first turn) and Next, a disposable `COVEN_HOME` holds a `coven.sock` that is a plain file, so every daemon request fails. `/coven sessions` puts `Error: Coven daemon offline. ...` on the status row; a following `/coven status` prints `Coven daemon: offline` and the earlier error is gone from the status row. No provider, nothing listens |
184+
| `cases/35_resume_short_session_id.sh` | Resuming an id that is not a UUID (#573) | In Classic (`COVEN_CODE_UI` unset) and Next, a fake `claude` answers one turn in a session started with `--session-id ab` and one started with `--session-id 日本語セッション` (byte 8 falls inside its third character). A fresh launch for each runs `/session resume ab` or `/session resume 日本語セッション`: each shows that session's transcript, the app is still running and nothing panicked; Next's status names the session (`Resumed session ab.`). No network or model |
184185
| `cases/36_saved_permission_mode.sh` | Saved permission mode at startup | In Classic (`COVEN_CODE_UI` unset) and Next, each in a throwaway home and project, with no turn sent. `/config set permission-mode accept-edits` saves the mode, and the next start without `--permission-mode` says it restored it and `/config get permission-mode` reports `AcceptEdits`. `--permission-mode plan` and `--permission-mode default` win over the saved mode and announce nothing. A saved `bypassPermissions` starts in `Default` and says once, in a notification, that it was not restored. A repository's `.coven-code/settings.json` naming `bypassPermissions` or `acceptEdits` leaves the session in `Default`, and one that omits the mode does not reset a saved `plan` |
185186

186187
## Configuration
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#!/usr/bin/env bash
2+
# shellcheck shell=bash
3+
#
4+
# Resuming a session whose id is not a UUID (#573), in Classic and in Next.
5+
# `--session-id` takes any string, and the history keeps it as given. Two
6+
# sessions are saved, one with the 2-byte id `ab` and one with
7+
# `日本語セッション`, whose byte 8 falls inside its third character. A fresh
8+
# launch resumes each with `/session resume <id>`, which replaced `/resume`.
9+
# The app keeps running and shows the resumed transcript; Next also shows the
10+
# shortened id in its status. A fake
11+
# `claude` answers each turn at once; no network or model. Classic shows the
12+
# status row only before its first turn, so there only the transcript and the
13+
# running process are checked.
14+
15+
register_case tc_resume_short_session_id
16+
17+
_rss_fake_claude() {
18+
cat >"$1" <<'FAKE'
19+
#!/bin/sh
20+
# Fake `claude`: answer once and finish.
21+
cat >/dev/null &
22+
printf '%s\n' '{"type":"system","subtype":"init","session_id":"fake","model":"fake-model"}'
23+
printf '%s\n' '{"type":"assistant","message":{"model":"fake-model","content":[{"type":"text","text":"fake answer"}]}}'
24+
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"usage":{"input_tokens":3,"output_tokens":1}}'
25+
FAKE
26+
chmod +x "$1"
27+
}
28+
29+
# One saved session: start with the id, answer one prompt, quit.
30+
_rss_save() { # renderer, id, prompt
31+
if tui_start --session-id "$2"; then
32+
tui_type "$3"; tui_keys Enter
33+
if wait_for "fake answer" 15; then _pass "$1: session $2 answers"
34+
else _fail "$1: session $2 answers" "$(tui_capture)"; fi
35+
tui_keys C-c; sleep 0.3; tui_keys C-c
36+
sleep 1
37+
fi
38+
tui_stop
39+
}
40+
41+
# Resume one saved session in a fresh launch, so each id is tried on a
42+
# running app.
43+
_rss_resume() { # renderer, id, prompt of that session
44+
local r="$1" id="$2" prompt="$3" running
45+
if ! tui_start; then return 0; fi
46+
running="$(_tmux display-message -p -t "$TUI_SESSION" '#{pane_current_command}')"
47+
tui_type "/session resume $id"; sleep 0.3; tui_keys Enter
48+
if wait_for "$prompt" 10; then _pass "$r: /session resume $id shows that session's transcript"
49+
else _fail "$r: /session resume $id shows that session's transcript" "$(tui_capture)"; fi
50+
sleep 0.5
51+
assert_eq "$(_tmux display-message -p -t "$TUI_SESSION" '#{pane_current_command}')" \
52+
"$running" "$r: the app is still running after /session resume $id"
53+
assert_absent "$(tui_capture)" "panicked" "$r: /session resume $id does not panic"
54+
if [ "$r" = next ]; then
55+
if wait_for "Resumed session $id." 5; then _pass "$r: the status names session $id"
56+
else _fail "$r: the status names session $id" "$(tui_capture)"; fi
57+
fi
58+
tui_stop
59+
}
60+
61+
_rss_journey() { # renderer
62+
local r="$1" scratch
63+
scratch="$(mktemp -d)"
64+
mkdir -p "$scratch/home/.coven-code" "$scratch/bin" "$scratch/project"
65+
printf '%s\n' '{"hasCompletedOnboarding": true}' >"$scratch/home/.coven-code/settings.json"
66+
_rss_fake_claude "$scratch/bin/claude"
67+
68+
local saved_prefix="$TUI_LAUNCH_PREFIX" saved_boot="$TUI_BOOT_STRING" var ui=""
69+
TUI_LAUNCH_PREFIX="cd $(printf '%q' "$scratch/project") && env"
70+
for var in ANTHROPIC_API_KEY ANTHROPIC_BASE_URL OPENAI_API_KEY COVEN_CODE_PROVIDER \
71+
COVEN_CODE_API_BASE COVEN_CODE_HOME COVEN_CODE_TEST_HOME COVEN_PARENT \
72+
COVEN_DAEMON_SOCKET COVEN_CODE_UI; do
73+
TUI_LAUNCH_PREFIX+=" -u $var"
74+
done
75+
if [ "$r" = next ]; then ui="COVEN_CODE_UI=next"; TUI_BOOT_STRING="preview"
76+
else TUI_BOOT_STRING="Coven v"; fi
77+
# shellcheck disable=SC2086 # an empty selector adds nothing
78+
TUI_LAUNCH_PREFIX+=" $(printf '%q ' "HOME=$scratch/home" "COVEN_HOME=$scratch/home/.coven" \
79+
"COVEN_CODE_CLAUDE_BIN=$scratch/bin/claude" $ui)"
80+
81+
_rss_save "$r" ab "alpha question"
82+
_rss_save "$r" "日本語セッション" "beta question"
83+
84+
_rss_resume "$r" ab "alpha question"
85+
_rss_resume "$r" "日本語セッション" "beta question"
86+
87+
TUI_LAUNCH_PREFIX="$saved_prefix"
88+
TUI_BOOT_STRING="$saved_boot"
89+
rm -rf "$scratch"
90+
}
91+
92+
tc_resume_short_session_id() {
93+
describe "/session resume of a short or non-ASCII session id does not panic"
94+
if ! have_tmux; then _skip "tmux not installed"; return 0; fi
95+
_rss_journey classic
96+
_rss_journey next
97+
}

‎src-rust/crates/cli/src/main.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4529,7 +4529,7 @@ async fn run_interactive(
45294529
.map(|title| claurst_tui::terminal_title_topic(renderer, title));
45304530
claurst_tui::update_terminal_title(title.as_deref());
45314531
app.status_message =
4532-
Some(format!("Resumed session {}.", &session.id[..8]));
4532+
Some(format!("Resumed session {}.", claurst_core::truncate::short_id(&session.id)));
45334533
}
45344534
Some(CommandResult::RenameSession(title)) => {
45354535
session.title = Some(title.clone());

‎src-rust/crates/core/src/truncate.rs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,17 @@ pub fn truncate_text(text: &str, max_chars: usize) -> String {
1414
format!("{}… (truncated)", &text[..end])
1515
}
1616

17+
/// An id shortened for display: its first 8 characters, or all of it when it
18+
/// is shorter. Session ids come from `--session-id` and need not be UUIDs, so
19+
/// they can be shorter than 8 bytes or have a multibyte character across byte
20+
/// 8; this never cuts inside a character.
21+
pub fn short_id(id: &str) -> &str {
22+
match id.char_indices().nth(8) {
23+
Some((end, _)) => &id[..end],
24+
None => id,
25+
}
26+
}
27+
1728
/// Truncate a list of lines to at most `max_lines`.
1829
/// If truncated, appends a `"… N more lines"` indicator.
1930
pub fn truncate_lines(lines: &[String], max_lines: usize) -> (Vec<String>, bool) {
@@ -95,6 +106,17 @@ mod tests {
95106
assert!(t.contains("truncated"));
96107
}
97108

109+
#[test]
110+
fn short_id_keeps_eight_characters_without_splitting_one() {
111+
assert_eq!(short_id(""), "");
112+
assert_eq!(short_id("ab"), "ab");
113+
assert_eq!(short_id("abcdefgé"), "abcdefgé");
114+
assert_eq!(short_id("abcdefgéh"), "abcdefgé");
115+
assert_eq!(short_id("日本語セッション"), "日本語セッション");
116+
assert_eq!(short_id("日本語セッション名"), "日本語セッション");
117+
assert_eq!(short_id("0f8e2c1a-7b6d-4e5f-9a8b-1c2d3e4f5a6b"), "0f8e2c1a");
118+
}
119+
98120
#[test]
99121
fn truncate_lines_over_limit() {
100122
let lines: Vec<String> = (0..10).map(|i| format!("line {}", i)).collect();

‎src-rust/crates/tools/src/remote_trigger.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ impl Tool for RemoteTriggerTool {
9494
Err(e) => return ToolResult::error(format!("HTTP error: {e}")),
9595
};
9696

97-
let target_prefix = &params.session_id[..params.session_id.len().min(8)];
97+
let target_prefix = claurst_core::truncate::short_id(&params.session_id);
9898

9999
if resp.status().is_success() {
100100
match resp.json::<Value>().await {

‎src-rust/crates/tui/src/render.rs‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3504,9 +3504,8 @@ pub fn render_full_status_line(
35043504

35053505
// Session ID
35063506
if let Some(sid) = &data.session_id {
3507-
let short = &sid[..sid.len().min(8)];
35083507
spans.push(Span::styled(
3509-
format!("[session:{}]", short),
3508+
format!("[session:{}]", claurst_core::truncate::short_id(sid)),
35103509
Style::default().fg(Color::DarkGray),
35113510
));
35123511
}
@@ -3836,6 +3835,36 @@ mod welcome_tests {
38363835
assert_eq!(welcome_provider_label(&app), "anthropic");
38373836
}
38383837

3838+
/// #573: a session id from `--session-id` can be shorter than 8 bytes or
3839+
/// have a multibyte character across byte 8. The status line shortens it
3840+
/// without panicking.
3841+
#[test]
3842+
fn full_status_line_shortens_short_and_non_ascii_session_ids() {
3843+
for (id, shown) in [
3844+
("ab", "[session:ab]"),
3845+
("abcdefgé", "[session:abcdefgé]"),
3846+
("abcdefgéh", "[session:abcdefgé]"),
3847+
("日本語セッション名", "[session:日本語セッション]"),
3848+
("0f8e2c1a-7b6d-4e5f-9a8b-1c2d3e4f5a6b", "[session:0f8e2c1a]"),
3849+
] {
3850+
let data = StatusLineData {
3851+
session_id: Some(id.to_string()),
3852+
..Default::default()
3853+
};
3854+
let area = Rect::new(0, 0, 80, 1);
3855+
let mut buf = Buffer::empty(area);
3856+
render_full_status_line(&data, area, &mut buf);
3857+
// A wide character's second cell is blank, so compare without
3858+
// whitespace; the expected text has none.
3859+
let line: String = (0..area.width)
3860+
.map(|x| buf[(x, 0)].symbol())
3861+
.collect::<String>()
3862+
.split_whitespace()
3863+
.collect();
3864+
assert!(line.contains(shown), "{id:?}: {line:?}");
3865+
}
3866+
}
3867+
38393868
#[test]
38403869
fn welcome_familiar_label_uses_none_by_default() {
38413870
let temp = tempfile::tempdir().expect("tempdir");

0 commit comments

Comments
 (0)