Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf8821f3f9 | ||
|
|
fe4df10210 | ||
|
|
963d2f5413 | ||
|
|
c0f475bffe | ||
|
|
afdbf6eaec | ||
|
|
74927a7640 | ||
|
|
73e77aca73 | ||
|
|
f82c13612d | ||
|
|
a92d10ace3 | ||
|
|
66321f4748 | ||
|
|
927920c162 | ||
|
|
dee1843986 |
@@ -157,6 +157,8 @@ jobs:
|
||||
steps:
|
||||
# CT 126's webhook listener runs /usr/lib/devdesk/devdesk-deploy, which
|
||||
# waits for this version in the apt registry and upgrades the package.
|
||||
# The hook answers when the install is done (HTTP 500 if it failed), so
|
||||
# this job's result is the deploy's result.
|
||||
- name: Trigger devdesk-deploy webhook
|
||||
env:
|
||||
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
|
||||
@@ -164,12 +166,15 @@ jobs:
|
||||
run: |
|
||||
PAYLOAD="{\"ref\":\"${GIT_REF}\"}"
|
||||
SIG=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | awk '{print $2}')
|
||||
curl -sf --connect-timeout 10 \
|
||||
code=$(curl -sS --connect-timeout 10 --max-time 900 -o /tmp/deploy.out -w '%{http_code}' \
|
||||
-X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-Gitea-Signature: ${SIG}" \
|
||||
-d "$PAYLOAD" \
|
||||
"http://10.10.10.58:9000/hooks/devdesk-deploy"
|
||||
"http://10.10.10.58:9000/hooks/devdesk-deploy") || code=000
|
||||
cat /tmp/deploy.out 2>/dev/null || true
|
||||
echo "webhook: HTTP $code"
|
||||
[ "$code" = 200 ]
|
||||
|
||||
notify-failure:
|
||||
name: Notify on failure
|
||||
|
||||
@@ -40,8 +40,9 @@ install: all
|
||||
install -m 0644 libexec/devdesk-lib.sh $(DESTDIR)$(LIBDIR)/devdesk-lib.sh
|
||||
install -m 0755 libexec/devdesk-picker libexec/devdesk-claude-run libexec/devdesk-session-hook \
|
||||
libexec/devdesk-tmux-ready libexec/devdesk-serve libexec/devdesk-statusline \
|
||||
libexec/devdesk-deploy libexec/devdesk-state-hook libexec/devdesk-notify-matrix $(DESTDIR)$(LIBDIR)/
|
||||
install -m 0644 libexec/devdesk-files.sh $(DESTDIR)$(LIBDIR)/devdesk-files.sh
|
||||
libexec/devdesk-deploy libexec/devdesk-state-hook libexec/devdesk-notify-matrix libexec/devdesk-guard $(DESTDIR)$(LIBDIR)/
|
||||
install -m 0644 libexec/devdesk-files.sh libexec/devdesk-inbox.sh libexec/devdesk-history.sh libexec/devdesk-ops.sh \
|
||||
$(DESTDIR)$(LIBDIR)/
|
||||
install -m 0755 build/ttyd $(DESTDIR)$(LIBDIR)/bin/ttyd
|
||||
install -m 0644 dist/index.html share/tmux.conf share/claude-settings.json $(DESTDIR)$(SHAREDIR)/
|
||||
install -d $(DESTDIR)$(SHAREDIR)/assets
|
||||
|
||||
@@ -38,16 +38,25 @@ The tmux server runs in its own unit, so every Claude process lives in **that**
|
||||
- The sidebar shows it with context % and a context bar; the session chip's dot shows the current session's state.
|
||||
- A "… needs you" chip jumps to other sessions that are waiting, and a desktop notification fires when one starts waiting.
|
||||
- The **🔔 inbox** lists what needs you (waiting sessions, firing Grafana alerts) and what happened while you were away (a background session finished or started waiting, CI passed or failed); its badge counts them.
|
||||
- **Answer from the inbox:** a session waiting on a permission shows the exact command/file and **Allow / Deny** (the key is pressed only if that prompt is still on screen); other waits and finished sessions offer **Peek & reply**: the last exchange and a reply box.
|
||||
- **Matrix "Claude needs you":** when a session has waited for `DEVDESK_MATRIX_DELAY` seconds (30) and no browser tab or SSH client is attached to it, `devdesk-notify-matrix` posts one message per wait, with a link, to the hookshot webhook URL in `/etc/devdesk/matrix-webhook` (mode 600; no file = off).
|
||||
- **File & image drop:** drag files onto the terminal or paste a screenshot.
|
||||
- They're uploaded through ttyd to `/var/lib/devdesk/uploads/<session>/` (25 MB max, pruned after 7 days), and the path is pasted into Claude.
|
||||
- For images, Claude attaches them itself.
|
||||
- **Ops Alerts panel:** firing and pending Grafana alert rules, each with a link to the rule.
|
||||
- **Ask Claude** types an investigation prompt into the current session without sending it.
|
||||
- Configure `DEVDESK_GRAFANA_URL`, plus a Viewer token in `DEVDESK_GRAFANA_TOKEN_FILE`.
|
||||
- **Ops Alerts panel:** firing and pending Grafana alert rules, each with a link to the rule and the Proxmox guest or node it's about, e.g. `→ CT 110 draupnir · monitor-02 · stopped`.
|
||||
- **Ask Claude** starts Claude in a new session (`alert-<name>`) with the investigation already sent. The prompt has the rule, its query, summary and labels, and where it runs: the CT/VM id, the node it's on right now, and the `ssh <node> pct exec <id> --` line. Clicking it again just opens that session.
|
||||
- Guests are matched by the alert's `instance` IP (or host name), else by name in the job or alert ("by name"). Aggregate rules with no labels (`count(up == 0)`) get a hint to run the inner query instead.
|
||||
- **`devdesk guests [ID|IP|NAME]`** lists Proxmox CTs/VMs with the node each runs on now, status, HA state and IPs. Claude is told to use it before acting, because HA guests move. Stopped guests keep the IP they had when last seen running.
|
||||
- Configure `DEVDESK_GRAFANA_URL`, plus a Viewer token in `DEVDESK_GRAFANA_TOKEN_FILE`. For the guest lookup, set `DEVDESK_PVE_NODES` to a few Proxmox nodes reachable by root SSH key. VM IPs need the QEMU guest agent.
|
||||
- **Repo / CI panel:** branch, ahead/behind, uncommitted changes, HEAD's Gitea CI status and open PRs for the session's folder. When CI fails, **Ask Claude to fix CI** types a prompt to read the failed job's log.
|
||||
- **Files** (Ctrl+Shift+E), laid out like VS Code: an explorer tree (git colours, gitignored entries dimmed) and an editor with tabs (a click opens a preview tab, a double-click keeps it), **Go to file** (Ctrl+P in the pane), markdown previews (sanitized, with relative images), images, and a Changes view of uncommitted files with line counts, a **C** badge on files Claude edited, and diffs against HEAD. **@Claude** types `@path` into the prompt. Tabs and open folders are remembered per session. Read-only for now. Paths can't leave the session folder. The editor bundle (`/usr/share/devdesk/assets/editor.js`) loads over ttyd the first time and is cached by the browser.
|
||||
- **Context:** a Claude `statusLine` command (`devdesk-statusline`) snapshots each session's model, context-window use and cost to `/var/lib/devdesk/context/<session>.json`. The Sessions panel shows it as a bar (cost in the tooltip), and Claude's own footer shows a one-line summary.
|
||||
- **Files** (Ctrl+Shift+E), laid out like VS Code: an explorer tree (git colours, gitignored entries dimmed) and an editor with tabs (a click opens a preview tab, a double-click keeps it), **Go to file** (Ctrl+P in the pane), markdown previews (sanitized, with relative images), images, and a Changes view of uncommitted files with line counts, a **C** badge on files Claude edited, and diffs against HEAD. **@Claude** types `@path` into the prompt. Tabs and open folders are remembered per session. Paths can't leave the session folder.
|
||||
- **Editing:** text files are editable; ● marks unsaved tabs; Ctrl+S (or Save) writes atomically and keeps the file's mode and owner. If the file changed on disk since you opened it (Claude edited it), saving asks: Compare (a diff of disk vs yours), Overwrite or Cancel; a change on disk while you edit shows a banner instead of replacing your text. Unsaved edits are kept as drafts in the browser, so a reload or a session switch doesn't lose them. + creates a file (folders as needed). The editor bundle (`/usr/share/devdesk/assets/editor.js`) loads over ttyd the first time and is cached by the browser.
|
||||
- **Paths are links:** a file path Claude prints (`web/src/files.js`, `notes.md:12`) opens in Files when clicked, at that line if given.
|
||||
- **Ops guard:** `devdesk-guard` (a PreToolUse hook) makes Claude ask before destructive commands (`pct destroy`, `zfs destroy`, Ceph pool/OSD removal, `rm -r /…`, `git push --force`, `reboot`…), even in auto mode. `DEVDESK_GUARD=0` turns it off; `/etc/devdesk/guard.local` adds rules (`regex<TAB>reason`). Bash commands are logged per session, and sessions are tagged with the hosts they touch (ssh targets, CT/VM ids).
|
||||
- **Search past conversations** (⋯ menu, palette): full text over every Claude conversation on the host; **Resume** it in a new session or **Fork** it.
|
||||
- **Plan usage:** the 5-hour and weekly windows as meters in the footer (warning at 90 %); a **PR** chip on sessions whose branch has a pull request.
|
||||
- **Quiet phone at the desk:** while a tab shows a session, Remote Control holds back phone pushes for it (client-presence marker, expires ~2 min after you leave).
|
||||
- **Context:** a Claude `statusLine` command (`devdesk-statusline`) snapshots each session's model, context-window use, plan usage and cost to `/var/lib/devdesk/context/<session>.json`. The Sessions panel shows it as a bar and Claude's own footer shows a one-line summary. On a Pro/Max plan that summary shows 5-hour plan usage; the dollar figure Claude reports there is an API-price estimate, not a bill, so it appears only for API-key billing.
|
||||
- **Light mode:** the terminal switches palettes with the page. DevDesk starts Claude with its `dark-ansi` theme so Claude draws with the terminal's 16 colours, and the light palette maps bright white to ink; tmux and the status line use ANSI colours too. A session picks up Claude's theme the next time Claude starts in it (`/exit`, then ⏎ resumes the same conversation).
|
||||
- **Phone:** a key bar replaces the shortcut hints (Esc, Tab, ⇧Tab, ^C, ↑, ↓, ⏎, Claude/Shell window), and the panels open as a drawer.
|
||||
- **SSH:** `devdesk attach <name>`, `devdesk new <name> [project]`, `devdesk rename <old> <new>`, `devdesk end <name>`, `devdesk ls`, `devdesk pick`, `devdesk repo <name>`, `devdesk alerts`.
|
||||
|
||||
+53
-44
@@ -7,11 +7,12 @@
|
||||
# devdesk end NAME stop session NAME and forget it
|
||||
# devdesk repo NAME git + Gitea CI status of the session's folder (JSON)
|
||||
# devdesk alerts firing/pending Grafana alerts (JSON)
|
||||
# devdesk guests [ID|IP|NAME] Proxmox CTs/VMs: the node each runs on now, state, IPs
|
||||
# devdesk ls list sessions
|
||||
# devdesk pick interactive picker
|
||||
#
|
||||
# The web UI calls `devdesk attach --list | --repo NAME | --alerts | --upload SESSION FILE BYTES |
|
||||
# --new NAME [PROJECT] | --rename OLD NEW | --end NAME | --existing NAME`
|
||||
# The web UI calls `devdesk attach --list | --repo NAME | --alerts | --investigate SESSION UID |
|
||||
# --upload SESSION FILE BYTES | --new NAME [PROJECT] | --rename OLD NEW | --end NAME | --existing NAME`
|
||||
# through ttyd; those print JSON.
|
||||
set -euo pipefail
|
||||
|
||||
@@ -19,9 +20,15 @@ set -euo pipefail
|
||||
. "${DEVDESK_LIBEXEC:-/usr/lib/devdesk}/devdesk-lib.sh"
|
||||
# shellcheck source=libexec/devdesk-files.sh
|
||||
. "$DEVDESK_LIBEXEC/devdesk-files.sh"
|
||||
# shellcheck source=libexec/devdesk-inbox.sh
|
||||
. "$DEVDESK_LIBEXEC/devdesk-inbox.sh"
|
||||
# shellcheck source=libexec/devdesk-history.sh
|
||||
. "$DEVDESK_LIBEXEC/devdesk-history.sh"
|
||||
# shellcheck source=libexec/devdesk-ops.sh
|
||||
. "$DEVDESK_LIBEXEC/devdesk-ops.sh"
|
||||
|
||||
usage() {
|
||||
sed -n '2,12s/^# \{0,1\}//p' "$0"
|
||||
sed -n '2,13s/^# \{0,1\}//p' "$0"
|
||||
}
|
||||
|
||||
# Tab-separated running sessions: name, dir, attached clients, last activity, windows.
|
||||
@@ -67,6 +74,7 @@ cmd_list() {
|
||||
--arg proj "$(projects_tsv)" \
|
||||
--argjson ctx "$(per_session_json "$DEVDESK_CONTEXT_DIR")" \
|
||||
--argjson st "$(per_session_json "$DEVDESK_STATUS_DIR")" \
|
||||
--argjson tags "$(per_session_json "$DEVDESK_STATE_DIR/tags")" \
|
||||
--arg dflt "$DEVDESK_DEFAULT_SESSION" \
|
||||
--arg root "$DEVDESK_PROJECTS_ROOT" '
|
||||
def rows($s): $s | split("\n") | map(select(length > 0) | split("\t"));
|
||||
@@ -83,7 +91,7 @@ cmd_list() {
|
||||
| map({name: .key, dir: .value.dir, running: false, attached: 0,
|
||||
activity: null, windows: 0,
|
||||
claude_session_id: (.value.claude_session_id // null)}))
|
||||
) | map(. + {context: ($ctx[.name] // null), status: ($st[.name] // null)}),
|
||||
) | map(. + {context: ($ctx[.name] // null), status: ($st[.name] // null), tags: ($tags[.name].hosts // [])}),
|
||||
projects: ([{name: $dflt, dir: $root}]
|
||||
+ [rows($proj)[] | {name: .[0], dir: (.[1:] | join("\t"))}
|
||||
| select(.name | test("^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$"))])}'
|
||||
@@ -136,11 +144,17 @@ cmd_rename() {
|
||||
if dd_server_up && dd_tmux has-session -t "=$old" 2>/dev/null; then running=1; fi
|
||||
[ "$running" = 1 ] || [ -n "$(dd_registry_get "$old" dir)" ] || dd_die "no session named '$old'"
|
||||
! session_exists "$new" || dd_die "a session named '$new' already exists"
|
||||
if [ "$running" = 1 ]; then
|
||||
dd_tmux rename-session -t "=$old" "$new"
|
||||
dd_tmux set-environment -t "=$new" DEVDESK_SESSION "$new"
|
||||
dd_registry_locked rename_locked "$old" "$new" "$running" || dd_die "could not rename '$old'"
|
||||
}
|
||||
|
||||
# tmux and the registry change together, under the registry lock (see
|
||||
# devdesk-session-hook).
|
||||
rename_locked() {
|
||||
if [ "$3" = 1 ]; then
|
||||
dd_tmux rename-session -t "=$1" "$2" || return 1
|
||||
dd_tmux set-environment -t "=$2" DEVDESK_SESSION "$2"
|
||||
fi
|
||||
dd_registry_rename "$old" "$new"
|
||||
dd_registry_rename "$1" "$2"
|
||||
}
|
||||
|
||||
cmd_end() {
|
||||
@@ -219,41 +233,6 @@ cmd_repo() {
|
||||
prs: $prs}'
|
||||
}
|
||||
|
||||
# Firing and pending Grafana alert rules, most severe first.
|
||||
cmd_alerts() {
|
||||
if [ -z "$DEVDESK_GRAFANA_URL" ]; then
|
||||
jq -cMn '{configured: false, alerts: []}'
|
||||
return
|
||||
fi
|
||||
local raw
|
||||
if ! raw=$({
|
||||
if [ -r "$DEVDESK_GRAFANA_TOKEN_FILE" ]; then
|
||||
# shellcheck disable=SC1003 # tr deletes whitespace, quotes and backslashes from the token
|
||||
printf 'header = "Authorization: Bearer %s"\n' "$(tr -d '[:space:]"\\' <"$DEVDESK_GRAFANA_TOKEN_FILE")"
|
||||
fi
|
||||
} | curl -fsS --max-time 6 -K - "$DEVDESK_GRAFANA_URL/api/prometheus/grafana/api/v1/rules" 2>&1); then
|
||||
jq -cMn --arg e "${raw:-no response}" '{configured: true, error: $e, alerts: []}'
|
||||
return
|
||||
fi
|
||||
jq -cM --arg pub "$DEVDESK_GRAFANA_PUBLIC_URL" '
|
||||
def num: (tonumber? // .) | tostring;
|
||||
{configured: true, checked: (now | floor), alerts: [
|
||||
.data.groups[] | .name as $group | .file as $folder | .rules[]
|
||||
| select(.state == "firing" or .state == "pending")
|
||||
| . as $r
|
||||
| ([.alerts[]? | select(.state == "Alerting" or .state == "Pending")]) as $active
|
||||
| {name, state, severity: (.labels.severity // null), group: $group, folder: $folder,
|
||||
since: (.activeAt // $active[0].activeAt // null),
|
||||
summary: ((.annotations.summary // .annotations.description // "")
|
||||
| gsub("\\{\\{ *\\$value *\\}\\}"; ($active[0].value // "?" | num))),
|
||||
instances: [$active[] | .labels
|
||||
| del(.__alert_rule_uid__, .__grafana_origin__, .alertname, .grafana_folder, .__name__, .severity)
|
||||
| to_entries | map("\(.key)=\(.value)") | join(" ")
|
||||
| select(. != "")],
|
||||
url: "\($pub)/alerting/grafana/\(.uid)/view"}
|
||||
] | sort_by(if .severity == "critical" then 0 elif .severity == "warning" then 1 else 2 end)}' <<<"$raw"
|
||||
}
|
||||
|
||||
# Receive a file for SESSION over the terminal: the browser waits for the ready
|
||||
# line, then sends exactly ceil(BYTES/3)*4 bytes of base64 as input.
|
||||
cmd_upload() {
|
||||
@@ -312,19 +291,48 @@ cmd_attach() {
|
||||
dd_linger
|
||||
return
|
||||
;;
|
||||
--investigate)
|
||||
shift
|
||||
cmd_investigate "$@"
|
||||
dd_linger
|
||||
return
|
||||
;;
|
||||
--upload)
|
||||
shift
|
||||
cmd_upload "$@"
|
||||
dd_linger
|
||||
return
|
||||
;;
|
||||
--fs-list | --fs-find | --fs-read | --git-status | --git-show | --asset)
|
||||
--fs-list | --fs-find | --fs-read | --fs-write | --git-status | --git-show | --asset)
|
||||
local action=${1#--}
|
||||
shift
|
||||
"cmd_${action//-/_}" "$@"
|
||||
dd_linger
|
||||
return
|
||||
;;
|
||||
--peek | --search)
|
||||
local action=${1#--}
|
||||
shift
|
||||
"cmd_$action" "$@"
|
||||
dd_linger
|
||||
return
|
||||
;;
|
||||
--resume-convo | --presence)
|
||||
local action=${1#--}
|
||||
shift
|
||||
"cmd_${action//-/_}" "$@"
|
||||
ok_json
|
||||
dd_linger
|
||||
return
|
||||
;;
|
||||
--answer | --reply)
|
||||
local action=${1#--}
|
||||
shift
|
||||
"cmd_$action" "$@"
|
||||
ok_json
|
||||
dd_linger
|
||||
return
|
||||
;;
|
||||
--new | --rename | --end)
|
||||
local action=${1#--}
|
||||
shift
|
||||
@@ -374,6 +382,7 @@ new) cmd_new "$@" ;;
|
||||
rename | mv) cmd_rename "$@" ;;
|
||||
repo) cmd_repo "$@" ;;
|
||||
alerts) cmd_alerts ;;
|
||||
guests) cmd_guests "$@" ;;
|
||||
ls | list) cmd_ls ;;
|
||||
--list) cmd_list ;;
|
||||
end) cmd_end "$@" ;;
|
||||
|
||||
Vendored
+189
@@ -1,3 +1,192 @@
|
||||
devdesk (0.9.5) bookworm; urgency=medium
|
||||
|
||||
* Context use is shown in tokens as well as percent (#43): Claude's
|
||||
footer shows "ctx 34% 346k/1M", and the Sessions panel and session
|
||||
switcher show "ctx 34% · 346k/1M".
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sun, 11 Oct 2026 23:07:00 -0400
|
||||
|
||||
devdesk (0.9.4) bookworm; urgency=medium
|
||||
|
||||
* The inbox badge no longer only grows (#42). Opening the bell marks its
|
||||
events seen, leaving just what is live (sessions waiting on you,
|
||||
firing alerts). Viewing a session reads the events it reported while
|
||||
you were away.
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sun, 11 Oct 2026 22:46:00 -0400
|
||||
|
||||
devdesk (0.9.3) bookworm; urgency=medium
|
||||
|
||||
* Claude's footer shows 5-hour plan use instead of a dollar figure on a
|
||||
Pro/Max subscription (#40). Claude Code's cost is an API-price
|
||||
estimate, not a bill; it is still shown for API-key billing. The
|
||||
Sessions tooltip follows the same rule.
|
||||
* The bottom row is larger and easier to read (#41): 40px tall, larger
|
||||
hints, and 5h/week usage meters in bold monospace with wider bars.
|
||||
Narrow windows drop the least-used hints instead of clipping the
|
||||
meters.
|
||||
* Tests clear inherited DevDesk variables, so they pass when run from
|
||||
inside a DevDesk session.
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sun, 11 Oct 2026 22:08:00 -0400
|
||||
|
||||
devdesk (0.9.2) bookworm; urgency=medium
|
||||
|
||||
* Ops Alerts → Ask Claude starts an investigation (#39):
|
||||
- It opens a new session (alert-<name>) and starts Claude with the
|
||||
prompt already sent, instead of typing it into the current session.
|
||||
Clicking again opens the running session.
|
||||
- The server writes the prompt from Grafana: rule, query, summary,
|
||||
details, labels, and where the alert runs. That is the Proxmox CT/VM
|
||||
id, the node it is on right now, its state and HA state, and the
|
||||
`ssh <node> pct exec <id> --` line.
|
||||
- Each alert card shows that guest or node.
|
||||
* `devdesk guests [ID|IP|NAME]`: Proxmox guests with their current node,
|
||||
status, HA state and IPs, read over SSH from DEVDESK_PVE_NODES. CT IPs
|
||||
come from lxc-info, VM IPs from the guest agent. Cached in
|
||||
/var/lib/devdesk/guests.json; stopped guests keep their last-seen IPs.
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sun, 11 Oct 2026 11:23:53 -0400
|
||||
|
||||
devdesk (0.9.1) bookworm; urgency=medium
|
||||
|
||||
* Robustness (#12):
|
||||
- A resume that fails (an early Ctrl+C, a network error) no longer
|
||||
replaces the session's recorded conversation with a new one: Claude
|
||||
starts fresh only when the conversation's file is really gone;
|
||||
otherwise the menu offers to try again.
|
||||
- The SessionStart hook reads the session name under the registry lock
|
||||
that rename holds, so renaming during /clear or a restart can't leave
|
||||
the conversation id under the old name.
|
||||
- Env files are parsed the way systemd parses them instead of being
|
||||
sourced: values are literal (no $ expansion or command substitution),
|
||||
and bad lines are reported and skipped.
|
||||
- Deploys wait for the dpkg lock (120 s), log an explicit "deploy
|
||||
FAILED" line, and the webhook answers with the result, so CI's deploy
|
||||
job fails (and alerts) when the install fails. The deploy log is
|
||||
rotated monthly.
|
||||
- postinst removes the duplicate tmux terminal-features entries left by
|
||||
upgrades before 0.3.1.
|
||||
- Temp files of hooks killed mid-write are swept.
|
||||
- NPM now sends X-Frame-Options DENY and CSP frame-ancestors 'none' for
|
||||
dev.lotusguild.org (proxy config, not part of the package).
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sun, 11 Oct 2026 01:01:33 -0400
|
||||
|
||||
devdesk (0.9.0) bookworm; urgency=medium
|
||||
|
||||
* Search past conversations (#24): every Claude conversation on this host
|
||||
(DevDesk and code-server), by what you asked, what Claude said, the
|
||||
commands it ran and their output (⋯ menu or the palette). Results show
|
||||
the title, folder, dates and highlighted snippets; Resume opens the
|
||||
conversation in a new session in its folder, Fork continues it as a new
|
||||
conversation (claude --fork-session) and leaves the original as it is.
|
||||
A conversation already open in a running session offers "Open" instead,
|
||||
and resuming it twice is refused.
|
||||
* Plan usage and PRs (#25): the 5-hour and weekly plan windows from
|
||||
Claude's statusLine, as meters in the footer (⋯ menu on phones), with a
|
||||
warning at 90 % of the 5-hour window; a PR chip (with review state) on
|
||||
sessions whose branch has a pull request. (The statusLine has no prompt
|
||||
cache expiry, so there is no cache timer.)
|
||||
* Phone pushes held back while you're at the desk (#26): while a DevDesk
|
||||
tab shows a session, its Claude sees a client-presence marker
|
||||
(CLAUDE_CLIENT_PRESENCE_FILE) and Remote Control holds back pushes; the
|
||||
marker expires about 2 minutes after the tab stops showing it. Applies to
|
||||
sessions whose Claude started on this version (/exit, then ⏎).
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sat, 10 Oct 2026 21:44:07 -0400
|
||||
|
||||
devdesk (0.8.2) bookworm; urgency=medium
|
||||
|
||||
* Click file paths in the terminal (#21): a path Claude prints
|
||||
(web/src/files.js, ./notes.md:12, /root/code/x/y.py:3) is a link when it
|
||||
is a file of the session; it opens in Files, at that line if given.
|
||||
* Alerts: "In a new session" (#18) opens (or reuses) alert-<name> in the
|
||||
default folder and types the investigation prompt there once Claude is
|
||||
up, without sending it.
|
||||
* Ops trail and guard (#27):
|
||||
- devdesk-guard, a PreToolUse hook for Bash, makes Claude ask before
|
||||
commands that destroy things (pct/qm destroy, zfs/zpool destroy, Ceph
|
||||
pool/OSD removal, rbd rm, wipefs/mkfs/dd to /dev, rm -r of / or a
|
||||
top-level folder, git push --force, DROP TABLE, stopping devdesk-tmux,
|
||||
reboot/poweroff…), also in auto mode. It never blocks or allows on its
|
||||
own. DEVDESK_GUARD=0 turns it off; /etc/devdesk/guard.local adds rules
|
||||
(regex<TAB>reason).
|
||||
- Every Bash command is logged per session (last 500); sessions are
|
||||
tagged with the hosts they work on (ssh targets, CT/VM ids), shown in
|
||||
the session list, the switcher and the palette; Peek lists the last
|
||||
commands.
|
||||
* Sessions pick up the new hooks when Claude next starts (/exit, then ⏎).
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sat, 10 Oct 2026 20:36:32 -0400
|
||||
|
||||
devdesk (0.8.1) bookworm; urgency=medium
|
||||
|
||||
* Answer sessions from the 🔔 inbox without switching to them:
|
||||
- Allow / Deny (#22): a PermissionRequest hook records what Claude wants
|
||||
to run (tool, command/file/URL, Claude's description); the inbox shows
|
||||
it with Allow, Deny and Open. The key is pressed in that session's
|
||||
Claude window only if the same wait is still on and the permission
|
||||
prompt is on screen, so a stale button never types into Claude.
|
||||
- Peek & reply (#23): the last thing you asked and Claude's latest answer
|
||||
(from the session's transcript), and a reply box; the reply is pasted
|
||||
as one bracketed paste and sent. Available for sessions that wait for
|
||||
input and from "finished" entries.
|
||||
- Matrix "needs you" messages include the command.
|
||||
* New attach commands: --answer SESSION SINCE allow|deny, --peek SESSION,
|
||||
--reply SESSION BYTES (text streamed like uploads).
|
||||
* Sessions pick up the new PermissionRequest hook when Claude next starts
|
||||
(/exit, then ⏎).
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sat, 10 Oct 2026 20:22:37 -0400
|
||||
|
||||
devdesk (0.8.0) bookworm; urgency=medium
|
||||
|
||||
* Edit and save files in the Files pane (#20):
|
||||
- Text files open editable; ● marks unsaved tabs; Ctrl+S or Save writes
|
||||
through `devdesk attach --fs-write`: a temp file in the same folder,
|
||||
mode and owner kept, swapped in with mv.
|
||||
- Conflict detection: the save carries the sha256 of the version you
|
||||
opened; if Claude (or anyone) changed the file since, nothing is written
|
||||
and you choose Compare (diff of disk vs yours), Overwrite or Cancel.
|
||||
- A file that changes on disk while you edit it shows a banner (Compare,
|
||||
Reload, Keep mine) instead of replacing your text; clean files still
|
||||
reload in place.
|
||||
- Unsaved edits are mirrored to the browser as drafts (flushed when the
|
||||
page closes), so a reload, a crash or a session switch doesn't lose
|
||||
them; a draft for a file that changed since offers Compare/Restore/
|
||||
Discard.
|
||||
- Closing a tab with unsaved changes asks Save / Don't save / Cancel;
|
||||
leaving the page warns.
|
||||
- + New file (missing folders are created; never outside the session
|
||||
folder, and never through a symlink out of it).
|
||||
- Markdown previews show unsaved Source edits. Latin-1 files stay
|
||||
read-only.
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sat, 10 Oct 2026 20:09:49 -0400
|
||||
|
||||
devdesk (0.7.3) bookworm; urgency=medium
|
||||
|
||||
* Fix (#38): links that mean "go to that session" no longer re-create one
|
||||
that was ended. The 🔔 inbox, the session switcher, palette switches, the
|
||||
"needs you" chip and Matrix links (now ?arg=NAME&existing=1) open sessions
|
||||
existing-only; an ended one shows "NAME has ended" with an explicit
|
||||
"Start NAME again". Inbox entries for ended sessions are marked as such,
|
||||
and entries older than 7 days are dropped.
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Sat, 10 Oct 2026 19:57:52 -0400
|
||||
|
||||
devdesk (0.7.2) bookworm; urgency=medium
|
||||
|
||||
* Fix: Go to file failed in big non-git folders such as /root/code: the
|
||||
file walk was cut off at its cap with SIGPIPE, which failed the command
|
||||
and truncated its reply. Producers piped into a cap now tolerate it (also
|
||||
for very large folders and git status). Outside git, Go to file skips
|
||||
build/cache folders and stops at 10,000 files.
|
||||
* Large side-channel replies no longer cost quadratic time in the browser.
|
||||
|
||||
-- Jared Vititoe <jjvititoe1@gmail.com> Thu, 08 Oct 2026 01:50:50 -0400
|
||||
|
||||
devdesk (0.7.1) bookworm; urgency=medium
|
||||
|
||||
* Files pane reworked like VS Code (#37):
|
||||
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
/var/log/devdesk-deploy.log {
|
||||
monthly
|
||||
rotate 6
|
||||
compress
|
||||
delaycompress
|
||||
missingok
|
||||
notifempty
|
||||
}
|
||||
Vendored
+7
@@ -13,6 +13,13 @@ configure)
|
||||
# Apply tmux.conf changes to a running server without restarting it.
|
||||
if [ -S /run/devdesk/tmux.sock ]; then
|
||||
tmux -N -S /run/devdesk/tmux.sock source-file /usr/share/devdesk/tmux.conf >/dev/null 2>&1 || true
|
||||
# Before 0.3.1 every upgrade appended another copy of DevDesk's
|
||||
# terminal-features entry; tmux.conf now sets index 90. Drop the copies.
|
||||
tmux -N -S /run/devdesk/tmux.sock show -s terminal-features 2>/dev/null |
|
||||
awk '$2 == "xterm-256color:RGB" && $1 != "terminal-features[90]" { print $1 }' |
|
||||
while read -r opt; do
|
||||
tmux -N -S /run/devdesk/tmux.sock set -su "$opt" >/dev/null 2>&1 || true
|
||||
done
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
+5
-1
@@ -37,7 +37,9 @@ Then run `authelia validate-config --config /etc/authelia/configuration.yml && s
|
||||
- **Pi-hole:** add `"10.10.10.27 dev.lotusguild.org"` to `dns.hosts` in `pve-infra/containers/163-pihole/etc/pihole/pihole.toml`. A push auto-deploys it, and LAN clients then reach NPM directly instead of hairpinning.
|
||||
|
||||
## 5. Auto-deploy on release
|
||||
A `v*` tag makes CI publish the package, then send a signed webhook (the house HMAC pattern) to CT 126's existing `webhook` listener on :9000. The listener runs `/usr/lib/devdesk/devdesk-deploy <ref>`, which waits for that version in the apt registry and upgrades only `devdesk` with `--force-confold`. Running Claude sessions are untouched. The log is `/var/log/devdesk-deploy.log`.
|
||||
A `v*` tag makes CI publish the package, then send a signed webhook (the house HMAC pattern) to CT 126's existing `webhook` listener on :9000. The listener runs `/usr/lib/devdesk/devdesk-deploy <ref>`, which waits for that version in the apt registry and upgrades only `devdesk` with `--force-confold`. Running Claude sessions are untouched. The log is `/var/log/devdesk-deploy.log` (rotated monthly).
|
||||
|
||||
The hook answers when the deploy has finished, with the script's last line, and with HTTP 500 if it failed. CI's **Deploy to CT 126** job therefore fails when the install fails, and the failure alert goes to Matrix.
|
||||
|
||||
**Setup, done once:**
|
||||
1. Generate a secret.
|
||||
@@ -48,6 +50,8 @@ A `v*` tag makes CI publish the package, then send a signed webhook (the house H
|
||||
"execute-command": "/usr/lib/devdesk/devdesk-deploy",
|
||||
"command-working-directory": "/",
|
||||
"pass-arguments-to-command": [{"source": "payload", "name": "ref"}],
|
||||
"include-command-output-in-response": true,
|
||||
"include-command-output-in-response-on-error": true,
|
||||
"trigger-rule": {"and": [
|
||||
{"match": {"type": "payload-hash-sha256", "secret": "<WEBHOOK_SECRET>",
|
||||
"parameter": {"source": "header", "name": "X-Gitea-Signature"}}},
|
||||
|
||||
@@ -9,7 +9,12 @@
|
||||
include /snippets/authelia-location.conf;
|
||||
|
||||
location / {
|
||||
# Headers go here, not at server level: a location with its own add_header
|
||||
# (HSTS) doesn't inherit the server's.
|
||||
add_header Strict-Transport-Security $hsts_header always;
|
||||
# No other site may frame the terminal (clickjacking).
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Content-Security-Policy "frame-ancestors 'none'" always;
|
||||
|
||||
auth_request /authelia;
|
||||
auth_request_set $user $upstream_http_remote_user;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
# DevDesk defaults, shipped by the package. Don't edit: put your changes in
|
||||
# /etc/devdesk/env.local (same KEY=value format, read after this file), so
|
||||
# package upgrades never prompt about this file.
|
||||
# Read by systemd (EnvironmentFile=) and by the devdesk scripts. Plain KEY=value
|
||||
# lines only: systemd does not support inline comments.
|
||||
# Read by systemd (EnvironmentFile=) and by the devdesk scripts, the same way:
|
||||
# plain KEY=value lines, values taken literally (no $VAR, no $(…)), optionally
|
||||
# in quotes. No inline comments. Other lines are ignored with a warning.
|
||||
# The ttyd credential lives in /etc/devdesk/secret.env (generated on install).
|
||||
|
||||
# Port ttyd listens on (NPM proxies dev.lotusguild.org here).
|
||||
@@ -29,6 +30,13 @@ DEVDESK_GRAFANA_URL=http://10.10.10.49:3000
|
||||
DEVDESK_GRAFANA_PUBLIC_URL=https://dashboard.lotusguild.org
|
||||
DEVDESK_GRAFANA_TOKEN_FILE=/etc/devdesk/grafana-token
|
||||
|
||||
# Proxmox nodes to ask where guests run (`devdesk guests`, and the CT/VM and node
|
||||
# shown on each alert and given to Claude by "Ask Claude"). Space-separated SSH
|
||||
# hosts; the first that answers gives the cluster view, then every online node is
|
||||
# asked for its containers' IPs, by node name. Needs root SSH keys to the nodes.
|
||||
# Empty = off.
|
||||
DEVDESK_PVE_NODES=
|
||||
|
||||
# Claude Code binary and extra arguments for every session.
|
||||
CLAUDE_BIN=/root/.local/bin/claude
|
||||
CLAUDE_ARGS=
|
||||
@@ -42,5 +50,10 @@ DEVDESK_PUBLIC_URL=https://dev.lotusguild.org
|
||||
DEVDESK_MATRIX_WEBHOOK_FILE=/etc/devdesk/matrix-webhook
|
||||
DEVDESK_MATRIX_DELAY=30
|
||||
|
||||
# 0 turns off the guard that makes Claude ask before destructive commands
|
||||
# (pct/zfs/ceph destroy, rm -r /…, force pushes, reboots). Extra rules:
|
||||
# /etc/devdesk/guard.local, one "regex<TAB>reason" per line.
|
||||
DEVDESK_GUARD=1
|
||||
|
||||
# 1 = also enable Remote Control so sessions can be continued from the Claude app.
|
||||
DEVDESK_REMOTE_CONTROL=0
|
||||
|
||||
+32
-11
@@ -36,30 +36,43 @@ common_args() {
|
||||
}
|
||||
|
||||
run_new() {
|
||||
local args
|
||||
local args prompt=() file="$DEVDESK_STATE_DIR/prompts/$NAME.txt"
|
||||
mapfile -d '' args < <(common_args)
|
||||
"$CLAUDE_BIN" -n "$NAME" "${args[@]}"
|
||||
# A first prompt left by `devdesk attach --investigate` (Ops Alerts → Ask
|
||||
# Claude, devdesk#39): sent once, right after the session name so options
|
||||
# in CLAUDE_ARGS can't swallow it.
|
||||
if [ -s "$file" ]; then
|
||||
prompt=("$(cat "$file")")
|
||||
rm -f "$file"
|
||||
fi
|
||||
"$CLAUDE_BIN" -n "$NAME" "${prompt[@]}" "${args[@]}"
|
||||
}
|
||||
|
||||
run_resume() {
|
||||
local id args started rc
|
||||
local id args fork=()
|
||||
id=$(dd_registry_get "$NAME" claude_session_id)
|
||||
if [ -z "$id" ]; then
|
||||
run_new
|
||||
return
|
||||
fi
|
||||
mapfile -d '' args < <(common_args)
|
||||
started=$SECONDS
|
||||
"$CLAUDE_BIN" --resume "$id" "${args[@]}"
|
||||
rc=$?
|
||||
# A resume that fails straight away means the transcript is gone; start fresh.
|
||||
if [ "$rc" -ne 0 ] && [ $((SECONDS - started)) -lt 10 ]; then
|
||||
printf '%sCould not resume conversation %s — starting a new one.%s\n' "$MUTED" "$id" "$RESET"
|
||||
# Start fresh only when the conversation's file is really gone. Any other
|
||||
# failure (an early Ctrl+C, a network error) leaves the recorded id alone
|
||||
# and ends at the menu, where ⏎ tries again (devdesk#12).
|
||||
if [ -z "$(dd_convo_file "$id")" ]; then
|
||||
printf "%sConversation %s is no longer in Claude's history — starting a new one.%s\n" "$MUTED" "$id" "$RESET"
|
||||
sleep 1
|
||||
run_new
|
||||
return
|
||||
fi
|
||||
return "$rc"
|
||||
mapfile -d '' args < <(common_args)
|
||||
# "Fork" from conversation search (devdesk#24): continue as a new
|
||||
# conversation, once; the SessionStart hook then records the new id.
|
||||
if [ "$(dd_registry_get "$NAME" fork)" = true ]; then
|
||||
fork=(--fork-session)
|
||||
# shellcheck disable=SC2016 # $n is a jq variable
|
||||
dd_registry_update 'del(.sessions[$n].fork)' --arg n "$NAME" 2>/dev/null || true
|
||||
fi
|
||||
"$CLAUDE_BIN" --resume "$id" "${fork[@]}" "${args[@]}"
|
||||
}
|
||||
|
||||
menu() {
|
||||
@@ -69,6 +82,14 @@ menu() {
|
||||
}
|
||||
|
||||
printf '\033]2;%s\033\134' "$NAME" # pane title (ST = ESC \\)
|
||||
|
||||
# While a DevDesk tab shows this session, this marker exists and Claude tells
|
||||
# Remote Control a client is present, which holds back phone pushes (devdesk#26).
|
||||
# Keyed by tmux's session id, which survives renames.
|
||||
sid=$(dd_tmux display -p -t "${TMUX_PANE:-}" '#{session_id}' 2>/dev/null)
|
||||
if [ -n "$sid" ]; then
|
||||
export CLAUDE_CLIENT_PRESENCE_FILE="$DEVDESK_PRESENCE_DIR/${sid#\$}"
|
||||
fi
|
||||
mode=resume
|
||||
while :; do
|
||||
NAME=$(dd_current_session) # follow renames
|
||||
|
||||
+32
-9
@@ -3,6 +3,9 @@
|
||||
# listener (hook "devdesk-deploy") when CI publishes a v* tag; the tag's ref is
|
||||
# passed as $1. Safe for running sessions: package upgrades restart only
|
||||
# devdesk.service (ttyd), never devdesk-tmux.service where Claude lives.
|
||||
#
|
||||
# The hook runs this synchronously and returns its output, with HTTP 500 when
|
||||
# it fails, so CI's "Deploy to CT 126" job shows the real result (devdesk#12).
|
||||
set -euo pipefail
|
||||
|
||||
LOG=${DEVDESK_DEPLOY_LOG:-/var/log/devdesk-deploy.log}
|
||||
@@ -12,11 +15,28 @@ log() {
|
||||
printf '%s %s\n' "$(date '+%F %T')" "$*" >>"$LOG"
|
||||
}
|
||||
|
||||
exec 9>/run/devdesk-deploy.lock
|
||||
flock -w 900 9 || {
|
||||
log "another deploy is still running; giving up"
|
||||
# The outcome goes to the log and to stdout (the webhook response).
|
||||
say() {
|
||||
log "$*"
|
||||
printf '%s\n' "$*"
|
||||
}
|
||||
fail() {
|
||||
say "deploy FAILED: $*"
|
||||
exit 1
|
||||
}
|
||||
on_error() {
|
||||
local rc=$?
|
||||
say "deploy FAILED: line $1 exited $rc (details in $LOG)"
|
||||
exit "$rc"
|
||||
}
|
||||
trap 'on_error $LINENO' ERR
|
||||
|
||||
# Wait for dpkg/apt rather than fail when unattended-upgrades or a manual apt
|
||||
# run holds the lock.
|
||||
APT_OPTS=(-o DPkg::Lock::Timeout=120 -o Dpkg::Use-Pty=0)
|
||||
|
||||
exec 9>/run/devdesk-deploy.lock
|
||||
flock -w 900 9 || fail "another deploy is still running"
|
||||
|
||||
want=${1:-}
|
||||
want=${want#refs/tags/}
|
||||
@@ -25,7 +45,7 @@ before=$(dpkg-query -W -f='${Version}' devdesk 2>/dev/null || echo none)
|
||||
log "=== deploy: installed $before, release ${want:-latest}"
|
||||
|
||||
refresh() {
|
||||
apt-get update -q -o Dir::Etc::sourcelist="$SOURCES" -o Dir::Etc::sourceparts=- \
|
||||
apt-get update -q "${APT_OPTS[@]}" -o Dir::Etc::sourcelist="$SOURCES" -o Dir::Etc::sourceparts=- \
|
||||
-o APT::Get::List-Cleanup=0 >>"$LOG" 2>&1
|
||||
}
|
||||
|
||||
@@ -41,14 +61,17 @@ for _ in $(seq 1 18); do
|
||||
done
|
||||
|
||||
if [ -n "$want" ] && [ "$candidate" != "$want" ]; then
|
||||
log "registry still offers $candidate, not $want; giving up"
|
||||
exit 1
|
||||
fail "the registry still offers ${candidate:-nothing}, not $want"
|
||||
fi
|
||||
if [ "$candidate" = "$before" ]; then
|
||||
log "already at $before; nothing to do"
|
||||
say "already at $before; nothing to do"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -q --only-upgrade \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -q --only-upgrade "${APT_OPTS[@]}" \
|
||||
-o Dpkg::Options::=--force-confold devdesk </dev/null >>"$LOG" 2>&1
|
||||
log "devdesk $before -> $(dpkg-query -W -f='${Version}' devdesk)"
|
||||
after=$(dpkg-query -W -f='${Version}' devdesk)
|
||||
if [ -n "$want" ] && [ "$after" != "$want" ]; then
|
||||
fail "installed $after, not $want"
|
||||
fi
|
||||
say "devdesk $before -> $after"
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
: "${DEVDESK_FS_LIST_MAX:=2000}" # entries per directory listing
|
||||
: "${DEVDESK_ASSETS:=$DEVDESK_SHARE/assets}"
|
||||
|
||||
# Producers piped into `head` get SIGPIPE once the cap is reached; under
|
||||
# pipefail that would fail the command and cut its reply short, so they are
|
||||
# wrapped as `{ producer || true; }`.
|
||||
|
||||
# Blob replies: a JSON header line, then base64 between markers (no body for
|
||||
# binary files the viewer can't show). The client waits for the END marker.
|
||||
DD_BLOB_BEGIN=DEVDESK-BLOB-BEGIN
|
||||
@@ -81,7 +85,7 @@ cmd_fs_list() {
|
||||
[ -d "$dir" ] || dd_die "not a folder: $rel"
|
||||
tmp=$(mktemp)
|
||||
# %y: type, %Y: type behind a symlink, %s: size, %T@: mtime, %f: name.
|
||||
find "$dir" -mindepth 1 -maxdepth 1 ! -name .git -printf '%y\t%Y\t%s\t%T@\t%f\0' 2>/dev/null |
|
||||
{ find "$dir" -mindepth 1 -maxdepth 1 ! -name .git -printf '%y\t%Y\t%s\t%T@\t%f\0' 2>/dev/null || true; } |
|
||||
head -z -n "$((DEVDESK_FS_LIST_MAX + 1))" >"$tmp"
|
||||
if git --no-optional-locks -C "$dir" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
ignored=$(tr '\0' '\n' <"$tmp" | cut -f5- | git --no-optional-locks -C "$dir" check-ignore --stdin 2>/dev/null || true)
|
||||
@@ -98,16 +102,18 @@ cmd_fs_list() {
|
||||
|
||||
# --fs-find SESSION: every file under the session folder, for "go to file".
|
||||
# git ls-files in a repository (tracked + untracked, .gitignore honoured), else
|
||||
# find without node_modules and .git; capped at DEVDESK_FS_FIND_MAX.
|
||||
# find without node_modules, .git and build/cache folders; capped at
|
||||
# DEVDESK_FS_FIND_MAX (10000).
|
||||
cmd_fs_find() {
|
||||
[ $# -eq 1 ] || dd_die "usage: devdesk attach --fs-find SESSION"
|
||||
local root max=${DEVDESK_FS_FIND_MAX:-20000}
|
||||
local root max=${DEVDESK_FS_FIND_MAX:-10000}
|
||||
root=$(dd_session_root "$1")
|
||||
if git --no-optional-locks -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
git --no-optional-locks -C "$root" ls-files -co --exclude-standard -z 2>/dev/null
|
||||
git --no-optional-locks -C "$root" ls-files -co --exclude-standard -z 2>/dev/null || true
|
||||
else
|
||||
(cd "$root" && find . -maxdepth 8 \( -name node_modules -o -name .git -o -name __pycache__ -o -name .venv \) -prune \
|
||||
-o -type f -printf '%P\0' 2>/dev/null)
|
||||
(cd "$root" && find . -maxdepth 8 \( -name node_modules -o -name .git -o -name __pycache__ -o -name .venv -o -name venv \
|
||||
-o -name dist -o -name build -o -name target -o -name .cache -o -name .next -o -name coverage \) -prune \
|
||||
-o -type f -printf '%P\0' 2>/dev/null) || true
|
||||
fi | head -z -n "$((max + 1))" |
|
||||
jq -cMRs --argjson max "$max" --arg root "$root" \
|
||||
'(split("\u0000") | map(select(length > 0))) as $f | {root: $root, truncated: ($f | length > $max), files: $f[:$max]}'
|
||||
@@ -142,9 +148,9 @@ cmd_git_status() {
|
||||
branch=$("${g[@]}" symbolic-ref --short -q HEAD || echo "(detached)")
|
||||
{
|
||||
printf 'S\n'
|
||||
"${g[@]}" status --porcelain=v1 -z --untracked-files=all -- . 2>/dev/null | head -z -n 1000 | tr '\0' '\n'
|
||||
{ "${g[@]}" status --porcelain=v1 -z --untracked-files=all -- . 2>/dev/null || true; } | head -z -n 1000 | tr '\0' '\n'
|
||||
printf 'N\n'
|
||||
"${g[@]}" diff --numstat HEAD -- . 2>/dev/null | head -n 1000
|
||||
{ "${g[@]}" diff --numstat HEAD -- . 2>/dev/null || true; } | head -n 1000
|
||||
} | jq -cMRs --arg root "$root" --arg top "$top" --arg prefix "$prefix" --arg branch "$branch" \
|
||||
--rawfile e <(cat -- "$edits" 2>/dev/null || true) '
|
||||
(split("\nN\n") | .[0] | ltrimstr("S\n") | split("\n") | map(select(length > 2))) as $st
|
||||
@@ -184,6 +190,81 @@ cmd_git_show() {
|
||||
rm -f "$tmp"
|
||||
}
|
||||
|
||||
# --fs-write SESSION REL BYTES BASE (devdesk#20): save a file from the editor.
|
||||
# The content arrives as base64 on stdin after the READY line (like uploads).
|
||||
# BASE is the sha256 the editor loaded: if the file changed since, nothing is
|
||||
# written and the reply is {conflict: true, sha: <current>}. BASE "new" creates
|
||||
# a file (and missing folders) and refuses to overwrite one. Writes go to a
|
||||
# temp file in the same folder, keep the mode and owner, and land with mv.
|
||||
cmd_fs_write() {
|
||||
[ $# -eq 4 ] || dd_die "usage: devdesk attach --fs-write SESSION PATH BYTES BASESHA|new"
|
||||
local root rel=$2 size=$3 base=$4 target dir name tmp b64len actual current sha mtime
|
||||
root=$(dd_session_root "$1")
|
||||
if ! [[ $size =~ ^[0-9]+$ ]] || [ "$size" -gt "$DEVDESK_FS_MAX" ]; then
|
||||
dd_die "too large: the editor saves files up to $((DEVDESK_FS_MAX / 1024)) KiB"
|
||||
fi
|
||||
[[ $base =~ ^([0-9a-f]{64}|new)$ ]] || dd_die "bad base: $base"
|
||||
case $rel in /* | *$'\n'* | *$'\r'* | '' | */ | . | ..) dd_die "bad path: $rel" ;; esac
|
||||
name=${rel##*/}
|
||||
if [ "$name" = . ] || [ "$name" = .. ]; then dd_die "bad path: $rel"; fi
|
||||
if [ "$base" = new ]; then
|
||||
if [ -e "$root/$rel" ] || [ -L "$root/$rel" ]; then dd_die "already exists: $rel"; fi
|
||||
case $rel in */*) dir=$root/${rel%/*} ;; *) dir=$root ;; esac
|
||||
# Missing folders are created, but never through a symlink out of the
|
||||
# root: check the deepest folder that exists before creating any.
|
||||
local existing=$dir
|
||||
while [ ! -e "$existing" ]; do existing=${existing%/*}; done
|
||||
existing=${existing#"$root"}
|
||||
dd_fs_path "$root" "${existing#/}" >/dev/null
|
||||
mkdir -p -- "$dir" || dd_die "cannot create folder for $rel"
|
||||
dir=${dir#"$root"}
|
||||
dir=$(dd_fs_path "$root" "${dir#/}")
|
||||
target="$dir/$name"
|
||||
else
|
||||
target=$(dd_fs_path "$root" "$rel")
|
||||
[ -f "$target" ] || dd_die "not a file: $rel"
|
||||
dir=${target%/*}
|
||||
fi
|
||||
tmp=$(mktemp --tmpdir="$dir" ".${name}.devdesk-XXXXXX") || dd_die "cannot write in ${dir#"$root"/}"
|
||||
trap 'rm -f "$tmp"' HUP INT TERM
|
||||
# shellcheck disable=SC2017 # integer ceil(size/3)*4: the base64 length, on purpose
|
||||
b64len=$(((size + 2) / 3 * 4))
|
||||
stty raw -echo 2>/dev/null || true
|
||||
printf 'DEVDESK-WRITE-READY\r\n'
|
||||
if [ "$b64len" -gt 0 ]; then
|
||||
head -c "$b64len" | base64 -d >"$tmp" 2>/dev/null || true
|
||||
fi
|
||||
stty sane 2>/dev/null || true
|
||||
actual=$(stat -c %s "$tmp" 2>/dev/null || echo 0)
|
||||
if [ "$actual" != "$size" ]; then
|
||||
rm -f "$tmp"
|
||||
dd_die "save incomplete ($actual of $size bytes)"
|
||||
fi
|
||||
if [ "$base" = new ]; then
|
||||
if [ -e "$target" ]; then
|
||||
rm -f "$tmp"
|
||||
dd_die "already exists: $rel"
|
||||
fi
|
||||
chmod 0644 "$tmp"
|
||||
else
|
||||
current=$(sha256sum -- "$target" | cut -d' ' -f1)
|
||||
if [ "$current" != "$base" ]; then
|
||||
rm -f "$tmp"
|
||||
trap - HUP INT TERM
|
||||
jq -cMn --arg p "$rel" --arg h "$current" '{ok: false, conflict: true, path: $p, sha: $h}'
|
||||
return
|
||||
fi
|
||||
chmod --reference="$target" "$tmp" 2>/dev/null || true
|
||||
chown --reference="$target" "$tmp" 2>/dev/null || true
|
||||
fi
|
||||
mv -f -- "$tmp" "$target" || { rm -f "$tmp"; dd_die "cannot replace $rel"; }
|
||||
trap - HUP INT TERM
|
||||
sha=$(sha256sum -- "$target" | cut -d' ' -f1)
|
||||
mtime=$(stat -c %Y -- "$target")
|
||||
jq -cMn --arg p "${target#"$root"/}" --arg h "$sha" --argjson s "$size" --argjson m "$mtime" \
|
||||
'{ok: true, path: $p, sha: $h, size: $s, mtime: $m}'
|
||||
}
|
||||
|
||||
# --asset NAME: a lazily loaded part of the web UI (the file viewer's editor),
|
||||
# shipped in $DEVDESK_ASSETS and cached by the browser.
|
||||
cmd_asset() {
|
||||
|
||||
Executable
+54
@@ -0,0 +1,54 @@
|
||||
#!/bin/bash
|
||||
# Claude Code PreToolUse hook for Bash (wired in via claude-settings.json):
|
||||
# commands that destroy things (containers, VMs, pools, disks, root-level
|
||||
# folders, cluster members…) get permissionDecision "ask", so Claude has to get
|
||||
# your OK even in auto mode (devdesk#27). It never blocks and never allows on
|
||||
# its own; anything else passes through untouched.
|
||||
#
|
||||
# DEVDESK_GUARD=0 in /etc/devdesk/env.local turns it off. Extra rules go in
|
||||
# /etc/devdesk/guard.local, one per line: an extended regex, a tab, a reason.
|
||||
|
||||
# shellcheck source=libexec/devdesk-lib.sh
|
||||
. "${DEVDESK_LIBEXEC:-/usr/lib/devdesk}/devdesk-lib.sh" 2>/dev/null || exit 0
|
||||
[ "${DEVDESK_GUARD:-1}" != 0 ] || exit 0
|
||||
|
||||
command=$(jq -rM '.tool_input.command // empty' 2>/dev/null) || exit 0
|
||||
[ -n "$command" ] || exit 0
|
||||
|
||||
# Built-in rules: extended regex <TAB> reason.
|
||||
rules=$(
|
||||
cat <<'RULES'
|
||||
\bpct[[:space:]]+destroy\b destroys a Proxmox container
|
||||
\bqm[[:space:]]+destroy\b destroys a Proxmox VM
|
||||
\bpvecm[[:space:]]+delnode\b removes a node from the Proxmox cluster
|
||||
\bpveceph[[:space:]]+(osd|pool|mon|mgr|mds|fs)[[:space:]]+destroy\b destroys Ceph components
|
||||
\bceph[[:space:]]+osd[[:space:]]+(purge|destroy|rm|out)\b removes or takes out a Ceph OSD
|
||||
\bceph[[:space:]]+osd[[:space:]]+pool[[:space:]]+(delete|rm)\b deletes a Ceph pool
|
||||
\bceph[[:space:]]+(fs[[:space:]]+rm|mon[[:space:]]+remove|auth[[:space:]]+del)\b removes Ceph components
|
||||
\brbd[[:space:]]+(rm|remove|purge)\b deletes RBD images
|
||||
\bzfs[[:space:]]+destroy\b destroys a ZFS dataset or snapshot
|
||||
\bzpool[[:space:]]+(destroy|labelclear)\b destroys a ZFS pool
|
||||
\b(lvremove|vgremove|pvremove|wipefs|shred)\b wipes volumes or disks
|
||||
\bmkfs(\.[a-z0-9]+)?\b formats a filesystem
|
||||
\bsgdisk[[:space:]]+(-[a-zA-Z]*Z|--zap) wipes a partition table
|
||||
\bdd\b[^|;&]*\bof=/dev/ writes raw to a device
|
||||
\brm[[:space:]]+(-[^[:space:]]*[[:space:]]+)*-[^[:space:]]*[rR][^[:space:]]*[[:space:]]+(-[^[:space:]]*[[:space:]]+)*['"]?/([a-z0-9_.*-]+/?)?['"]?([[:space:];&|)]|$) recursively deletes / or a top-level folder
|
||||
\bgit[[:space:]]+push\b[^|;&]*([[:space:]]-f\b|--force) force-pushes (rewrites remote history)
|
||||
\b(DROP[[:space:]]+(DATABASE|SCHEMA|TABLE)|TRUNCATE[[:space:]]+TABLE)\b drops database objects
|
||||
\bsystemctl[[:space:]]+(stop|restart|kill|disable|mask)[[:space:]]+devdesk-tmux ends every DevDesk session
|
||||
(^|[;&|][[:space:]]*|\bssh[[:space:]]+[^[:space:]]+[[:space:]]+['"]?|\bsystemctl[[:space:]]+)(reboot|poweroff|halt|shutdown)\b reboots or shuts down a machine
|
||||
\bkubectl[[:space:]]+delete\b deletes Kubernetes resources
|
||||
\bdocker[[:space:]]+(system[[:space:]]+prune|volume[[:space:]]+(rm|prune))\b deletes Docker data
|
||||
RULES
|
||||
cat "${DEVDESK_GUARD_LOCAL:-/etc/devdesk/guard.local}" 2>/dev/null
|
||||
)
|
||||
|
||||
while IFS=$'\t' read -r pattern reason; do
|
||||
if [ -z "$pattern" ] || [ "${pattern:0:1}" = "#" ]; then continue; fi
|
||||
if grep -Eiq -- "$pattern" <<<"$command" 2>/dev/null; then
|
||||
jq -cMn --arg r "DevDesk guard: this command ${reason:-matches a rule in guard.local}. Confirm before it runs." \
|
||||
'{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "ask", permissionDecisionReason: $r}}'
|
||||
exit 0
|
||||
fi
|
||||
done <<<"$rules"
|
||||
exit 0
|
||||
@@ -0,0 +1,117 @@
|
||||
# shellcheck shell=bash disable=SC2016 # single-quoted jq filters use jq variables
|
||||
# Past conversations (devdesk#24) and client presence (devdesk#26), sourced by
|
||||
# bin/devdesk and reached through `devdesk attach --search|--resume-convo|--presence`.
|
||||
|
||||
# --search QUERY: full-text search over every Claude conversation on this host
|
||||
# (DevDesk and code-server alike). Case-insensitive, plain text. Newest first;
|
||||
# per conversation: title, folder, dates and up to 3 snippets (what you asked,
|
||||
# Claude's answers, commands it ran, their output).
|
||||
cmd_search() {
|
||||
[ $# -eq 1 ] || dd_die "usage: devdesk attach --search QUERY"
|
||||
local query=$1 dir files f
|
||||
if [ ${#query} -lt 2 ] || [ ${#query} -gt 200 ] || [[ $query == *$'\n'* ]]; then dd_die "search for 2 to 200 characters"; fi
|
||||
dir=$(dd_projects_dir)
|
||||
# Files that mention it at all (grep is fast even over hundreds of MB), newest first.
|
||||
mapfile -t files < <({ LC_ALL=C grep -rlFi --include='*.jsonl' -- "$query" "$dir" 2>/dev/null || true; } |
|
||||
while IFS= read -r f; do printf '%s\t%s\n' "$(stat -c %Y "$f")" "$f"; done | sort -rn | head -n 30 | cut -f2-)
|
||||
# Six conversations at a time (each is a grep and a jq over large lines).
|
||||
local tmp i=0
|
||||
tmp=$(mktemp -d)
|
||||
for f in "${files[@]}"; do
|
||||
dd_search_one "$query" "$f" >"$tmp/$(printf '%03d' "$i")" &
|
||||
i=$((i + 1))
|
||||
if [ $((i % 6)) -eq 0 ]; then wait; fi
|
||||
done
|
||||
wait
|
||||
{ cat "$tmp"/* 2>/dev/null || true; } | jq -cMs --arg q "$query" '{query: $q, results: [.[] | select(. != null)][:25]}'
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
# One conversation's search result (or nothing), for cmd_search.
|
||||
dd_search_one() {
|
||||
local query=$1 f=$2
|
||||
{ LC_ALL=C grep -Fi -m 30 -- "$query" "$f" || true; } | jq -cMs --arg q "$query" --arg id "$(basename "$f" .jsonl)" \
|
||||
--arg mtime "$(stat -c %Y "$f")" --slurpfile head <(head -n 80 "$f" | jq -cM 'select(.type == "custom-title" or .type == "user" or .cwd)' 2>/dev/null | jq -cMs .) '
|
||||
def texts:
|
||||
if .type == "user" then
|
||||
(.message.content | if type == "string" then [{role: "you", text: .}]
|
||||
else [.[]? | if .type == "text" then {role: "you", text: .text}
|
||||
elif .type == "tool_result" then {role: "output", text: (.content | if type == "string" then . else ([.[]? | .text? // empty] | join("\n")) end)}
|
||||
else empty end] end)
|
||||
elif .type == "assistant" then
|
||||
[.message.content[]? | if .type == "text" then {role: "claude", text: .text}
|
||||
elif .type == "tool_use" then {role: "command", text: (.input.command // .input.file_path // .input.url // .input.pattern // empty)}
|
||||
else empty end]
|
||||
else [] end;
|
||||
($q | ascii_downcase) as $lq
|
||||
| [.[] | select(.isSidechain != true) | . as $e | texts[] | select(.text | type == "string")
|
||||
| (.text | ascii_downcase | index($lq)) as $i | select($i != null)
|
||||
| {role, at: $e.timestamp,
|
||||
snippet: ((if $i > 90 then "…" else "" end) + (.text[([$i - 90, 0] | max):($i + ($q | length) + 140)] | gsub("\\s+"; " "))
|
||||
+ (if (.text | length) > $i + ($q | length) + 140 then "…" else "" end))}] as $m
|
||||
| select($m | length > 0)
|
||||
| ($head[0] // []) as $h
|
||||
| {id: $id,
|
||||
title: (([$h[] | select(.type == "custom-title") | .customTitle] | last)
|
||||
// ([$h[] | select(.type == "user" and (.message.content | type == "string") and (.message.content | startswith("<") | not)) | .message.content] | first | .[0:120])
|
||||
// "untitled"),
|
||||
prompt: ([$h[] | select(.type == "user" and (.message.content | type == "string") and (.message.content | startswith("<") | not)) | .message.content] | first | .[0:160]),
|
||||
cwd: ([$h[] | .cwd // empty] | first),
|
||||
started: ([$h[] | .timestamp // empty] | first),
|
||||
updated: ($mtime | tonumber),
|
||||
hits: ($m | length), matches: ($m[:3])}' 2>/dev/null
|
||||
}
|
||||
|
||||
# --resume-convo NAME ID [fork]: open a past conversation in a new session NAME,
|
||||
# in the folder it ran in. "fork" continues it as a new conversation and leaves
|
||||
# the original untouched (claude --fork-session).
|
||||
cmd_resume_convo() {
|
||||
if [ $# -lt 2 ] || [ $# -gt 3 ]; then dd_die "usage: devdesk attach --resume-convo NAME ID [fork]"; fi
|
||||
local name=$1 id=$2 fork=${3:-} file dir
|
||||
dd_valid_name "$name" || dd_die "invalid session name: $name"
|
||||
if [ -n "$fork" ] && [ "$fork" != fork ]; then dd_die "the third argument can only be: fork"; fi
|
||||
file=$(dd_convo_file "$id") || dd_die "no conversation $id"
|
||||
[ -n "$file" ] || dd_die "no conversation $id"
|
||||
if dd_server_up && dd_tmux has-session -t "=$name" 2>/dev/null; then dd_die "a session called $name is already running"; fi
|
||||
# Two Claudes on one transcript would interleave it: resuming one that is
|
||||
# open elsewhere is refused (forking is fine).
|
||||
if [ -z "$fork" ]; then
|
||||
local other
|
||||
for other in $(jq -rM --arg id "$id" '.sessions | to_entries[] | select(.value.claude_session_id == $id) | .key' "$DEVDESK_REGISTRY" 2>/dev/null); do
|
||||
if [ "$other" != "$name" ] && dd_tmux has-session -t "=$other" 2>/dev/null; then
|
||||
dd_die "that conversation is open in session $other: open it there, or fork it"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
dir=$(jq -rM 'select(.cwd) | .cwd' "$file" 2>/dev/null | head -n1)
|
||||
[ -n "$dir" ] && [ -d "$dir" ] || dir=$(dd_resolve_dir "$name")
|
||||
dd_registry_update '.sessions[$n] = ((.sessions[$n] // {}) + {dir: $d, claude_session_id: $id, claude_source: "devdesk-history"}
|
||||
+ (if $fork == "fork" then {fork: true} else {} end))' \
|
||||
--arg n "$name" --arg d "$dir" --arg id "$id" --arg fork "$fork"
|
||||
dd_ensure_server
|
||||
create_detached "$name" "$dir"
|
||||
}
|
||||
|
||||
# --presence SESSION on|off (devdesk#26): while a DevDesk tab shows a session,
|
||||
# its Claude sees a client-presence marker (CLAUDE_CLIENT_PRESENCE_FILE, set by
|
||||
# devdesk-claude-run per tmux session) and Remote Control holds back phone
|
||||
# pushes. The browser refreshes it every ~45 s; it disappears ~2 minutes after
|
||||
# the last refresh, so pushes resume once you walk away.
|
||||
cmd_presence() {
|
||||
[ $# -eq 2 ] || dd_die "usage: devdesk attach --presence SESSION on|off"
|
||||
local session=$1 state=$2 sid marker
|
||||
dd_valid_name "$session" || dd_die "invalid session name: $session"
|
||||
dd_server_up || return 0
|
||||
sid=$(dd_tmux display -p -t "=$session:" '#{session_id}' 2>/dev/null) || return 0
|
||||
marker="$DEVDESK_PRESENCE_DIR/${sid#\$}"
|
||||
if [ "$state" = off ]; then
|
||||
rm -f "$marker"
|
||||
return 0
|
||||
fi
|
||||
[ "$state" = on ] || dd_die "presence is on or off"
|
||||
mkdir -p "$DEVDESK_PRESENCE_DIR" && touch "$marker"
|
||||
# Expire it unless refreshed meanwhile.
|
||||
# (fd 3 closed too: a reaper must not hold a caller's extra descriptors open)
|
||||
setsid -f bash -c 'sleep 120; [ -n "$(find "$1" -newermt "-110 seconds" 2>/dev/null)" ] || rm -f "$1"' _ "$marker" \
|
||||
</dev/null >/dev/null 2>&1 3>&- || true
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
# shellcheck shell=bash disable=SC2016 # single-quoted jq filters use jq variables
|
||||
# Answer a session without switching to it (devdesk#22, #23), sourced by
|
||||
# bin/devdesk and reached through `devdesk attach --answer|--peek|--reply`.
|
||||
|
||||
dd_state_file() {
|
||||
printf '%s/%s.json\n' "$DEVDESK_STATUS_DIR" "$1"
|
||||
}
|
||||
|
||||
# The Claude window's visible screen (not the scrollback).
|
||||
dd_claude_screen() {
|
||||
dd_tmux capture-pane -p -J -t "=$1:claude" 2>/dev/null
|
||||
}
|
||||
|
||||
# --answer SESSION SINCE allow|deny: press the permission prompt's key in that
|
||||
# session's Claude window. Only when the same wait is still on (SINCE) and the
|
||||
# prompt is actually on screen, so a stale button never types into Claude.
|
||||
cmd_answer() {
|
||||
[ $# -eq 3 ] || dd_die "usage: devdesk attach --answer SESSION SINCE allow|deny"
|
||||
local session=$1 since=$2 choice=$3 file
|
||||
dd_valid_name "$session" || dd_die "invalid session name: $session"
|
||||
[[ $since =~ ^[0-9]+$ ]] || dd_die "bad wait id: $since"
|
||||
case $choice in allow | deny) ;; *) dd_die "answer allow or deny" ;; esac
|
||||
if ! { dd_server_up && dd_tmux has-session -t "=$session" 2>/dev/null; }; then dd_die "session '$session' isn't running"; fi
|
||||
file=$(dd_state_file "$session")
|
||||
if [ "$(jq -rM '"\(.state) \(.since) \(.request != null)"' "$file" 2>/dev/null)" != "waiting $since true" ]; then
|
||||
dd_die "nothing to answer: it was already answered"
|
||||
fi
|
||||
# Every permission prompt lists "1. Yes" first (Bash, edits, fetches, MCP).
|
||||
if ! dd_claude_screen "$session" | tail -n 40 | grep -Eq '^[[:space:]]*(❯[[:space:]]*)?1\.[[:space:]]+Yes'; then
|
||||
dd_die "the permission prompt isn't on screen any more"
|
||||
fi
|
||||
if [ "$choice" = allow ]; then
|
||||
dd_tmux send-keys -t "=$session:claude" 1
|
||||
else
|
||||
dd_tmux send-keys -t "=$session:claude" Escape
|
||||
fi
|
||||
# A denial doesn't fire a hook; the turn ends there. An approval is followed
|
||||
# by PostToolUse, which takes it from here.
|
||||
local tmp
|
||||
tmp=$(mktemp "$DEVDESK_STATUS_DIR/.$session.XXXXXX") || return 0
|
||||
if jq -cMn --arg s "$([ "$choice" = allow ] && echo working || echo idle)" --arg m "$([ "$choice" = allow ] && echo "Allowed from DevDesk" || echo "Denied from DevDesk")" \
|
||||
'{state: $s, since: (now | floor), event: "DevDeskAnswer", message: $m}' >"$tmp"; then
|
||||
mv -f "$tmp" "$file"
|
||||
else
|
||||
rm -f "$tmp"
|
||||
fi
|
||||
}
|
||||
|
||||
# The session's conversation file, from the id the SessionStart hook recorded.
|
||||
dd_transcript() {
|
||||
local id
|
||||
id=$(dd_registry_get "$1" claude_session_id)
|
||||
dd_convo_file "$id"
|
||||
}
|
||||
|
||||
# --peek SESSION: what the session is doing and the last exchange, from the end
|
||||
# of its transcript (the last assistant text and the last thing you asked).
|
||||
cmd_peek() {
|
||||
[ $# -eq 1 ] || dd_die "usage: devdesk attach --peek SESSION"
|
||||
local session=$1 transcript status commands
|
||||
dd_valid_name "$session" || dd_die "invalid session name: $session"
|
||||
status=$(jq -cM . "$(dd_state_file "$session")" 2>/dev/null) || status=null
|
||||
# The last commands this session ran (devdesk#27).
|
||||
commands=$(tail -n 8 "$DEVDESK_STATE_DIR/commands/$session.jsonl" 2>/dev/null | jq -cMs '.' 2>/dev/null) || commands='[]'
|
||||
[ -n "$commands" ] || commands='[]'
|
||||
transcript=$(dd_transcript "$session") || transcript=""
|
||||
if [ -z "$transcript" ] || [ ! -r "$transcript" ]; then
|
||||
jq -cMn --arg s "$session" --argjson st "${status:-null}" --argjson c "$commands" '{session: $s, status: $st, assistant: null, user: null, commands: $c}'
|
||||
return
|
||||
fi
|
||||
tail -n 400 -- "$transcript" | jq -cMs --arg s "$session" --argjson st "${status:-null}" --argjson c "$commands" '
|
||||
def text: if type == "string" then . else ([.[]? | select(.type == "text") | .text] | join("\n")) end;
|
||||
[.[] | select(.isSidechain != true and .isMeta != true)] as $all
|
||||
| ([$all[] | select(.type == "assistant") | {text: (.message.content | text), at: .timestamp} | select(.text != "")] | last) as $a
|
||||
| ([$all[] | select(.type == "user" and (.message.content | type == "string" or (any(.[]?; .type == "text"))))
|
||||
| {text: (.message.content | text), at: .timestamp}
|
||||
| select(.text != "" and (.text | startswith("<") | not))] | last) as $u
|
||||
| {session: $s, status: $st,
|
||||
assistant: (if $a then {text: ($a.text | .[-4000:]), at: $a.at, truncated: ($a.text | length > 4000)} else null end),
|
||||
user: (if $u then {text: ($u.text | .[-600:]), at: $u.at} else null end), commands: $c}' 2>/dev/null ||
|
||||
jq -cMn --arg s "$session" --argjson st "${status:-null}" --argjson c "$commands" '{session: $s, status: $st, assistant: null, user: null, commands: $c}'
|
||||
}
|
||||
|
||||
# --reply SESSION BYTES: type a message into the session's Claude prompt and
|
||||
# send it. The text arrives as base64 after the READY line (like uploads) and is
|
||||
# pasted as one bracketed paste, so newlines in it don't send it early.
|
||||
cmd_reply() {
|
||||
[ $# -eq 2 ] || dd_die "usage: devdesk attach --reply SESSION BYTES"
|
||||
local session=$1 size=$2 file tmp b64len
|
||||
dd_valid_name "$session" || dd_die "invalid session name: $session"
|
||||
if ! [[ $size =~ ^[0-9]+$ ]] || [ "$size" -lt 1 ] || [ "$size" -gt 16384 ]; then dd_die "a reply is 1 to 16384 bytes"; fi
|
||||
if ! { dd_server_up && dd_tmux has-session -t "=$session" 2>/dev/null; }; then dd_die "session '$session' isn't running"; fi
|
||||
file=$(dd_state_file "$session")
|
||||
if [ "$(jq -rM '"\(.state) \(.request != null)"' "$file" 2>/dev/null)" = "waiting true" ]; then
|
||||
dd_die "Claude is asking for a permission: answer that first"
|
||||
fi
|
||||
tmp=$(mktemp)
|
||||
trap 'rm -f "$tmp"' HUP INT TERM
|
||||
# shellcheck disable=SC2017 # integer ceil(size/3)*4: the base64 length, on purpose
|
||||
b64len=$(((size + 2) / 3 * 4))
|
||||
stty raw -echo 2>/dev/null || true
|
||||
printf 'DEVDESK-REPLY-READY\r\n'
|
||||
head -c "$b64len" | base64 -d >"$tmp" 2>/dev/null || true
|
||||
stty sane 2>/dev/null || true
|
||||
if [ "$(stat -c %s "$tmp")" != "$size" ]; then
|
||||
rm -f "$tmp"
|
||||
dd_die "reply incomplete"
|
||||
fi
|
||||
dd_tmux load-buffer -b devdesk-reply "$tmp" && dd_tmux paste-buffer -p -d -b devdesk-reply -t "=$session:claude" &&
|
||||
sleep 0.2 && dd_tmux send-keys -t "=$session:claude" Enter
|
||||
rm -f "$tmp"
|
||||
trap - HUP INT TERM
|
||||
}
|
||||
+86
-24
@@ -8,13 +8,34 @@ DEVDESK_ENV=${DEVDESK_ENV:-/etc/devdesk/env}
|
||||
# Local overrides go in env.local: it is never shipped, so upgrades don't prompt about it.
|
||||
DEVDESK_ENV_LOCAL=${DEVDESK_ENV_LOCAL:-${DEVDESK_ENV}.local}
|
||||
|
||||
# The env files are read by systemd (EnvironmentFile=) as well, so they are
|
||||
# parsed here the way systemd parses them, never sourced: KEY=value lines, the
|
||||
# value taken literally (no $ expansion, no command substitution), optionally
|
||||
# in matching quotes. Anything else is reported and skipped (devdesk#12).
|
||||
dd_load_env() {
|
||||
local f
|
||||
for f in "$DEVDESK_ENV" "$DEVDESK_ENV_LOCAL"; do
|
||||
if [ -r "$f" ]; then
|
||||
# shellcheck source=/dev/null
|
||||
. "$f"
|
||||
fi
|
||||
local _dd_f _dd_line _dd_n _dd_key _dd_val
|
||||
for _dd_f in "$DEVDESK_ENV" "$DEVDESK_ENV_LOCAL"; do
|
||||
[ -r "$_dd_f" ] || continue
|
||||
_dd_n=0
|
||||
while IFS= read -r _dd_line || [ -n "$_dd_line" ]; do
|
||||
_dd_n=$((_dd_n + 1))
|
||||
_dd_line=${_dd_line%$'\r'}
|
||||
[[ $_dd_line =~ ^[[:space:]]*([#\;].*)?$ ]] && continue
|
||||
if ! [[ $_dd_line =~ ^[[:space:]]*([A-Z_][A-Z0-9_]*)=(.*)$ ]]; then
|
||||
printf 'devdesk: %s:%s: not a KEY=value line, ignored\n' "$_dd_f" "$_dd_n" >&2
|
||||
continue
|
||||
fi
|
||||
_dd_key=${BASH_REMATCH[1]}
|
||||
_dd_val=${BASH_REMATCH[2]}
|
||||
_dd_val=${_dd_val%"${_dd_val##*[![:space:]]}"} # trailing blanks, like systemd
|
||||
if [[ $_dd_val =~ ^\"(.*)\"$ || $_dd_val =~ ^\'(.*)\'$ ]]; then
|
||||
_dd_val=${BASH_REMATCH[1]}
|
||||
elif [[ $_dd_val == [\"\']* ]]; then
|
||||
printf 'devdesk: %s:%s: unmatched quote, ignored\n' "$_dd_f" "$_dd_n" >&2
|
||||
continue
|
||||
fi
|
||||
printf -v "$_dd_key" '%s' "$_dd_val"
|
||||
done <"$_dd_f"
|
||||
done
|
||||
}
|
||||
dd_load_env
|
||||
@@ -33,10 +54,12 @@ dd_load_env
|
||||
: "${DEVDESK_GRAFANA_URL:=}"
|
||||
: "${DEVDESK_GRAFANA_PUBLIC_URL:=$DEVDESK_GRAFANA_URL}"
|
||||
: "${DEVDESK_GRAFANA_TOKEN_FILE:=/etc/devdesk/grafana-token}"
|
||||
: "${DEVDESK_PVE_NODES:=}"
|
||||
: "${DEVDESK_UPLOAD_MAX:=26214400}"
|
||||
: "${DEVDESK_PUBLIC_URL:=}"
|
||||
: "${DEVDESK_MATRIX_WEBHOOK_FILE:=/etc/devdesk/matrix-webhook}"
|
||||
: "${DEVDESK_MATRIX_DELAY:=30}"
|
||||
: "${DEVDESK_PRESENCE_DIR:=/run/devdesk/presence}"
|
||||
|
||||
DEVDESK_REGISTRY="$DEVDESK_STATE_DIR/registry.json"
|
||||
DEVDESK_CONTEXT_DIR="$DEVDESK_STATE_DIR/context"
|
||||
@@ -100,26 +123,59 @@ dd_registry_get() {
|
||||
jq -Mr --arg n "$1" --arg f "$2" '.sessions[$n][$f] // empty' "$DEVDESK_REGISTRY" 2>/dev/null
|
||||
}
|
||||
|
||||
# dd_registry_update JQ_FILTER [jq args...] — read-modify-write under flock.
|
||||
dd_registry_update() {
|
||||
local filter=$1
|
||||
shift
|
||||
# dd_registry_locked CMD [ARGS...] — run CMD holding the registry lock, so a
|
||||
# step that reads tmux and then writes the registry (the SessionStart hook,
|
||||
# rename) can't interleave with another. Nests: an update inside reuses it.
|
||||
dd_registry_locked() {
|
||||
if [ -n "${DD_REGISTRY_LOCKED:-}" ]; then
|
||||
"$@"
|
||||
return
|
||||
fi
|
||||
mkdir -p "$DEVDESK_STATE_DIR"
|
||||
(
|
||||
flock -w 5 9 || exit 1
|
||||
[ -s "$DEVDESK_REGISTRY" ] || printf '{"sessions":{}}\n' >"$DEVDESK_REGISTRY"
|
||||
local tmp
|
||||
tmp=$(mktemp "$DEVDESK_REGISTRY.XXXXXX") || exit 1
|
||||
if jq "$@" "$filter" "$DEVDESK_REGISTRY" >"$tmp"; then
|
||||
chmod 600 "$tmp"
|
||||
mv -f "$tmp" "$DEVDESK_REGISTRY"
|
||||
else
|
||||
rm -f "$tmp"
|
||||
exit 1
|
||||
fi
|
||||
DD_REGISTRY_LOCKED=1
|
||||
"$@"
|
||||
) 9>"$DEVDESK_REGISTRY.lock"
|
||||
}
|
||||
|
||||
# dd_registry_update JQ_FILTER [jq args...] — read-modify-write under flock.
|
||||
dd_registry_update() {
|
||||
dd_registry_locked _dd_registry_apply "$@"
|
||||
}
|
||||
|
||||
_dd_registry_apply() {
|
||||
local filter=$1 tmp
|
||||
shift
|
||||
[ -s "$DEVDESK_REGISTRY" ] || printf '{"sessions":{}}\n' >"$DEVDESK_REGISTRY"
|
||||
tmp=$(mktemp "$DEVDESK_REGISTRY.XXXXXX") || return 1
|
||||
if jq "$@" "$filter" "$DEVDESK_REGISTRY" >"$tmp"; then
|
||||
chmod 600 "$tmp"
|
||||
mv -f "$tmp" "$DEVDESK_REGISTRY"
|
||||
else
|
||||
rm -f "$tmp"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Claude's conversation files: ~/.claude/projects/<folder>/<id>.jsonl.
|
||||
dd_projects_dir() {
|
||||
printf '%s/projects\n' "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
|
||||
}
|
||||
|
||||
dd_convo_file() {
|
||||
[[ $1 =~ ^[0-9a-f-]{36}$ ]] || return 1
|
||||
compgen -G "$(dd_projects_dir)/*/$1.jsonl" | head -n1
|
||||
}
|
||||
|
||||
# Temp files of writers that were killed mid-write (hooks run under Claude's
|
||||
# timeouts): .<session>.XXXXXX and registry.json.XXXXXX, older than 10 minutes.
|
||||
dd_sweep_tmp() {
|
||||
find "$DEVDESK_CONTEXT_DIR" "$DEVDESK_STATUS_DIR" -maxdepth 1 -type f -name '.*.??????' -mmin +10 -delete 2>/dev/null
|
||||
find "$DEVDESK_STATE_DIR" -maxdepth 1 -type f -name 'registry.json.??????' -mmin +10 -delete 2>/dev/null
|
||||
return 0
|
||||
}
|
||||
|
||||
dd_registry_set_dir() {
|
||||
dd_registry_update '.sessions[$n] = ((.sessions[$n] // {}) + {dir: $d, updated: $t})' \
|
||||
--arg n "$1" --arg d "$2" --arg t "$(date -Is)"
|
||||
@@ -132,7 +188,8 @@ dd_registry_set_claude() {
|
||||
|
||||
dd_registry_remove() {
|
||||
dd_registry_update 'del(.sessions[$n])' --arg n "$1"
|
||||
rm -f "$DEVDESK_CONTEXT_DIR/$1.json" "$DEVDESK_STATUS_DIR/$1.json" "$DEVDESK_STATE_DIR/edits/$1.txt"
|
||||
rm -f "$DEVDESK_CONTEXT_DIR/$1.json" "$DEVDESK_STATUS_DIR/$1.json" "$DEVDESK_STATE_DIR/edits/$1.txt" \
|
||||
"$DEVDESK_STATE_DIR/commands/$1.jsonl" "$DEVDESK_STATE_DIR/tags/$1.json" "$DEVDESK_STATE_DIR/prompts/$1.txt"
|
||||
}
|
||||
|
||||
dd_registry_rename() {
|
||||
@@ -144,9 +201,14 @@ dd_registry_rename() {
|
||||
mv -f "$d/$1.json" "$d/$2.json"
|
||||
fi
|
||||
done
|
||||
if [ -f "$DEVDESK_STATE_DIR/edits/$1.txt" ]; then
|
||||
mv -f "$DEVDESK_STATE_DIR/edits/$1.txt" "$DEVDESK_STATE_DIR/edits/$2.txt"
|
||||
fi
|
||||
local f
|
||||
for f in "edits/%s.txt" "commands/%s.jsonl" "tags/%s.json" "prompts/%s.txt"; do
|
||||
# shellcheck disable=SC2059 # the pattern is ours
|
||||
if [ -f "$DEVDESK_STATE_DIR/$(printf "$f" "$1")" ]; then
|
||||
# shellcheck disable=SC2059
|
||||
mv -f "$DEVDESK_STATE_DIR/$(printf "$f" "$1")" "$DEVDESK_STATE_DIR/$(printf "$f" "$2")"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Project name (directory or its slug) -> absolute directory inside the projects root.
|
||||
|
||||
@@ -27,8 +27,12 @@ attached=$(dd_tmux list-sessions -F '#{session_name} #{session_attached}' 2>/dev
|
||||
[ "${attached:-0}" = 0 ] || exit 0
|
||||
|
||||
message=$(jq -rM '.message // "Claude is waiting for your input"' "$state_file" 2>/dev/null)
|
||||
detail=$(jq -rM '.request.detail // empty' "$state_file" 2>/dev/null)
|
||||
[ -z "$detail" ] || message="$message: ${detail:0:300}"
|
||||
url=""
|
||||
[ -z "$DEVDESK_PUBLIC_URL" ] || url="${DEVDESK_PUBLIC_URL%/}/?arg=$session"
|
||||
# existing=1: if the session was ended by the time you tap, say so instead of
|
||||
# starting a new Claude there (devdesk#38).
|
||||
[ -z "$DEVDESK_PUBLIC_URL" ] || url="${DEVDESK_PUBLIC_URL%/}/?arg=$session&existing=1"
|
||||
body=$(jq -cMn --arg s "$session" --arg m "$message" --arg u "$url" --arg h "$(hostname)" \
|
||||
'{session: $s, message: $m, url: (if $u == "" then null else $u end), host: $h,
|
||||
text: ("Claude needs you in " + $s + ": " + $m + (if $u == "" then "" else " — " + $u end))}')
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
# shellcheck shell=bash disable=SC2016 # single-quoted jq filters use jq variables
|
||||
# Ops (devdesk#39): Grafana alerts, the Proxmox guests they are about, and
|
||||
# "Ask Claude" investigations in a session of their own. Sourced by bin/devdesk.
|
||||
|
||||
DEVDESK_GUESTS="$DEVDESK_STATE_DIR/guests.json"
|
||||
|
||||
# ---------------------------------------------------------------- Proxmox guests
|
||||
# Which CT/VM has which IP, and on which node it runs right now: guests are HA
|
||||
# and move between nodes, so this is read live from the cluster, over SSH to the
|
||||
# nodes in DEVDESK_PVE_NODES (empty = off). Cached in guests.json, where a
|
||||
# stopped guest keeps the IPs it had when it was last seen running.
|
||||
|
||||
# Cluster view, from any one node: guests (id, name, node, status, HA) and nodes.
|
||||
DD_PVE_INVENTORY='pvesh get /cluster/resources --type vm --output-format json && echo && pvesh get /cluster/status --output-format json'
|
||||
# Per node: its own addresses, then those of its running guests ("<id>\t<IPs>").
|
||||
IFS= read -r -d '' DD_PVE_NODE_SCAN <<'EOF' || true
|
||||
printf '%s\t%s\n' "$(hostname)" "$(hostname -I)"
|
||||
for id in $(lxc-ls --running 2>/dev/null); do
|
||||
printf '%s\t%s\n' "$id" "$(lxc-info -n "$id" -iH 2>/dev/null | tr '\n' ' ')"
|
||||
done
|
||||
# VMs only through the QEMU guest agent, where one is configured; slow, so all at once.
|
||||
for f in /var/run/qemu-server/*.pid; do
|
||||
id=${f##*/}
|
||||
id=${id%.pid}
|
||||
case $id in '' | *[!0-9]*) continue ;; esac
|
||||
grep -qE '^agent: *(1|enabled=1)' "/etc/pve/qemu-server/$id.conf" 2>/dev/null || continue
|
||||
printf '%s\t%s\n' "$id" "$(timeout 3 qm guest cmd "$id" network-get-interfaces 2>/dev/null |
|
||||
grep -oE '"ip-address" *: *"[0-9.]+"' | grep -oE '[0-9.]+' | tr '\n' ' ')" &
|
||||
done
|
||||
wait
|
||||
EOF
|
||||
|
||||
dd_pve_ssh() {
|
||||
local host=$1
|
||||
shift
|
||||
timeout 12 "${DEVDESK_PVE_SSH:-ssh}" -o BatchMode=yes -o ConnectTimeout=4 "$host" "$@"
|
||||
}
|
||||
|
||||
# Refresh guests.json. Returns non-zero if no node answered (the cache stays).
|
||||
dd_pve_scan() {
|
||||
[ -n "${DEVDESK_PVE_NODES:-}" ] || return 1
|
||||
local host inv="" tmp node ip pids=() rc=0
|
||||
for host in $DEVDESK_PVE_NODES; do
|
||||
inv=$(dd_pve_ssh "$host" "$DD_PVE_INVENTORY" 2>/dev/null) && jq -es 'length == 2' >/dev/null 2>&1 <<<"$inv" && break
|
||||
inv=""
|
||||
done
|
||||
[ -n "$inv" ] || return 1
|
||||
tmp=$(mktemp -d) || return 1
|
||||
# Every online node at once: by name, or by its cluster address if the name doesn't answer.
|
||||
while IFS=$'\t' read -r node ip; do
|
||||
{ dd_pve_ssh "$node" "$DD_PVE_NODE_SCAN" || dd_pve_ssh "$ip" "$DD_PVE_NODE_SCAN"; } >"$tmp/$node" 2>/dev/null </dev/null &
|
||||
pids+=($!)
|
||||
done < <(jq -rs '.[1][] | select(.type == "node" and .online == 1) | [.name, .ip] | @tsv' <<<"$inv")
|
||||
[ ${#pids[@]} -eq 0 ] || wait "${pids[@]}" 2>/dev/null || true
|
||||
mkdir -p "$DEVDESK_STATE_DIR"
|
||||
# Scan lines: the first is "<node>\t<its IPs>", then "<CT id>\t<its IPs>".
|
||||
if { cat "$tmp"/* 2>/dev/null || true; } | jq -cMRs --slurpfile inv <(jq -s . <<<"$inv") \
|
||||
--slurpfile old <(cat "$DEVDESK_GUESTS" 2>/dev/null || echo '{}') --arg src "$host" '
|
||||
def v4: [splits("[[:space:]]+") | select(test("^[0-9]{1,3}(\\.[0-9]{1,3}){3}$") and (startswith("127.") | not))];
|
||||
(split("\n") | map(select(length > 0) | split("\t"))) as $rows
|
||||
| ([$rows[] | select(.[0] | test("^[0-9]+$")) | {key: .[0], value: (.[1] // "" | v4)}] | from_entries) as $live
|
||||
| ([$rows[] | select(.[0] | test("^[0-9]+$") | not) | {key: .[0], value: (.[1] // "" | v4)}] | from_entries) as $nodeips
|
||||
| ([$old[0].guests[]? | {key: (.id | tostring), value: .ips}] | from_entries) as $prev
|
||||
| {updated: (now | floor), source: $src,
|
||||
nodes: [$inv[0][1][] | select(.type == "node")
|
||||
| {name, online: (.online == 1), ips: (([.ip] + ($nodeips[.name] // [])) | map(select(. != null)) | unique)}],
|
||||
guests: [$inv[0][0][] | select(.vmid != null) | (.vmid | tostring) as $id
|
||||
| ($live[$id] // []) as $now
|
||||
| {id: .vmid, type, name, node, status, ha: (.hastate // null),
|
||||
ips: (if ($now | length) > 0 then $now else ($prev[$id] // []) end),
|
||||
ips_live: (($now | length) > 0)}]
|
||||
| sort_by(.id)}' >"$tmp/out" && [ -s "$tmp/out" ]; then
|
||||
chmod 644 "$tmp/out"
|
||||
mv -f "$tmp/out" "$DEVDESK_GUESTS"
|
||||
else
|
||||
rc=1
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
return $rc
|
||||
}
|
||||
|
||||
# Refresh, one scan at a time: "wait" for a running one (then scan again), else
|
||||
# skip when one is already running.
|
||||
dd_pve_refresh() {
|
||||
mkdir -p "$DEVDESK_STATE_DIR"
|
||||
if [ "${1:-}" = wait ]; then
|
||||
(flock -w 30 9 || exit 1; dd_pve_scan) 9>"$DEVDESK_GUESTS.lock"
|
||||
else
|
||||
(flock -n 9 || exit 0; dd_pve_scan) 9>"$DEVDESK_GUESTS.lock"
|
||||
fi
|
||||
}
|
||||
|
||||
# Seconds since guests.json was written (large when there is none).
|
||||
dd_guests_age() {
|
||||
local m
|
||||
m=$(stat -c %Y "$DEVDESK_GUESTS" 2>/dev/null) || { echo 999999; return; }
|
||||
echo $(($(date +%s) - m))
|
||||
}
|
||||
|
||||
# jq: locate the guest or node a host/label is about, given the guests.json
|
||||
# document as $g. A target: {kind: "ct"|"vm"|"node", id, name, node, status, ha,
|
||||
# ip, by: "ip"|"host"|"name"}.
|
||||
DD_LOCATE_JQ='
|
||||
def kindof: if .type == "qemu" then "vm" else "ct" end;
|
||||
def as_guest: {kind: kindof, id, name, node, status, ha};
|
||||
def as_node: {kind: "node", name, node: .name, status: (if .online then "online" else "offline" end)};
|
||||
def isv4: test("^[0-9]{1,3}(\\.[0-9]{1,3}){3}$");
|
||||
# "http://10.0.0.1:8080/x", "10.0.0.1:9100", "host.example.org:9100" -> the host
|
||||
def hostpart: sub("^[A-Za-z][A-Za-z0-9+.-]*://"; "") | sub("/.*$"; "") | sub("^[^@]*@"; "") | sub(":[0-9]+$"; "") | ascii_downcase;
|
||||
def norm: ascii_downcase | gsub("[^a-z0-9]+"; "-");
|
||||
def by_host($g; $h):
|
||||
if ($h | isv4) then
|
||||
([$g.nodes[]? | select(.ips | index([$h])) | as_node + {ip: $h, by: "ip"}]
|
||||
+ [$g.guests[]? | select(.ips | index([$h])) | as_guest + {ip: $h, by: "ip", ip_seen: (.ips_live | not)}]) | first
|
||||
else
|
||||
($h | split(".")[0]) as $s
|
||||
| ([$g.nodes[]? | select((.name | ascii_downcase) == $s) | as_node + {by: "host"}]
|
||||
+ [$g.guests[]? | select((.name | ascii_downcase) == $s) | as_guest + {by: "host"}]) | first
|
||||
end;
|
||||
# A guest or node whose name appears as whole words in $v ("draupnir-node",
|
||||
# "compute-storage-01-ceph", "Draupnir Down"); the longest name wins.
|
||||
def by_name($g; $v):
|
||||
("-" + ($v | norm) + "-") as $t
|
||||
| [($g.nodes[]? | as_node), ($g.guests[]? | as_guest)]
|
||||
| map(select((.name // "" | norm) as $n | ($n | length) >= 4 and ($t | contains("-" + $n + "-"))))
|
||||
| sort_by(-(.name | length)) | first | if . then . + {by: "name"} else empty end;
|
||||
# Targets of one alert (an element of the alerts list below): by each label
|
||||
# set: its instance (IP or host name), else its job; with no labels at all, by the
|
||||
# name of the alert itself ("Draupnir Down").
|
||||
def targets($g):
|
||||
if ($g | type) != "object" then [] else
|
||||
.name as $alert
|
||||
| [.labelsets[] | (.instance // "" | hostpart) as $h
|
||||
| if $h != "" then (by_host($g; $h) // by_name($g; .job // "") // {kind: "unknown", ip: $h})
|
||||
elif .job then by_name($g; .job)
|
||||
else empty end]
|
||||
| if length == 0 then [by_name($g; $alert)] else . end
|
||||
| map(select(. != null)) | unique_by([.kind, .id, .name, .ip]) | .[:6]
|
||||
end;
|
||||
'
|
||||
|
||||
# ---------------------------------------------------------------- alerts
|
||||
|
||||
# Firing and pending Grafana alert rules, most severe first, each with the
|
||||
# guests/nodes it is about (from the guest cache, refreshed in the background).
|
||||
cmd_alerts() {
|
||||
if [ -z "$DEVDESK_GRAFANA_URL" ]; then
|
||||
jq -cMn '{configured: false, alerts: []}'
|
||||
return
|
||||
fi
|
||||
local raw
|
||||
if ! raw=$({
|
||||
if [ -r "$DEVDESK_GRAFANA_TOKEN_FILE" ]; then
|
||||
# shellcheck disable=SC1003 # tr deletes whitespace, quotes and backslashes from the token
|
||||
printf 'header = "Authorization: Bearer %s"\n' "$(tr -d '[:space:]"\\' <"$DEVDESK_GRAFANA_TOKEN_FILE")"
|
||||
fi
|
||||
} | curl -fsS --max-time 6 -K - "$DEVDESK_GRAFANA_URL/api/prometheus/grafana/api/v1/rules" 2>&1); then
|
||||
jq -cMn --arg e "${raw:-no response}" '{configured: true, error: $e, alerts: []}'
|
||||
return
|
||||
fi
|
||||
if [ -n "${DEVDESK_PVE_NODES:-}" ] && [ "$(dd_guests_age)" -gt 300 ]; then
|
||||
setsid -f "$0" guests --refresh </dev/null >/dev/null 2>&1 3>&- || true
|
||||
fi
|
||||
jq -cM --arg pub "$DEVDESK_GRAFANA_PUBLIC_URL" --slurpfile g <(cat "$DEVDESK_GUESTS" 2>/dev/null || echo null) "$DD_LOCATE_JQ"'
|
||||
def num: (tonumber? // .) | tostring;
|
||||
($g[0]) as $guests
|
||||
| {configured: true, checked: (now | floor), pve: ($guests != null), alerts: [
|
||||
.data.groups[] | .name as $group | .file as $folder | .rules[]
|
||||
| select(.state == "firing" or .state == "pending")
|
||||
| ([.alerts[]? | select(.state == "Alerting" or .state == "Pending")]) as $active
|
||||
| {uid, name, state, severity: (.labels.severity // null), group: $group, folder: $folder,
|
||||
query: (.query // null),
|
||||
since: (.activeAt // $active[0].activeAt // null),
|
||||
summary: ((.annotations.summary // .annotations.description // "")
|
||||
| gsub("\\{\\{ *\\$value *\\}\\}"; ($active[0].value // "?" | num))),
|
||||
description: (if .annotations.summary then (.annotations.description // null) else null end),
|
||||
labelsets: [$active[] | .labels
|
||||
| del(.__alert_rule_uid__, .__grafana_origin__, .alertname, .grafana_folder, .__name__, .severity)
|
||||
| select(length > 0)],
|
||||
url: "\($pub)/alerting/grafana/\(.uid)/view"}
|
||||
| .instances = [.labelsets[] | to_entries | map("\(.key)=\(.value)") | join(" ")]
|
||||
| .targets = targets($guests)
|
||||
] | sort_by(if .severity == "critical" then 0 elif .severity == "warning" then 1 else 2 end)}' <<<"$raw"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- guests command
|
||||
|
||||
# devdesk guests [--json] [--cached] [FILTER...]: Proxmox guests with their node,
|
||||
# state and IPs, fresh from the cluster (the cache if no node answers).
|
||||
# FILTER matches an id, an IP, or part of a name or node.
|
||||
cmd_guests() {
|
||||
local json="" cached="" filters=()
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--json) json=1 ;;
|
||||
--cached) cached=1 ;;
|
||||
--refresh)
|
||||
dd_pve_refresh
|
||||
return 0
|
||||
;;
|
||||
-*) dd_die "usage: devdesk guests [--json] [--cached] [ID|IP|NAME...]" ;;
|
||||
*) filters+=("$1") ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[ -n "${DEVDESK_PVE_NODES:-}" ] || dd_die "no Proxmox nodes configured (DEVDESK_PVE_NODES in /etc/devdesk/env.local)"
|
||||
if [ -z "$cached" ] && ! dd_pve_refresh wait; then
|
||||
[ -s "$DEVDESK_GUESTS" ] || dd_die "no Proxmox node answered ($DEVDESK_PVE_NODES)"
|
||||
printf 'devdesk: no Proxmox node answered; showing what was known %s minutes ago\n' "$(($(dd_guests_age) / 60))" >&2
|
||||
fi
|
||||
[ -s "$DEVDESK_GUESTS" ] || dd_die "nothing known yet: run devdesk guests without --cached"
|
||||
local select='[.guests[] | . as $x | select(($f | length) == 0 or any($f[]; . as $q
|
||||
| ($x.id | tostring) == $q or ($x.ips | index([$q])) or ($x.name | ascii_downcase | contains($q | ascii_downcase))
|
||||
or ($x.node | ascii_downcase | contains($q | ascii_downcase))))]'
|
||||
local f
|
||||
f=$(printf '%s\n' "${filters[@]}" | jq -R . | jq -cs 'map(select(length > 0))')
|
||||
if [ -n "$json" ]; then
|
||||
jq -cM --argjson f "$f" "{updated, nodes, guests: $select}" "$DEVDESK_GUESTS"
|
||||
return
|
||||
fi
|
||||
jq -rM --argjson f "$f" "$select"' as $g
|
||||
| if ($g | length) == 0 then "no matching guests" else
|
||||
(["ID", "TYPE", "NAME", "NODE", "STATUS", "HA", "IP"] | @tsv),
|
||||
($g[] | [(.id | tostring), (if .type == "qemu" then "vm" else "ct" end), .name, .node, .status, (.ha // "-"),
|
||||
((.ips | join(",")) + (if (.ips | length) > 0 and (.ips_live | not) then " (last seen)" else "" end) | if . == "" then "-" else . end)] | @tsv)
|
||||
end' "$DEVDESK_GUESTS" | column -t -s $'\t'
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- investigate
|
||||
|
||||
# The opening prompt for an investigation of alert $a (one element of the
|
||||
# alerts output), with $since already readable.
|
||||
DD_PROMPT_JQ='
|
||||
def ref: if .kind == "ct" then "CT \(.id) \"\(.name)\"" elif .kind == "vm" then "VM \(.id) \"\(.name)\"" else "Proxmox node \(.name)" end;
|
||||
def state: [(if .status then .status else empty end), (if .ha then "HA state \(.ha)" else empty end)] | join(", ");
|
||||
def how:
|
||||
if .kind == "ct" then "commands inside it: `ssh \(.node) pct exec \(.id) -- <command>`"
|
||||
elif .kind == "vm" then "commands inside it (needs the guest agent): `ssh \(.node) qm guest exec \(.id) -- <command>`"
|
||||
else "reach it with `ssh \(.name)`" end;
|
||||
def where:
|
||||
if .kind == "unknown" then "- \(.ip) is not a Proxmox guest or node that DevDesk knows (`devdesk guests` lists them all)."
|
||||
elif .kind == "node" then "- \(if .ip then "\(.ip) is " else "" end)\(ref)\(if .by == "name" then " (probably: matched by name)" else "" end), \(.status); \(how)"
|
||||
else "- \(if .by == "name" then "Probably " else "" end)\(if .ip then "\(.ip) is " else "" end)\(ref) on node \(.node)"
|
||||
+ "\(if .by == "name" then " (matched by name, not by IP)" elif .ip_seen then " (its IP when last seen running)" else "" end), \(state); \(how)"
|
||||
end;
|
||||
$a
|
||||
| ([.targets[] | select(.kind == "ct" or .kind == "vm")] | first) as $guest
|
||||
| [
|
||||
"Investigate this Grafana alert and find the cause. Look first and change nothing yet: tell me what you found and what you would change, then wait for my go-ahead.",
|
||||
"",
|
||||
"Alert: \(.name) (\(.severity // "no severity"), \(.state) since \($since))",
|
||||
"Rule: \(.folder) / \(.group), uid \(.uid). Look at it with the grafana MCP server: \(.url)",
|
||||
(if .query then "Query: `\(.query)`" else empty end),
|
||||
(if .summary != "" then "Summary: \(.summary)" else empty end),
|
||||
(if .description then "Details: \(.description)" else empty end),
|
||||
(if (.instances | length) > 0 then "Firing for: \(.instances | join("; "))"
|
||||
else "Firing for: no labels. The rule aggregates, so it does not say what it is about: run the inner query to find the series"
|
||||
+ (if $pve then ", then `devdesk guests <IP>` shows which Proxmox guest each one is and where it runs." else "." end) end),
|
||||
(if $pve and (.targets | length) > 0 then
|
||||
("", "Where it runs (Proxmox, looked up just now):"),
|
||||
(.targets[] | where),
|
||||
(if $guest then "Guests are HA and can migrate between nodes, so check again before acting: `devdesk guests \($guest.id)` shows where it is now." else empty end)
|
||||
else empty end)
|
||||
] | join("\n")'
|
||||
|
||||
# --investigate SESSION RULE_UID: start Claude in a new session SESSION with an
|
||||
# investigation of that alert as its first prompt. An existing session is left as
|
||||
# it is: {"ok":true,"session":…,"started":false}.
|
||||
cmd_investigate() {
|
||||
[ $# -eq 2 ] || dd_die "usage: devdesk attach --investigate SESSION ALERT_RULE_UID"
|
||||
local name=$1 uid=$2 alerts alert since prompt dir pve=false
|
||||
dd_valid_name "$name" || dd_die "invalid session name: $name"
|
||||
[[ $uid =~ ^[A-Za-z0-9_-]{1,64}$ ]] || dd_die "invalid alert rule id: $uid"
|
||||
if dd_server_up && dd_tmux has-session -t "=$name" 2>/dev/null; then
|
||||
jq -cMn --arg s "$name" '{ok: true, session: $s, started: false}'
|
||||
return
|
||||
fi
|
||||
[ -n "$DEVDESK_GRAFANA_URL" ] || dd_die "Grafana is not configured"
|
||||
# Where the guests are right now (HA moves them); the cache if no node answers.
|
||||
[ -z "${DEVDESK_PVE_NODES:-}" ] || dd_pve_refresh wait || true
|
||||
alerts=$(cmd_alerts)
|
||||
alert=$(jq -cM --arg uid "$uid" '.alerts[] | select(.uid == $uid)' <<<"$alerts" | head -n1)
|
||||
if [ -z "$alert" ]; then
|
||||
dd_die "$(jq -rM 'if .error then "Grafana unreachable: \(.error)" else "that alert is no longer firing" end' <<<"$alerts")"
|
||||
fi
|
||||
since=$(jq -rM '.since // empty' <<<"$alert")
|
||||
since=$(date -d "$since" '+%a %-d %b %H:%M %Z' 2>/dev/null || echo "${since:-an unknown time}")
|
||||
[ -s "$DEVDESK_GUESTS" ] && [ -n "${DEVDESK_PVE_NODES:-}" ] && pve=true
|
||||
prompt=$(jq -rnM --argjson a "$alert" --arg since "$since" --argjson pve "$pve" "$DD_PROMPT_JQ") || dd_die "could not write the prompt"
|
||||
# devdesk-claude-run sends this once, as the new conversation's first prompt.
|
||||
mkdir -p "$DEVDESK_STATE_DIR/prompts"
|
||||
(umask 077 && printf '%s\n' "$prompt" >"$DEVDESK_STATE_DIR/prompts/$name.txt")
|
||||
# A new conversation, even if an earlier investigation used this name (that
|
||||
# one stays in Search past conversations).
|
||||
dd_registry_update 'if .sessions[$n] then .sessions[$n] |= del(.claude_session_id, .claude_source, .fork) else . end' --arg n "$name"
|
||||
dir=$(dd_resolve_dir "$name")
|
||||
dd_ensure_server
|
||||
create_detached "$name" "$dir"
|
||||
jq -cMn --arg s "$name" '{ok: true, session: $s, started: true}'
|
||||
}
|
||||
@@ -7,14 +7,20 @@
|
||||
# shellcheck source=libexec/devdesk-lib.sh
|
||||
. "${DEVDESK_LIBEXEC:-/usr/lib/devdesk}/devdesk-lib.sh" || exit 0
|
||||
|
||||
session=$(dd_current_session)
|
||||
[ -n "$session" ] || exit 0
|
||||
dd_valid_name "$session" || exit 0
|
||||
|
||||
input=$(cat)
|
||||
id=$(jq -r '.session_id // empty' <<<"$input" 2>/dev/null)
|
||||
source=$(jq -r '.source // empty' <<<"$input" 2>/dev/null)
|
||||
[ -n "$id" ] || exit 0
|
||||
|
||||
dd_registry_set_claude "$session" "$id" "$source" 2>/dev/null
|
||||
# The session's name is read under the registry lock: a rename holds it too,
|
||||
# so the id can't land under the old name after the entry moved.
|
||||
# shellcheck disable=SC2317 # called through dd_registry_locked
|
||||
record() {
|
||||
local session
|
||||
session=$(dd_current_session)
|
||||
if [ -z "$session" ] || ! dd_valid_name "$session"; then return 0; fi
|
||||
dd_registry_set_claude "$session" "$id" "$source"
|
||||
}
|
||||
dd_registry_locked record 2>/dev/null
|
||||
dd_sweep_tmp
|
||||
exit 0
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
# Claude Code hook (wired in via claude-settings.json) that tracks what Claude is
|
||||
# doing in each DevDesk session, for the sidebar's at-a-glance status:
|
||||
# UserPromptSubmit, PostToolUse -> working
|
||||
# PermissionRequest -> waiting, with what Claude wants to run
|
||||
# (tool + command/file/URL), for the inbox's
|
||||
# Allow/Deny (devdesk#22)
|
||||
# Notification -> waiting (Claude needs input or a permission)
|
||||
# Stop, SessionStart -> idle
|
||||
# SessionEnd -> exited
|
||||
@@ -33,9 +36,39 @@ PostToolUse:Edit | PostToolUse:Write | PostToolUse:MultiEdit | PostToolUse:Noteb
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
# Ops trail (devdesk#27): every Bash command, and the hosts a session works on
|
||||
# (ssh targets, Proxmox CT/VM ids) as tags for the session list.
|
||||
if [ "$event:$tool" = PostToolUse:Bash ]; then
|
||||
cmd=$(jq -rM '.tool_input.command // empty' <<<"$input" 2>/dev/null)
|
||||
if [ -n "$cmd" ]; then
|
||||
base="${DEVDESK_STATE_DIR:-/var/lib/devdesk}"
|
||||
mkdir -p "$base/commands" "$base/tags" 2>/dev/null
|
||||
log="$base/commands/$session.jsonl"
|
||||
jq -cMn --arg c "${cmd:0:500}" '{at: (now | floor), cmd: $c}' >>"$log" 2>/dev/null
|
||||
if [ "$(wc -l <"$log" 2>/dev/null || echo 0)" -gt 600 ]; then
|
||||
tail -n 500 "$log" >"$log.tmp" 2>/dev/null && mv -f "$log.tmp" "$log"
|
||||
fi
|
||||
hosts=$(
|
||||
# ssh [options] [user@]host: the first word that isn't an option (or an option's value)
|
||||
awk '{ for (i = 1; i <= NF; i++) if ($i == "ssh") { j = i + 1
|
||||
while (j <= NF && $j ~ /^-/) { if ($j ~ /^-[bcDEeFIiJLlmOopQRSWw]$/) j++; j++ }
|
||||
if (j <= NF) { h = $j; sub(/^[^@]*@/, "", h); gsub(/[^A-Za-z0-9_.-].*$/, "", h); if (h != "") print h } } }' <<<"$cmd"
|
||||
grep -oE '\bpct[[:space:]]+(exec|enter|push|pull|config|set|start|stop|shutdown|reboot|status|snapshot|rollback|migrate)[[:space:]]+[0-9]{3,}' <<<"$cmd" | grep -oE '[0-9]+$' | sed 's/^/CT /'
|
||||
grep -oE '\bqm[[:space:]]+(guest[[:space:]]+exec|terminal|config|set|start|stop|shutdown|reboot|status|snapshot|rollback|migrate)[[:space:]]+[0-9]{3,}' <<<"$cmd" | grep -oE '[0-9]+$' | sed 's/^/VM /'
|
||||
)
|
||||
if [ -n "$hosts" ]; then
|
||||
tags="$base/tags/$session.json"
|
||||
jq -cMn --rawfile new <(printf '%s\n' "$hosts") --slurpfile old <(cat "$tags" 2>/dev/null || echo '{}') '
|
||||
($new | split("\n") | map(select(length > 0))) as $n
|
||||
| {hosts: ($n + ($old[0].hosts // []) | reduce .[] as $h ([]; if index([$h]) then . else . + [$h] end) | .[:4]),
|
||||
at: (now | floor)}' >"$tags.tmp" 2>/dev/null && mv -f "$tags.tmp" "$tags"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
case $event in
|
||||
UserPromptSubmit | PostToolUse) state=working ;;
|
||||
Notification) state=waiting ;;
|
||||
Notification | PermissionRequest) state=waiting ;;
|
||||
Stop | SessionStart) state=idle ;;
|
||||
SessionEnd) state=exited ;;
|
||||
*) exit 0 ;;
|
||||
@@ -47,19 +80,33 @@ file="$dir/$session.json"
|
||||
if [ "$state" != waiting ] && [ -f "$file" ] && grep -q "\"state\":\"$state\"" "$file"; then
|
||||
exit 0
|
||||
fi
|
||||
# What a permission prompt is about. tool_use_id is null in PermissionRequest,
|
||||
# so a wait is identified by its `since` instead.
|
||||
request=null
|
||||
if [ "$event" = PermissionRequest ]; then
|
||||
request=$(jq -cM '(.tool_input // {}) as $i | {tool: (.tool_name // "a tool"),
|
||||
detail: (($i.command // $i.file_path // $i.notebook_path // $i.url // $i.pattern // $i.query // $i.path // ($i | tostring)) | tostring | .[0:600]),
|
||||
description: ($i.description // null)}' <<<"$input" 2>/dev/null) || request=null
|
||||
message="Claude wants to use ${tool:-a tool}"
|
||||
fi
|
||||
# A second Notification during the same wait updates the message but keeps
|
||||
# `since`, so the wait stays one wait (one Matrix message at most).
|
||||
# `since` (and what the wait is about), so the wait stays one wait (one Matrix
|
||||
# message at most).
|
||||
since=$(date +%s)
|
||||
was_waiting=0
|
||||
if [ "$state" = waiting ] && grep -q '"state":"waiting"' "$file" 2>/dev/null; then
|
||||
was_waiting=1
|
||||
since=$(jq -rM '.since // empty' "$file" 2>/dev/null) || since=$(date +%s)
|
||||
[[ $since =~ ^[0-9]+$ ]] || since=$(date +%s)
|
||||
if [ "$request" = null ]; then
|
||||
request=$(jq -cM '.request // null' "$file" 2>/dev/null) || request=null
|
||||
[ "$request" = null ] || message=$(jq -rM '.message // empty' "$file" 2>/dev/null)
|
||||
fi
|
||||
fi
|
||||
mkdir -p "$dir" 2>/dev/null || exit 0
|
||||
tmp=$(mktemp "$dir/.$session.XXXXXX" 2>/dev/null) || exit 0
|
||||
if jq -cMn --arg s "$state" --arg m "$message" --arg e "$event" --argjson t "$since" \
|
||||
'{state: $s, since: $t, event: $e, message: (if $m == "" then null else $m end)}' >"$tmp"; then
|
||||
if jq -cMn --arg s "$state" --arg m "$message" --arg e "$event" --argjson t "$since" --argjson r "${request:-null}" \
|
||||
'{state: $s, since: $t, event: $e, message: (if $m == "" then null else $m end)} + (if $r then {request: $r} else {} end)' >"$tmp"; then
|
||||
mv -f "$tmp" "$file"
|
||||
else
|
||||
rm -f "$tmp"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/bash
|
||||
# Claude Code statusLine command (wired in via claude-settings.json). Claude pipes
|
||||
# its status JSON in on every update; we keep a snapshot per DevDesk session for
|
||||
# the web UI's Claude Context panel and print a one-line status for Claude's footer.
|
||||
# the web UI (context, plan usage, PR) and print a one-line status for Claude's footer.
|
||||
# Runs often while Claude streams, so it stays cheap and never fails loudly.
|
||||
|
||||
input=$(cat)
|
||||
@@ -29,7 +29,12 @@ if [[ $session =~ ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$ ]]; then
|
||||
+ (.cache_read_input_tokens // 0)) else null end),
|
||||
cost_usd: .cost.total_cost_usd,
|
||||
lines_added: .cost.total_lines_added,
|
||||
lines_removed: .cost.total_lines_removed
|
||||
lines_removed: .cost.total_lines_removed,
|
||||
# devdesk#25: plan usage (account-wide) and the pull request of the branch
|
||||
rate_limits: (.rate_limits // null | if . then {
|
||||
five_hour: (.five_hour | if . then {pct: .used_percentage, resets_at} else null end),
|
||||
seven_day: (.seven_day | if . then {pct: .used_percentage, resets_at} else null end)} else null end),
|
||||
pr: (.pr // null | if . then {number, url, review_state, kind} else null end)
|
||||
}' <<<"$input" >"$tmp" 2>/dev/null; then
|
||||
mv -f "$tmp" "$dir/$session.json"
|
||||
else
|
||||
@@ -38,13 +43,21 @@ if [[ $session =~ ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$ ]]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# Footer line: session · model · context % · cost. ANSI colour numbers, not RGB,
|
||||
# so the browser's dark or light palette applies (devdesk#31).
|
||||
# Footer line: session · model · context % and tokens · plan use. ANSI colour numbers, not
|
||||
# RGB, so the browser's dark or light palette applies (devdesk#31). Claude sends
|
||||
# rate_limits only to Pro/Max subscribers; there .cost is an API-price estimate,
|
||||
# not a bill, so show the 5-hour plan use instead and keep $ for API-key billing.
|
||||
jq -rM --arg s "$session" '
|
||||
def c($sgr; $t): "\u001b[\($sgr)m\($t)\u001b[0m";
|
||||
def pct: if . == null then "—" else "\(. | floor)%" end;
|
||||
def tok: if . >= 1000000 then "\(. / 100000 | round / 10)M" elif . >= 1000 then "\(. / 1000 | round)k" else "\(.)" end;
|
||||
def ctxtok: .context_window | (.current_usage | if . then (.input_tokens // 0) + (.cache_creation_input_tokens // 0)
|
||||
+ (.cache_read_input_tokens // 0) else null end) as $u
|
||||
| if $u == null then "" else " \($u | tok)\(if .context_window_size then "/\(.context_window_size | tok)" else "" end)" end;
|
||||
[ (if $s != "" then c("33"; "◈ \($s)") else empty end),
|
||||
c("36"; .model.display_name // "Claude"),
|
||||
c("37"; "ctx \(.context_window.used_percentage | pct)"),
|
||||
c("37"; "$\((.cost.total_cost_usd // 0) * 100 | round / 100)")
|
||||
c("37"; "ctx \(.context_window.used_percentage | pct)\(ctxtok)"),
|
||||
(if .rate_limits.five_hour.used_percentage != null
|
||||
then c("37"; "5h \(.rate_limits.five_hour.used_percentage | pct)")
|
||||
else c("37"; "$\((.cost.total_cost_usd // 0) * 100 | round / 100)") end)
|
||||
] | join(c("90"; " · "))' <<<"$input" 2>/dev/null || true
|
||||
|
||||
@@ -73,6 +73,29 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PermissionRequest": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "/usr/lib/devdesk/devdesk-state-hook",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "/usr/lib/devdesk/devdesk-guard",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"statusLine": {
|
||||
|
||||
+459
-5
@@ -5,6 +5,7 @@ REPO=$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)
|
||||
|
||||
setup() {
|
||||
TMP=$(mktemp -d /tmp/devdesk-test.XXXXXX) # short path: unix socket limit
|
||||
unset DEVDESK_REMOTE_CONTROL CLAUDE_ARGS DEVDESK_SESSION TMUX TMUX_PANE # when run from inside DevDesk
|
||||
export DEVDESK_ENV=/dev/null
|
||||
export DEVDESK_PROJECTS_ROOT="$TMP/projects"
|
||||
export DEVDESK_STATE_DIR="$TMP/state"
|
||||
@@ -15,12 +16,14 @@ setup() {
|
||||
export DEVDESK_MATRIX_WEBHOOK_FILE="$TMP/no-webhook" # never the real room
|
||||
export FAKE_LOG="$TMP/claude-args"
|
||||
export CLAUDE_BIN="$TMP/fake-claude"
|
||||
export CLAUDE_CONFIG_DIR="$TMP/claude" # never the real conversation history
|
||||
export PATH="$REPO/bin:$PATH"
|
||||
mkdir -p "$DEVDESK_PROJECTS_ROOT/alpha" "$DEVDESK_PROJECTS_ROOT/test code" "$TMP/outside" "$FAKE_LOG"
|
||||
ln -s "$TMP/outside" "$DEVDESK_PROJECTS_ROOT/escape"
|
||||
cat >"$CLAUDE_BIN" <<'EOF'
|
||||
#!/bin/bash
|
||||
printf '%s\n' "$*" >>"$FAKE_LOG/$DEVDESK_SESSION"
|
||||
[ -z "${FAKE_EXIT:-}" ] || exit "$FAKE_EXIT"
|
||||
exec sleep 300
|
||||
EOF
|
||||
chmod +x "$CLAUDE_BIN"
|
||||
@@ -192,12 +195,23 @@ claude_args() {
|
||||
"cost":{"total_cost_usd":1.5,"total_lines_added":10,"total_lines_removed":2}}'
|
||||
run bash -c "echo '$status_json' | TMUX='$DEVDESK_SOCKET,1,0' TMUX_PANE='$pane' '$REPO/libexec/devdesk-statusline'"
|
||||
[ "$status" -eq 0 ]
|
||||
[[ $output == *"alpha"* && $output == *"ctx 34%"* ]]
|
||||
[[ $output == *"alpha"* && $output == *"ctx 34% 346k/1M"* ]]
|
||||
run devdesk attach --list
|
||||
[ "$(jq -r '.sessions[] | select(.name=="alpha") | .context.used_tokens' <<<"$output")" = 346000 ]
|
||||
[ "$(jq -r '.sessions[] | select(.name=="alpha") | .context.model' <<<"$output")" = Opus ]
|
||||
}
|
||||
|
||||
@test "statusline footer shows plan use on a subscription and dollars only on API billing" {
|
||||
sub='{"model":{"display_name":"Opus"},"context_window":{"used_percentage":10},
|
||||
"cost":{"total_cost_usd":1186.99},"rate_limits":{"five_hour":{"used_percentage":8.4}}}'
|
||||
run bash -c "echo '$sub' | '$REPO/libexec/devdesk-statusline'"
|
||||
[[ $output == *"5h 8%"* ]]
|
||||
[[ $output != *'$'* ]]
|
||||
api='{"model":{"display_name":"Opus"},"context_window":{"used_percentage":10},"cost":{"total_cost_usd":1.5}}'
|
||||
run bash -c "echo '$api' | '$REPO/libexec/devdesk-statusline'"
|
||||
[[ $output == *'$1.5'* ]]
|
||||
}
|
||||
|
||||
@test "hooks ignore Claude running in some other tmux server" {
|
||||
start_server
|
||||
other="$TMP/other.sock"
|
||||
@@ -310,7 +324,7 @@ posts() { [ -f "$TMP/posts" ] && wc -l <"$TMP/posts" || echo 0; }
|
||||
sleep 2.5
|
||||
[ "$(posts)" -eq 1 ]
|
||||
run jq -r '[.session, .url, (.text | test("Claude needs you in alpha"))] | @tsv' "$TMP/posts"
|
||||
[ "$output" = "$(printf 'alpha\thttps://dev.example.org/?arg=alpha\ttrue')" ]
|
||||
[ "$output" = "$(printf 'alpha\thttps://dev.example.org/?arg=alpha&existing=1\ttrue')" ]
|
||||
|
||||
# answered within the delay: nothing is posted
|
||||
echo '{"hook_event_name":"PostToolUse"}' | hook
|
||||
@@ -440,12 +454,91 @@ posts() { [ -f "$TMP/posts" ] && wc -l <"$TMP/posts" || echo 0; }
|
||||
|
||||
@test "session hook records the Claude session and the next start resumes it" {
|
||||
start_server
|
||||
echo '{"session_id":"abc-123","source":"startup"}' | DEVDESK_SESSION=alpha "$REPO/libexec/devdesk-session-hook"
|
||||
id=abcabcab-1234-1234-1234-123412341234
|
||||
mkdir -p "$CLAUDE_CONFIG_DIR/projects/-p" && touch "$CLAUDE_CONFIG_DIR/projects/-p/$id.jsonl"
|
||||
echo "{\"session_id\":\"$id\",\"source\":\"startup\"}" | DEVDESK_SESSION=alpha "$REPO/libexec/devdesk-session-hook"
|
||||
run jq -r '.sessions.alpha.claude_session_id' "$DEVDESK_STATE_DIR/registry.json"
|
||||
[ "$output" = "abc-123" ]
|
||||
[ "$output" = "$id" ]
|
||||
devdesk new alpha
|
||||
run claude_args alpha
|
||||
[ "$output" = "--resume abc-123 --settings $REPO/share/claude-settings.json" ]
|
||||
[ "$output" = "--resume $id --settings $REPO/share/claude-settings.json" ]
|
||||
}
|
||||
|
||||
@test "a conversation whose file is gone starts fresh; a failed resume keeps the id (#12)" {
|
||||
start_server
|
||||
id=abcabcab-1234-1234-1234-123412341234
|
||||
echo "{\"session_id\":\"$id\"}" | DEVDESK_SESSION=alpha "$REPO/libexec/devdesk-session-hook"
|
||||
devdesk new alpha
|
||||
run claude_args alpha
|
||||
[ "$output" = "-n alpha --settings $REPO/share/claude-settings.json" ]
|
||||
tmux -S "$DEVDESK_SOCKET" kill-server
|
||||
# The file exists, but Claude exits at once (Ctrl+C, network): the menu, not a new conversation.
|
||||
mkdir -p "$CLAUDE_CONFIG_DIR/projects/-p" && touch "$CLAUDE_CONFIG_DIR/projects/-p/$id.jsonl"
|
||||
rm -f "$FAKE_LOG/alpha"
|
||||
FAKE_EXIT=1 start_server
|
||||
devdesk new alpha
|
||||
run claude_args alpha
|
||||
[ "$output" = "--resume $id --settings $REPO/share/claude-settings.json" ]
|
||||
for _ in $(seq 1 30); do
|
||||
tmux -S "$DEVDESK_SOCKET" capture-pane -p -t =alpha:claude | grep -q "Claude exited" && break
|
||||
sleep 0.1
|
||||
done
|
||||
tmux -S "$DEVDESK_SOCKET" capture-pane -p -t =alpha:claude | grep -q "Claude exited"
|
||||
[ "$(wc -l <"$FAKE_LOG/alpha")" = 1 ]
|
||||
[ "$(jq -r '.sessions.alpha.claude_session_id' "$DEVDESK_STATE_DIR/registry.json")" = "$id" ]
|
||||
}
|
||||
|
||||
@test "env files are parsed like systemd does, never run (#12)" {
|
||||
cat >"$TMP/env" <<'ENV'
|
||||
# comment
|
||||
; also a comment
|
||||
DEVDESK_DEFAULT_DIR=/srv/ops
|
||||
CLAUDE_ARGS=--model opus --verbose
|
||||
DEVDESK_PUBLIC_URL="https://dev.example.org"
|
||||
DEVDESK_GRAFANA_URL='http://g:3000'
|
||||
DEVDESK_MATRIX_DELAY=$(touch /tmp/devdesk-env-pwned)
|
||||
lowercase=x
|
||||
not a line
|
||||
DEVDESK_BIND="unterminated
|
||||
ENV
|
||||
run env DEVDESK_ENV="$TMP/env" DEVDESK_ENV_LOCAL=/dev/null bash -c '. "$1/libexec/devdesk-lib.sh"; printf "%s|" "$DEVDESK_DEFAULT_DIR" "$CLAUDE_ARGS" "$DEVDESK_PUBLIC_URL" "$DEVDESK_GRAFANA_URL" "$DEVDESK_MATRIX_DELAY" "${lowercase:-unset}" "${DEVDESK_BIND:-unset}"' _ "$REPO"
|
||||
[ ! -e /tmp/devdesk-env-pwned ]
|
||||
[[ $output == *'/srv/ops|--model opus --verbose|https://dev.example.org|http://g:3000|$(touch /tmp/devdesk-env-pwned)|unset|unset|'* ]]
|
||||
[[ $output == *"env:8: not a KEY=value line"* ]]
|
||||
[[ $output == *"env:10: unmatched quote"* ]]
|
||||
}
|
||||
|
||||
@test "the SessionStart hook reads the session name under the rename lock (#12)" {
|
||||
start_server
|
||||
devdesk new alpha
|
||||
claude_args alpha >/dev/null
|
||||
pane=$(tmux -S "$DEVDESK_SOCKET" display -p -t =alpha:claude '#{pane_id}')
|
||||
# A rename holds the lock; the hook fires meanwhile, while tmux still says "alpha".
|
||||
(
|
||||
flock 9
|
||||
sleep 0.5
|
||||
tmux -S "$DEVDESK_SOCKET" rename-session -t =alpha beta
|
||||
DEVDESK_ENV=/dev/null bash -c '. "$1/libexec/devdesk-lib.sh"; DD_REGISTRY_LOCKED=1 dd_registry_rename alpha beta' _ "$REPO"
|
||||
) 9>"$DEVDESK_STATE_DIR/registry.json.lock" 3>&- &
|
||||
renamer=$!
|
||||
sleep 0.1
|
||||
echo '{"session_id":"ffffffff-0000-0000-0000-000000000000","source":"clear"}' |
|
||||
TMUX="$DEVDESK_SOCKET,1,0" TMUX_PANE=$pane "$REPO/libexec/devdesk-session-hook"
|
||||
wait "$renamer"
|
||||
[ "$(jq -r '.sessions | keys | join(",")' "$DEVDESK_STATE_DIR/registry.json")" = beta ]
|
||||
[ "$(jq -r '.sessions.beta.claude_session_id' "$DEVDESK_STATE_DIR/registry.json")" = ffffffff-0000-0000-0000-000000000000 ]
|
||||
}
|
||||
|
||||
@test "leftover temp files of killed writers are swept (#12)" {
|
||||
mkdir -p "$DEVDESK_STATE_DIR/state" "$DEVDESK_STATE_DIR/context"
|
||||
touch -d '20 minutes ago' "$DEVDESK_STATE_DIR/state/.alpha.Ab12Cd" "$DEVDESK_STATE_DIR/context/.alpha.Xy34Zw" "$DEVDESK_STATE_DIR/registry.json.Qq11Rr"
|
||||
touch "$DEVDESK_STATE_DIR/state/.beta.Ab12Cd" "$DEVDESK_STATE_DIR/state/alpha.json"
|
||||
echo '{"session_id":"x"}' | DEVDESK_SESSION=alpha "$REPO/libexec/devdesk-session-hook"
|
||||
[ ! -e "$DEVDESK_STATE_DIR/state/.alpha.Ab12Cd" ]
|
||||
[ ! -e "$DEVDESK_STATE_DIR/context/.alpha.Xy34Zw" ]
|
||||
[ ! -e "$DEVDESK_STATE_DIR/registry.json.Qq11Rr" ]
|
||||
[ -e "$DEVDESK_STATE_DIR/state/.beta.Ab12Cd" ]
|
||||
[ -e "$DEVDESK_STATE_DIR/state/alpha.json" ]
|
||||
}
|
||||
|
||||
@test "session hook ignores sessions it does not own" {
|
||||
@@ -611,6 +704,367 @@ blob_body() {
|
||||
rm -rf "$p/.git"
|
||||
run devdesk attach --fs-find alpha
|
||||
[ "$(jq -r '.files | sort | join(",")' <<<"$output")" = ".gitignore,debug.log,src/a.js" ]
|
||||
# Hitting the cap must not fail the command (SIGPIPE in the producer).
|
||||
for i in $(seq 1 3000); do : >"$p/src/f$i.txt"; done
|
||||
run env DEVDESK_FS_FIND_MAX=1 "$REPO/bin/devdesk" attach --fs-find alpha
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(jq -r '[(.files | length), .truncated] | @tsv' <<<"$output")" = "$(printf '1\ttrue')" ]
|
||||
run env DEVDESK_FS_LIST_MAX=5 "$REPO/bin/devdesk" attach --fs-list alpha src
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(jq -r '[(.entries | length), .truncated] | @tsv' <<<"$output")" = "$(printf '5\ttrue')" ]
|
||||
}
|
||||
|
||||
# Save through --fs-write the way the browser does: content as base64 on stdin.
|
||||
fs_write() { # SESSION PATH BASE CONTENT-FILE
|
||||
local size
|
||||
size=$(stat -c %s "$4")
|
||||
base64 -w0 "$4" | devdesk attach --fs-write "$1" "$2" "$size" "$3"
|
||||
}
|
||||
|
||||
@test "fs-write saves atomically, keeps the mode, and refuses stale bases (#20)" {
|
||||
p="$DEVDESK_PROJECTS_ROOT/alpha"
|
||||
printf 'v1\n' >"$p/conf.sh"
|
||||
chmod 0750 "$p/conf.sh"
|
||||
base=$(sha256sum "$p/conf.sh" | cut -d' ' -f1)
|
||||
printf 'v2\n' >"$TMP/new"
|
||||
run fs_write alpha conf.sh "$base" "$TMP/new"
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(tail -n1 <<<"$output" | jq -r '.ok')" = true ]
|
||||
[ "$(cat "$p/conf.sh")" = v2 ]
|
||||
[ "$(stat -c %a "$p/conf.sh")" = 750 ]
|
||||
[ "$(tail -n1 <<<"$output" | jq -r '.sha')" = "$(sha256sum "$p/conf.sh" | cut -d' ' -f1)" ]
|
||||
# Someone (Claude) changed it since: the old base no longer matches.
|
||||
printf 'v3 from me\n' >"$TMP/mine"
|
||||
run fs_write alpha conf.sh "$base" "$TMP/mine"
|
||||
[ "$(tail -n1 <<<"$output" | jq -r '[.ok, .conflict] | @tsv')" = "$(printf 'false\ttrue')" ]
|
||||
[ "$(cat "$p/conf.sh")" = v2 ]
|
||||
# No temp files left behind
|
||||
[ -z "$(find "$p" -name '*.devdesk-*')" ]
|
||||
# Empty files are fine
|
||||
: >"$TMP/empty"
|
||||
base=$(sha256sum "$p/conf.sh" | cut -d' ' -f1)
|
||||
run fs_write alpha conf.sh "$base" "$TMP/empty"
|
||||
[ "$(tail -n1 <<<"$output" | jq -r '.ok')" = true ]
|
||||
[ ! -s "$p/conf.sh" ]
|
||||
}
|
||||
|
||||
@test "fs-write creates new files (and folders) but never overwrites or escapes (#20)" {
|
||||
p="$DEVDESK_PROJECTS_ROOT/alpha"
|
||||
printf 'hello\n' >"$TMP/c"
|
||||
run fs_write alpha docs/notes/new.md new "$TMP/c"
|
||||
[ "$(tail -n1 <<<"$output" | jq -r '[.ok, .path] | @tsv')" = "$(printf 'true\tdocs/notes/new.md')" ]
|
||||
[ "$(cat "$p/docs/notes/new.md")" = hello ]
|
||||
run fs_write alpha docs/notes/new.md new "$TMP/c"
|
||||
[ "$status" -ne 0 ]
|
||||
[[ $output == *"already exists"* ]]
|
||||
ln -s "$TMP/outside" "$p/out"
|
||||
for bad in ../escape.txt /etc/x out/pwned.txt out/newdir/x.txt docs/ ""; do
|
||||
run fs_write alpha "$bad" new "$TMP/c"
|
||||
[ "$status" -ne 0 ]
|
||||
done
|
||||
[ ! -e "$TMP/outside/pwned.txt" ] && [ ! -e "$TMP/outside/newdir" ] && [ ! -e "$DEVDESK_PROJECTS_ROOT/escape.txt" ]
|
||||
# A short stream fails without touching anything
|
||||
run bash -c "printf aGVs | '$REPO/bin/devdesk' attach --fs-write alpha docs/notes/new.md 6 $(sha256sum "$p/docs/notes/new.md" | cut -d' ' -f1)"
|
||||
[ "$status" -ne 0 ]
|
||||
[ "$(cat "$p/docs/notes/new.md")" = hello ]
|
||||
}
|
||||
|
||||
@test "permission requests are recorded and answered only while their prompt shows (#22)" {
|
||||
start_server
|
||||
devdesk new alpha
|
||||
claude_args alpha >/dev/null
|
||||
pane=$(tmux -S "$DEVDESK_SOCKET" display -p -t =alpha:shell '#{pane_id}')
|
||||
hook() { TMUX="$DEVDESK_SOCKET,1,0" TMUX_PANE="$pane" "$REPO/libexec/devdesk-state-hook"; }
|
||||
echo '{"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":"rm -rf /tmp/x","description":"Remove x"}}' | hook
|
||||
echo '{"hook_event_name":"Notification","message":"Claude needs your permission","notification_type":"permission_prompt"}' | hook
|
||||
st="$DEVDESK_STATE_DIR/state/alpha.json"
|
||||
[ "$(jq -r '[.state, .request.tool, .request.detail, .request.description, .message] | @tsv' "$st")" = \
|
||||
"$(printf 'waiting\tBash\trm -rf /tmp/x\tRemove x\tClaude wants to use Bash')" ]
|
||||
since=$(jq -r .since "$st")
|
||||
# The fake Claude window shows no prompt: refused, nothing typed.
|
||||
run devdesk attach --answer alpha "$since" allow
|
||||
[ "$status" -ne 0 ]
|
||||
[[ $output == *"isn't on screen"* ]]
|
||||
# Put a prompt on screen (what Claude draws), then allow.
|
||||
tmux -S "$DEVDESK_SOCKET" respawn-window -k -t =alpha:claude "printf ' Do you want to proceed?\n ❯ 1. Yes\n 2. No\n'; read -r -n1 k; echo \"got:\$k\" > '$TMP/key'; sleep 30"
|
||||
sleep 0.5
|
||||
run devdesk attach --answer alpha 999 allow
|
||||
[ "$status" -ne 0 ]
|
||||
[[ $output == *"already answered"* ]]
|
||||
run devdesk attach --answer alpha "$since" allow
|
||||
[ "$status" -eq 0 ]
|
||||
sleep 0.5
|
||||
[ "$(cat "$TMP/key")" = "got:1" ]
|
||||
[ "$(jq -r .state "$st")" = working ]
|
||||
# Answered: a second click is refused.
|
||||
run devdesk attach --answer alpha "$since" deny
|
||||
[ "$status" -ne 0 ]
|
||||
}
|
||||
|
||||
@test "peek shows the last exchange; reply pastes into the Claude window (#23)" {
|
||||
start_server
|
||||
devdesk new alpha
|
||||
claude_args alpha >/dev/null
|
||||
export CLAUDE_CONFIG_DIR="$TMP/claude"
|
||||
id=11111111-2222-3333-4444-555555555555
|
||||
mkdir -p "$CLAUDE_CONFIG_DIR/projects/-x"
|
||||
cat >"$CLAUDE_CONFIG_DIR/projects/-x/$id.jsonl" <<'JSONL'
|
||||
{"type":"user","message":{"role":"user","content":"Please upgrade PBS"},"timestamp":"2026-10-10T10:00:00Z"}
|
||||
{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash","input":{}}]},"timestamp":"2026-10-10T10:00:05Z"}
|
||||
{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"ok"}]},"timestamp":"2026-10-10T10:00:06Z"}
|
||||
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"PBS is on 4.1. Reboot now?"}]},"timestamp":"2026-10-10T10:00:09Z"}
|
||||
JSONL
|
||||
jq --arg id "$id" '.sessions.alpha.claude_session_id = $id' "$DEVDESK_STATE_DIR/registry.json" >"$TMP/r" && mv "$TMP/r" "$DEVDESK_STATE_DIR/registry.json"
|
||||
run devdesk attach --peek alpha
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(jq -r '[.assistant.text, .user.text] | @tsv' <<<"$output")" = "$(printf 'PBS is on 4.1. Reboot now?\tPlease upgrade PBS')" ]
|
||||
# reply: lands in the Claude window as one paste + Enter
|
||||
tmux -S "$DEVDESK_SOCKET" respawn-window -k -t =alpha:claude "IFS= read -r line; printf '%s' \"\$line\" > '$TMP/got'; sleep 30"
|
||||
sleep 0.3
|
||||
printf 'yes, reboot it' >"$TMP/msg"
|
||||
run bash -c "base64 -w0 '$TMP/msg' | '$REPO/bin/devdesk' attach --reply alpha 14"
|
||||
[ "$status" -eq 0 ]
|
||||
sleep 0.5
|
||||
[ "$(cat "$TMP/got")" = "yes, reboot it" ]
|
||||
# not while a permission prompt waits
|
||||
mkdir -p "$DEVDESK_STATE_DIR/state"
|
||||
printf '{"state":"waiting","since":1,"request":{"tool":"Bash"}}\n' >"$DEVDESK_STATE_DIR/state/alpha.json"
|
||||
run bash -c "base64 -w0 '$TMP/msg' | '$REPO/bin/devdesk' attach --reply alpha 14"
|
||||
[ "$status" -ne 0 ]
|
||||
[[ $output == *"answer that first"* ]]
|
||||
}
|
||||
|
||||
@test "the guard asks before destructive commands and lets the rest through (#27)" {
|
||||
guard() { jq -cn --arg c "$1" '{hook_event_name: "PreToolUse", tool_name: "Bash", tool_input: {command: $c}}' | "$REPO/libexec/devdesk-guard"; }
|
||||
asks=("pct destroy 105" "ssh root@large1 'pct destroy 105 --purge'" "qm destroy 210" "zfs destroy rpool/data/vm-105-disk-0"
|
||||
"zpool destroy tank" "ceph osd pool delete rbd rbd --yes-i-really-really-mean-it" "rbd rm vm-105-disk-0"
|
||||
"rm -rf /" "rm -rf /etc" "sudo rm -r -f /var/" "dd if=/dev/zero of=/dev/sdb bs=1M" "mkfs.ext4 /dev/sdb1" "wipefs -a /dev/sdc"
|
||||
"git push --force origin main" "git push -f" "psql -c 'drop table users'" "systemctl restart devdesk-tmux"
|
||||
"ssh pve1 reboot" "systemctl poweroff" "cd /tmp && shutdown -h now")
|
||||
for c in "${asks[@]}"; do
|
||||
run guard "$c"
|
||||
[ "$(jq -r '.hookSpecificOutput.permissionDecision' <<<"$output")" = ask ] || { echo "should ask: $c"; false; }
|
||||
done
|
||||
passes=("pct list" "pct exec 105 -- df -h" "zfs list" "rm -rf /tmp/build-cache" "rm -rf node_modules" "rm -rf ./dist"
|
||||
"git push origin main" "dd if=a.img of=b.img" "echo reboot later" "systemctl restart devdesk" "ceph -s" "ls -la /")
|
||||
for c in "${passes[@]}"; do
|
||||
run guard "$c"
|
||||
[ -z "$output" ] || { echo "should pass: $c -> $output"; false; }
|
||||
done
|
||||
# Local rules and the off switch
|
||||
printf 'nuke-it\tis a local rule\n' >"$TMP/guard.local"
|
||||
run env DEVDESK_GUARD_LOCAL="$TMP/guard.local" bash -c "jq -cn '{tool_input: {command: \"nuke-it now\"}}' | '$REPO/libexec/devdesk-guard'"
|
||||
[[ $output == *"is a local rule"* ]]
|
||||
run env DEVDESK_GUARD=0 bash -c "jq -cn '{tool_input: {command: \"pct destroy 1\"}}' | '$REPO/libexec/devdesk-guard'"
|
||||
[ -z "$output" ]
|
||||
}
|
||||
|
||||
@test "Bash commands are logged and tag the session with the hosts it works on (#27)" {
|
||||
start_server
|
||||
devdesk new alpha
|
||||
pane=$(tmux -S "$DEVDESK_SOCKET" display -p -t =alpha:shell '#{pane_id}')
|
||||
bash_cmd() { jq -cn --arg c "$1" '{hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: {command: $c}}' |
|
||||
TMUX="$DEVDESK_SOCKET,1,0" TMUX_PANE="$pane" "$REPO/libexec/devdesk-state-hook"; }
|
||||
bash_cmd "ssh -o BatchMode=yes root@large1 'pct exec 167 -- systemctl status authelia'"
|
||||
bash_cmd "ls -la"
|
||||
bash_cmd "ssh pve2 qm status 210"
|
||||
[ "$(wc -l <"$DEVDESK_STATE_DIR/commands/alpha.jsonl")" -eq 3 ]
|
||||
run devdesk attach --list
|
||||
[ "$(jq -r '.sessions[] | select(.name == "alpha") | .tags | join(",")' <<<"$output")" = "pve2,VM 210,large1,CT 167" ]
|
||||
run devdesk attach --peek alpha
|
||||
[ "$(jq -r '.commands | map(.cmd) | .[1]' <<<"$output")" = "ls -la" ]
|
||||
devdesk rename alpha beta
|
||||
[ -f "$DEVDESK_STATE_DIR/commands/beta.jsonl" ] && [ -f "$DEVDESK_STATE_DIR/tags/beta.json" ]
|
||||
devdesk end beta
|
||||
[ ! -e "$DEVDESK_STATE_DIR/commands/beta.jsonl" ] && [ ! -e "$DEVDESK_STATE_DIR/tags/beta.json" ]
|
||||
}
|
||||
|
||||
# A fake Claude history: one conversation in $1 with id $2.
|
||||
fake_convo() {
|
||||
mkdir -p "$CLAUDE_CONFIG_DIR/projects/-p"
|
||||
jq -cn --arg cwd "$1" --arg id "$2" '
|
||||
{type: "user", cwd: $cwd, sessionId: $id, timestamp: "2026-08-01T10:00:00Z", message: {role: "user", content: "Fix the NFS mount on pbs"}},
|
||||
{type: "assistant", timestamp: "2026-08-01T10:00:05Z", message: {role: "assistant", content: [{type: "tool_use", name: "Bash", input: {command: "mount -t nfs 10.10.10.9:/backup /mnt/pbs"}}]}},
|
||||
{type: "assistant", timestamp: "2026-08-01T10:00:09Z", message: {role: "assistant", content: [{type: "text", text: "The NFS export needed no_root_squash."}]}}' \
|
||||
>"$CLAUDE_CONFIG_DIR/projects/-p/$2.jsonl"
|
||||
}
|
||||
|
||||
@test "search finds past conversations by what was said and run (#24)" {
|
||||
export CLAUDE_CONFIG_DIR="$TMP/claude"
|
||||
fake_convo "$DEVDESK_PROJECTS_ROOT/alpha" 11111111-1111-1111-1111-111111111111
|
||||
run devdesk attach --search "no_root_squash"
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(jq -r '.results[0] | [.id, .title, .cwd, .matches[0].role] | @tsv' <<<"$output")" = \
|
||||
"$(printf '11111111-1111-1111-1111-111111111111\tFix the NFS mount on pbs\t%s\tclaude' "$DEVDESK_PROJECTS_ROOT/alpha")" ]
|
||||
run devdesk attach --search "MOUNT -t NFS"
|
||||
[ "$(jq -r '.results[0].matches[0].role' <<<"$output")" = command ]
|
||||
run devdesk attach --search "nothing like this anywhere"
|
||||
[ "$(jq -r '.results | length' <<<"$output")" = 0 ]
|
||||
run devdesk attach --search "x"
|
||||
[ "$status" -ne 0 ]
|
||||
}
|
||||
|
||||
@test "resume-convo opens a past conversation in its folder; fork is passed once (#24)" {
|
||||
export CLAUDE_CONFIG_DIR="$TMP/claude"
|
||||
id=22222222-2222-2222-2222-222222222222
|
||||
fake_convo "$DEVDESK_PROJECTS_ROOT/alpha" "$id"
|
||||
start_server
|
||||
run devdesk attach --resume-convo nfs-fix "$id" fork
|
||||
[ "$status" -eq 0 ]
|
||||
claude_args nfs-fix >/dev/null
|
||||
[[ "$(claude_args nfs-fix)" == "--resume $id --fork-session --settings"* ]]
|
||||
[ "$(tmux -S "$DEVDESK_SOCKET" display -p -t =nfs-fix:claude '#{pane_current_path}')" = "$DEVDESK_PROJECTS_ROOT/alpha" ]
|
||||
[ "$(jq -r '.sessions["nfs-fix"].fork // "cleared"' "$DEVDESK_STATE_DIR/registry.json")" = cleared ]
|
||||
# Resuming (not forking) the same conversation while it's open elsewhere is refused.
|
||||
jq --arg id "$id" '.sessions["nfs-fix"].claude_session_id = $id' "$DEVDESK_STATE_DIR/registry.json" >"$TMP/r" && mv "$TMP/r" "$DEVDESK_STATE_DIR/registry.json"
|
||||
run devdesk attach --resume-convo nfs-again "$id"
|
||||
[ "$status" -ne 0 ]
|
||||
[[ $output == *"open in session nfs-fix"* ]]
|
||||
run devdesk attach --resume-convo nfs-fix "$id" fork
|
||||
[ "$status" -ne 0 ]
|
||||
[[ $output == *"already running"* ]]
|
||||
}
|
||||
|
||||
@test "presence marks a session while a tab shows it (#26)" {
|
||||
export DEVDESK_PRESENCE_DIR="$TMP/presence"
|
||||
start_server
|
||||
devdesk new alpha
|
||||
claude_args alpha >/dev/null
|
||||
sid=$(tmux -S "$DEVDESK_SOCKET" display -p -t =alpha: '#{session_id}')
|
||||
run devdesk attach --presence alpha on
|
||||
[ "$status" -eq 0 ]
|
||||
[ -e "$TMP/presence/${sid#\$}" ]
|
||||
# The Claude window was told where the marker lives.
|
||||
[ "$(tmux -S "$DEVDESK_SOCKET" show-environment -t =alpha CLAUDE_CLIENT_PRESENCE_FILE 2>/dev/null || true)" = "" ] # set per process, not per session
|
||||
run devdesk attach --presence alpha off
|
||||
[ ! -e "$TMP/presence/${sid#\$}" ]
|
||||
}
|
||||
|
||||
# A fake Proxmox cluster for `devdesk guests`: DEVDESK_PVE_SSH answers the
|
||||
# inventory (pvesh) from $FAKE_PVE/inventory and each node's scan from node-<name>.
|
||||
fake_pve() {
|
||||
export FAKE_PVE="$TMP/pve" DEVDESK_PVE_SSH="$TMP/fake-ssh" DEVDESK_PVE_NODES="down-node large1"
|
||||
mkdir -p "$FAKE_PVE"
|
||||
cat >"$DEVDESK_PVE_SSH" <<'EOF'
|
||||
#!/bin/bash
|
||||
while [ "${1:-}" = -o ]; do shift 2; done
|
||||
case $1:$2 in
|
||||
down-node:*) exit 255 ;;
|
||||
*:*pvesh*) cat "$FAKE_PVE/inventory" ;;
|
||||
*) cat "$FAKE_PVE/node-$1" 2>/dev/null || exit 255 ;;
|
||||
esac
|
||||
EOF
|
||||
chmod +x "$DEVDESK_PVE_SSH"
|
||||
pve_state running
|
||||
printf 'large1\t10.10.10.2 10.10.90.10 fe80::1\n139\t10.10.10.27 \n102\t127.0.0.1 10.10.10.23 \n' >"$FAKE_PVE/node-large1"
|
||||
}
|
||||
|
||||
# Draupnir (CT 110) running on monitor-02, or stopped (and so absent from the node scan).
|
||||
pve_state() {
|
||||
printf '%s\n' \
|
||||
'[{"vmid":110,"name":"draupnir","node":"monitor-02","status":"'"$1"'","type":"lxc","hastate":"'"${1/running/started}"'"},' \
|
||||
' {"vmid":139,"name":"nginxproxymanager","node":"large1","status":"running","type":"lxc","hastate":"started"},' \
|
||||
' {"vmid":102,"name":"homeAssistant","node":"large1","status":"running","type":"qemu"}]' \
|
||||
'[{"id":"cluster","type":"cluster"},{"name":"large1","ip":"10.10.90.10","online":1,"type":"node"},' \
|
||||
' {"name":"monitor-02","ip":"10.10.10.9","online":1,"type":"node"}]' >"$FAKE_PVE/inventory"
|
||||
if [ "$1" = running ]; then
|
||||
printf 'monitor-02\t10.10.10.9\n110\t10.10.10.24\n' >"$FAKE_PVE/node-monitor-02"
|
||||
else
|
||||
printf 'monitor-02\t10.10.10.9\n' >"$FAKE_PVE/node-monitor-02"
|
||||
fi
|
||||
}
|
||||
|
||||
# Grafana's rules API, served from a file.
|
||||
fake_grafana() {
|
||||
export DEVDESK_GRAFANA_URL="file://$TMP/grafana" DEVDESK_GRAFANA_PUBLIC_URL=https://grafana.example
|
||||
mkdir -p "$TMP/grafana/api/prometheus/grafana/api/v1"
|
||||
jq -n '{data: {groups: [{name: "Bots", file: "Matrix", rules: [
|
||||
{uid: "u-draupnir", name: "Draupnir Down", state: "firing", query: "up{job=\"draupnir-node\"}", labels: {severity: "critical"},
|
||||
annotations: {summary: "Draupnir is unreachable", description: "Cannot scrape 10.10.10.24:9100"},
|
||||
alerts: [{state: "Alerting", activeAt: "2026-10-11T07:10:00Z", value: "0", labels: {instance: "10.10.10.24:9100", job: "draupnir-node", alertname: "Draupnir Down"}}]},
|
||||
{uid: "u-ceph", name: "Ceph Unhealthy", state: "firing", query: "ceph_health_status", labels: {severity: "warning"},
|
||||
annotations: {summary: "status={{ $value }}"},
|
||||
alerts: [{state: "Alerting", value: "1e+00", labels: {instance: "http://10.10.10.2:9283/metrics", job: "ceph"}}]},
|
||||
{uid: "u-count", name: "Exporter Down", state: "firing", query: "count(up == 0)", labels: {},
|
||||
annotations: {summary: "{{ $value }} down"}, alerts: [{state: "Alerting", value: "2", labels: {alertname: "Exporter Down"}}]},
|
||||
{uid: "u-lan", name: "Printer Offline", state: "pending", query: "up", labels: {},
|
||||
annotations: {}, alerts: [{state: "Pending", value: "0", labels: {instance: "10.99.0.1:9100"}}]},
|
||||
{uid: "u-ok", name: "Fine", state: "inactive", alerts: []}]}]}}' >"$TMP/grafana/api/prometheus/grafana/api/v1/rules"
|
||||
}
|
||||
|
||||
@test "guests: where each CT/VM runs, from any node that answers; stopped ones keep their last IP (#39)" {
|
||||
fake_pve
|
||||
run devdesk guests
|
||||
[ "$status" -eq 0 ]
|
||||
[[ $output == *"110"*"draupnir"*"monitor-02"*"running"*"started"*"10.10.10.24"* ]]
|
||||
[[ $output == *"102"*"vm"*"homeAssistant"*"large1"*"10.10.10.23"* ]]
|
||||
[[ $output != *"127.0.0.1"* ]]
|
||||
run devdesk guests --json 10.10.10.27
|
||||
[ "$(jq -r '[.guests[].id] | join(",")' <<<"$output")" = 139 ]
|
||||
[ "$(jq -r '.nodes[] | select(.name == "large1") | .ips | join(",")' <<<"$output")" = 10.10.10.2,10.10.90.10 ]
|
||||
# Draupnir stops: its IP is remembered, marked as last seen.
|
||||
pve_state stopped
|
||||
run devdesk guests drau
|
||||
[[ $output == *"stopped"*"10.10.10.24 (last seen)"* ]]
|
||||
# No node answers: the cache, with a warning.
|
||||
run env DEVDESK_PVE_NODES=down-node devdesk guests draupnir
|
||||
[ "$status" -eq 0 ]
|
||||
[[ $output == *"no Proxmox node answered"*"10.10.10.24"* ]]
|
||||
run env DEVDESK_PVE_NODES= devdesk guests
|
||||
[ "$status" -ne 0 ]
|
||||
[[ $output == *"DEVDESK_PVE_NODES"* ]]
|
||||
}
|
||||
|
||||
@test "alerts name the guest or node each one is about (#39)" {
|
||||
fake_pve
|
||||
fake_grafana
|
||||
devdesk guests >/dev/null
|
||||
pve_state stopped
|
||||
devdesk guests >/dev/null
|
||||
run devdesk alerts
|
||||
[ "$status" -eq 0 ]
|
||||
t() { jq -c --arg u "$1" '.alerts[] | select(.uid == $u) | .targets | map({kind, id, name, node, by})' <<<"$output"; }
|
||||
[ "$(t u-draupnir)" = '[{"kind":"ct","id":110,"name":"draupnir","node":"monitor-02","by":"ip"}]' ]
|
||||
[ "$(t u-ceph)" = '[{"kind":"node","id":null,"name":"large1","node":"large1","by":"ip"}]' ]
|
||||
[ "$(t u-count)" = '[]' ]
|
||||
[ "$(t u-lan)" = '[{"kind":"unknown","id":null,"name":null,"node":null,"by":null}]' ]
|
||||
[ "$(jq -r '.alerts[] | select(.uid == "u-ceph") | .summary' <<<"$output")" = "status=1" ]
|
||||
[ "$(jq -r '[.alerts[].uid] | join(",")' <<<"$output")" = u-draupnir,u-ceph,u-count,u-lan ]
|
||||
# Never seen running: matched by the name in its job label instead.
|
||||
rm "$DEVDESK_STATE_DIR/guests.json"
|
||||
devdesk guests >/dev/null
|
||||
run devdesk alerts
|
||||
[ "$(t u-draupnir)" = '[{"kind":"ct","id":110,"name":"draupnir","node":"monitor-02","by":"name"}]' ]
|
||||
}
|
||||
|
||||
@test "investigate starts Claude in its own session with the alert and where it runs (#39)" {
|
||||
fake_pve
|
||||
fake_grafana
|
||||
devdesk guests >/dev/null
|
||||
start_server
|
||||
run devdesk attach --investigate alert-draupnir-down u-draupnir
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(jq -c . <<<"$output")" = '{"ok":true,"session":"alert-draupnir-down","started":true}' ]
|
||||
claude_args alert-draupnir-down >/dev/null
|
||||
log="$FAKE_LOG/alert-draupnir-down"
|
||||
grep -q '^-n alert-draupnir-down Investigate this Grafana alert' "$log"
|
||||
grep -q 'Alert: Draupnir Down (critical, firing since' "$log"
|
||||
grep -q 'Query: `up{job="draupnir-node"}`' "$log"
|
||||
grep -q '10.10.10.24 is CT 110 "draupnir" on node monitor-02, running, HA state started; commands inside it: `ssh monitor-02 pct exec 110 -- <command>`' "$log"
|
||||
grep -q '`devdesk guests 110` shows where it is now' "$log"
|
||||
# The prompt is sent once: not again when Claude is resumed.
|
||||
[ ! -e "$DEVDESK_STATE_DIR/prompts/alert-draupnir-down.txt" ]
|
||||
run devdesk attach --investigate alert-draupnir-down u-draupnir
|
||||
[ "$(jq -r .started <<<"$output")" = false ]
|
||||
# Aggregates get a hint instead; alerts that resolved meanwhile are refused.
|
||||
run devdesk attach --investigate exporters u-count
|
||||
claude_args exporters >/dev/null
|
||||
grep -q 'The rule aggregates' "$FAKE_LOG/exporters"
|
||||
run grep -c 'Where it runs' "$FAKE_LOG/exporters"
|
||||
[ "$output" = 0 ]
|
||||
run devdesk attach --investigate gone u-ok
|
||||
[ "$status" -ne 0 ]
|
||||
[[ $output == *"no longer firing"* ]]
|
||||
run devdesk attach --investigate 'bad name' u-ok
|
||||
[[ $output == *"invalid session name"* ]]
|
||||
}
|
||||
|
||||
@@ -86,3 +86,15 @@ test('untrusted text loses control characters before it is typed (#2)', () => {
|
||||
assert.equal(pasteSafe('plain text'), 'plain text');
|
||||
assert.equal(pasteSafe(null), '');
|
||||
});
|
||||
|
||||
test('file paths in terminal output are found, URLs and plain words are not (#21)', async () => {
|
||||
const { findPaths } = await import('../web/src/links.js');
|
||||
const paths = (text) => findPaths(text).map((p) => `${p.path}${p.line ? `:${p.line}` : ''}`);
|
||||
assert.deepEqual(paths('● Update(web/src/files.js)'), ['web/src/files.js']);
|
||||
assert.deepEqual(paths(' ⎿ Wrote 12 lines to notes/todo.md'), ['notes/todo.md']);
|
||||
assert.deepEqual(paths('error at src/app.py:42:7 and ./README.md:3'), ['src/app.py:42', './README.md:3']);
|
||||
assert.deepEqual(paths('see /root/code/devdesk/Makefile'), ['/root/code/devdesk/Makefile']);
|
||||
assert.deepEqual(paths('open https://code.lotusguild.org/a/b.js now'), []);
|
||||
// Candidates only: they become links only if they're files of the session.
|
||||
assert.deepEqual(paths('just some words, v1.2 and e.g. stuff'), ['v1.2']);
|
||||
});
|
||||
|
||||
+39
-3
@@ -4,7 +4,7 @@
|
||||
// the first time the Files pane opens, so the page itself stays small.
|
||||
import { EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter, drawSelection, highlightSpecialChars } from '@codemirror/view';
|
||||
import { EditorState } from '@codemirror/state';
|
||||
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands';
|
||||
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
|
||||
import { syntaxHighlighting, HighlightStyle, StreamLanguage, bracketMatching, foldGutter, foldKeymap } from '@codemirror/language';
|
||||
import { search, searchKeymap, highlightSelectionMatches } from '@codemirror/search';
|
||||
import { markdownLanguage } from '@codemirror/lang-markdown';
|
||||
@@ -135,10 +135,46 @@ function baseExtensions(path, { readOnly = true, wrap = false } = {}) {
|
||||
];
|
||||
}
|
||||
|
||||
// Read-only (v1) view of a file.
|
||||
// Put the cursor on a line (1-based) and scroll it to the middle.
|
||||
function gotoLine(view, line) {
|
||||
const target = view.state.doc.line(Math.max(1, Math.min(line, view.state.doc.lines)));
|
||||
view.dispatch({ selection: { anchor: target.from, head: target.to }, effects: EditorView.scrollIntoView(target.from, { y: 'center' }) });
|
||||
view.focus();
|
||||
}
|
||||
|
||||
// Read-only view of a file.
|
||||
export function viewer(parent, { doc, path, wrap }) {
|
||||
const view = new EditorView({ parent, state: EditorState.create({ doc, extensions: baseExtensions(path, { wrap }) }) });
|
||||
return { view, destroy: () => view.destroy() };
|
||||
return { view, goto: (line) => gotoLine(view, line), destroy: () => view.destroy() };
|
||||
}
|
||||
|
||||
// Editable file (devdesk#20): onChange(text) after every edit, onSave() on
|
||||
// Ctrl/Cmd+S (which never reaches the browser or the terminal).
|
||||
export function editor(parent, { doc, path, wrap, onChange, onSave }) {
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
extensions: [
|
||||
keymap.of([{ key: 'Mod-s', preventDefault: true, run: () => { onSave?.(); return true; } }, indentWithTab]),
|
||||
baseExtensions(path, { readOnly: false, wrap }),
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) onChange?.(update.state.doc.toString());
|
||||
}),
|
||||
],
|
||||
}),
|
||||
});
|
||||
return {
|
||||
view,
|
||||
goto: (line) => gotoLine(view, line),
|
||||
text: () => view.state.doc.toString(),
|
||||
// Replace the whole document (reload from disk) keeping the cursor roughly where it was.
|
||||
setText: (text) => {
|
||||
const pos = Math.min(view.state.selection.main.head, text.length);
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, selection: { anchor: pos } });
|
||||
},
|
||||
destroy: () => view.destroy(),
|
||||
};
|
||||
}
|
||||
|
||||
// Unified diff of the HEAD version against the working copy.
|
||||
|
||||
@@ -63,6 +63,8 @@
|
||||
</div>
|
||||
<button type="button" class="dd-menu-item" id="theme-menu" role="menuitem">Light mode</button>
|
||||
<button type="button" class="dd-menu-item" id="notify-toggle" role="menuitem">Desktop notifications</button>
|
||||
<div class="dd-menu-row dd-usage-row" id="usage-row" hidden><span>Plan usage</span><span class="dd-usage" id="usage-menu"></span></div>
|
||||
<button type="button" class="dd-menu-item" id="history-menu" role="menuitem">Search past conversations</button>
|
||||
<button type="button" class="dd-menu-item" id="palette-menu" role="menuitem">Command palette</button>
|
||||
<button type="button" class="dd-menu-item" id="help-open" role="menuitem">Keyboard shortcuts</button>
|
||||
<button type="button" class="dd-menu-item" id="fullscreen-toggle" role="menuitem" title="In Chromium, fullscreen also captures Ctrl+W/Ctrl+T for the terminal">Fullscreen</button>
|
||||
@@ -96,6 +98,7 @@
|
||||
<button type="button" class="dd-icon-btn dd-explorer-toggle" title="Show / hide the explorer" aria-label="Toggle explorer">☰</button>
|
||||
<div class="dd-tabs" role="tablist" aria-label="Open files"></div>
|
||||
<span class="dd-files-actions">
|
||||
<button type="button" class="dd-icon-btn dd-files-new" title="New file" aria-label="New file">+</button>
|
||||
<button type="button" class="dd-icon-btn dd-files-find" title="Go to file (Ctrl+P)" aria-label="Go to file">⌕</button>
|
||||
<button type="button" class="dd-icon-btn dd-files-refresh" title="Refresh" aria-label="Refresh">↻</button>
|
||||
<button type="button" class="dd-icon-btn dd-files-close" title="Close (Esc)" aria-label="Close files">✕</button>
|
||||
@@ -178,6 +181,7 @@
|
||||
<span class="lt-footer-hint"><span class="lt-footer-key">^⇧P</span>commands</span>
|
||||
<button type="button" class="dd-footer-help" id="footer-help">all keys</button>
|
||||
</div>
|
||||
<div class="dd-usage dd-footer-usage" id="usage-footer" hidden></div>
|
||||
<div class="dd-keybar" id="keybar" role="toolbar" aria-label="Terminal keys" hidden>
|
||||
<button type="button" data-keys="esc">Esc</button>
|
||||
<button type="button" data-keys="tab">Tab</button>
|
||||
|
||||
+29
-9
@@ -1,8 +1,10 @@
|
||||
// Ops Alerts panel: firing/pending Grafana alert rules (`devdesk attach --alerts`),
|
||||
// each with an "Ask Claude" button that types an investigation prompt into the
|
||||
// current session (without pressing Enter).
|
||||
// the Proxmox guest or node each is about (CT id, the node it runs on now), and
|
||||
// an "Ask Claude" button that starts an investigation in a session of its own
|
||||
// (devdesk#39).
|
||||
|
||||
import { el } from './dom.js';
|
||||
import { slugify } from './protocol.js';
|
||||
|
||||
const SEVERITY = {
|
||||
critical: 'lt-chip-critical',
|
||||
@@ -18,14 +20,24 @@ function age(iso) {
|
||||
return `${Math.floor(s / 86400)}d`;
|
||||
}
|
||||
|
||||
export function investigatePrompt(alert) {
|
||||
const where = alert.instances?.length ? ` on ${alert.instances.join('; ')}` : '';
|
||||
return `Investigate the ${alert.state} Grafana alert "${alert.name}"`
|
||||
+ ` (${alert.severity || 'no severity'}, ${alert.folder} / ${alert.group}${where}, since ${alert.since}).`
|
||||
+ ` Summary: ${alert.summary || 'n/a'}. Use the grafana MCP server to look at the rule and the related`
|
||||
+ ' metrics, find the cause, and tell me what you would change before changing anything.';
|
||||
// "CT 110 draupnir · monitor-02 · stopped", "node compute-storage-01".
|
||||
function targetLabel(t) {
|
||||
if (t.kind === 'unknown') return null;
|
||||
const what = t.kind === 'node' ? `node ${t.name}` : `${t.kind.toUpperCase()} ${t.id} ${t.name}`;
|
||||
const parts = [what, t.kind === 'node' ? null : t.node, t.status === 'running' || t.status === 'online' ? null : t.status];
|
||||
return parts.filter(Boolean).join(' · ') + (t.by === 'name' ? ' (by name)' : '');
|
||||
}
|
||||
|
||||
function targetTitle(t) {
|
||||
const how = t.kind === 'ct' ? `ssh ${t.node} pct exec ${t.id} -- …`
|
||||
: t.kind === 'vm' ? `ssh ${t.node} qm guest exec ${t.id} -- …` : `ssh ${t.name}`;
|
||||
const note = t.by === 'name' ? '\nMatched by name, not by IP (the guest has not been seen running with this IP).'
|
||||
: t.ip_seen ? '\nIts IP when it was last seen running.' : '';
|
||||
return `${how}${t.ha ? `\nHA state: ${t.ha}` : ''}${note}`;
|
||||
}
|
||||
|
||||
export const alertSession = (alert) => slugify(`alert-${alert.name}`).toLowerCase().slice(0, 48) || 'alert';
|
||||
|
||||
export function renderAlerts(root, data) {
|
||||
const list = root.querySelector('.dd-alert-list');
|
||||
const note = root.querySelector('.dd-alerts-note');
|
||||
@@ -59,6 +71,14 @@ export function renderAlerts(root, data) {
|
||||
el('a', { class: 'dd-alert-name', href: a.url, target: '_blank', rel: 'noopener', title: `${a.folder} / ${a.group}` }, a.name),
|
||||
el('span', { class: 'dd-muted dd-alert-age' }, age(a.since))),
|
||||
a.instances?.length ? el('div', { class: 'dd-muted dd-alert-instances' }, a.instances.join(' · ')) : null,
|
||||
...(a.targets ?? []).map((t) => {
|
||||
const label = targetLabel(t);
|
||||
return label ? el('div', { class: `dd-alert-where${t.by === 'name' ? ' is-guess' : ''}`, title: targetTitle(t) }, label) : null;
|
||||
}),
|
||||
a.summary ? el('div', { class: 'dd-alert-summary' }, a.summary) : null,
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-sm dd-ask', 'data-ask-claude': investigatePrompt(a) }, 'Ask Claude'))));
|
||||
el('div', { class: 'dd-ask-row' },
|
||||
el('button', {
|
||||
type: 'button', class: 'lt-btn lt-btn-sm dd-ask', 'data-investigate': a.uid, 'data-session': alertSession(a),
|
||||
title: `Start Claude in a new session (${alertSession(a)}) on this alert, with the rule, the query and where it runs (CT id, node)`,
|
||||
}, 'Ask Claude')))));
|
||||
}
|
||||
|
||||
+63
-15
@@ -152,13 +152,21 @@ async function runCommandNow(args, timeoutMs) {
|
||||
clearTimeout(timer);
|
||||
resolve(new TextDecoder().decode(concat(chunks)));
|
||||
};
|
||||
const decoder = new TextDecoder();
|
||||
let head = '';
|
||||
let tail = '';
|
||||
socket.onmessage = (event) => {
|
||||
const { type, payload } = decodeServer(event.data);
|
||||
if (type !== Server.OUTPUT) return;
|
||||
chunks.push(payload.slice());
|
||||
const piece = decoder.decode(payload, { stream: true });
|
||||
if (head.length < 4096) head += piece;
|
||||
tail = (tail + piece).slice(-64);
|
||||
// Hang up as soon as the answer is complete: devdesk waits for that
|
||||
// before exiting, so ttyd can't drop its last output (devdesk#35).
|
||||
if (isComplete(new TextDecoder().decode(concat(chunks)))) {
|
||||
// Replies are one JSON line (or a devdesk: error), so only a chunk that
|
||||
// ends a line with "}" is worth a full parse; big replies stay linear.
|
||||
if (/^devdesk: .*\n/m.test(head) || (/\}\s*\n\s*$/.test(tail) && isComplete(new TextDecoder().decode(concat(chunks))))) {
|
||||
finish();
|
||||
socket.close();
|
||||
}
|
||||
@@ -201,11 +209,43 @@ export function uploadFile(session, file, onProgress) {
|
||||
}
|
||||
|
||||
async function uploadNow(session, file, onProgress) {
|
||||
const token = await fetchToken();
|
||||
const name = (file.name || 'pasted-image.png').slice(-100);
|
||||
const result = await streamIn(['--upload', session, name, String(file.size)], 'DEVDESK-UPLOAD-READY', file, onProgress);
|
||||
if (!result.ok || !result.path) throw new Error('upload failed');
|
||||
return result.path;
|
||||
}
|
||||
|
||||
// Answer a session from the inbox (devdesk#22, #23).
|
||||
export function answerPrompt(session, since, choice) {
|
||||
return sessionAction('answer', session, String(since), choice);
|
||||
}
|
||||
|
||||
export async function peekSession(session) {
|
||||
return parseListOutput(await runCommand(['--peek', session], 15000));
|
||||
}
|
||||
|
||||
export async function replyTo(session, text) {
|
||||
const bytes = new TextEncoder().encode(text);
|
||||
const result = await limited(() => streamIn(['--reply', session, String(bytes.length)], 'DEVDESK-REPLY-READY', new Blob([bytes])));
|
||||
if (!result.ok) throw new Error('not sent');
|
||||
}
|
||||
|
||||
// Save a file from the editor (devdesk#20): `--fs-write SESSION PATH BYTES BASE`
|
||||
// with the content streamed after the ready line. Resolves the server's JSON:
|
||||
// {ok: true, sha, size, mtime} or {ok: false, conflict: true, sha} when the file
|
||||
// changed since `base` (a sha256, or "new" to create).
|
||||
export function writeFile(session, path, bytes, base) {
|
||||
return limited(() => streamIn(['--fs-write', session, path, String(bytes.length), base], 'DEVDESK-WRITE-READY', new Blob([bytes])));
|
||||
}
|
||||
|
||||
// Run a devdesk command that reads base64 from the terminal after printing
|
||||
// `ready`: stream `blob` in slices (never all in memory), then resolve the JSON
|
||||
// reply. Fails on 20 s of inactivity rather than a fixed total (devdesk#9).
|
||||
async function streamIn(args, ready, blob, onProgress) {
|
||||
const token = await fetchToken();
|
||||
const slice = 3 * 16 * 1024; // multiple of 3: base64 of slices concatenates cleanly
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new WebSocket(wsUrl(window.location, ['--upload', session, name, String(file.size)]), ['tty']);
|
||||
const socket = new WebSocket(wsUrl(window.location, args), ['tty']);
|
||||
socket.binaryType = 'arraybuffer';
|
||||
const decoder = new TextDecoder();
|
||||
let output = '';
|
||||
@@ -216,15 +256,16 @@ async function uploadNow(session, file, onProgress) {
|
||||
idle = setTimeout(() => socket.close(), 20000);
|
||||
};
|
||||
const send = async () => {
|
||||
for (let offset = 0; offset < file.size; offset += slice) {
|
||||
for (let offset = 0; offset < blob.size; offset += slice) {
|
||||
while (socket.bufferedAmount > 1 << 20) await sleep(20);
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
const bytes = new Uint8Array(await file.slice(offset, offset + slice).arrayBuffer());
|
||||
const bytes = new Uint8Array(await blob.slice(offset, offset + slice).arrayBuffer());
|
||||
socket.send(encodeInput(toBase64(bytes)));
|
||||
touch();
|
||||
onProgress?.(Math.min(1, (offset + slice) / file.size));
|
||||
onProgress?.(Math.min(1, (offset + slice) / blob.size));
|
||||
}
|
||||
};
|
||||
const after = () => output.slice(output.indexOf(ready) + ready.length);
|
||||
touch();
|
||||
socket.onopen = () => socket.send(encodeInit(token, 240, 24));
|
||||
socket.onmessage = (event) => {
|
||||
@@ -232,28 +273,26 @@ async function uploadNow(session, file, onProgress) {
|
||||
const { type, payload } = decodeServer(event.data);
|
||||
if (type !== Server.OUTPUT) return;
|
||||
output += decoder.decode(payload, { stream: true });
|
||||
if (!sending && output.includes('DEVDESK-UPLOAD-READY')) {
|
||||
if (!sending && output.includes(ready)) {
|
||||
sending = true;
|
||||
send();
|
||||
} else if (sending && isComplete(output.replace(/^[\s\S]*DEVDESK-UPLOAD-READY/, ''))) {
|
||||
}
|
||||
if (sending && isComplete(after())) {
|
||||
socket.close(); // the reply is in; let devdesk exit (devdesk#35)
|
||||
}
|
||||
};
|
||||
socket.onerror = () => {};
|
||||
socket.onclose = () => {
|
||||
clearTimeout(idle);
|
||||
const text = stripAnsi(output.replace(/^[\s\S]*DEVDESK-UPLOAD-READY/, ''));
|
||||
const text = stripAnsi(output.includes(ready) ? after() : output);
|
||||
try {
|
||||
const result = parseListOutput(text);
|
||||
if (result.ok && result.path) {
|
||||
resolve(result.path);
|
||||
return;
|
||||
}
|
||||
resolve(parseListOutput(text));
|
||||
return;
|
||||
} catch {
|
||||
// fall through to the error message
|
||||
}
|
||||
const message = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean).pop();
|
||||
reject(new Error((message || 'upload failed').replace(/^devdesk:\s*/, '')));
|
||||
reject(new Error((message || 'no reply').replace(/^devdesk:\s*/, '')));
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -337,6 +376,15 @@ export async function sessionAction(action, ...args) {
|
||||
throw new Error(message.replace(/^devdesk:\s*/, ''));
|
||||
}
|
||||
|
||||
// Ops Alerts → Ask Claude (devdesk#39): start Claude in SESSION on alert rule UID.
|
||||
// The server looks the alert up and writes the prompt. {session, started}.
|
||||
export async function investigateAlert(session, uid) {
|
||||
const output = stripAnsi(await runCommand(['--investigate', session, uid], 40000)).trim();
|
||||
if (/"ok"\s*:\s*true/.test(output)) return parseListOutput(output);
|
||||
const message = output.split(/\r?\n/).filter(Boolean).pop() || 'no response';
|
||||
throw new Error(message.replace(/^devdesk:\s*/, ''));
|
||||
}
|
||||
|
||||
function concat(chunks) {
|
||||
const total = chunks.reduce((n, c) => n + c.length, 0);
|
||||
const out = new Uint8Array(total);
|
||||
|
||||
+378
-16
@@ -5,11 +5,11 @@
|
||||
// see what Claude edited, and jump to any file by name. Read-only for now.
|
||||
// Everything goes through `devdesk attach --fs-*` over ttyd.
|
||||
|
||||
import { runBlob, runCommand } from './connection.js';
|
||||
import { runBlob, runCommand, writeFile } from './connection.js';
|
||||
import { parseListOutput } from './protocol.js';
|
||||
import { el } from './dom.js';
|
||||
import { ago } from './sessions.js';
|
||||
import { CommandPalette, toast } from './ui.js';
|
||||
import { CommandPalette, openDialog, toast } from './ui.js';
|
||||
|
||||
// ---------------------------------------------------------------- editor bundle
|
||||
|
||||
@@ -164,6 +164,27 @@ function writeJson(key, value) {
|
||||
}
|
||||
}
|
||||
|
||||
// Unsaved edits survive a reload, a session switch or a crash (devdesk#20):
|
||||
// each dirty buffer is mirrored to localStorage with the sha it was based on.
|
||||
const draftKey = (session, path) => `devdesk.draft.${session}:${path}`;
|
||||
|
||||
function readDraft(session, path) {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(draftKey(session, path)));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeDraft(session, path, draft) {
|
||||
try {
|
||||
if (draft) localStorage.setItem(draftKey(session, path), JSON.stringify(draft));
|
||||
else localStorage.removeItem(draftKey(session, path));
|
||||
} catch {
|
||||
// Quota or private mode: the edit just isn't backed up.
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- icons
|
||||
|
||||
// A two-character badge per file type (VS Code's icon idea, in the terminal style).
|
||||
@@ -249,6 +270,7 @@ export class FilesPane {
|
||||
root.querySelector('.dd-files-refresh').addEventListener('click', () => this.refresh());
|
||||
root.querySelector('.dd-files-close').addEventListener('click', () => this.close());
|
||||
root.querySelector('.dd-files-find').addEventListener('click', () => this.quickOpen.open());
|
||||
root.querySelector('.dd-files-new').addEventListener('click', () => this.newFile());
|
||||
root.querySelector('.dd-explorer-toggle').addEventListener('click', () => this.setExplorer(!this.explorerShown()));
|
||||
this.explorer.addEventListener('keydown', (event) => this.treeKey(event));
|
||||
root.addEventListener('keydown', (event) => {
|
||||
@@ -256,8 +278,15 @@ export class FilesPane {
|
||||
event.preventDefault();
|
||||
this.quickOpen.open();
|
||||
}
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.code === 'KeyS') {
|
||||
event.preventDefault();
|
||||
if (this.active) this.save(this.active);
|
||||
}
|
||||
});
|
||||
this.wireExplorerResize();
|
||||
// Leaving or reloading the page: write pending drafts now, not in 400 ms.
|
||||
window.addEventListener('pagehide', () => this.flushDrafts());
|
||||
window.addEventListener('beforeunload', () => this.flushDrafts());
|
||||
// Narrow pane (phone, or dragged small): the explorer slides over the editor.
|
||||
new ResizeObserver(() => root.classList.toggle('is-narrow', root.clientWidth < 680)).observe(root);
|
||||
this.quickOpen = new CommandPalette(() => this.loadFileList(), {
|
||||
@@ -343,6 +372,7 @@ export class FilesPane {
|
||||
syncSession() {
|
||||
const session = this.hooks.session();
|
||||
if (session === this.session) return false;
|
||||
this.flushDrafts();
|
||||
for (const v of this.views.values()) v.editor?.destroy();
|
||||
this.views.clear();
|
||||
this.listings.clear();
|
||||
@@ -406,7 +436,8 @@ export class FilesPane {
|
||||
|
||||
async loadFileList() {
|
||||
if (this.fileList && Date.now() - this.fileList.at < 60000 && this.fileList.session === this.session) return this.fileList.items;
|
||||
const list = parseListOutput(await runCommand(['--fs-find', this.session], 20000));
|
||||
const list = parseListOutput(await runCommand(['--fs-find', this.session], 45000));
|
||||
this.fileListRoot = list.root;
|
||||
const items = list.files.map((path) => {
|
||||
const name = base(path);
|
||||
const [icon] = iconFor(name);
|
||||
@@ -432,6 +463,9 @@ export class FilesPane {
|
||||
}
|
||||
|
||||
async claudeTurnEnded() {
|
||||
// New files may exist now: refresh the list terminal links are checked against.
|
||||
this.fileList = null;
|
||||
this.knownFiles();
|
||||
if (!this.isOpen) {
|
||||
// Next time it opens it revalidates anyway; open tabs re-check on activation.
|
||||
for (const v of this.views.values()) v.stale = true;
|
||||
@@ -677,8 +711,9 @@ export class FilesPane {
|
||||
|
||||
// Single click opens a preview tab (italic) that the next click replaces;
|
||||
// double click, Enter or go-to-file keeps it.
|
||||
openFile(path, { mode, pin = false } = {}) {
|
||||
const wanted = mode ?? (isMarkdown(path) ? 'preview' : 'view');
|
||||
openFile(path, { mode, pin = false, line } = {}) {
|
||||
// A line number means source: markdown opens as text, not as a preview.
|
||||
const wanted = mode ?? (isMarkdown(path) && !line ? 'preview' : 'view');
|
||||
const key = `${wanted}:${path}`;
|
||||
let tab = this.tabs.find((t) => t.key === key) ?? this.tabs.find((t) => t.path === path && !mode);
|
||||
if (!tab) {
|
||||
@@ -689,12 +724,21 @@ export class FilesPane {
|
||||
this.tabs[preview] = tab;
|
||||
} else {
|
||||
this.tabs.push(tab);
|
||||
while (this.tabs.length > 12) this.closeTab(this.tabs.find((t) => t.key !== key).key, { render: false });
|
||||
while (this.tabs.length > 12) {
|
||||
const victim = this.tabs.find((t) => t.key !== key && !this.views.get(t.key)?.dirty);
|
||||
if (!victim) break;
|
||||
this.closeTab(victim.key, { render: false, force: true });
|
||||
}
|
||||
}
|
||||
} else if (pin) {
|
||||
tab.pinned = true;
|
||||
}
|
||||
this.pushRecent(path);
|
||||
if (line) {
|
||||
const loaded = this.views.get(tab.key)?.editor;
|
||||
if (loaded?.goto) setTimeout(() => loaded.goto(line), 0);
|
||||
else tab.line = line;
|
||||
}
|
||||
this.activate(tab.key);
|
||||
if (this.root.classList.contains('is-narrow')) this.setExplorer(false);
|
||||
}
|
||||
@@ -716,7 +760,34 @@ export class FilesPane {
|
||||
this.renderExplorer();
|
||||
}
|
||||
|
||||
closeTab(key, { render = true } = {}) {
|
||||
flushDrafts() {
|
||||
for (const [key, view] of this.views) {
|
||||
if (!view.editable || !view.draftTimer) continue;
|
||||
clearTimeout(view.draftTimer);
|
||||
view.draftTimer = 0;
|
||||
const tab = this.tabs.find((t) => t.key === key);
|
||||
if (tab) writeDraft(this.session, tab.path, view.dirty ? { text: view.editor.text(), base: view.base, at: Date.now() } : null);
|
||||
}
|
||||
}
|
||||
|
||||
hasDirty() {
|
||||
return [...this.views.values()].some((v) => v.dirty);
|
||||
}
|
||||
|
||||
async closeTab(key, { render = true, force = false } = {}) {
|
||||
const view = this.views.get(key);
|
||||
const tab = this.tabs.find((t) => t.key === key);
|
||||
if (!force && view?.dirty && tab) {
|
||||
const choice = await openDialog({
|
||||
title: `Save changes to ${base(tab.path)}?`,
|
||||
size: 'sm',
|
||||
body: el('p', { class: 'dd-dialog-text' }, `${tab.path} has unsaved changes.`),
|
||||
actions: [{ label: 'Cancel', value: null }, { label: 'Don\'t save', value: 'discard' }, { label: 'Save', primary: true }],
|
||||
});
|
||||
if (!choice) return;
|
||||
if (choice === 'discard') writeDraft(this.session, tab.path, null);
|
||||
else if (!(await this.save(key))) return;
|
||||
}
|
||||
const i = this.tabs.findIndex((t) => t.key === key);
|
||||
if (i < 0) return;
|
||||
this.tabs.splice(i, 1);
|
||||
@@ -731,6 +802,7 @@ export class FilesPane {
|
||||
}
|
||||
|
||||
dropView(key) {
|
||||
clearTimeout(this.views.get(key)?.draftTimer);
|
||||
this.views.get(key)?.editor?.destroy();
|
||||
this.views.get(key)?.node.remove();
|
||||
this.views.delete(key);
|
||||
@@ -742,7 +814,7 @@ export class FilesPane {
|
||||
const change = this.changeFor(tab.path);
|
||||
const status = change ? statusOf(change) : null;
|
||||
return el('div', {
|
||||
class: `dd-tab${tab.key === this.active ? ' is-active' : ''}${tab.pinned ? '' : ' is-preview'}${status ? ` git-${status[2]}` : ''}`,
|
||||
class: `dd-tab${tab.key === this.active ? ' is-active' : ''}${tab.pinned ? '' : ' is-preview'}${status ? ` git-${status[2]}` : ''}${this.views.get(tab.key)?.dirty ? ' is-dirty' : ''}`,
|
||||
role: 'tab', 'aria-selected': String(tab.key === this.active), tabindex: tab.key === this.active ? '0' : '-1',
|
||||
title: `${tab.path}${tab.mode === 'diff' ? ' (diff against HEAD)' : ''}${tab.pinned ? '' : ' · preview: the next file replaces it; double-click to keep'}`,
|
||||
onclick: () => this.activate(tab.key),
|
||||
@@ -758,12 +830,12 @@ export class FilesPane {
|
||||
el('span', { class: 'dd-tab-name' }, name),
|
||||
tab.mode === 'diff' ? el('span', { class: 'dd-tab-tag' }, 'diff') : null,
|
||||
el('button', {
|
||||
type: 'button', class: 'dd-tab-close', 'aria-label': `Close ${name}`, title: 'Close',
|
||||
type: 'button', class: 'dd-tab-close', 'aria-label': `Close ${name}`, title: this.views.get(tab.key)?.dirty ? 'Unsaved changes: close…' : 'Close',
|
||||
onclick: (event) => {
|
||||
event.stopPropagation();
|
||||
this.closeTab(tab.key);
|
||||
},
|
||||
}, '×'));
|
||||
}, this.views.get(tab.key)?.dirty ? '●' : '×'));
|
||||
});
|
||||
this.tabStrip.replaceChildren(...nodes);
|
||||
this.tabStrip.querySelector('.is-active')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
||||
@@ -851,6 +923,10 @@ export class FilesPane {
|
||||
const [{ blob, original }, editor] = await Promise.all([this.fetchTab(tab), loadEditor().catch((error) => ({ error }))]);
|
||||
if (session !== this.session || this.views.get(key) !== view) return;
|
||||
if (blob.header.sha && blob.header.sha === view.header?.sha && tab.mode !== 'diff') return;
|
||||
if (view.dirty) {
|
||||
if (blob.header.sha !== view.base) this.changedOnDisk(key);
|
||||
return;
|
||||
}
|
||||
const scroller = view.node.querySelector('.cm-scroller');
|
||||
const top = scroller?.scrollTop ?? 0;
|
||||
view.editor?.destroy();
|
||||
@@ -863,7 +939,7 @@ export class FilesPane {
|
||||
}
|
||||
}
|
||||
|
||||
bar(tab, header) {
|
||||
bar(tab, header, view) {
|
||||
const change = this.changeFor(tab.path);
|
||||
const meta = header ? [
|
||||
size(header.size ?? 0),
|
||||
@@ -876,6 +952,10 @@ export class FilesPane {
|
||||
const button = (label, run, extra = {}) => el('button', { type: 'button', class: 'dd-viewer-btn', onclick: run, ...extra }, label);
|
||||
const switchMode = (mode) => this.openFile(tab.path, { mode, pin: true });
|
||||
const actions = [];
|
||||
if (view?.editable) {
|
||||
actions.push(button('Save', () => this.save(tab.key), { class: 'dd-viewer-btn is-primary dd-dirty-only', title: 'Save (Ctrl+S)' }));
|
||||
actions.push(button('Revert', () => this.revert(tab.key), { class: 'dd-viewer-btn dd-dirty-only', title: 'Discard your changes' }));
|
||||
}
|
||||
if (tab.mode !== 'diff' && isMarkdown(tab.path)) actions.push(button(tab.mode === 'preview' ? 'Source' : 'Preview', () => switchMode(tab.mode === 'preview' ? 'view' : 'preview')));
|
||||
if (change && change.x !== '?' && change.y !== '?' && this.changes?.git) {
|
||||
actions.push(button(tab.mode === 'diff' ? 'File' : 'Diff', () => switchMode(tab.mode === 'diff' ? (isMarkdown(tab.path) ? 'preview' : 'view') : 'diff')));
|
||||
@@ -897,7 +977,8 @@ export class FilesPane {
|
||||
return el('div', { class: 'dd-viewer-bar' },
|
||||
el('span', { class: 'dd-viewer-where', title: [tab.path, meta].filter(Boolean).join('\n') },
|
||||
el('span', { class: 'dd-viewer-path' }, tab.path),
|
||||
meta ? el('span', { class: 'dd-viewer-meta' }, ` · ${meta}`) : null),
|
||||
meta ? el('span', { class: 'dd-viewer-meta' }, ` · ${meta}`) : null,
|
||||
view?.editable ? el('span', { class: 'dd-unsaved dd-dirty-only' }, ' · unsaved') : null),
|
||||
el('span', { class: 'dd-viewer-actions' }, ...actions));
|
||||
}
|
||||
|
||||
@@ -917,20 +998,301 @@ export class FilesPane {
|
||||
content.append(el('pre', { class: 'dd-plain' }, text(base64, header.utf8)));
|
||||
} else if (tab.mode === 'preview') {
|
||||
content.classList.add('is-preview');
|
||||
// Unsaved edits in the Source tab show in the preview too.
|
||||
const source = this.views.get(`view:${tab.path}`);
|
||||
const md = source?.dirty ? source.editor.text() : text(base64);
|
||||
const frame = el('iframe', {
|
||||
class: 'dd-md-frame', title: `Preview of ${tab.path}`,
|
||||
sandbox: 'allow-popups allow-popups-to-escape-sandbox', srcdoc: previewDocument(editor.markdown(text(base64))),
|
||||
sandbox: 'allow-popups allow-popups-to-escape-sandbox', srcdoc: previewDocument(editor.markdown(md)),
|
||||
});
|
||||
content.append(frame);
|
||||
inlineImages(editor.markdown(text(base64)), this.session, tab.path).then((html) => {
|
||||
inlineImages(editor.markdown(md), this.session, tab.path).then((html) => {
|
||||
if (frame.isConnected) frame.srcdoc = previewDocument(html);
|
||||
});
|
||||
} else if (tab.mode === 'diff') {
|
||||
view.editor = editor.diff(content, { original: text(original?.base64), modified: text(base64), path: tab.path, wrap: this.wrap });
|
||||
} else if (header.utf8 === false) {
|
||||
// Not UTF-8: shown as Latin-1, read-only (saving would change the bytes).
|
||||
view.editor = editor.viewer(content, { doc: text(base64, false), path: tab.path, wrap: this.wrap });
|
||||
} else {
|
||||
view.editor = editor.viewer(content, { doc: text(base64, header.utf8), path: tab.path, wrap: this.wrap });
|
||||
const disk = text(base64);
|
||||
const draft = readDraft(this.session, tab.path);
|
||||
let doc = disk;
|
||||
let banner = null;
|
||||
if (draft && draft.text !== disk) {
|
||||
if (draft.base === header.sha) {
|
||||
doc = draft.text;
|
||||
toast.info(`Restored your unsaved changes to ${tab.path}`);
|
||||
} else {
|
||||
banner = draft;
|
||||
}
|
||||
}
|
||||
view.editable = true;
|
||||
view.saved = disk;
|
||||
view.base = header.sha;
|
||||
view.editor = editor.editor(content, {
|
||||
doc, path: tab.path, wrap: this.wrap,
|
||||
onChange: (now) => this.edited(tab.key, now),
|
||||
onSave: () => this.save(tab.key),
|
||||
});
|
||||
view.dirty = doc !== disk;
|
||||
view.node.classList.toggle('is-dirty', view.dirty);
|
||||
view.node.replaceChildren(this.bar(tab, header, view), content);
|
||||
if (banner) this.oldDraft(tab.key, banner);
|
||||
if (view.dirty) this.renderTabs();
|
||||
this.gotoPending(tab, view);
|
||||
return;
|
||||
}
|
||||
view.node.replaceChildren(this.bar(tab, header, view), content);
|
||||
this.gotoPending(tab, view);
|
||||
}
|
||||
|
||||
gotoPending(tab, view) {
|
||||
if (!tab.line || !view.editor?.goto) return;
|
||||
const line = tab.line;
|
||||
delete tab.line;
|
||||
setTimeout(() => view.editor.goto(line), 0);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ paths in the terminal (devdesk#21)
|
||||
|
||||
// The session's file list (cached by go-to-file). Loaded ahead of time (on
|
||||
// connect and after Claude's turns): xterm asks for a line's links once and
|
||||
// caches the answer, so it has to be ready before the first hover.
|
||||
knownFiles() {
|
||||
if (this.session !== this.hooks.session()) this.syncSession();
|
||||
if (this.fileList?.session === this.session) {
|
||||
if (!this.fileSet || this.fileSet.list !== this.fileList.items) {
|
||||
this.fileSet = { list: this.fileList.items, set: new Set(this.fileList.items.map((x) => x.id)) };
|
||||
}
|
||||
return this.fileSet.set;
|
||||
}
|
||||
if (!this.loadingList && this.session) {
|
||||
this.loadingList = true;
|
||||
this.loadFileList().catch(() => {}).finally(() => { this.loadingList = false; });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// A path as printed in the terminal -> the session-relative path, if it's a
|
||||
// file of this session (absolute paths inside the folder count too).
|
||||
resolvePrinted(text) {
|
||||
const known = this.knownFiles();
|
||||
if (!known) return null;
|
||||
let path = text.replace(/^\.\//, '');
|
||||
const root = this.fileListRoot;
|
||||
if (path.startsWith('/') && root && path.startsWith(`${root}/`)) path = path.slice(root.length + 1);
|
||||
return known.has(path) ? path : null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ editing (devdesk#20)
|
||||
|
||||
edited(key, now) {
|
||||
const view = this.views.get(key);
|
||||
const tab = this.tabs.find((t) => t.key === key);
|
||||
if (!view || !tab) return;
|
||||
const dirty = now !== view.saved;
|
||||
if (dirty && !tab.pinned) {
|
||||
tab.pinned = true; // editing keeps a preview tab
|
||||
this.saveState();
|
||||
}
|
||||
clearTimeout(view.draftTimer);
|
||||
view.draftTimer = setTimeout(() => writeDraft(this.session, tab.path, dirty ? { text: now, base: view.base, at: Date.now() } : null), 400);
|
||||
if (dirty !== view.dirty) {
|
||||
view.dirty = dirty;
|
||||
view.node.classList.toggle('is-dirty', dirty);
|
||||
this.renderTabs();
|
||||
}
|
||||
}
|
||||
|
||||
// Resolves true when saved. A conflict (the file changed on disk since it was
|
||||
// opened) asks before overwriting.
|
||||
async save(key, { base: forced } = {}) {
|
||||
const view = this.views.get(key);
|
||||
const tab = this.tabs.find((t) => t.key === key);
|
||||
if (!view?.editable || !tab || view.saving) return false;
|
||||
if (!view.dirty && !forced) return true;
|
||||
const now = view.editor.text();
|
||||
view.saving = true;
|
||||
try {
|
||||
const result = await writeFile(this.session, tab.path, new TextEncoder().encode(now), forced ?? view.base ?? 'new');
|
||||
if (result.conflict) return this.conflict(key, result.sha);
|
||||
if (!result.ok) throw new Error('not saved');
|
||||
view.saved = now;
|
||||
view.base = result.sha;
|
||||
view.header = { ...view.header, sha: result.sha, size: result.size, mtime: result.mtime };
|
||||
clearTimeout(view.draftTimer);
|
||||
writeDraft(this.session, tab.path, null);
|
||||
this.edited(key, view.editor.text());
|
||||
view.node.querySelector('.dd-viewer-banner')?.remove();
|
||||
toast.success(`Saved ${tab.path}`);
|
||||
this.loadChanges();
|
||||
this.fileList = null;
|
||||
return true;
|
||||
} catch (error) {
|
||||
toast.error(`Could not save ${tab.path}: ${error.message}`);
|
||||
return false;
|
||||
} finally {
|
||||
view.saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
revert(key) {
|
||||
const view = this.views.get(key);
|
||||
const tab = this.tabs.find((t) => t.key === key);
|
||||
if (!view?.editable || !tab) return;
|
||||
clearTimeout(view.draftTimer);
|
||||
writeDraft(this.session, tab.path, null);
|
||||
view.editor.setText(view.saved);
|
||||
view.node.querySelector('.dd-viewer-banner')?.remove();
|
||||
}
|
||||
|
||||
async diskText(path) {
|
||||
const { header, base64 } = await runBlob(['--fs-read', this.session, path]);
|
||||
return { sha: header.sha, text: new TextDecoder().decode(decodeBase64(base64 || '')) };
|
||||
}
|
||||
|
||||
async conflict(key, diskSha) {
|
||||
const tab = this.tabs.find((t) => t.key === key);
|
||||
const choice = await openDialog({
|
||||
title: `${base(tab.path)} changed on disk`,
|
||||
size: 'sm',
|
||||
body: el('p', { class: 'dd-dialog-text' }, `Someone (probably Claude) changed ${tab.path} after you opened it. Saving now would overwrite that.`),
|
||||
actions: [{ label: 'Cancel', value: null }, { label: 'Compare', value: 'compare' }, { label: 'Overwrite', primary: true, danger: true }],
|
||||
danger: true,
|
||||
});
|
||||
if (choice === 'compare') return this.compare(key);
|
||||
if (choice) return this.save(key, { base: diskSha });
|
||||
return false;
|
||||
}
|
||||
|
||||
// Disk version vs yours, side by side in a unified diff; pick one.
|
||||
async compare(key) {
|
||||
const view = this.views.get(key);
|
||||
const tab = this.tabs.find((t) => t.key === key);
|
||||
if (!view || !tab) return false;
|
||||
let disk;
|
||||
let editor;
|
||||
try {
|
||||
[disk, editor] = await Promise.all([this.diskText(tab.path), loadEditor()]);
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
return false;
|
||||
}
|
||||
const holder = el('div', { class: 'dd-compare' });
|
||||
let diffView = null;
|
||||
const choice = await openDialog({
|
||||
title: `${tab.path}: disk (red) vs yours (green)`,
|
||||
className: 'is-wide',
|
||||
body: holder,
|
||||
onOpen: () => {
|
||||
diffView = editor.diff(holder, { original: disk.text, modified: view.editor.text(), path: tab.path, wrap: this.wrap });
|
||||
return holder.querySelector('.cm-content');
|
||||
},
|
||||
actions: [{ label: 'Close', value: null }, { label: 'Take the disk version', value: 'disk' }, { label: 'Save mine', primary: true }],
|
||||
});
|
||||
diffView?.destroy();
|
||||
if (choice === 'disk') {
|
||||
view.saved = disk.text;
|
||||
view.base = disk.sha;
|
||||
view.header = { ...view.header, sha: disk.sha };
|
||||
view.editor.setText(disk.text);
|
||||
writeDraft(this.session, tab.path, null);
|
||||
view.node.querySelector('.dd-viewer-banner')?.remove();
|
||||
return false;
|
||||
}
|
||||
if (choice) return this.save(key, { base: disk.sha });
|
||||
return false;
|
||||
}
|
||||
|
||||
banner(key, text, actions) {
|
||||
const view = this.views.get(key);
|
||||
if (!view) return;
|
||||
view.node.querySelector('.dd-viewer-banner')?.remove();
|
||||
const node = el('div', { class: 'dd-viewer-banner', role: 'alert' }, el('span', {}, text),
|
||||
...actions.map(([label, run]) => el('button', { type: 'button', class: 'dd-viewer-btn', onclick: run }, label)));
|
||||
view.node.querySelector('.dd-viewer-bar')?.after(node);
|
||||
}
|
||||
|
||||
// Claude changed a file you're editing: nothing is replaced until you choose.
|
||||
changedOnDisk(key) {
|
||||
this.banner(key, 'This file changed on disk while you were editing it.', [
|
||||
['Compare', () => this.compare(key)],
|
||||
['Reload (discard mine)', () => {
|
||||
this.revert(key);
|
||||
this.dropView(key);
|
||||
this.renderEditor();
|
||||
}],
|
||||
['Keep mine', () => this.views.get(key)?.node.querySelector('.dd-viewer-banner')?.remove()],
|
||||
]);
|
||||
}
|
||||
|
||||
// Unsaved changes from an earlier visit, but the file changed since.
|
||||
oldDraft(key, draft) {
|
||||
const view = this.views.get(key);
|
||||
const tab = this.tabs.find((t) => t.key === key);
|
||||
const age = ago(Math.floor(draft.at / 1000));
|
||||
this.banner(key, `You have unsaved changes from ${age === 'now' ? 'a moment ago' : `${age} ago`}, but the file changed on disk since.`, [
|
||||
['Compare', async () => {
|
||||
view.editor.setText(draft.text);
|
||||
await this.compare(key);
|
||||
}],
|
||||
['Restore mine', () => {
|
||||
view.editor.setText(draft.text);
|
||||
view.node.querySelector('.dd-viewer-banner')?.remove();
|
||||
}],
|
||||
['Discard', () => {
|
||||
writeDraft(this.session, tab.path, null);
|
||||
view.node.querySelector('.dd-viewer-banner')?.remove();
|
||||
}],
|
||||
]);
|
||||
}
|
||||
|
||||
// New file in the folder you're looking at (folders are created as needed).
|
||||
async newFile() {
|
||||
if (!this.session) return;
|
||||
const activePath = this.tabs.find((t) => t.key === this.active)?.path;
|
||||
const row = this.treeRows?.[this.focusIndex];
|
||||
const folder = row?.kind === 'dir' ? row.path : parent(row?.path ?? activePath ?? '');
|
||||
const input = el('input', { class: 'lt-input', value: folder ? `${folder}/` : '', spellcheck: 'false', autocomplete: 'off', 'aria-describedby': 'dd-newfile-hint' });
|
||||
const hint = el('p', { class: 'dd-dialog-hint', id: 'dd-newfile-hint' }, `Relative to ${this.listings.get('')?.root ?? 'the session folder'}. Missing folders are created.`);
|
||||
const path = await openDialog({
|
||||
title: 'New file',
|
||||
size: 'sm',
|
||||
body: el('div', { class: 'dd-dialog-fields' }, el('label', { class: 'dd-field' }, el('span', {}, 'Path'), input), hint),
|
||||
actions: [{ label: 'Cancel' }, { label: 'Create', primary: true }],
|
||||
onOpen: () => {
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
return input;
|
||||
},
|
||||
submit: () => {
|
||||
const value = input.value.trim().replace(/^\/+/, '');
|
||||
if (!value || value.endsWith('/') || value.split('/').some((part) => part === '..' || part === '.')) {
|
||||
hint.textContent = 'Type a file name (no .. or trailing /).';
|
||||
hint.classList.add('is-error');
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
},
|
||||
});
|
||||
if (!path) return;
|
||||
try {
|
||||
const result = await writeFile(this.session, path, new Uint8Array(0), 'new');
|
||||
if (!result.ok) throw new Error('not created');
|
||||
// Show it: re-list every folder above the new file and open them.
|
||||
const parts = result.path.split('/').slice(0, -1);
|
||||
for (let i = 0; i <= parts.length; i += 1) {
|
||||
const dir = parts.slice(0, i).join('/');
|
||||
if (dir) this.expanded.add(dir);
|
||||
this.listDir(dir);
|
||||
}
|
||||
this.saveState();
|
||||
this.fileList = null;
|
||||
this.openFile(result.path, { mode: 'view', pin: true });
|
||||
toast.success(`Created ${result.path}`);
|
||||
} catch (error) {
|
||||
toast.error(`Could not create ${path}: ${error.message}`);
|
||||
}
|
||||
view.node.replaceChildren(this.bar(tab, header), content);
|
||||
}
|
||||
|
||||
// Theme switch: the editor follows CSS variables; previews need a re-render.
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// Search past conversations (devdesk#24): every Claude conversation on this host
|
||||
// (DevDesk and code-server), by what you asked, what Claude said, the commands
|
||||
// it ran and their output. Resume one in a new session, or fork it.
|
||||
|
||||
import { runCommand, sessionAction } from './connection.js';
|
||||
import { parseListOutput, slugify } from './protocol.js';
|
||||
import { el } from './dom.js';
|
||||
import { ago } from './sessions.js';
|
||||
import { openDialog, toast } from './ui.js';
|
||||
|
||||
const ROLE = { you: 'You', claude: 'Claude', command: 'Ran', output: 'Output' };
|
||||
|
||||
// Text with every case-insensitive occurrence of `query` in <mark>.
|
||||
function highlight(text, query) {
|
||||
const nodes = [];
|
||||
const lower = text.toLowerCase();
|
||||
const q = query.toLowerCase();
|
||||
let at = 0;
|
||||
for (let i = lower.indexOf(q); i >= 0 && q; i = lower.indexOf(q, at)) {
|
||||
if (i > at) nodes.push(text.slice(at, i));
|
||||
nodes.push(el('mark', {}, text.slice(i, i + q.length)));
|
||||
at = i + q.length;
|
||||
}
|
||||
nodes.push(text.slice(at));
|
||||
return nodes;
|
||||
}
|
||||
|
||||
const day = (iso) => (iso ? new Date(iso).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : '');
|
||||
|
||||
// hooks: sessions() -> session list, open(name), refresh()
|
||||
export function openHistory(hooks) {
|
||||
const input = el('input', { class: 'lt-input dd-history-input', type: 'search', placeholder: 'What did you work on? e.g. "NFS mount", "pct exec 167", "no_root_squash"', spellcheck: 'false', autocomplete: 'off' });
|
||||
const status = el('div', { class: 'dd-dialog-hint' }, 'Searches every Claude conversation on this host: your prompts, Claude\'s answers, the commands it ran and their output.');
|
||||
const results = el('div', { class: 'dd-history-results' });
|
||||
let seq = 0;
|
||||
let timer = 0;
|
||||
let close = null;
|
||||
|
||||
const liveSessionFor = (id) => hooks.sessions().find((s) => s.running && s.claude_session_id === id)?.name;
|
||||
|
||||
// Resume or fork: confirm the new session's name inline, then open it.
|
||||
const start = (result, fork, holder) => {
|
||||
const name = el('input', { class: 'lt-input', value: slugify(`${fork ? 'fork-' : ''}${result.title}`).slice(0, 40) || 'resumed', spellcheck: 'false' });
|
||||
const go = async () => {
|
||||
const value = slugify(name.value);
|
||||
if (!value) return;
|
||||
try {
|
||||
await sessionAction('resume-convo', value, result.id, ...(fork ? ['fork'] : []));
|
||||
close?.();
|
||||
toast.success(`${fork ? 'Forked' : 'Resumed'} “${result.title.slice(0, 40)}” in ${value}`);
|
||||
hooks.refresh();
|
||||
hooks.open(value);
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
};
|
||||
name.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
go();
|
||||
}
|
||||
});
|
||||
holder.replaceChildren(el('span', { class: 'dd-dialog-hint' }, `New session for ${fork ? 'a fork of ' : ''}this conversation:`), name,
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-primary lt-btn-sm', onclick: go }, fork ? 'Fork' : 'Resume'));
|
||||
name.focus();
|
||||
name.select();
|
||||
};
|
||||
|
||||
const render = (data) => {
|
||||
if (!data.results.length) {
|
||||
results.replaceChildren(el('div', { class: 'dd-files-msg' }, `Nothing found for “${data.query}”.`));
|
||||
return;
|
||||
}
|
||||
results.replaceChildren(...data.results.map((r) => {
|
||||
const live = liveSessionFor(r.id);
|
||||
const actions = el('div', { class: 'dd-history-actions' });
|
||||
const fill = () => actions.replaceChildren(
|
||||
live
|
||||
? el('button', { type: 'button', class: 'lt-btn lt-btn-primary lt-btn-sm', onclick: () => { close?.(); hooks.open(live); } }, `Open ${live}`)
|
||||
: el('button', { type: 'button', class: 'lt-btn lt-btn-primary lt-btn-sm', onclick: () => start(r, false, actions) }, 'Resume…'),
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-sm', onclick: () => start(r, true, actions), title: 'Continue as a new conversation; the original stays as it is' }, 'Fork…'),
|
||||
el('button', {
|
||||
type: 'button', class: 'lt-btn lt-btn-ghost lt-btn-sm',
|
||||
onclick: () => navigator.clipboard?.writeText(`claude --resume ${r.id}`).then(() => toast.success('Copied the resume command')),
|
||||
}, 'Copy command'));
|
||||
fill();
|
||||
return el('div', { class: 'dd-history-item' },
|
||||
el('div', { class: 'dd-history-title' }, r.title),
|
||||
el('div', { class: 'dd-history-meta' },
|
||||
[r.cwd, day(r.started), `updated ${ago(r.updated)}${ago(r.updated) === 'now' ? '' : ' ago'}`, `${r.hits} match${r.hits === 1 ? '' : 'es'}`, live ? `open in ${live}` : '']
|
||||
.filter(Boolean).join(' · ')),
|
||||
...r.matches.map((m) => el('div', { class: `dd-history-snippet is-${m.role}` },
|
||||
el('span', { class: 'dd-history-role' }, ROLE[m.role] ?? m.role), el('span', {}, ...highlight(m.snippet, data.query)))),
|
||||
actions);
|
||||
}));
|
||||
};
|
||||
|
||||
const search = async () => {
|
||||
const query = input.value.trim();
|
||||
if (query.length < 2) return;
|
||||
const mine = ++seq;
|
||||
status.textContent = `Searching for “${query}”…`;
|
||||
try {
|
||||
const data = parseListOutput(await runCommand(['--search', query], 30000));
|
||||
if (mine !== seq) return;
|
||||
const n = data.results.length;
|
||||
status.textContent = `${n}${n === 25 ? '+' : ''} conversation${n === 1 ? ' mentions' : 's mention'} “${query}”, newest first.`;
|
||||
render(data);
|
||||
} catch (error) {
|
||||
if (mine === seq) status.textContent = error.message;
|
||||
}
|
||||
};
|
||||
input.addEventListener('input', () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(search, 500);
|
||||
});
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
clearTimeout(timer);
|
||||
search();
|
||||
}
|
||||
});
|
||||
|
||||
openDialog({
|
||||
title: 'Search past conversations',
|
||||
className: 'is-wide',
|
||||
body: el('div', { class: 'dd-history' }, input, status, results),
|
||||
actions: [{ label: 'Close', value: null }],
|
||||
onOpen: (overlay) => {
|
||||
close = () => overlay.querySelector('.lt-modal-close')?.click();
|
||||
return input;
|
||||
},
|
||||
});
|
||||
}
|
||||
+151
-10
@@ -5,14 +5,17 @@
|
||||
|
||||
import { el } from './dom.js';
|
||||
import { ago } from './sessions.js';
|
||||
import { answerPrompt, peekSession, replyTo } from './connection.js';
|
||||
import { toast } from './ui.js';
|
||||
|
||||
const KEY = 'devdesk.inbox';
|
||||
const MAX = 30;
|
||||
const MAX_AGE = 7 * 86400 * 1000;
|
||||
|
||||
function load() {
|
||||
try {
|
||||
const list = JSON.parse(localStorage.getItem(KEY) || '[]');
|
||||
return Array.isArray(list) ? list : [];
|
||||
return Array.isArray(list) ? list.filter((e) => Date.now() - e.at < MAX_AGE) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
@@ -45,6 +48,7 @@ export class Inbox {
|
||||
this.events = load();
|
||||
this.waiting = [];
|
||||
this.alerts = [];
|
||||
this.known = null; // session names that exist, once the list has loaded
|
||||
this.list = panel.querySelector('.lt-notif-panel-list');
|
||||
panel.querySelector('.lt-notif-panel-clear').addEventListener('click', () => this.markAllRead());
|
||||
window.addEventListener('storage', (event) => {
|
||||
@@ -63,7 +67,29 @@ export class Inbox {
|
||||
if (open) this.panel.removeAttribute('aria-hidden');
|
||||
else this.panel.setAttribute('aria-hidden', 'true');
|
||||
this.button.setAttribute('aria-expanded', String(open));
|
||||
if (open) this.render();
|
||||
if (!open) this.peeking = null;
|
||||
this.panel.classList.toggle('is-peek', false);
|
||||
if (open) {
|
||||
this.render();
|
||||
this.markSeen();
|
||||
}
|
||||
}
|
||||
|
||||
// Opening the bell counts as seeing what's in it (devdesk#42): the badge clears
|
||||
// but the entries keep their highlight until the panel is redrawn.
|
||||
markSeen() {
|
||||
if (!this.events.some((e) => !e.read)) return;
|
||||
this.events = this.events.map((e) => ({ ...e, read: true }));
|
||||
save(this.events);
|
||||
this.renderBadge();
|
||||
}
|
||||
|
||||
// Looking at a session reads what it reported (finished, waiting) while you were away.
|
||||
markSessionRead(session) {
|
||||
if (!session || !this.events.some((e) => !e.read && e.session === session && !e.url)) return;
|
||||
this.events = this.events.map((e) => (e.session === session && !e.url ? { ...e, read: true } : e));
|
||||
save(this.events);
|
||||
this.render();
|
||||
}
|
||||
|
||||
// Something happened. The same kind for the same session within a minute is
|
||||
@@ -78,9 +104,10 @@ export class Inbox {
|
||||
}
|
||||
|
||||
// Live state: other sessions waiting on you, firing alerts.
|
||||
setLive({ waiting, alerts }) {
|
||||
setLive({ waiting, alerts, sessions }) {
|
||||
if (waiting) this.waiting = waiting;
|
||||
if (alerts) this.alerts = alerts;
|
||||
if (sessions) this.known = new Set(sessions);
|
||||
this.render();
|
||||
}
|
||||
|
||||
@@ -91,10 +118,15 @@ export class Inbox {
|
||||
}
|
||||
|
||||
unread() {
|
||||
return this.events.filter((e) => !e.read && e.kind !== 'waiting').length;
|
||||
return this.events.filter((e) => !e.read && e.kind !== 'waiting' && !(this.known && e.session && !e.url && !this.known.has(e.session))).length;
|
||||
}
|
||||
|
||||
render() {
|
||||
this.renderBadge();
|
||||
if (this.isOpen) this.renderPanel();
|
||||
}
|
||||
|
||||
renderBadge() {
|
||||
const count = this.waiting.length + this.alerts.length + this.unread();
|
||||
const urgent = this.waiting.length > 0 || this.alerts.some((a) => a.severity === 'critical');
|
||||
this.badge.textContent = count ? String(count) : '';
|
||||
@@ -107,10 +139,90 @@ export class Inbox {
|
||||
this.unread() && `${this.unread()} new event(s)`,
|
||||
].filter(Boolean).join(' · ')
|
||||
: 'Inbox: nothing new';
|
||||
if (this.isOpen) this.renderPanel();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ answer from here
|
||||
|
||||
async answer(session, since, choice, button) {
|
||||
button.disabled = true;
|
||||
try {
|
||||
await answerPrompt(session, since, choice);
|
||||
toast.success(choice === 'allow' ? `Allowed in ${session}` : `Denied in ${session}`);
|
||||
this.hooks.refresh?.();
|
||||
} catch (error) {
|
||||
toast.error(`${session}: ${error.message}`);
|
||||
this.hooks.refresh?.();
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Peek: the last exchange of a session, and a reply box.
|
||||
async peek(session) {
|
||||
this.peeking = session;
|
||||
this.panel.classList.add('is-peek');
|
||||
const body = el('div', { class: 'dd-peek' }, el('div', { class: 'dd-notif-empty' }, 'Loading…'));
|
||||
this.list.replaceChildren(body);
|
||||
let data;
|
||||
try {
|
||||
data = await peekSession(session);
|
||||
} catch (error) {
|
||||
body.replaceChildren(el('div', { class: 'dd-notif-empty' }, error.message));
|
||||
return;
|
||||
}
|
||||
if (this.peeking !== session) return;
|
||||
const input = el('textarea', { class: 'lt-input dd-peek-input', rows: '3', placeholder: `Reply to ${session}… (Ctrl+Enter sends)`, 'aria-label': `Reply to ${session}` });
|
||||
const send = el('button', { type: 'button', class: 'lt-btn lt-btn-primary lt-btn-sm' }, 'Send');
|
||||
const submit = async () => {
|
||||
const text = input.value.trim();
|
||||
if (!text) return;
|
||||
send.disabled = true;
|
||||
try {
|
||||
await replyTo(session, text);
|
||||
toast.success(`Sent to ${session}`);
|
||||
this.peeking = null;
|
||||
this.setOpen(false);
|
||||
this.hooks.refresh?.();
|
||||
} catch (error) {
|
||||
toast.error(`${session}: ${error.message}`);
|
||||
} finally {
|
||||
send.disabled = false;
|
||||
}
|
||||
};
|
||||
send.addEventListener('click', submit);
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
|
||||
event.preventDefault();
|
||||
submit();
|
||||
}
|
||||
event.stopPropagation(); // keys belong to the reply box, not the terminal or shortcuts
|
||||
});
|
||||
const status = data.status;
|
||||
const waitingRequest = status?.state === 'waiting' && status.request;
|
||||
body.replaceChildren(
|
||||
el('div', { class: 'dd-peek-head' },
|
||||
el('button', { type: 'button', class: 'dd-peek-back', onclick: () => { this.peeking = null; this.panel.classList.remove('is-peek'); this.renderPanel(); } }, '←'),
|
||||
el('span', { class: 'dd-peek-title' }, session),
|
||||
el('span', { class: 'dd-peek-state' }, status?.state ? `${status.state}${status.since ? ` · ${ago(status.since)}` : ''}` : '')),
|
||||
data.user ? el('div', { class: 'dd-peek-user' }, el('span', { class: 'dd-peek-label' }, 'You'), data.user.text) : null,
|
||||
el('div', { class: 'dd-peek-assistant' },
|
||||
el('span', { class: 'dd-peek-label' }, 'Claude'),
|
||||
data.assistant ? `${data.assistant.truncated ? '…' : ''}${data.assistant.text}` : 'Nothing yet.'),
|
||||
data.commands?.length ? el('div', { class: 'dd-peek-commands' },
|
||||
el('span', { class: 'dd-peek-label' }, 'Recent commands'),
|
||||
...data.commands.slice(-8).map((c) => el('div', { class: 'dd-peek-command', title: c.cmd },
|
||||
el('span', { class: 'dd-peek-when' }, ago(c.at)), el('code', {}, c.cmd)))) : null,
|
||||
waitingRequest
|
||||
? el('div', { class: 'dd-notif-empty' }, 'Claude is asking for a permission: answer it from the list, or open the session.')
|
||||
: el('div', { class: 'dd-peek-reply' }, input, el('div', { class: 'dd-peek-actions' },
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-ghost lt-btn-sm', onclick: () => { this.setOpen(false); this.hooks.openSession(session); } }, 'Open session'),
|
||||
send)));
|
||||
if (!waitingRequest) input.focus();
|
||||
body.querySelector('.dd-peek-assistant').scrollTop = 1e9;
|
||||
}
|
||||
|
||||
renderPanel() {
|
||||
if (this.peeking) return; // the peek view stays until you go back
|
||||
const close = (run) => () => {
|
||||
this.setOpen(false);
|
||||
run();
|
||||
@@ -133,11 +245,31 @@ export class Inbox {
|
||||
if (this.waiting.length) {
|
||||
nodes.push(el('div', { class: 'dd-notif-section' }, 'Needs you'));
|
||||
for (const s of this.waiting) {
|
||||
nodes.push(item({
|
||||
const request = s.status?.request;
|
||||
const node = item({
|
||||
dot: 'red', unread: true, title: `${s.name}: ${s.status?.message || 'Claude is waiting for your input'}`,
|
||||
meta: s.status?.since ? `waiting ${ago(s.status.since)}` : 'waiting',
|
||||
onclick: close(() => this.hooks.openSession(s.name)),
|
||||
}));
|
||||
});
|
||||
const stop = (run) => (event) => {
|
||||
event.stopPropagation();
|
||||
run(event.currentTarget);
|
||||
};
|
||||
const body = node.querySelector('.lt-notif-item-body');
|
||||
if (request) {
|
||||
body.append(
|
||||
request.description ? el('div', { class: 'dd-request-desc' }, request.description) : null,
|
||||
el('code', { class: 'dd-request' }, request.detail || request.tool),
|
||||
el('div', { class: 'dd-request-actions' },
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-primary lt-btn-sm', onclick: stop((b) => this.answer(s.name, s.status.since, 'allow', b)) }, 'Allow'),
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-danger lt-btn-sm', onclick: stop((b) => this.answer(s.name, s.status.since, 'deny', b)) }, 'Deny'),
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-ghost lt-btn-sm', onclick: stop(() => { this.setOpen(false); this.hooks.openSession(s.name); }) }, 'Open')));
|
||||
} else {
|
||||
body.append(el('div', { class: 'dd-request-actions' },
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-sm', onclick: stop(() => this.peek(s.name)) }, 'Peek & reply'),
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-ghost lt-btn-sm', onclick: stop(() => { this.setOpen(false); this.hooks.openSession(s.name); }) }, 'Open')));
|
||||
}
|
||||
nodes.push(node);
|
||||
}
|
||||
}
|
||||
if (this.alerts.length) {
|
||||
@@ -155,15 +287,24 @@ export class Inbox {
|
||||
nodes.push(el('div', { class: 'dd-notif-section' }, 'Recent'));
|
||||
for (const e of recent.slice(0, 12)) {
|
||||
const kind = KINDS[e.kind] ?? { tone: 'cyan' };
|
||||
nodes.push(item({
|
||||
dot: e.read ? 'read' : kind.tone, unread: !e.read, title: e.text, meta: when(e.at),
|
||||
// An entry about a session that has since ended must not bring it back (devdesk#38).
|
||||
const ended = !e.url && e.session && this.known && !this.known.has(e.session);
|
||||
const recentNode = item({
|
||||
dot: e.read || ended ? 'read' : kind.tone, unread: !e.read && !ended, title: e.text,
|
||||
meta: `${when(e.at)}${ended ? ' · session ended' : ''}`,
|
||||
onclick: close(() => {
|
||||
this.events = this.events.map((x) => (x.id === e.id ? { ...x, read: true } : x));
|
||||
save(this.events);
|
||||
if (e.url) window.open(e.url, '_blank', 'noopener');
|
||||
else if (ended) this.hooks.ended?.(e.session);
|
||||
else if (e.session) this.hooks.openSession(e.session);
|
||||
}),
|
||||
}));
|
||||
});
|
||||
if (e.kind === 'finished' && !ended) {
|
||||
recentNode.querySelector('.lt-notif-item-body').append(el('div', { class: 'dd-request-actions' },
|
||||
el('button', { type: 'button', class: 'lt-btn lt-btn-ghost lt-btn-sm', onclick: (event) => { event.stopPropagation(); this.peek(e.session); } }, 'Peek & reply')));
|
||||
}
|
||||
nodes.push(recentNode);
|
||||
}
|
||||
}
|
||||
if (!nodes.length) nodes.push(el('div', { class: 'dd-notif-empty' }, 'Nothing needs you. Sessions that finish or wait while you\'re elsewhere show up here.'));
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// File paths in the terminal become links (devdesk#21): click one in Claude's
|
||||
// output (web/src/files.js, ./notes.md:12, /root/code/x/y.py:3:9) to open it in
|
||||
// the Files pane, at that line if there is one. Only paths that are files of
|
||||
// the session become links, so words and URLs are left alone.
|
||||
|
||||
// A path: optional ./ ../ or /, segments, and either a slash or an extension;
|
||||
// then an optional :line[:col].
|
||||
const PATH_RE = /(?<![\w/.@~+-])((?:\.{1,2}\/|\/)?(?:[\w@+~-][\w.@+~-]*\/)*[\w@+~-][\w.@+~-]*(?:\.[A-Za-z0-9]{1,10})?)(?::(\d+)(?::(\d+))?)?/g;
|
||||
const URL_RE = /\b[a-z][a-z0-9+.-]*:\/\/\S+/gi;
|
||||
|
||||
export function findPaths(text) {
|
||||
const urls = [...text.matchAll(URL_RE)].map((m) => [m.index, m.index + m[0].length]);
|
||||
const out = [];
|
||||
for (const m of text.matchAll(PATH_RE)) {
|
||||
const candidate = m[1];
|
||||
if (!candidate.includes('/') && !/\.[A-Za-z0-9]{1,10}$/.test(candidate)) continue;
|
||||
if (urls.some(([a, b]) => m.index >= a && m.index < b)) continue;
|
||||
out.push({ index: m.index, length: m[0].length, path: candidate, line: m[2] ? Number(m[2]) : undefined });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function registerPathLinks(term, { resolve, open }) {
|
||||
term.registerLinkProvider({
|
||||
provideLinks(y, callback) {
|
||||
const line = term.buffer.active.getLine(y - 1);
|
||||
if (!line) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
const links = [];
|
||||
for (const found of findPaths(line.translateToString(true))) {
|
||||
const path = resolve(found.path);
|
||||
if (!path) continue;
|
||||
links.push({
|
||||
range: { start: { x: found.index + 1, y }, end: { x: found.index + found.length, y } },
|
||||
text: path,
|
||||
decorations: { underline: true, pointerCursor: true },
|
||||
activate: () => open(path, found.line),
|
||||
});
|
||||
}
|
||||
callback(links.length ? links : undefined);
|
||||
},
|
||||
});
|
||||
}
|
||||
+163
-18
@@ -2,10 +2,10 @@
|
||||
import { THEMES, createTerminal, loadFonts } from './term.js';
|
||||
import { getTheme, initTheme, onThemeChange, toggleTheme } from './theme.js';
|
||||
import {
|
||||
TtydConnection, fetchAlerts, fetchRepo, fetchToken, uploadFile, AuthExpiredError, UnauthorizedError,
|
||||
TtydConnection, fetchAlerts, fetchRepo, fetchToken, investigateAlert, sessionAction, uploadFile, AuthExpiredError, UnauthorizedError,
|
||||
} from './connection.js';
|
||||
import { parseTitle, pasteSafe, sessionFromSearch } from './protocol.js';
|
||||
import { SessionsPanel, recentNames, rememberSession, sessionStatus } from './sessions.js';
|
||||
import { SessionsPanel, ctxLabel, recentNames, rememberSession, sessionStatus } from './sessions.js';
|
||||
import { renderAlerts } from './alerts.js';
|
||||
import { renderRepo } from './repo.js';
|
||||
import { bindAskClaude } from './widgets.js';
|
||||
@@ -13,6 +13,8 @@ import { heardWithin, onShared, share } from './shared.js';
|
||||
import { CommandPalette, dialogOpen, openDialog, toast } from './ui.js';
|
||||
import { Inbox } from './inbox.js';
|
||||
import { FilesPane } from './files.js';
|
||||
import { registerPathLinks } from './links.js';
|
||||
import { openHistory } from './history.js';
|
||||
import { el } from './dom.js';
|
||||
import * as notify from './notify.js';
|
||||
|
||||
@@ -58,6 +60,8 @@ const ui = {
|
||||
};
|
||||
|
||||
const urlSession = sessionFromSearch(window.location.search);
|
||||
// Notification links (Matrix) add existing=1: open, never re-create (devdesk#38).
|
||||
const urlExisting = new URLSearchParams(window.location.search).get('existing') === '1';
|
||||
const state = {
|
||||
session: urlSession, // null = picker
|
||||
conn: null,
|
||||
@@ -169,10 +173,16 @@ function recordTransitions(sessions) {
|
||||
}
|
||||
|
||||
function renderPanelsBadge() {
|
||||
inbox?.setLive({ waiting: waitingOthers, alerts: lastAlerts?.alerts ?? [] });
|
||||
inbox?.setLive({
|
||||
waiting: waitingOthers,
|
||||
alerts: lastAlerts?.alerts ?? [],
|
||||
sessions: sessionsPanel?.data ? sessionsPanel.data.sessions.map((x) => x.name) : null,
|
||||
});
|
||||
}
|
||||
|
||||
function onSessionData({ fetched = false } = {}) {
|
||||
if (document.visibilityState === 'visible') inbox?.markSessionRead(state.session);
|
||||
renderUsage();
|
||||
renderSessionChip();
|
||||
renderAttention(fetched);
|
||||
if (!ui.switcher.hidden) renderSwitcher();
|
||||
@@ -316,14 +326,19 @@ function updateUrl(session) {
|
||||
const url = new URL(window.location.href);
|
||||
if (session) url.searchParams.set('arg', session);
|
||||
else url.searchParams.delete('arg');
|
||||
url.searchParams.delete('existing');
|
||||
if (url.href !== window.location.href) window.history.replaceState(null, '', url);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- connection
|
||||
|
||||
// reconnect: automatic re-attach after a drop. It must not re-create a session
|
||||
// that was ended or renamed meanwhile, so it asks for --existing (devdesk#4).
|
||||
function connect(session, { reconnect = false } = {}) {
|
||||
// existing: go to a session that should already exist (reconnects, the
|
||||
// switcher, inbox entries, notification links). It must not re-create one that
|
||||
// was ended or renamed meanwhile, so it asks for --existing (devdesk#4, #38).
|
||||
// Creating is explicit: a typed name, the New dialog, the picker, recents.
|
||||
function connect(session, { existing = false, reconnect = false } = {}) {
|
||||
const existingOnly = Boolean(session) && (existing || reconnect);
|
||||
state.existingOnly = existingOnly;
|
||||
clearTimeout(state.retryTimer);
|
||||
state.conn?.dispose();
|
||||
state.session = session;
|
||||
@@ -339,13 +354,15 @@ function connect(session, { reconnect = false } = {}) {
|
||||
term.reset();
|
||||
|
||||
const conn = new TtydConnection({
|
||||
arg: session && reconnect ? ['--existing', session] : session,
|
||||
arg: existingOnly ? ['--existing', session] : session,
|
||||
size: () => ({ cols: term.cols, rows: term.rows }),
|
||||
onOpen: () => {
|
||||
state.openedAt = Date.now();
|
||||
state.attempts = 0;
|
||||
setWsState('connected', 'live');
|
||||
if (session) rememberSession(session);
|
||||
if (session) files?.knownFiles(); // so paths in the output are links from the first hover
|
||||
presenceTick();
|
||||
refreshSoon(800); // opening ?arg=<new name> just created this session
|
||||
refreshRepo();
|
||||
fit.fit();
|
||||
@@ -373,6 +390,25 @@ function onClosed(code) {
|
||||
// few seconds of opening means the session could not start (the reason is
|
||||
// printed in the terminal), so don't retry forever.
|
||||
const failedFast = code !== 1000 && Date.now() - state.openedAt < 4000;
|
||||
if (failedFast && state.existingOnly) {
|
||||
// Most likely ended or renamed since the link was made: say so, and only
|
||||
// start it again when asked.
|
||||
const name = state.session;
|
||||
sessionsPanel?.reload().then(() => {
|
||||
const known = sessionsPanel.data?.sessions?.some((x) => x.name === name);
|
||||
if (known) {
|
||||
scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
setWsState('disconnected', 'ended');
|
||||
showOverlay({
|
||||
title: `${name} has ended`,
|
||||
text: `The session "${name}" no longer exists: it was ended or renamed. Its conversation is still in Claude's history.`,
|
||||
actions: [pickerAction, { label: `Start ${name} again`, run: () => connect(name) }],
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (failedFast) {
|
||||
showOverlay({
|
||||
title: 'Session did not start',
|
||||
@@ -511,14 +547,15 @@ function renderSwitcher() {
|
||||
};
|
||||
const items = sessions.map((s) => {
|
||||
const status = sessionStatus(s);
|
||||
const ctx = s.context?.used_pct != null ? ` · ctx ${Math.floor(s.context.used_pct)}%` : '';
|
||||
const ctx = s.context?.used_pct != null ? ` · ${ctxLabel(s.context)}` : '';
|
||||
return el('button', {
|
||||
type: 'button', role: 'menuitem',
|
||||
class: `dd-menu-item dd-switch-item is-${status.key}${s.name === state.session ? ' is-current' : ''}`,
|
||||
title: s.dir || '', onclick: choose(() => connect(s.name)),
|
||||
title: s.dir || '', onclick: choose(() => connect(s.name, { existing: true })),
|
||||
},
|
||||
el('span', { class: `lt-dot ${status.dot}` }),
|
||||
el('span', { class: 'dd-switch-name' }, s.name),
|
||||
el('span', { class: 'dd-switch-name' }, s.name,
|
||||
s.tags?.length ? el('span', { class: 'dd-tags' }, ...s.tags.slice(0, 2).map((t) => el('span', { class: 'dd-tag' }, t))) : null),
|
||||
el('span', { class: 'dd-switch-meta' }, `${status.label}${ctx}`));
|
||||
});
|
||||
if (!items.length) items.push(el('div', { class: 'dd-menu-note' }, sessionsPanel?.data ? 'No sessions yet.' : 'Loading…'));
|
||||
@@ -559,6 +596,89 @@ async function toggleNotifications() {
|
||||
}
|
||||
}
|
||||
|
||||
// Ops Alerts → Ask Claude (devdesk#39): the server starts Claude in a session of
|
||||
// its own with the alert, its rule and where it runs (CT id, node) as the first
|
||||
// prompt; then we open that session. A session already running is just opened.
|
||||
async function investigate(button) {
|
||||
const { investigate: uid, session } = button.dataset;
|
||||
if (!uid || !session || button.disabled) return;
|
||||
closeDrawerIfNarrow();
|
||||
button.disabled = true;
|
||||
const label = button.textContent;
|
||||
button.textContent = 'Starting…';
|
||||
try {
|
||||
const result = await investigateAlert(session, uid);
|
||||
if (result.started) toast.success(`Claude is on it in ${session}`);
|
||||
else toast.info(`${session} is already running: opening it`);
|
||||
await sessionsPanel.reload();
|
||||
connect(session, { existing: true });
|
||||
} catch (error) {
|
||||
toast.error(`Ask Claude: ${error.message}`);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = label;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- history & usage
|
||||
|
||||
function showHistory() {
|
||||
closeMenus();
|
||||
openHistory({
|
||||
sessions: () => sessionsPanel?.data?.sessions ?? [],
|
||||
open: (name) => connect(name, { existing: true }),
|
||||
refresh: () => sessionsPanel.reload(),
|
||||
});
|
||||
}
|
||||
|
||||
// Plan usage (devdesk#25): the 5-hour and weekly windows, from the newest
|
||||
// statusLine snapshot of any session (they're account-wide). A toast when the
|
||||
// 5-hour window passes 90 %, once per window.
|
||||
let usageWarned = 0;
|
||||
function renderUsage() {
|
||||
const snapshots = (sessionsPanel?.data?.sessions ?? []).map((s) => s.context).filter((c) => c?.rate_limits);
|
||||
const latest = snapshots.sort((a, b) => (b.updated || 0) - (a.updated || 0))[0]?.rate_limits;
|
||||
const footer = $('usage-footer');
|
||||
const menuRow = $('usage-row');
|
||||
if (!latest || (!latest.five_hour && !latest.seven_day)) {
|
||||
footer.hidden = true;
|
||||
menuRow.hidden = true;
|
||||
return;
|
||||
}
|
||||
const at = (epoch) => (epoch ? new Date(epoch * 1000).toLocaleString(undefined, { weekday: 'short', hour: '2-digit', minute: '2-digit' }) : '?');
|
||||
const meter = (label, w) => {
|
||||
if (!w || w.pct === null || w.pct === undefined) return null;
|
||||
const pct = Math.round(w.pct);
|
||||
return el('span', { class: `dd-meter${pct >= 95 ? ' is-full' : pct >= 80 ? ' is-high' : ''}`, title: `${label}: ${pct}% used, resets ${at(w.resets_at)}` },
|
||||
el('span', { class: 'dd-meter-label' }, label),
|
||||
el('span', { class: 'dd-meter-bar' }, el('span', { class: 'dd-meter-fill', style: `width:${Math.min(100, pct)}%` })),
|
||||
`${pct}%`);
|
||||
};
|
||||
const parts = () => [meter('5h', latest.five_hour), meter('week', latest.seven_day)].filter(Boolean);
|
||||
footer.replaceChildren(...parts());
|
||||
$('usage-menu').replaceChildren(...parts());
|
||||
footer.hidden = false;
|
||||
menuRow.hidden = false;
|
||||
const five = latest.five_hour;
|
||||
if (five?.pct >= 90 && five.resets_at !== usageWarned) {
|
||||
usageWarned = five.resets_at;
|
||||
toast.warning(`Plan usage: ${Math.round(five.pct)}% of the 5-hour window (resets ${at(five.resets_at)})`, 10000);
|
||||
}
|
||||
}
|
||||
|
||||
// Remote Control presence (devdesk#26): while this tab shows a session and is
|
||||
// visible, its Claude knows a client is present and holds back phone pushes.
|
||||
let presenceFor = null;
|
||||
function presence(on) {
|
||||
const session = state.session;
|
||||
if (presenceFor && presenceFor !== session) sessionAction('presence', presenceFor, 'off').catch(() => {});
|
||||
presenceFor = on ? session : null;
|
||||
if (session) sessionAction('presence', session, on ? 'on' : 'off').catch(() => {});
|
||||
}
|
||||
function presenceTick() {
|
||||
presence(Boolean(state.session && state.conn?.isOpen && document.visibilityState === 'visible'));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- palette & help
|
||||
|
||||
const sendKeys = (keys) => state.conn?.sendInput(keys);
|
||||
@@ -590,8 +710,9 @@ function buildCommands() {
|
||||
if (s.name === state.session) continue;
|
||||
const status = sessionStatus(s);
|
||||
add({
|
||||
id: `switch:${s.name}`, group: 'Sessions', label: `Switch to ${s.name}`, hint: status.label, keywords: s.dir,
|
||||
icon: status.key === 'waiting' ? '!' : s.running ? '●' : '○', run: () => connect(s.name),
|
||||
id: `switch:${s.name}`, group: 'Sessions', label: `Switch to ${s.name}`, hint: [status.label, ...(s.tags ?? []).slice(0, 2)].join(' · '),
|
||||
keywords: `${s.dir} ${(s.tags ?? []).join(' ')}`,
|
||||
icon: status.key === 'waiting' ? '!' : s.running ? '●' : '○', run: () => connect(s.name, { existing: true }),
|
||||
});
|
||||
}
|
||||
add({ id: 'new', group: 'Sessions', icon: '+', label: 'New session…', keywords: 'create open project', run: () => sessionsPanel.newDialog() });
|
||||
@@ -604,6 +725,7 @@ function buildCommands() {
|
||||
add({ id: 'copy-link', group: 'Sessions', icon: '⧉', label: 'Copy link to this session', keywords: 'url share', run: copyLink });
|
||||
}
|
||||
add({ id: 'picker', group: 'Sessions', icon: '≡', label: 'Open the session picker', keywords: 'fzf list', run: () => connect(null) });
|
||||
add({ id: 'history', group: 'Sessions', icon: '⌕', label: 'Search past conversations…', keywords: 'history transcript resume fork find old', run: showHistory });
|
||||
|
||||
if (state.session && state.conn?.isOpen) {
|
||||
add({ id: 'win-claude', group: 'Terminal', icon: '0', label: 'Claude window', kbd: '^b 0', run: () => sendKeys('\x020') });
|
||||
@@ -682,10 +804,13 @@ const KEY_HELP = [
|
||||
]],
|
||||
['DevDesk', [
|
||||
['Ctrl+⇧ P', 'Command palette'],
|
||||
['Ctrl+⇧ E', 'Files: browse, preview, diff (Esc closes)'],
|
||||
['Ctrl+⇧ E', 'Files: browse, preview, diff, edit (Esc closes)'],
|
||||
['Ctrl+P', 'Files: go to file'],
|
||||
['Ctrl+S', 'Files: save the open file'],
|
||||
['Ctrl+⇧ C / V', 'Copy selection / paste'],
|
||||
['⇧ drag', 'Select text in the browser'],
|
||||
['Drop or paste a file', 'Upload it and attach it for Claude'],
|
||||
['Click a file path', 'Open it in Files (at the line, if given)'],
|
||||
['Ctrl+W', 'Asks before closing; Chromium fullscreen keeps it for the terminal'],
|
||||
]],
|
||||
];
|
||||
@@ -818,6 +943,9 @@ function wireChrome() {
|
||||
showHelp();
|
||||
});
|
||||
$('footer-help').addEventListener('click', showHelp);
|
||||
$('history-menu').addEventListener('click', showHistory);
|
||||
setInterval(presenceTick, 45 * 1000);
|
||||
document.addEventListener('visibilitychange', presenceTick);
|
||||
$('palette-menu').addEventListener('click', () => {
|
||||
closeMenus();
|
||||
palette.open();
|
||||
@@ -835,6 +963,13 @@ function wireChrome() {
|
||||
},
|
||||
});
|
||||
$('files-toggle').addEventListener('click', () => files.toggle());
|
||||
registerPathLinks(term, {
|
||||
resolve: (printed) => (state.session ? files.resolvePrinted(printed) : null),
|
||||
open: (path, line) => {
|
||||
if (!files.isOpen) files.open();
|
||||
files.openFile(path, { pin: true, line });
|
||||
},
|
||||
});
|
||||
wireResizer();
|
||||
palette = new CommandPalette(buildCommands);
|
||||
$('cmd-toggle').addEventListener('click', () => palette.open());
|
||||
@@ -866,7 +1001,9 @@ function wireChrome() {
|
||||
badge: $('inbox-badge'),
|
||||
panel: $('inbox-panel'),
|
||||
hooks: {
|
||||
openSession: (name) => connect(name),
|
||||
openSession: (name) => connect(name, { existing: true }),
|
||||
ended: (name) => toast.info(`${name} has ended; its conversation is still in Claude's history`),
|
||||
refresh: () => sessionsPanel.reload(),
|
||||
showAlerts: () => {
|
||||
setSidebar(true);
|
||||
$('widget-alerts').scrollIntoView({ block: 'start', behavior: 'smooth' });
|
||||
@@ -921,7 +1058,7 @@ function wireChrome() {
|
||||
|
||||
// Ctrl+W closes the tab before the terminal sees it; ask first.
|
||||
window.addEventListener('beforeunload', (event) => {
|
||||
if (state.conn?.isOpen && state.session) {
|
||||
if ((state.conn?.isOpen && state.session) || files?.hasDirty()) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
@@ -938,7 +1075,10 @@ function wireChrome() {
|
||||
|
||||
window.addEventListener('online', retrySoon);
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (!document.hidden) retrySoon();
|
||||
if (!document.hidden) {
|
||||
retrySoon();
|
||||
inbox.markSessionRead(state.session);
|
||||
}
|
||||
});
|
||||
// Session states feed the header chip and the notifications for other sessions,
|
||||
// so poll even in a background tab (browsers throttle that to about once a
|
||||
@@ -957,7 +1097,7 @@ function wireChrome() {
|
||||
if (!document.hidden && ui.body.classList.contains('dd-sidebar-open')) refreshRepo();
|
||||
}, 60 * 1000);
|
||||
ui.attention.addEventListener('click', () => {
|
||||
if (ui.attention.dataset.target) connect(ui.attention.dataset.target);
|
||||
if (ui.attention.dataset.target) connect(ui.attention.dataset.target, { existing: true });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1045,6 +1185,10 @@ async function boot() {
|
||||
onData: (_data, meta) => onSessionData(meta),
|
||||
},
|
||||
});
|
||||
$('widget-alerts').addEventListener('click', (event) => {
|
||||
const button = event.target.closest('[data-investigate]');
|
||||
if (button) investigate(button);
|
||||
});
|
||||
bindAskClaude($('sidebar'), (text) => {
|
||||
// Alert text is untrusted: no control characters (a newline would run it in a
|
||||
// shell window, CR would submit), and bracketed paste around it (devdesk#2).
|
||||
@@ -1057,7 +1201,8 @@ async function boot() {
|
||||
wireUploads();
|
||||
refreshAlerts();
|
||||
await sessionsPanel.refresh();
|
||||
connect(urlSession ?? defaultSession(sessionsPanel.data));
|
||||
if (urlSession) connect(urlSession, { existing: urlExisting });
|
||||
else connect(defaultSession(sessionsPanel.data), { existing: true });
|
||||
}
|
||||
|
||||
boot();
|
||||
|
||||
+19
-3
@@ -46,6 +46,14 @@ function renameRecent(from, to) {
|
||||
writeRecents(readRecents().map((r) => (r.name === from ? { ...r, name: to } : r)));
|
||||
}
|
||||
|
||||
// "ctx 34% · 346k/1M": context use as a share of the window and in tokens.
|
||||
const tokens = (n) => (n >= 1e6 ? `${+(n / 1e6).toFixed(n % 1e6 ? 1 : 0)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n));
|
||||
export function ctxLabel(c) {
|
||||
if (c?.used_pct == null) return '';
|
||||
const count = c.used_tokens != null ? ` · ${tokens(c.used_tokens)}${c.window ? `/${tokens(c.window)}` : ''}` : '';
|
||||
return `ctx ${Math.floor(c.used_pct)}%${count}`;
|
||||
}
|
||||
|
||||
export function ago(epochSeconds) {
|
||||
if (!epochSeconds) return '';
|
||||
const s = Math.max(0, Date.now() / 1000 - epochSeconds);
|
||||
@@ -267,7 +275,7 @@ export class SessionsPanel {
|
||||
renderSession(s) {
|
||||
const isCurrent = s.name === this.current;
|
||||
const status = sessionStatus(s);
|
||||
const ctx = s.context?.used_pct != null ? `ctx ${Math.floor(s.context.used_pct)}%` : '';
|
||||
const ctx = ctxLabel(s.context);
|
||||
const since = s.status?.since ? ago(s.status.since) : ago(s.activity);
|
||||
const model = isCurrent && s.context?.model ? s.context.model.replace(/^Claude\s+/i, '') : '';
|
||||
const meta = s.running
|
||||
@@ -278,14 +286,22 @@ export class SessionsPanel {
|
||||
const title = [
|
||||
s.dir,
|
||||
status.key === 'waiting' && s.status?.message,
|
||||
s.context?.model && `${s.context.model}${s.context.cost_usd != null ? ` · $${s.context.cost_usd.toFixed(2)}` : ''}`,
|
||||
// rate_limits means a Pro/Max plan, where cost_usd is only an API-price estimate
|
||||
s.context?.model && `${s.context.model}${s.context.rate_limits ? '' : s.context.cost_usd != null ? ` · $${s.context.cost_usd.toFixed(2)}` : ''}`,
|
||||
].filter(Boolean).join('\n');
|
||||
const iconButton = (label, glyph, onclick, extra = '') =>
|
||||
el('button', { class: `dd-icon-btn ${extra}`, type: 'button', title: label, 'aria-label': `${label} ${s.name}`, onclick }, glyph);
|
||||
return el('li', { class: `dd-session-item is-${status.key}${isCurrent ? ' is-current' : ''}` },
|
||||
el('button', { class: 'dd-session-open', type: 'button', title, onclick: () => this.hooks.onOpen(s.name) },
|
||||
el('span', { class: `lt-dot ${status.dot}` }),
|
||||
el('span', { class: 'dd-session-name' }, s.name),
|
||||
el('span', { class: 'dd-session-name' }, s.name,
|
||||
s.tags?.length ? el('span', { class: 'dd-tags', title: 'Hosts this session worked on' }, ...s.tags.slice(0, 3).map((t) => el('span', { class: 'dd-tag' }, t))) : null,
|
||||
// The pull request of this branch (devdesk#25)
|
||||
s.context?.pr?.number ? el('a', {
|
||||
class: `dd-pr is-${s.context.pr.review_state || 'open'}`, href: s.context.pr.url, target: '_blank', rel: 'noopener',
|
||||
title: `PR #${s.context.pr.number}${s.context.pr.review_state ? ` · ${s.context.pr.review_state.replace(/_/g, ' ')}` : ''}`,
|
||||
onclick: (event) => event.stopPropagation(),
|
||||
}, `PR #${s.context.pr.number}${{ approved: ' ✓', changes_requested: ' ✗' }[s.context.pr.review_state] ?? ''}`) : null),
|
||||
el('span', { class: 'dd-session-meta' }, meta),
|
||||
pct != null ? el('span', { class: `dd-ctx${pct >= 90 ? ' is-full' : pct >= 70 ? ' is-high' : ''}`, 'aria-hidden': 'true' },
|
||||
el('span', { class: 'dd-ctx-fill', style: `width:${Math.min(100, pct)}%` })) : null),
|
||||
|
||||
+2
-2
@@ -52,7 +52,7 @@ export const dialogOpen = () => openDialogs > 0 || !!document.querySelector('.lt
|
||||
// A .lt-modal dialog. `body` is a node; `actions` are { label, value, primary,
|
||||
// danger }. Resolves with the chosen action's value (or `submit()`'s value when
|
||||
// a form is submitted), or null when dismissed (✕, Esc, backdrop).
|
||||
export function openDialog({ title, body, actions = [], danger = false, size = '', onOpen, submit }) {
|
||||
export function openDialog({ title, body, actions = [], danger = false, size = '', className = '', onOpen, submit }) {
|
||||
return new Promise((resolve) => {
|
||||
const opener = document.activeElement;
|
||||
let done = false;
|
||||
@@ -81,7 +81,7 @@ export function openDialog({ title, body, actions = [], danger = false, size = '
|
||||
if (button.type === 'submit') button.setAttribute('form', titleId);
|
||||
}
|
||||
form.id = titleId;
|
||||
const overlay = el('div', { class: 'lt-modal-overlay is-open dd-dialog', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': `${titleId}-title` },
|
||||
const overlay = el('div', { class: `lt-modal-overlay is-open dd-dialog${className ? ` ${className}` : ''}`, role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': `${titleId}-title` },
|
||||
el('div', { class: `lt-modal${size ? ` lt-modal-${size}` : ''}` },
|
||||
el('div', { class: `lt-modal-header${danger ? ' lt-modal-header--danger' : ''}` },
|
||||
el('h2', { class: 'lt-modal-title', id: `${titleId}-title` }, title),
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
// "Ask Claude": any [data-ask-claude] button (Ops Alerts, Repo/CI) types its
|
||||
// prompt into the current session without pressing Enter, so you can review it
|
||||
// before sending.
|
||||
// "Ask Claude": any [data-ask-claude] button (Repo/CI) types its prompt into the
|
||||
// current session without pressing Enter, so you can review it before sending.
|
||||
// (Ops Alerts start their own session instead: devdesk#39.)
|
||||
|
||||
export function bindAskClaude(root, send) {
|
||||
root.addEventListener('click', (event) => {
|
||||
|
||||
+117
-3
@@ -2,7 +2,7 @@
|
||||
everything visual comes from the TDS tokens defined in base.css :root. */
|
||||
|
||||
:root {
|
||||
--dd-footer-height: 30px;
|
||||
--dd-footer-height: 40px;
|
||||
--dd-sidebar-width: 320px;
|
||||
--dd-gap: 8px;
|
||||
}
|
||||
@@ -402,6 +402,9 @@ body.dd-sidebar-open .dd-sidebar {
|
||||
.dd-alert-name { font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.dd-alert-age { margin-left: auto; white-space: nowrap; }
|
||||
.dd-alert-instances { overflow-wrap: anywhere; }
|
||||
.dd-alert-where { color: var(--accent-cyan); font-family: var(--font-mono); overflow-wrap: anywhere; }
|
||||
.dd-alert-where::before { content: "\2192 "; color: var(--text-muted); }
|
||||
.dd-alert-where.is-guess { color: var(--text-secondary); }
|
||||
.dd-alert-summary { color: var(--text-secondary); }
|
||||
.dd-alert .dd-ask { align-self: flex-start; margin-top: 2px; }
|
||||
.dd-all-clear { display: flex; align-items: center; gap: var(--space-sm); color: var(--accent-green); font-size: 0.74rem; }
|
||||
@@ -489,7 +492,19 @@ body.dd-sidebar-open .dd-sidebar {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.dd-footer .lt-footer-key { margin-right: 4px; }
|
||||
.dd-footer .lt-footer-key { margin-right: 5px; font-size: 0.86rem; }
|
||||
/* devdesk#41: the bottom row was too small to read at a glance */
|
||||
.dd-footer .lt-footer-hint { font-size: 0.9rem; }
|
||||
.dd-footer .lt-footer-sep { font-size: 0.9rem; }
|
||||
/* Narrower windows keep the usage meters and drop the least-used hints. */
|
||||
@media (max-width: 1400px) {
|
||||
.dd-footer .lt-footer-hints .lt-footer-hint:nth-child(n + 13),
|
||||
.dd-footer .lt-footer-sep:nth-child(n + 12) { display: none; }
|
||||
}
|
||||
@media (max-width: 1150px) {
|
||||
.dd-footer .lt-footer-hints .lt-footer-hint:nth-child(n + 9),
|
||||
.dd-footer .lt-footer-sep:nth-child(n + 8) { display: none; }
|
||||
}
|
||||
|
||||
.dd-keybar { display: flex; gap: 4px; width: 100%; overflow-x: auto; scrollbar-width: none; }
|
||||
.dd-keybar[hidden] { display: none; }
|
||||
@@ -622,7 +637,7 @@ html[data-theme="light"] .lt-cmd-item.is-selected { background: var(--accent-cya
|
||||
background: none;
|
||||
color: var(--accent-cyan);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.64rem;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dd-footer-help:hover { border-color: var(--accent-cyan); }
|
||||
@@ -924,3 +939,102 @@ html[data-theme="light"] .dd-files.is-narrow .dd-explorer { box-shadow: 8px 0 24
|
||||
.dd-tree-row { min-height: 34px; }
|
||||
.dd-tab-close { opacity: 0.7; width: 28px; height: 28px; }
|
||||
}
|
||||
|
||||
/* ---- editing (devdesk#20) ------------------------------------------------------------- */
|
||||
.dd-tab-view:not(.is-dirty) .dd-dirty-only { display: none; }
|
||||
.dd-unsaved { color: var(--accent-amber); }
|
||||
.dd-tab.is-dirty .dd-tab-close { opacity: 1; color: var(--accent-amber); }
|
||||
.dd-tab.is-dirty .dd-tab-close:hover { color: var(--accent-red); }
|
||||
.dd-viewer-btn.is-primary { border-color: var(--accent-orange); color: var(--accent-orange); }
|
||||
.dd-viewer-btn.is-primary:hover { background: var(--accent-orange-dim); }
|
||||
.dd-viewer-banner {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 10px;
|
||||
padding: 5px 10px;
|
||||
border-bottom: 1px solid var(--accent-amber-dim);
|
||||
background: var(--accent-amber-dim);
|
||||
color: var(--accent-amber);
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
.dd-dialog.is-wide .lt-modal { width: min(1100px, 94vw); max-height: 88vh; }
|
||||
.dd-dialog.is-wide .lt-modal-body { padding: 0; }
|
||||
.dd-compare { display: flex; height: min(64vh, 640px); }
|
||||
.dd-compare > .cm-editor { flex: 1; min-width: 0; }
|
||||
|
||||
/* ---- inbox: answer & peek (devdesk#22, #23) --------------------------------------------- */
|
||||
.dd-inbox-panel.is-peek { width: min(460px, calc(100vw - 16px)); }
|
||||
.dd-request-desc { margin-top: 4px; color: var(--text-secondary); font-size: 0.7rem; }
|
||||
.dd-request {
|
||||
display: block;
|
||||
max-height: 7.5em;
|
||||
margin-top: 4px;
|
||||
padding: 4px 6px;
|
||||
overflow: auto;
|
||||
border-left: 2px solid var(--accent-amber);
|
||||
background: var(--bg-terminal);
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.7rem;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dd-request-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
|
||||
.dd-peek { display: flex; flex-direction: column; gap: 8px; padding: 8px 10px 10px; }
|
||||
.dd-peek-head { display: flex; align-items: center; gap: 8px; }
|
||||
.dd-peek-back { padding: 0 6px; border: 1px solid var(--border-color); background: none; color: var(--accent-cyan); cursor: pointer; }
|
||||
.dd-peek-title { flex: 1; color: var(--text-primary); font-weight: 700; font-size: 0.8rem; }
|
||||
.dd-peek-state { color: var(--text-muted); font-size: 0.66rem; }
|
||||
.dd-peek-label { display: block; margin-bottom: 2px; color: var(--accent-orange); font-size: 0.6rem; letter-spacing: 0.1em; text-transform: uppercase; }
|
||||
.dd-peek-user { padding: 6px 8px; border-left: 2px solid var(--border-color); color: var(--text-secondary); font-size: 0.72rem; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.dd-peek-assistant { max-height: 38vh; padding: 6px 8px; overflow: auto; border-left: 2px solid var(--accent-cyan); background: var(--bg-terminal); color: var(--text-primary); font-size: 0.74rem; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.dd-peek-input { width: 100%; min-height: 4.5em; resize: vertical; font-family: var(--font-mono); font-size: 0.76rem; }
|
||||
.dd-peek-actions { display: flex; justify-content: flex-end; gap: 6px; margin-top: 6px; }
|
||||
.dd-ask-row { display: flex; flex-wrap: wrap; gap: 6px; align-self: flex-start; margin-top: 2px; }
|
||||
.dd-alert .dd-ask-row .dd-ask { margin-top: 0; }
|
||||
|
||||
/* ---- ops trail (devdesk#27) ------------------------------------------------------------- */
|
||||
.dd-tags { display: inline-flex; flex-wrap: wrap; gap: 3px; margin-left: 6px; vertical-align: middle; }
|
||||
.dd-tag { padding: 0 4px; border: 1px solid var(--accent-cyan-border); color: var(--accent-cyan); font-size: 0.58rem; font-weight: 400; letter-spacing: 0; }
|
||||
.dd-peek-commands { display: flex; flex-direction: column; gap: 2px; }
|
||||
.dd-peek-command { display: flex; gap: 8px; min-width: 0; font-size: 0.68rem; }
|
||||
.dd-peek-command code { overflow: hidden; color: var(--text-secondary); font-family: var(--font-mono); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.dd-peek-when { flex: 0 0 2.6em; color: var(--text-muted); text-align: right; }
|
||||
|
||||
/* ---- history, usage, PR (devdesk#24-#26) ------------------------------------------- */
|
||||
.dd-history { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px; }
|
||||
.dd-history-input { width: 100%; font-size: 0.82rem; }
|
||||
.dd-history-results { display: flex; flex-direction: column; gap: 8px; max-height: 60vh; overflow: auto; }
|
||||
.dd-history-item { padding: 8px 10px; border: 1px solid var(--border-dim); border-left: 2px solid var(--accent-cyan); background: var(--bg-terminal); }
|
||||
.dd-history-title { color: var(--text-primary); font-size: 0.8rem; font-weight: 700; overflow-wrap: anywhere; }
|
||||
.dd-history-meta { margin: 2px 0 6px; color: var(--text-muted); font-size: 0.66rem; overflow-wrap: anywhere; }
|
||||
.dd-history-snippet { display: flex; gap: 8px; margin-top: 3px; color: var(--text-secondary); font-size: 0.72rem; line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.dd-history-snippet mark { background: var(--accent-amber-dim); color: var(--accent-amber); padding: 0 1px; }
|
||||
.dd-history-role { flex: 0 0 4.2em; color: var(--accent-orange); font-size: 0.6rem; letter-spacing: 0.08em; text-transform: uppercase; padding-top: 2px; }
|
||||
.dd-history-snippet.is-command span:last-child,
|
||||
.dd-history-snippet.is-output span:last-child { font-family: var(--font-mono); }
|
||||
.dd-history-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 8px; }
|
||||
.dd-history-actions .lt-input { width: 220px; font-size: 0.74rem; }
|
||||
|
||||
.dd-footer-usage { margin-left: auto; padding-left: 16px; }
|
||||
.dd-footer-usage[hidden],
|
||||
.dd-usage-row[hidden] { display: none; }
|
||||
.dd-usage { display: inline-flex; align-items: center; gap: 10px; }
|
||||
.dd-footer-usage { display: inline-flex; align-items: center; gap: 18px; }
|
||||
.dd-meter { display: inline-flex; align-items: center; gap: 5px; color: var(--text-secondary); font-size: 0.66rem; white-space: nowrap; }
|
||||
.dd-footer-usage .dd-meter { gap: 7px; color: var(--text-primary); font-family: var(--font-mono); font-size: 1rem; font-weight: 600; }
|
||||
.dd-footer-usage .dd-meter-label { font-weight: 400; }
|
||||
.dd-footer-usage .dd-meter-bar { width: 80px; height: 8px; }
|
||||
.dd-meter-label { color: var(--text-muted); }
|
||||
.dd-meter-bar { width: 42px; height: 4px; background: var(--bg-tertiary); }
|
||||
.dd-meter-fill { display: block; height: 100%; background: var(--accent-cyan); }
|
||||
.dd-meter.is-high .dd-meter-fill { background: var(--accent-amber); }
|
||||
.dd-meter.is-high { color: var(--accent-amber); }
|
||||
.dd-meter.is-full .dd-meter-fill { background: var(--accent-red); }
|
||||
.dd-meter.is-full { color: var(--accent-red); }
|
||||
body.dd-touch .dd-footer-usage { display: none; }
|
||||
|
||||
.dd-pr { margin-left: 6px; padding: 0 4px; border: 1px solid var(--border-color); color: var(--text-secondary); font-size: 0.58rem; font-weight: 400; text-decoration: none; vertical-align: middle; }
|
||||
.dd-pr.is-approved { border-color: var(--accent-green-border); color: var(--accent-green); }
|
||||
.dd-pr.is-changes_requested { border-color: rgba(255, 45, 85, 0.4); color: var(--accent-red); }
|
||||
|
||||
Reference in New Issue
Block a user