fix(dispatch): make local + cloud dispatch reliable end-to-end

Local-only daemon installs were silently broken: prompts queued from
localhost:3000 sat unclaimed because the daemon polled cloud, and "Not
running / Workspace tab open" contradicted itself on every project card
whose Zellij tab was open without an agent. This change wires both
sources, auto-launches the configured agent when its tab is empty, and
honestly labels tab-open-but-untracked state.

Daemon (scripts/cockpit-daemon.sh, _agents.sh, agent-hook-lib.sh):
- COCKPIT_BASE_URLS=local,cloud forks one child per extra URL so both
  cockpit-app instances drain to the same machine; per-URL flock so
  the children coexist.
- execute_inject auto-launches the chosen agent when none is running in
  the project dir, then polls 20s for the process before injecting —
  fixes prompts being typed into a bare bash shell.
- Wrap every `zellij action` call in `timeout 3` so one hung subprocess
  no longer freezes the single-threaded dispatch loop.
- Delete the obsolete _base_url local-probe / DAEMON_FORCE_REMOTE
  branch; each child now owns exactly one URL.

Auth (src/lib/session.ts):
- Legacy COCKPIT_DAEMON_TOKEN bearer was short-circuited by the `ck_`
  prefix check, returning 401 against local cockpit-app. Fall through to
  the legacy env-var path when the ck_ token isn't in the DB.

Control UI (ProjectCard, control-presenter, ZellijLivePanel,
project-intent-panel, ControlPanel):
- Idle + tab-open + !session-open → badge reads "Tab open" (was
  contradictory "Not running"); evidence line and intent-panel copy
  follow suit.
- Hide Launch CTA + saved-handoff block when the workspace tab is
  already open — they were inviting the user to "launch" something
  the daemon would have to refuse.
- Replace autonomy hint when tab is open but no agent is tracked.
- Surface "Last dispatch <age> · <prompt>" in the header evidence line
  so the cloud UI shows what was sent without scrolling to Activity.
This commit is contained in:
g-but committed 2026-05-30 23:34:03 +02:00
1 parent 92757c655b
commit d6215feda6
9 files changed
+261 -133

No files matched your search

+17 -3
View File
@@ -118,6 +118,14 @@ _agent_direct_activity() {
| sort -nr | head -1 | cut -d' ' -f2-)
[ -n "$file" ] && printf '%s|Direct terminal activity\n' "$(stat -c '%Y' "$file" 2>/dev/null)"
;;
cursor)
# Cursor Agent CLI writes agent transcripts under
# ~/.cursor/projects/<cwd-without-leading-slash-dashes>/agent-transcripts/.
encoded_dir=$(printf '%s' "${dir#/}" | tr '/' '-')
file=$(find "$HOME/.cursor/projects/$encoded_dir/agent-transcripts" -name '*.jsonl' -printf '%T@ %p\n' 2>/dev/null \
| sort -nr | head -1 | cut -d' ' -f2-)
[ -n "$file" ] && printf '%s|Direct terminal activity\n' "$(stat -c '%Y' "$file" 2>/dev/null)"
;;
# Add adapters here only when they expose a stable, project-scoped log.
# Process detection, handoffs, and web-dispatched prompts work without it.
esac
@@ -126,6 +134,10 @@ _agent_direct_activity() {
# Returns 0 if the given basename+full argv looks like the Cursor agent (not a random "agent" binary).
_is_cursor_agent() {
local basename="$1" argv0="$2"
if [[ "$basename" == "cursor-agent" ]]; then
[[ "$argv0" == *"cursor-agent"* ]] || [[ "$argv0" == *"/.cursor/"* ]]
return $?
fi
[[ "$basename" == "agent" ]] && { [[ "$argv0" == *".local/bin/agent"* ]] || [[ "$argv0" == *"/.cursor/"* ]]; }
}
@@ -145,11 +157,13 @@ _scan_agents() {
basename="${argv0##*/}"
for a in "${AGENTS[@]}"; do
if [ "$a" = "cursor" ]; then
_is_cursor_agent "$basename" "$argv0" || continue
agent_id="$a"
break
fi
local expected="${AGENT_PROCESS_NAMES[$a]}"
if [ "$basename" = "$expected" ]; then
if [ "$a" = "cursor" ]; then
_is_cursor_agent "$basename" "$argv0" || continue
fi
agent_id="$a"
break
fi
+11 -11
View File
@@ -97,7 +97,7 @@ resolve_tab() {
cwd=$(realpath "$1" 2>/dev/null)
local actual_tabs
actual_tabs=$(zellij action query-tab-names 2>/dev/null)
actual_tabs=$(timeout 3 zellij action query-tab-names 2>/dev/null)
[ -z "$actual_tabs" ] && return
if [ -n "${AGENT_TAB_NAME:-}" ]; then
@@ -260,7 +260,7 @@ _resolve_live_tab_name() {
all_tabs=$(
zellij list-sessions -n 2>/dev/null | awk '{print $1}' | while read -r s; do
[ -z "$s" ] && continue
ZELLIJ_SESSION_NAME="$s" zellij action query-tab-names 2>/dev/null
ZELLIJ_SESSION_NAME="$s" timeout 3 zellij action query-tab-names 2>/dev/null
done
)
while IFS= read -r open_tab; do
@@ -286,14 +286,14 @@ _resolve_live_tab_name() {
}
# Find the zellij session that has a tab with the given name.
# Uses ZELLIJ_SESSION_NAME env var (required for zellij action outside a pane).
# Uses ZELLIJ_SESSION_NAME env var (required for timeout 3 zellij action outside a pane).
_find_session_for_tab() {
local tab="$1" live_tab="$1"
if type _resolve_live_tab_name >/dev/null 2>&1; then
live_tab=$(_resolve_live_tab_name "$tab" 2>/dev/null) || live_tab="$tab"
fi
zellij list-sessions -n 2>/dev/null | awk '{print $1}' | while read -r s; do
if ZELLIJ_SESSION_NAME="$s" zellij action query-tab-names 2>/dev/null \
if ZELLIJ_SESSION_NAME="$s" timeout 3 zellij action query-tab-names 2>/dev/null \
| grep -qxF "$live_tab"; then
echo "$s"
return 0
@@ -312,7 +312,7 @@ inject_prompt() {
fi
# When called from outside a zellij session (e.g. systemd daemon), find which
# session contains this tab — zellij action without ZELLIJ_SESSION_NAME set
# session contains this tab — timeout 3 zellij action without ZELLIJ_SESSION_NAME set
# lists sessions instead of acting, so write-chars goes nowhere.
local zellij_session="${ZELLIJ_SESSION_NAME:-}"
if [ -z "$zellij_session" ]; then
@@ -323,19 +323,19 @@ inject_prompt() {
# go-to-tab-name is fire-and-forget — the switch completes asynchronously.
# Poll dump-layout until the focused tab matches before sending characters,
# so write-chars never lands in the previously focused pane.
ZELLIJ_SESSION_NAME="$zellij_session" zellij action go-to-tab-name "$live_tab" 2>/dev/null
ZELLIJ_SESSION_NAME="$zellij_session" timeout 3 zellij action go-to-tab-name "$live_tab" 2>/dev/null
local i active
for i in $(seq 1 20); do
active=$(ZELLIJ_SESSION_NAME="$zellij_session" zellij action dump-layout 2>/dev/null \
active=$(ZELLIJ_SESSION_NAME="$zellij_session" timeout 3 zellij action dump-layout 2>/dev/null \
| grep 'focus=true' | grep 'tab name=' \
| sed 's/.*tab name="\([^"]*\)".*/\1/' | head -1)
[ "$active" = "$live_tab" ] && break
sleep 0.05
done
ZELLIJ_SESSION_NAME="$zellij_session" zellij action write-chars -- "$prompt" 2>/dev/null || true
ZELLIJ_SESSION_NAME="$zellij_session" timeout 3 zellij action write-chars -- "$prompt" 2>/dev/null || true
sleep 0.2
ZELLIJ_SESSION_NAME="$zellij_session" zellij action write 13 2>/dev/null || true
ZELLIJ_SESSION_NAME="$zellij_session" timeout 3 zellij action write 13 2>/dev/null || true
}
# Send a raw key code (e.g. 3 = Ctrl+C, 13 = Enter) to a tab without typing
@@ -348,9 +348,9 @@ send_raw_key_to_tab() {
zellij_session=$(_find_session_for_tab "$tab")
[ -z "$zellij_session" ] && return 1
fi
ZELLIJ_SESSION_NAME="$zellij_session" zellij action go-to-tab-name "$tab" 2>/dev/null || true
ZELLIJ_SESSION_NAME="$zellij_session" timeout 3 zellij action go-to-tab-name "$tab" 2>/dev/null || true
sleep 0.1
ZELLIJ_SESSION_NAME="$zellij_session" zellij action write "$keycode" 2>/dev/null || true
ZELLIJ_SESSION_NAME="$zellij_session" timeout 3 zellij action write "$keycode" 2>/dev/null || true
}
# Call after every injection to keep the Control panel and web beacon in sync.
+102 -85
View File
@@ -31,7 +31,32 @@ source "$SCRIPT_DIR/agent-hook-lib.sh" 2>/dev/null || {
# shellcheck source=_agents.sh
source "$SCRIPT_DIR/_agents.sh" 2>/dev/null || true
_LOCAL_URL="http://localhost:3000"
# Multi-source polling: COCKPIT_BASE_URLS is a comma-separated list of base URLs
# (e.g. "http://127.0.0.1:3000,https://cockpitapp.vercel.app"). When 2+ are
# present, this parent forks one child per extra URL — each runs the full
# daemon loop against its own URL with its own lock file. Runs BEFORE
# _REMOTE_URL is derived so the parent and child each pick their own.
# Falls back silently when only COCKPIT_BASE_URL (singular) is set.
_DAEMON_BASES=()
if [ -n "${COCKPIT_BASE_URLS:-${APP_BASE_URLS:-}}" ]; then
IFS=',' read -ra _DAEMON_BASES <<< "${COCKPIT_BASE_URLS:-${APP_BASE_URLS:-}}"
fi
if [ "${#_DAEMON_BASES[@]}" -gt 1 ] && [ -z "${COCKPIT_DAEMON_CHILD:-}" ]; then
for _extra in "${_DAEMON_BASES[@]:1}"; do
_extra="$(echo "$_extra" | xargs)"
[ -z "$_extra" ] && continue
(
export COCKPIT_BASE_URL="$_extra"
export COCKPIT_BASE_URLS=""
export COCKPIT_DAEMON_CHILD=1
exec "$0"
) &
done
# Parent owns the first URL; strip plural so its own startup is single-URL.
export COCKPIT_BASE_URL="$(echo "${_DAEMON_BASES[0]}" | xargs)"
export COCKPIT_BASE_URLS=""
fi
_REMOTE_URL="$(_brand_env BASE_URL "https://${APP_DOMAIN}")"
POLL_INTERVAL="$(_brand_env POLL_INTERVAL 8)"
PUSH_INTERVAL="$(_brand_env PUSH_INTERVAL 2)"
@@ -39,10 +64,7 @@ DRY_RUN="$(_brand_env DRY_RUN 0)"
TOKEN="$(_brand_env DAEMON_TOKEN "")"
CONF_FILE="${AGENT_PROJECTS_CONF:-${CLAUDE_PROJECTS_CONF:-$HOME/.config/agent-projects.conf}}"
RESTART_AFTER_COMMAND=0
# Cache file shared between the main poll loop and the background push loop.
_URL_CACHE="$(_brand_tmp "daemon-url-$$")"
_AUTH_HEADER="$(_brand_tmp "daemon-auth-$$")"
_URL_TTL=30 # re-detect every 30 s
if [ -z "$TOKEN" ]; then
echo "[${APP_SLUG}-daemon] ERROR: ${APP_SLUG^^}_DAEMON_TOKEN is not set" >&2
@@ -52,12 +74,13 @@ fi
umask 077
printf 'Authorization: Bearer %s\n' "$TOKEN" > "$_AUTH_HEADER"
# Single-instance lock — prevents duplicate daemons (manual start + systemd, etc.).
_DAEMON_LOCK="${XDG_RUNTIME_DIR:-/tmp}/${APP_SLUG}-daemon.lock"
# Single-instance lock — per-URL so multi-source daemons coexist.
_lock_suffix=$(echo "${COCKPIT_BASE_URL:-default}" | tr -c 'a-zA-Z0-9' '_' | cut -c1-40)
_DAEMON_LOCK="${XDG_RUNTIME_DIR:-/tmp}/${APP_SLUG}-daemon-${_lock_suffix}.lock"
mkdir -p "$(dirname "$_DAEMON_LOCK")" 2>/dev/null || true
exec 9>"$_DAEMON_LOCK"
if ! flock -n 9; then
echo "[${APP_SLUG}-daemon] ERROR: another daemon instance is already running." >&2
echo "[${APP_SLUG}-daemon] ERROR: another daemon for ${COCKPIT_BASE_URL:-default} is already running." >&2
echo "[${APP_SLUG}-daemon] Use: systemctl --user restart cockpit-daemon" >&2
exit 1
fi
@@ -79,71 +102,19 @@ sync_legacy_hook_runtime() {
chmod +x "$hook_dir/agent-hook-bridge.sh" 2>/dev/null || true
}
# Returns the configured control plane by default. Development can explicitly
# opt into localhost with COCKPIT_DAEMON_PREFER_LOCAL=1.
# Result is cached in $_URL_CACHE for $_URL_TTL seconds so we don't probe on
# every 2-second push. The file is shared between the main process and the
# background push-loop subshell.
# Each process owns exactly one base URL (set by the multi-source split above).
# Earlier versions probed localhost vs the configured remote per request and
# cached the choice; multi-source polling makes that obsolete — instead, every
# extra URL gets its own forked daemon child with its own COCKPIT_BASE_URL.
_base_url() {
local now ts cached url
now=$(date +%s)
if [ -f "$_URL_CACHE" ]; then
ts=$(cut -d' ' -f1 "$_URL_CACHE" 2>/dev/null)
cached=$(cut -d' ' -f2 "$_URL_CACHE" 2>/dev/null)
if [[ "$ts" =~ ^[0-9]+$ ]] && (( now - ts < _URL_TTL )) && [ -n "$cached" ]; then
echo "$cached"; return
fi
fi
# APP_DAEMON_FORCE_REMOTE=1 (or COCKPIT_DAEMON_FORCE_REMOTE=1 legacy) skips
# the local probe entirely. Use this when a local dev server is running with
# a different DB than the remote — without it, the daemon prefers local and
# remote runtime state goes stale (the cloud control panel shows
# daemonLastPushedAt frozen).
if [ "$(_brand_env DAEMON_FORCE_REMOTE 0)" = "1" ] || [ "$(_brand_env DAEMON_PREFER_LOCAL 0)" != "1" ]; then
url="$_REMOTE_URL"
elif curl -sf --max-time 0.8 "$_LOCAL_URL/api/health" >/dev/null 2>&1; then
url="$_LOCAL_URL"
else
url="$_REMOTE_URL"
fi
echo "$now $url" > "$_URL_CACHE"
echo "$url"
echo "$_REMOTE_URL"
}
# Warm the cache at startup, retrying briefly so the local app has time to boot.
_init_base_url() {
if [ "$(_brand_env DAEMON_FORCE_REMOTE 0)" = "1" ] || [ "$(_brand_env DAEMON_PREFER_LOCAL 0)" != "1" ]; then
echo "$(date +%s) $_REMOTE_URL" > "$_URL_CACHE"
log "using configured control plane $_REMOTE_URL (local probing disabled)"
return
fi
local i=0
while (( i < 8 )); do
if curl -sf --max-time 0.8 "$_LOCAL_URL/api/health" >/dev/null 2>&1; then
echo "$(date +%s) $_LOCAL_URL" > "$_URL_CACHE"
log "local server detected — using $_LOCAL_URL"
# Loud warning: if the configured remote URL is a real production
# endpoint (anything that isn't localhost / 127.0.0.1), the user
# almost certainly has a deployed app + a local dev server running
# side-by-side. Polling local means dispatches from the production
# /control page never reach this daemon — they queue silently on
# the remote DB. This exact trap cost a real session before the
# warning was added.
if [[ "$_REMOTE_URL" != *localhost* && "$_REMOTE_URL" != *127.0.0.1* ]]; then
log "WARN: ${APP_SLUG^^}_BASE_URL=$_REMOTE_URL but daemon picked LOCAL —"
log "WARN: dispatches from $_REMOTE_URL/control will NOT reach this daemon."
log "WARN: set ${APP_SLUG^^}_DAEMON_FORCE_REMOTE=1 in your daemon.env to poll $_REMOTE_URL instead."
fi
return
fi
(( i++ )) || true
sleep 1
done
echo "$(date +%s) $_REMOTE_URL" > "$_URL_CACHE"
log "local server not available — using $_REMOTE_URL"
log "polling $_REMOTE_URL"
}
trap 'rm -f "$_URL_CACHE" "$_AUTH_HEADER"' EXIT
trap 'rm -f "$_AUTH_HEADER"' EXIT
claim_next() {
local base wait_secs
@@ -229,7 +200,7 @@ next: <state to resume from; empty when nothing is mid-flight>"
}
execute_inject() {
local id="$1" tab="$2" prompt="$3" prompt_key="${4:-}" prompt_label="${5:-}"
local id="$1" tab="$2" prompt="$3" prompt_key="${4:-}" prompt_label="${5:-}" payload_adapter="${6:-}"
# Look up the project's directory and live adapter (process scan beats conf default).
local adapter="claude" project_dir=""
@@ -252,6 +223,47 @@ execute_inject() {
adapter="${ADAPTER:-claude}"
fi
# Payload adapter wins when scan detected nothing (fresh tab, no process).
# The UI/DB knows the project's preferred adapter (user_projects.agent_pref)
# so an empty tab launches the right agent, not just the bash default.
case "$payload_adapter" in
claude|grok|codex|gemini|cursor|openclaw)
if [ -n "$project_dir" ] && type _is_agent_running_in_dir >/dev/null 2>&1; then
# Only override if no live agent of any kind is in this project.
if ! _is_agent_running_in_dir "$adapter" "$project_dir"; then
adapter="$payload_adapter"
fi
else
adapter="$payload_adapter"
fi
;;
esac
# Auto-launch: if no agent of the chosen kind is running here, start it
# before injecting. Otherwise the prompt gets typed into a bare shell.
if [ -n "$project_dir" ] && type _is_agent_running_in_dir >/dev/null 2>&1 \
&& ! _is_agent_running_in_dir "$adapter" "$project_dir"; then
local _launch_cmd
_launch_cmd=$(_agent_launch_cmd "$adapter" "$project_dir" "" 2>/dev/null)
if [ -n "$_launch_cmd" ]; then
log "inject: no $adapter in $tab — auto-launching"
inject_prompt "$tab" "$_launch_cmd" 2>/dev/null || true
# Poll for the process to appear (Claude/Cursor TUI need ~1–3s to spawn).
local _deadline=$(( $(date +%s) + 20 ))
while (( $(date +%s) < _deadline )); do
sleep 0.5
if _is_agent_running_in_dir "$adapter" "$project_dir"; then
log "inject: $adapter ready in $tab"
sleep 2 # TUI input-handler warm-up
break
fi
done
if ! _is_agent_running_in_dir "$adapter" "$project_dir"; then
log "inject: $adapter did not appear in $tab within 20s — proceeding anyway"
fi
fi
fi
# If a promptKey was queued (cloud mode sends key string as prompt fallback),
# resolve it to the actual expanded prompt text with session context.
if [ -n "$prompt_key" ]; then
@@ -383,7 +395,7 @@ execute_focus_tab() {
local session
session=$(_find_session_for_tab "$tab" 2>/dev/null || true)
log "focus_tab → $tab"
if [ -n "$session" ] && ZELLIJ_SESSION_NAME="$session" zellij action go-to-tab-name "$tab" 2>/dev/null; then
if [ -n "$session" ] && ZELLIJ_SESSION_NAME="$session" timeout 3 zellij action go-to-tab-name "$tab" 2>/dev/null; then
mark_done "$id" "true"
log "focus_tab done ✓"
else
@@ -405,9 +417,9 @@ execute_close_tab() {
return 0
fi
log "close_tab → $tab"
ZELLIJ_SESSION_NAME="$session" zellij action go-to-tab-name "$tab" 2>/dev/null || true
ZELLIJ_SESSION_NAME="$session" timeout 3 zellij action go-to-tab-name "$tab" 2>/dev/null || true
sleep 0.15
if ZELLIJ_SESSION_NAME="$session" zellij action close-tab 2>/dev/null; then
if ZELLIJ_SESSION_NAME="$session" timeout 3 zellij action close-tab 2>/dev/null; then
mark_done "$id" "true"
log "close_tab done ✓"
else
@@ -433,7 +445,7 @@ execute_launch_agent() {
if [ -z "$session" ]; then
session=$(zellij list-sessions -n 2>/dev/null | awk 'NR==1{print $1}')
[ -z "$session" ] && { mark_done "$id" "false" "no zellij session found"; return 0; }
ZELLIJ_SESSION_NAME="$session" zellij action new-tab --name "$tab" 2>/dev/null || {
ZELLIJ_SESSION_NAME="$session" timeout 3 zellij action new-tab --name "$tab" 2>/dev/null || {
mark_done "$id" "false" "new-tab failed"; return 0;
}
sleep 0.5
@@ -592,7 +604,7 @@ execute_install_cli() {
local tab_name="Install $label"
# Create a fresh tab for the installer (user can close it when done)
ZELLIJ_SESSION_NAME="$session" zellij action new-tab --name "$tab_name" 2>/dev/null || true
ZELLIJ_SESSION_NAME="$session" timeout 3 zellij action new-tab --name "$tab_name" 2>/dev/null || true
sleep 0.6
# Inject the install command
@@ -724,15 +736,19 @@ _installed_agents_json() {
local ok="false"
case "$agent" in
cursor)
if command -v agent >/dev/null 2>&1; then
local agent_path
agent_path=$(command -v agent 2>/dev/null || true)
if [[ "$agent_path" == *".local/bin/agent"* ]] || [[ "$agent_path" == *"/.cursor/"* ]]; then
ok="true"
elif agent --version 2>&1 | grep -Eq '[0-9]{4}\.[0-9]{2}\.[0-9]{2}'; then
ok="true"
for _cursor_bin in agent cursor-agent; do
if command -v "$_cursor_bin" >/dev/null 2>&1; then
local agent_path
agent_path=$(command -v "$_cursor_bin" 2>/dev/null || true)
if [[ "$agent_path" == *".local/bin/agent"* ]] || [[ "$agent_path" == *"cursor-agent"* ]] || [[ "$agent_path" == *"/.cursor/"* ]]; then
ok="true"
break
elif "$_cursor_bin" --version 2>&1 | grep -Eq '[0-9]{4}\.[0-9]{2}\.[0-9]{2}'; then
ok="true"
break
fi
fi
fi
done
;;
*)
command -v "${AGENT_PROCESS_NAMES[$agent]}" >/dev/null 2>&1 && ok="true"
@@ -758,7 +774,7 @@ _build_state_json() {
while IFS= read -r zs; do
[ -z "$zs" ] && continue
local tabs
tabs=$(ZELLIJ_SESSION_NAME="$zs" zellij action query-tab-names 2>/dev/null || true)
tabs=$(ZELLIJ_SESSION_NAME="$zs" timeout 3 zellij action query-tab-names 2>/dev/null || true)
all_open_tabs="${all_open_tabs}"$'\n'"${tabs}"
done < <(zellij list-sessions -n 2>/dev/null | awk '{print $1}')
@@ -1034,7 +1050,7 @@ _autopilot_watchdog() {
while IFS= read -r zs; do
[ -z "$zs" ] && continue
local tabs
tabs=$(ZELLIJ_SESSION_NAME="$zs" zellij action query-tab-names 2>/dev/null || true)
tabs=$(ZELLIJ_SESSION_NAME="$zs" timeout 3 zellij action query-tab-names 2>/dev/null || true)
all_open_tabs="${all_open_tabs}"$'\n'"${tabs}"
done < <(zellij list-sessions -n 2>/dev/null | awk '{print $1}')
@@ -1184,7 +1200,7 @@ _PUSH_PID=$!
_shutdown() {
kill "$_PUSH_PID" 2>/dev/null || true
rm -f "$_URL_CACHE" "$_AUTH_HEADER"
rm -f "$_AUTH_HEADER"
exit 0
}
trap '_shutdown' INT TERM
@@ -1222,7 +1238,8 @@ while true; do
if [ -n "$run_id" ]; then
printf '%s' "$run_id" > "$(_brand_tmp "run-${tab}")"
fi
execute_inject "$id" "$tab" "$prompt" "$prompt_key" "$prompt_label"
payload_adapter=$(echo "$payload" | jq -r '.adapter // empty')
execute_inject "$id" "$tab" "$prompt" "$prompt_key" "$prompt_label" "$payload_adapter"
;;
focus_tab)
tab=$(echo "$payload" | jq -r '.tab')
@@ -1275,7 +1292,7 @@ while true; do
push_runtime_state &
if [ "$RESTART_AFTER_COMMAND" = "1" ]; then
kill "$_PUSH_PID" 2>/dev/null || true
rm -f "$_URL_CACHE" "$_AUTH_HEADER"
rm -f "$_AUTH_HEADER"
# Re-exec the same script tree we are running from — not a stale hosted bundle.
exec "$SCRIPT_DIR/cockpit-daemon.sh"
fi
+17 -9
View File
@@ -85,10 +85,16 @@ export function ControlPanel() {
const daemonAgoMs = lastUpdated && daemonLastPushedAt ? lastUpdated - new Date(daemonLastPushedAt).getTime() : null;
const daemonOffline = !runtimeAvailable && daemonAgoMs !== null && daemonAgoMs > 90_000;
const daemonNeverSeen = !runtimeAvailable && daemonLastPushedAt === null;
// Cloud cards cannot truthfully show live agent state without current daemon
// heartbeats. Queued commands remain visible as requests, not running work.
const daemonStateUnknown = daemonOffline || daemonNeverSeen;
const pageState = data ? buildControlPageState(data, nowS, !daemonStateUnknown) : null;
// Only hide cached runtime when the daemon has never connected. When offline
// but we have a last push, show last-known Working/Ready state with a stale label.
const daemonStateUnknown = daemonNeverSeen;
const runtimeStateKnown = !daemonNeverSeen;
const daemonSyncStale = daemonOffline && daemonLastPushedAt !== null;
const runtimeSyncCtx = {
syncStale: daemonSyncStale,
lastSyncedAt: daemonLastPushedAt,
};
const pageState = data ? buildControlPageState(data, nowS, runtimeStateKnown) : null;
const dashboard = pageState?.dashboard ?? null;
const attention = pageState?.attention ?? [];
const liveTabRows = useMemo(
@@ -96,7 +102,7 @@ export function ControlPanel() {
[data, nowS],
);
const snapshots = data
? buildProjectOperationsSnapshots(data.projects, data.zellijTabs, nowS, !daemonStateUnknown)
? buildProjectOperationsSnapshots(data.projects, data.zellijTabs, nowS, runtimeStateKnown, runtimeSyncCtx)
: null;
const failedCount = data?.failedCommands?.length ?? 0;
@@ -176,7 +182,8 @@ export function ControlPanel() {
onProfileSaved: () => { refresh(true); },
onLaunch: () => openLaunchModal(project),
runtimeAvailable,
runtimeStateKnown: !daemonStateUnknown,
runtimeStateKnown,
daemonSyncStale,
automationMode: automationPolicy.mode,
countdownSeconds: automationPolicy.countdownSeconds,
});
@@ -211,7 +218,8 @@ export function ControlPanel() {
const livePanelProps = {
rows: liveTabRows,
daemonStateUnknown,
daemonNeverSeen,
daemonSyncStale,
dashboard,
refreshing,
onRefresh: () => refresh(true),
@@ -232,7 +240,7 @@ export function ControlPanel() {
failedCount={failedCount}
daemonNeverSeen={daemonNeverSeen}
daemonOffline={daemonOffline}
daemonStateUnknown={daemonStateUnknown}
daemonStateUnknown={daemonNeverSeen}
daemonLastPushedAt={daemonLastPushedAt}
lastUpdated={lastUpdated}
automationMode={automationPolicy.mode}
@@ -274,7 +282,7 @@ export function ControlPanel() {
<summary className="ui-control-live-details-summary">
<span>Terminal workspaces</span>
<span className="ui-tag ui-tag-neutral text-micro">
{daemonStateUnknown ? "offline" : `${liveTabRows.length} open`}
{daemonNeverSeen ? "offline" : daemonSyncStale ? `${liveTabRows.length} open · stale` : `${liveTabRows.length} open`}
</span>
</summary>
<div className="ui-control-live-details-body">{livePanelMobile}</div>
+19 -3
View File
@@ -37,6 +37,7 @@ export function ProjectCard({
isOnlyReady = false,
runtimeAvailable = true,
runtimeStateKnown = true,
daemonSyncStale = false,
snapshot,
automationMode = "queue_only",
countdownSeconds,
@@ -57,6 +58,8 @@ export function ProjectCard({
isOnlyReady?: boolean;
runtimeAvailable?: boolean;
runtimeStateKnown?: boolean;
/** True when cloud view is showing last-known daemon state (sync >90s old). */
daemonSyncStale?: boolean;
snapshot?: ProjectOperationsSnapshot;
automationMode?: AutoInjectMode;
countdownSeconds?: number;
@@ -111,7 +114,10 @@ export function ProjectCard({
(automationMode === "queue_only" && queue.length > 0)
);
const queuePolicyWaiting = automationMode === "queue_only" && autoContinueEnabled && queue.length === 0;
const automationStatusLabel = automationMode === "off"
const tabOpenUntracked = display.tone === "idle" && display.tabOpen && !display.isRunning;
const automationStatusLabel = tabOpenUntracked
? "Tab open on your computer — focus the workspace to check the agent, or send a prompt below."
: automationMode === "off"
? "Manual: this project waits for your instruction."
: !autoContinueEnabled
? "Automatic continuation paused for this project."
@@ -216,7 +222,7 @@ export function ProjectCard({
{(display.isReady || display.isOrchestrationReady) && (
<SessionSummary session={project.session} isClosed={display.isClosed} />
)}
{display.tone === "idle" && project.session && (
{display.tone === "idle" && project.session && !display.tabOpen && (
<div className="border-t border-border-subtle">
<p className="px-4 pt-4 text-xs font-medium text-text-muted sm:px-5 md:px-6">Saved context from the last agent run</p>
<SessionSummary session={project.session} isClosed={false} />
@@ -224,7 +230,7 @@ export function ProjectCard({
)}
{display.showLatestOrchestration && latestOrchRun && <LatestOrchestrationPanel run={latestOrchRun} />}
{display.tone === "idle" && runtimeStateKnown && onLaunch && (
{display.tone === "idle" && !display.tabOpen && runtimeStateKnown && onLaunch && (
<div className="ui-card-section flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<p className="text-sm text-text-secondary">No agent is currently running for this project.</p>
<button onClick={onLaunch} className="ui-btn-primary shrink-0 gap-1.5">
@@ -233,12 +239,22 @@ export function ProjectCard({
</button>
</div>
)}
{display.tone === "idle" && display.tabOpen && !display.isRunning && (
<div className="ui-card-section">
<p className="text-sm text-text-secondary">
{daemonSyncStale
? "Terminal tab is open on your computer, but live status is stale. Check the tab locally or repair the daemon connection."
: "Terminal tab is open, but Cockpit is not tracking an active prompt. The agent may be idle, or status has not synced yet."}
</p>
</div>
)}
<IntentButtonPanel
project={project}
currentAdapter={currentAdapter}
runtimeAvailable={runtimeAvailable}
runtimeStateKnown={runtimeStateKnown}
daemonSyncStale={daemonSyncStale}
isRunning={display.isRunning}
autoContinueEnabled={automationMode === "off" ? false : autoContinueEnabled}
sending={sending}
+12 -8
View File
@@ -8,7 +8,8 @@ import type { ControlDashboardState, LiveTabRow } from "./control-presenter";
export function ZellijLivePanel({
rows,
daemonStateUnknown,
daemonNeverSeen,
daemonSyncStale = false,
dashboard,
refreshing,
onRefresh,
@@ -19,7 +20,8 @@ export function ZellijLivePanel({
embedded = false,
}: {
rows: LiveTabRow[];
daemonStateUnknown: boolean;
daemonNeverSeen: boolean;
daemonSyncStale?: boolean;
dashboard: ControlDashboardState | null;
refreshing: boolean;
onRefresh: () => void;
@@ -91,22 +93,24 @@ export function ZellijLivePanel({
<PanelsTopLeft className="h-3.5 w-3.5 shrink-0 text-accent-text" />
<h2 className="text-xs font-semibold text-text-primary">Terminal workspaces</h2>
<span className="ui-tag ui-tag-neutral text-[9px]">
{daemonStateUnknown ? "offline" : `${rows.length} open`}
{daemonNeverSeen ? "offline" : daemonSyncStale ? `${rows.length} open · stale` : `${rows.length} open`}
</span>
</div>
{!daemonStateUnknown && (
{!daemonNeverSeen && (
<p className="mt-0.5 text-micro text-text-tertiary">
Open tabs come from Zellij. Working and awaiting input come from live agent/process signals.
{daemonSyncStale
? "Showing last-known workspace state — local daemon sync is stale."
: "Open tabs come from Zellij. Working and awaiting input come from live agent/process signals."}
</p>
)}
</div>
<div className="flex shrink-0 items-center gap-1.5">
{dashboard && !daemonStateUnknown && (
{dashboard && !daemonNeverSeen && (
<span className="ui-micro-label text-text-muted text-[9px]">
{dashboard.runningCount} working · {dashboard.waitingCount} awaiting input
</span>
)}
{!daemonStateUnknown && (
{!daemonNeverSeen && (
<button
type="button"
onClick={repairHelper}
@@ -130,7 +134,7 @@ export function ZellijLivePanel({
</div>
</div>
{daemonStateUnknown ? (
{daemonNeverSeen ? (
<div className="ui-control-live-empty">
<p className="font-medium text-text-secondary">No live workspace data</p>
<p className="mt-1 max-w-xl text-sm leading-relaxed text-text-tertiary">
+76 -13
View File
@@ -5,6 +5,8 @@ import {
READY_WINDOW_S,
withinWindow,
} from "@/lib/constants/control";
import { timeAgo } from "@/lib/dates";
import { getIntentLabel } from "@/config/control-intents";
import type { ControlData, ProjectState } from "@/lib/control-types";
/**
@@ -15,6 +17,36 @@ import type { ControlData, ProjectState } from "@/lib/control-types";
* agent task should plausibly run; longer real work writes intermediate session
* files so the mtime-based signal below fires first.
*/
export type RuntimeSyncContext = {
/** True when the cloud has never received a daemon runtime-state push. */
stateUnknown?: boolean;
/** True when the last daemon push is older than the offline threshold. */
syncStale?: boolean;
/** ISO timestamp of the last successful runtime-state push from the local daemon. */
lastSyncedAt?: string | null;
};
function staleSyncLabel(lastSyncedAt: string | null | undefined): string {
if (!lastSyncedAt) return "Last sync unknown";
return `Last sync ${timeAgo(new Date(lastSyncedAt).getTime())}`;
}
function staleEvidenceLabel(
display: ProjectDisplayState,
project: ProjectState,
lastSyncedAt: string | null | undefined,
): string {
const prefix = staleSyncLabel(lastSyncedAt);
if (display.isRunning && project.currentPrompt?.label) {
return `${prefix} · ${project.currentPrompt.label}`;
}
if (display.isReady) return `${prefix} · Ready for next step`;
if (display.isSessionOpen) return `${prefix} · Agent shell open`;
if (display.tabOpen) return `${prefix} · Workspace tab open`;
return prefix;
}
/** Hard cap (seconds) before currentPrompt is treated as stale — see isCurrentPromptStale. */
const STALE_PROMPT_S = 30 * 60;
/**
@@ -73,7 +105,7 @@ export type ProjectDisplayState = {
| "closed"
| "idle";
/** Human-readable label for the state badge — single source of truth */
stateLabel: "Offline" | "Working" | "Ready for next step" | "Waiting for instructions" | "Closing" | "Completed" | "Not running";
stateLabel: "Offline" | "Working" | "Ready for next step" | "Waiting for instructions" | "Closing" | "Completed" | "Not running" | "Tab open";
/** Tailwind classes for the ui-tag badge */
stateTagClass: string;
};
@@ -135,6 +167,7 @@ const LIVE_TAB_RANK: Record<LiveTabRankLabel, number> = {
Closing: 2,
Completed: 3,
"Not running": 4,
"Tab open": 4,
"Open, idle": 4,
Open: 5,
};
@@ -416,6 +449,12 @@ export function getProjectDisplayState(
idle: "ui-tag ui-tag-neutral",
};
// When the Zellij tab is open but no agent/prompt is tracked, "Not running"
// reads like nothing exists — "Tab open" matches what the user can verify.
const stateLabel = tone === "idle" && tabOpen && !isSessionOpen
? "Tab open"
: STATE_LABEL[tone];
return {
isClosed,
isClosing,
@@ -430,7 +469,7 @@ export function getProjectDisplayState(
showLatestOrchestration,
tabOpen,
tone,
stateLabel: STATE_LABEL[tone],
stateLabel,
stateTagClass: STATE_TAG[tone],
};
}
@@ -440,7 +479,9 @@ export function buildProjectOperationsSnapshot(
zellijTabs: string[],
nowS: number,
runtimeStateKnown = true,
syncCtx: RuntimeSyncContext = {},
): ProjectOperationsSnapshot {
const { syncStale = false, lastSyncedAt = null } = syncCtx;
const display = getProjectDisplayState(project, zellijTabs, nowS, false, runtimeStateKnown);
const phase: ControlPhase = display.tone === "offline"
? "offline"
@@ -464,7 +505,22 @@ export function buildProjectOperationsSnapshot(
: project.session?.done?.trim()
? project.session.done.trim()
: null;
const liveObserved = runtimeStateKnown && (display.isRunning || display.isReady || display.isOrchestrationReady || display.isSessionOpen || display.tabOpen);
const liveObserved = runtimeStateKnown && !syncStale && (display.isRunning || display.isReady || display.isOrchestrationReady || display.isSessionOpen || display.tabOpen);
const latestInjection = project.recentInjections[0];
const latestInjectionAgeS = latestInjection?.dispatchedAt
? nowS - Math.floor(new Date(latestInjection.dispatchedAt).getTime() / 1000)
: null;
const latestInjectionLabel = latestInjection
? (latestInjection.customPrompt?.trim() || getIntentLabel(latestInjection.intent))
: null;
const recentDispatchSuffix =
latestInjection &&
latestInjectionAgeS !== null &&
latestInjectionAgeS >= 0 &&
latestInjectionAgeS < 30 * 60
? `Last dispatch ${timeAgo(new Date(latestInjection.dispatchedAt).getTime())}${latestInjectionLabel ? ` · ${latestInjectionLabel}` : ""}`
: null;
const liveEvidenceLabel = display.isRunning
? "Live agent process detected"
: display.isReady
@@ -474,22 +530,28 @@ export function buildProjectOperationsSnapshot(
: display.isSessionOpen
? "Agent shell waiting for instructions"
: display.tabOpen
? "Workspace tab open"
? recentDispatchSuffix
? `Workspace tab open · ${recentDispatchSuffix}`
: "Workspace tab open"
: "No live observation";
const evidenceLabel = !runtimeStateKnown
? "Live status unavailable"
: syncStale
? staleEvidenceLabel(display, project, lastSyncedAt)
: liveObserved
? liveEvidenceLabel
: handoffAt
? "Saved agent context"
: "No live observation";
return {
project,
phase,
display,
evidenceLabel: !runtimeStateKnown
? "Live status unavailable"
: liveObserved
? liveEvidenceLabel
: handoffAt
? "Saved agent context"
: "No live observation",
evidenceLabel,
evidenceAt: liveObserved ? null : handoffAt,
evidenceKind: !runtimeStateKnown ? "unknown" : liveObserved ? "live" : "historical",
evidenceKind: !runtimeStateKnown ? "unknown" : syncStale ? "historical" : liveObserved ? "live" : "historical",
contextSummary,
attentionReason: attention.score > 0 ? attention.reason : null,
};
@@ -500,9 +562,10 @@ export function buildProjectOperationsSnapshots(
zellijTabs: string[],
nowS: number,
runtimeStateKnown = true,
syncCtx: RuntimeSyncContext = {},
): ProjectOperationsSnapshot[] {
return projects
.map((project) => buildProjectOperationsSnapshot(project, zellijTabs, nowS, runtimeStateKnown))
.map((project) => buildProjectOperationsSnapshot(project, zellijTabs, nowS, runtimeStateKnown, syncCtx))
.sort((a, b) => compareProjects(a.project, b.project, zellijTabs, nowS, runtimeStateKnown));
}
@@ -40,6 +40,7 @@ export function IntentButtonPanel({
onCustomFocusChange,
runtimeAvailable = true,
runtimeStateKnown = true,
daemonSyncStale = false,
automationStatusLabel,
}: {
project: ProjectState;
@@ -74,6 +75,7 @@ export function IntentButtonPanel({
runtimeAvailable?: boolean;
/** False when cached daemon-driven runtime fields cannot be trusted. */
runtimeStateKnown?: boolean;
daemonSyncStale?: boolean;
automationStatusLabel?: string;
}) {
const [showMore, setShowMore] = useState(false);
@@ -104,6 +106,8 @@ export function IntentButtonPanel({
onToggleAutoContinue,
statusLabel: !runtimeStateKnown
? "Daemon offline: sends will queue until this computer reconnects."
: daemonSyncStale
? "Sync stale: sends queue on your computer until the daemon reconnects."
: automationStatusLabel
? automationStatusLabel
: autoContinueEnabled
+3 -1
View File
@@ -78,7 +78,9 @@ export async function getApiUserId(): Promise<string | null> {
// DB agent token (ck_*) — preferred path. Per-user, per-device, revocable.
if (bearer.startsWith("ck_")) {
const result = await validateAgentToken(bearer);
return result?.userId ?? null;
if (result) return result.userId;
// Fall through: a ck_-prefixed bearer can still be a legacy env-var token
// on single-tenant local installs that haven't minted a per-user token yet.
}
// Legacy env-var token → "default" user. Opt-in only; not multi-tenant safe.