-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathdashboard-service.sh
More file actions
executable file
·283 lines (264 loc) · 10.7 KB
/
dashboard-service.sh
File metadata and controls
executable file
·283 lines (264 loc) · 10.7 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
275
276
277
278
279
280
281
282
283
#!/usr/bin/env bash
# Auto-start the claude-smart Next.js dashboard (port 3001) if it's not
# already running. Mirrors how claude-mem boots its worker on SessionStart:
# detached, returns immediately so the hook doesn't block the session.
#
# Subcommands:
# start probe the port; spawn `npm run start` if our dashboard
# isn't already answering. Never builds in foreground — if
# .next is missing, logs and bails (Setup is responsible for
# the build; rerun it or restart Claude Code to retry).
# stop kill the recorded process group, and (if our dashboard
# is still responding on the port) kill the port listener
# as a fallback — covers dashboards started outside this
# script or whose PGID signalling missed
# session-end no-op by default; stops the dashboard if
# CLAUDE_SMART_DASHBOARD_STOP_ON_END=1 (opt-in — the dashboard
# is intended to be long-lived across sessions)
# status print "running on http://localhost:PORT" or "not running"
set -eu
HERE="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=_lib.sh
. "$HERE/_lib.sh"
claude_smart_source_login_path
claude_smart_prepend_node_bins
claude_smart_source_reflexio_env
CMD="${1:-start}"
PORT=3001
PLUGIN_ROOT="$(cd "$HERE/.." && pwd)"
claude_smart_reexec_stable_plugin_root_if_needed "$PLUGIN_ROOT" "dashboard-service.sh" "$@"
DASHBOARD_DIR="$PLUGIN_ROOT/dashboard"
WORKSPACE_CWD="${PWD:-}"
STATE_DIR="$HOME/.claude-smart"
PID_FILE="$STATE_DIR/dashboard.pid"
LOG_FILE="$STATE_DIR/dashboard.log"
mkdir -p "$STATE_DIR"
emit_ok() { claude_smart_emit_continue; }
# Tree-kill the recorded process. Delegates to claude_smart_kill_tree
# (POSIX: signal the process group; Windows: taskkill /T /F /PID).
kill_group() {
claude_smart_kill_tree "$1"
}
# True if the marker header served by app/api/health is present on the
# port. Requires curl — absence is reported as false. This deliberately
# accepts any claude-smart dashboard, including stale cache versions, so
# stop/uninstall can safely reap them without touching foreign listeners.
marker_responds() {
command -v curl >/dev/null 2>&1 || return 1
curl -sfI "http://127.0.0.1:$PORT/api/health" 2>/dev/null \
| grep -qi '^x-claude-smart-dashboard:'
}
dashboard_health_headers() {
command -v curl >/dev/null 2>&1 || return 1
curl -sfI --connect-timeout 2 --max-time 5 "http://127.0.0.1:$PORT/api/health" 2>/dev/null
}
header_value_from() {
header_name="$1"
awk -v wanted="$header_name" '
BEGIN { wanted = tolower(wanted) ":" }
{
line = $0
sub(/\r$/, "", line)
lower = tolower(line)
if (index(lower, wanted) == 1) {
sub(/^[^:]*:[[:space:]]*/, "", line)
print line
exit
}
}
'
}
canonical_dir() {
dir="$1"
(cd "$dir" 2>/dev/null && pwd -P) || printf '%s\n' "$dir"
}
normalize_identity_path() {
path="$1"
if claude_smart_is_windows; then
if command -v cygpath >/dev/null 2>&1; then
path="$(cygpath -u "$path" 2>/dev/null || printf '%s\n' "$path")"
else
path="$(
printf '%s\n' "$path" | awk '{
gsub(/\\/, "/")
if ($0 ~ /^[A-Za-z]:/) {
drive = tolower(substr($0, 1, 1))
sub(/^[A-Za-z]:/, "/" drive)
}
print
}'
)"
fi
fi
while [ "${path%/}" != "$path" ] && [ "$path" != "/" ]; do
path="${path%/}"
done
printf '%s\n' "$path"
}
# True only if *this plugin root's* dashboard is on the port. The generic
# x-claude-smart-dashboard marker is intentionally not enough: after an
# install/update, an older cache can keep serving port 3001 until restarted.
dashboard_matches_current_root() {
expected_root="$(normalize_identity_path "$(canonical_dir "$PLUGIN_ROOT")")"
headers="$(dashboard_health_headers)" || return 1
printf '%s\n' "$headers" | grep -qi '^x-claude-smart-dashboard:' || return 1
actual_root="$(printf '%s\n' "$headers" | header_value_from "x-claude-smart-plugin-root")"
[ -n "$actual_root" ] || return 1
actual_root="$(normalize_identity_path "$actual_root")"
[ "$actual_root" = "$expected_root" ]
}
# Kill a claude-smart dashboard listener currently holding the port. Gated by
# marker_responds so a foreign app on 3001 is never killed.
stop_dashboard_listener() {
marker_responds || return 0
command -v lsof >/dev/null 2>&1 || return 0
port_pid=$(lsof -t -i ":$PORT" -sTCP:LISTEN 2>/dev/null | head -n1)
[ -n "$port_pid" ] || return 0
kill -TERM "$port_pid" 2>/dev/null || true
for _ in 1 2 3 4 5; do
kill -0 "$port_pid" 2>/dev/null || return 0
sleep 0.2
done
kill -KILL "$port_pid" 2>/dev/null || true
}
# True only if *our* dashboard is on the port. Uses plugin-root identity so a
# stale claude-smart listener doesn't cause us to silently skip starting.
is_our_dashboard_running() {
if [ -f "$PID_FILE" ]; then
pid=$(cat "$PID_FILE" 2>/dev/null || echo "")
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
# PID alive — still verify the port responds with our marker so we
# don't claim "running" when the server crashed but the group leader
# lingered.
if command -v curl >/dev/null 2>&1; then
dashboard_matches_current_root && return 0
else
# No curl — fall back to PID liveness alone.
return 0
fi
fi
fi
# No PID or dead PID — probe the port for our marker (recovers after a
# stale PID file from a crash).
dashboard_matches_current_root && return 0
return 1
}
# True if *something* is listening on the port, regardless of marker.
port_occupied() {
if command -v curl >/dev/null 2>&1; then
curl -sf -o /dev/null "http://127.0.0.1:$PORT" 2>/dev/null && return 0
# curl with -sfI against a 404/405 still indicates "something answered".
# Use a connect-only probe as a secondary signal.
fi
(echo >"/dev/tcp/127.0.0.1/$PORT") 2>/dev/null
}
case "$CMD" in
start)
if claude_smart_is_internal_invocation_env; then
emit_ok; exit 0
fi
# Opt-out: users who don't want the dashboard long-lived can set
# CLAUDE_SMART_DASHBOARD_AUTOSTART=0 in their environment.
if [ "${CLAUDE_SMART_DASHBOARD_AUTOSTART:-1}" = "0" ]; then
emit_ok; exit 0
fi
if [ ! -d "$DASHBOARD_DIR" ]; then emit_ok; exit 0; fi
if is_our_dashboard_running; then claude_smart_clear_dashboard_unavailable; emit_ok; exit 0; fi
if marker_responds; then
echo "[claude-smart] dashboard: stale claude-smart dashboard on port $PORT; restarting from $PLUGIN_ROOT" >>"$LOG_FILE"
stop_dashboard_listener
fi
if port_occupied; then
echo "[claude-smart] dashboard: port $PORT held by another process; skipping" >>"$LOG_FILE"
emit_ok; exit 0
fi
NPM_BIN=$(claude_smart_resolve_npm || true)
if [ -z "$NPM_BIN" ] || ! "$NPM_BIN" --version >/dev/null 2>&1; then
if [ "${CLAUDE_SMART_BOOTSTRAPPING:-}" != "1" ] && [ -x "$PLUGIN_ROOT/scripts/smart-install.sh" ]; then
echo "[claude-smart] dashboard: npm is not on PATH; starting installer in background" >>"$LOG_FILE"
claude_smart_spawn_detached env CLAUDE_SMART_BOOTSTRAPPING=1 \
bash "$PLUGIN_ROOT/scripts/smart-install.sh" \
>>"$STATE_DIR/install.log" 2>&1 || true
fi
if [ -z "$NPM_BIN" ] || ! "$NPM_BIN" --version >/dev/null 2>&1; then
reason="npm is not on PATH; installer recovery scheduled; dashboard cannot start yet"
echo "[claude-smart] dashboard: $reason; skipping" >>"$LOG_FILE"
claude_smart_write_dashboard_unavailable "$reason"
emit_ok; exit 0
fi
fi
# `npm run start` requires a prior `next build`. Do NOT build in the
# foreground here — SessionStart hooks have a tight timeout and a cold
# Next build easily exceeds it. If .next is missing, spawn a detached
# build (dashboard-build.sh) so the first-install cost is paid out of
# band. dashboard-open.sh detects the build-pid file to surface a
# "still building" message instead of a generic error.
if [ ! -d "$DASHBOARD_DIR/.next" ]; then
BUILD_PID_FILE="$STATE_DIR/dashboard-build.pid"
if ! claude_smart_pid_alive_file "$BUILD_PID_FILE"; then
echo "[claude-smart] dashboard: .next missing — starting background build (~1-2 min)" >>"$LOG_FILE"
claude_smart_spawn_detached bash "$HERE/dashboard-build.sh" >>"$LOG_FILE" 2>&1
fi
emit_ok; exit 0
fi
cd "$DASHBOARD_DIR"
# Detach so the hook returns immediately. claude_smart_spawn_detached
# picks the strongest primitive available:
# - Linux: setsid (puts child in its own session/group, pid==pgid).
# - macOS: python3 os.setsid + execvp (same effect as setsid).
# - Windows: nohup alone (no process groups; tree-kill via taskkill).
# Caller-side `>>file 2>&1` redirection is honoured before the child
# detaches, so per-OS log paths stay identical.
export CLAUDE_SMART_DASHBOARD_WORKSPACE="$WORKSPACE_CWD"
claude_smart_spawn_detached "$NPM_BIN" run start >>"$LOG_FILE" 2>&1
dash_pid=$!
# Record the spawned pid, not a pgid sampled with ps. On POSIX,
# setsid/python os.setsid make this pid the new process group leader;
# sampling immediately can race and capture the caller's pgid instead.
# On Windows, claude_smart_kill_tree translates the MSYS pid to WINPID.
echo "$dash_pid" > "$PID_FILE"
dashboard_ready=0
for _ in 1 2 3 4 5; do
if dashboard_matches_current_root; then
dashboard_ready=1
claude_smart_clear_dashboard_unavailable
break
fi
sleep 1
done
if [ "$dashboard_ready" != "1" ]; then
claude_smart_write_dashboard_unavailable "dashboard process spawned but did not respond on http://127.0.0.1:$PORT within 5s; see $LOG_FILE"
fi
emit_ok
;;
stop)
if [ -f "$PID_FILE" ]; then
kill_group "$(cat "$PID_FILE" 2>/dev/null)"
rm -f "$PID_FILE"
fi
# Fallback: if a claude-smart dashboard is still responding on the port (e.g.,
# was started outside this script, or the PGID kill missed because
# the process wasn't the group leader) kill whoever owns the port.
# Gated on the marker header so we never touch a foreign listener.
stop_dashboard_listener
emit_ok
;;
session-end)
# Default: leave the dashboard running so users can keep browsing
# interactions/playbooks between sessions. Opt in to teardown by setting
# CLAUDE_SMART_DASHBOARD_STOP_ON_END=1 in the environment.
if [ "${CLAUDE_SMART_DASHBOARD_STOP_ON_END:-0}" = "1" ]; then
if [ -f "$PID_FILE" ]; then
kill_group "$(cat "$PID_FILE" 2>/dev/null)"
rm -f "$PID_FILE"
fi
fi
emit_ok
;;
status)
if is_our_dashboard_running; then echo "running on http://localhost:$PORT"; else echo "not running"; fi
;;
*)
emit_ok
;;
esac