-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatusline.sh
More file actions
executable file
·274 lines (246 loc) · 10.1 KB
/
Copy pathstatusline.sh
File metadata and controls
executable file
·274 lines (246 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/bin/sh
# Claude statusline cached launcher.
#
# Claude Code invokes statusLine commands for every render. Starting Node and
# importing the HUD bundle each time can take hundreds of milliseconds, which
# makes the first frame blank/flickery. This POSIX wrapper keeps the statusLine
# protocol unchanged (stdin JSON in, one line out) while making the hot path a
# shell read + cat of the last rendered line. A single background Node refresh
# updates the session-scoped cache for the next frame.
case "$0" in
*/*) SCRIPT_DIR=${0%/*} ;;
*) SCRIPT_DIR=. ;;
esac
SCRIPT_DIR=$(cd "$SCRIPT_DIR" 2>/dev/null && pwd -P) || SCRIPT_DIR=.
# Cache lives inside this folder so the statusline is fully relocatable.
CACHE_DIR=${HUD_CACHE_DIR:-"$SCRIPT_DIR/cache"}
HUD_SCRIPT=${1:-"$SCRIPT_DIR/statusline.mjs"}
# User config path, mirroring Node's getHudConfigFile(): HUD_CONFIG override
# else <install>/config.json. Used to invalidate the render cache when the
# config changes (see config_newer_than).
HUD_CONFIG_FILE=${HUD_CONFIG:-"$SCRIPT_DIR/config.json"}
INPUT_TMP="$CACHE_DIR/stdin.$$.tmp"
LOCK_STALE_SECONDS=${HUD_LOCK_STALE_SECONDS:-10}
mkdir -p "$CACHE_DIR" 2>/dev/null || {
printf '[HUD] Starting...\n'
exit 0
}
CACHE_DIR=$(cd "$CACHE_DIR" 2>/dev/null && pwd -P) || {
printf '[HUD] Starting...\n'
exit 0
}
INPUT_TMP="$CACHE_DIR/stdin.$$.tmp"
file_mtime() {
(stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null) | head -1
}
is_stale_path() {
path=$1
now=$(date +%s 2>/dev/null || printf '0')
path_mtime=$(file_mtime "$path")
[ -n "$path_mtime" ] || return 1
[ "$now" -gt 0 ] || return 1
[ $((now - path_mtime)) -gt "$LOCK_STALE_SECONDS" ] || return 1
}
# True when the user config was modified more recently than the reference file
# (a cached render), meaning that render predates the current config and is
# stale. Returns false (cache still valid) when there is no config file or
# either mtime is unreadable, so a missing/unreadable config never forces a
# re-render. POSIX test has no -nt, hence the explicit mtime comparison.
config_newer_than() {
[ -f "$HUD_CONFIG_FILE" ] || return 1
cfg_mtime=$(file_mtime "$HUD_CONFIG_FILE")
[ -n "$cfg_mtime" ] || return 1
ref_mtime=$(file_mtime "$1")
[ -n "$ref_mtime" ] || return 1
[ "$cfg_mtime" -gt "$ref_mtime" ]
}
cleanup_empty_temp_files() {
for temp_path in "$CACHE_DIR"/stdin.*.tmp "$CACHE_DIR"/*/statusline.*.tmp "$CACHE_DIR"/*/statusline.*.err; do
[ -f "$temp_path" ] || continue
[ -s "$temp_path" ] && continue
is_stale_path "$temp_path" || continue
rm -f "$temp_path" 2>/dev/null || :
done
}
cleanup_stale_render_locks() {
for stale_lock_dir in "$CACHE_DIR"/*/render.lock; do
[ -d "$stale_lock_dir" ] || continue
is_stale_path "$stale_lock_dir" || continue
rm -rf "$stale_lock_dir" 2>/dev/null || :
done
}
PRUNE_MARKER="$CACHE_DIR/.last-prune"
PRUNE_INTERVAL_SECONDS=86400
CACHE_MAX_AGE_DAYS=${HUD_CACHE_MAX_AGE_DAYS:-14}
# Evict abandoned cache state. Runs from the locked refresh path (never the hot
# path) and at most once per PRUNE_INTERVAL_SECONDS via the marker file.
prune_old_cache() {
if [ -f "$PRUNE_MARKER" ]; then
prune_now=$(date +%s 2>/dev/null || printf '0')
prune_mtime=$(file_mtime "$PRUNE_MARKER")
if [ -n "$prune_mtime" ] && [ "$prune_now" -gt 0 ] \
&& [ $((prune_now - prune_mtime)) -lt "$PRUNE_INTERVAL_SECONDS" ]; then
return
fi
fi
touch "$PRUNE_MARKER" 2>/dev/null || :
# Legacy flat files from the pre-subfolder layout (<name>.<session>.json at
# the cache root) — dead since sessions moved into subfolders; remove.
find "$CACHE_DIR" -maxdepth 1 -type f \
\( -name 'hud-state.*.json' -o -name 'hud-stdin-cache.*.json' \
-o -name 'stdin.*.json' -o -name 'statusline.*.txt' \
-o -name 'compact-requested.*.json' \) \
-exec rm -f {} + 2>/dev/null || :
# Session folders idle longer than the retention window. A folder's mtime
# refreshes on every render (files are renamed into it), so live sessions are
# never this old; a wrongly-pruned idle session self-heals via the
# synchronous first-render path.
find "$CACHE_DIR" -mindepth 1 -maxdepth 1 -type d -mtime +"$CACHE_MAX_AGE_DAYS" \
-exec rm -rf {} + 2>/dev/null || :
}
cleanup_empty_temp_files
cleanup_stale_render_locks
# Capture Claude's current statusLine stdin first so rendered output can be
# scoped per session/worktree instead of leaking across concurrent sessions.
cat > "$INPUT_TMP" 2>/dev/null || :
extract_json_string() {
key=$1
sed -n "s/.*\"$key\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" "$INPUT_TMP" 2>/dev/null | head -1
}
SESSION_KEY=$(extract_json_string session_id)
if [ -z "$SESSION_KEY" ] && [ -n "${CLAUDE_CODE_SESSION_ID:-}" ]; then
SESSION_KEY=$CLAUDE_CODE_SESSION_ID
fi
if [ -z "$SESSION_KEY" ] && [ -n "${CLAUDE_SESSION_ID:-}" ]; then
SESSION_KEY=$CLAUDE_SESSION_ID
fi
if [ -z "$SESSION_KEY" ] && [ -n "${CLAUDECODE_SESSION_ID:-}" ]; then
SESSION_KEY=$CLAUDECODE_SESSION_ID
fi
TRANSCRIPT_PATH=$(extract_json_string transcript_path)
if [ -z "$SESSION_KEY" ] && [ -n "$TRANSCRIPT_PATH" ]; then
SESSION_KEY=$(printf '%s\n' "$TRANSCRIPT_PATH" | sed -n 's/.*\([0-9a-fA-F][0-9a-fA-F-]\{35\}\).*/\1/p' | head -1)
if [ -z "$SESSION_KEY" ]; then
SESSION_KEY=$(printf '%s\n' "$TRANSCRIPT_PATH" | cksum 2>/dev/null | awk '{print "transcript-" $1}')
fi
fi
if [ -z "$SESSION_KEY" ]; then
CWD_VALUE=$(extract_json_string cwd)
if [ -n "$CWD_VALUE" ]; then
SESSION_KEY=$(printf '%s\n' "$CWD_VALUE" | cksum 2>/dev/null | awk '{print "cwd-" $1}')
fi
fi
if [ -z "$SESSION_KEY" ]; then
SESSION_KEY=default
fi
SESSION_KEY=$(printf '%s' "$SESSION_KEY" | sed 's/[^A-Za-z0-9_.-]/_/g')
# A bare . or .. would point the session dir at the cache root or its parent.
case "$SESSION_KEY" in
. | ..) SESSION_KEY=default ;;
esac
# Every file for a session lives together in its own subfolder. If it can't be
# created, degrade gracefully without stranding the captured stdin payload.
SESSION_DIR="$CACHE_DIR/$SESSION_KEY"
mkdir -p "$SESSION_DIR" 2>/dev/null || {
printf '[HUD] Starting...\n'
rm -f "$INPUT_TMP" 2>/dev/null || :
exit 0
}
INPUT_FILE="$SESSION_DIR/stdin.json"
OUTPUT_FILE="$SESSION_DIR/statusline.txt"
LOCK_DIR="$SESSION_DIR/render.lock"
NODE_STDOUT_TMP="$SESSION_DIR/statusline.$$.tmp"
NODE_STDERR_TMP="$SESSION_DIR/statusline.$$.err"
if [ -s "$INPUT_TMP" ]; then
mv "$INPUT_TMP" "$INPUT_FILE" 2>/dev/null || cp "$INPUT_TMP" "$INPUT_FILE" 2>/dev/null || :
fi
rm -f "$INPUT_TMP" 2>/dev/null || :
try_acquire_lock() {
if mkdir "$LOCK_DIR" 2>/dev/null; then
return 0
fi
if [ ! -d "$LOCK_DIR" ]; then
return 1
fi
is_stale_path "$LOCK_DIR" || return 1
rm -rf "$LOCK_DIR" 2>/dev/null || :
mkdir "$LOCK_DIR" 2>/dev/null
}
refresh_cache() {
cleanup_refresh_artifacts() {
rm -f "$NODE_STDOUT_TMP" 2>/dev/null || :
if [ ! -s "$NODE_STDERR_TMP" ]; then
rm -f "$NODE_STDERR_TMP" 2>/dev/null || :
fi
rm -rf "$LOCK_DIR" 2>/dev/null || :
}
trap 'cleanup_refresh_artifacts' EXIT
trap 'cleanup_refresh_artifacts; exit 0' HUP INT TERM
if [ ! -s "$INPUT_FILE" ]; then
cleanup_refresh_artifacts
return
fi
# HUD_SESSION_KEY hands Node the exact key that named this session folder, so
# the renderer's cache files land in the same folder even when the key came
# from a fallback (transcript/cwd checksum) Node cannot recompute itself.
if [ -x "$SCRIPT_DIR/find-node.sh" ]; then
HUD_SESSION_KEY="$SESSION_KEY" sh "$SCRIPT_DIR/find-node.sh" "$HUD_SCRIPT" < "$INPUT_FILE" > "$NODE_STDOUT_TMP" 2> "$NODE_STDERR_TMP"
else
HUD_SESSION_KEY="$SESSION_KEY" node "$HUD_SCRIPT" < "$INPUT_FILE" > "$NODE_STDOUT_TMP" 2> "$NODE_STDERR_TMP"
fi
# Keep the last good line if rendering fails or returns empty output. A
# failed render either leaves stdout empty or prints a "[HUD] ..." fallback
# line there (e.g. "[HUD] HUD error - check stderr"), so non-empty stdout
# alone does not mean success. On failure, keep stderr as statusline.err so
# the "check stderr" hint points at something; only a successful render
# clears it. Successful renders may emit benign stderr noise (worktree
# warnings, HUD_DEBUG) — that is discarded, never persisted.
if [ ! -s "$NODE_STDOUT_TMP" ] || grep -q '^\[HUD\]' "$NODE_STDOUT_TMP" 2>/dev/null; then
if [ -s "$NODE_STDERR_TMP" ]; then
mv "$NODE_STDERR_TMP" "$SESSION_DIR/statusline.err" 2>/dev/null || :
fi
else
rm -f "$SESSION_DIR/statusline.err" 2>/dev/null || :
fi
if [ -s "$NODE_STDOUT_TMP" ]; then
mv "$NODE_STDOUT_TMP" "$OUTPUT_FILE" 2>/dev/null || cp "$NODE_STDOUT_TMP" "$OUTPUT_FILE" 2>/dev/null || :
fi
prune_old_cache
rm -f "$NODE_STDOUT_TMP" "$NODE_STDERR_TMP" 2>/dev/null || :
rm -rf "$LOCK_DIR" 2>/dev/null || :
trap - EXIT HUP INT TERM
}
# Hot path: return immediately from the last successful render for this session
# — unless config.json changed since that render, in which case fall through to
# a synchronous refresh so the edit shows on this frame, not the next.
if [ -s "$OUTPUT_FILE" ] && ! config_newer_than "$OUTPUT_FILE"; then
cat "$OUTPUT_FILE" 2>/dev/null || printf '[HUD] Starting...\n'
# Refresh in background for the next frame.
if try_acquire_lock; then
if [ "${HUD_SYNC_REFRESH:-0}" = "1" ]; then
refresh_cache
else
( refresh_cache ) >/dev/null 2>&1 &
fi
fi
exit 0
fi
# Synchronous refresh: either the first render for this session, or config.json
# changed since the last render. Claude Code re-runs the statusLine command only
# on its own triggers (new assistant message, /compact, a permission-mode or vim
# toggle, or a configured refreshInterval), so an async background refresh can
# leave the pane stuck on the old frame (or "[HUD] Starting...") for a long time.
if [ -s "$INPUT_FILE" ] && try_acquire_lock; then
refresh_cache
if [ -s "$OUTPUT_FILE" ]; then
cat "$OUTPUT_FILE" 2>/dev/null && exit 0
fi
fi
# Synchronous refresh was unavailable (lock held or render failed). Prefer the
# last good line — even if it predates a config edit — over the placeholder, so
# an existing HUD never flashes back to "[HUD] Starting...".
if [ -s "$OUTPUT_FILE" ]; then
cat "$OUTPUT_FILE" 2>/dev/null && exit 0
fi
printf '[HUD] Starting...\n'
exit 0