Upgrading the agy Launch Experience: agyr Wrapper, Directory-Scoped Session Isolation, and 5-Color Terminal Notifications
Once you use agy CLI as your daily driver for a while, the friction rarely comes from model code quality. It comes from four recurring papercuts around the edges:
- Repeated auth prompts over SSH: Even when your local desktop session is already signed in, running
agyover SSH still prompts you with an out-of-band (OOB) login link. - Cross-repo session collisions: With three or four repositories open locally, it is far too easy to pick a stale conversation from a neighboring project in the native list—polluting context at best, editing the wrong directory at worst.
- Hardcoded project mappings: Separating native Projects per repository is useful, but editing
~/.zshrcevery time you add a new repo is pure overhead. - Lost visibility across split panes: Running several sessions in Terminator and switching over to a browser to check docs leaves you blind to which pane finished, which one errored out, and which one is blocked on
ask_questionwaiting for your input.
This post walks through the exact setup running on my daily Linux workstation. The entire pipeline relies only on the Python standard library, jq, xdotool, and notify-send. Every script and config snippet below comes straight from the live files on my machine (with only the username and hostname redacted).

What the Finished Setup Looks Like
Here are the three interfaces you actually see every day after the upgrade—the directory-scoped session picker, the 5-color Terminator window title bar, and the two-line powerline status bar at the bottom:

In any repository, you run a single command: agyr. Keyring reuse, session filtering, Project binding, window title updates, and background notifications all happen automatically.
Evolution note: This post documents the initial Linux implementation (agyr() inline in ~/.zshrc + title.sh 5-color title bar). To support cross-platform reuse (macOS + Linux) and visual concurrency troubleshooting, #4 Cross-Platform Backup and One-Click Bootstrap later extracts agyr.zsh into a standalone module and replaces title.sh with pure-Python title.py, while #5 Multi-Session Chrome Guardrails and Orange UI Status expands the indicator to six colors. If you plan to adopt these configs directly, read those two posts alongside this one.
1. Taking Over the Launch Entry Point with agyr() in ~/.zshrc
Here is the full launch decision flow for agyr—showing when arguments pass straight through, when the picker opens, and when --project gets injected automatically:
flowchart TD
IN["Run agyr [args...] in terminal"] --> SSH{"SSH_* set and local D-Bus available?"}
SSH -- "Yes" --> UNSET["Subprocess env -u SSH_* to reuse desktop keyring"]
SSH -- "No" --> RAW["Invoke command agy directly"]
UNSET --> TTY{"Interactive TTY with no args or -r only?"}
RAW --> TTY
TTY -- "No args" --> PICK1["agy-pick.py --new-first<br/>+ New session listed first"]
TTY -- "Only -r / --resume" --> PICK2["agy-pick.py<br/>Most recent session listed first"]
TTY -- "Other args" --> SUB
PICK1 --> SUB{"Subcommand or -h/-v?"}
PICK2 --> SUB
SUB -- "Yes (mcp/plugin/models...)" --> PASS["Pass through verbatim without session flags"]
SUB -- "No" --> HAS{"--project / -r / -c already passed?"}
HAS -- "Yes" --> EXEC["Execute agy"]
HAS -- "No" --> PROJ["agy-project.py derives & lazily creates Project JSON<br/>Append --project <slug>"]
PROJ --> EXEC
1. Reusing an Unlocked Local Desktop Keyring over SSH
Early on, SSHing into my Linux dev box and running agy always forced a fresh OOB auth flow. The root cause turned out to be straightforward:
- SSH shells lack
XDG_RUNTIME_DIRandDBUS_SESSION_BUS_ADDRESSby default, so they cannot reach the already-unlocked local desktop keyring. - More subtly, whenever
agyseesSSH_CONNECTION,SSH_CLIENT, orSSH_TTYin its environment, it deliberately bypasses the desktop keyring and falls back to remote OOB authentication.
The fix takes two steps: populate the runtime bus paths in ~/.zshrc, and never run unset SSH_* globally in the outer shell (doing so breaks shell prompts, clipboard detection, and other SSH-aware tooling). Instead, strip those three variables only for the agy subprocess:
1 | # Reuse the unlocked local desktop Keyring (D-Bus) and display over SSH to avoid repeated agy auth prompts |
2. The Complete agyr() Function
1 | agyr() { |
3. Pitfall: Never Bake --remote-control into agyr
My first draft included --remote-control inside agyr_defaults so I could take over any terminal from a phone or browser. Opening five or six split panes immediately flooded the web UI with randomly named instances, making it impossible to tell which pane was which.
The clean fix is to remove --remote-control from interactive launches completely and run a single persistent daemon via user-level systemd (~/.config/systemd/user/antigravity-cli-daemon.service):
1 | [Unit] |
Pair that with "cliRemoteControlHostname": "my-dev-host" in ~/.gemini/config/config.json. You get one stable, predictable remote-control endpoint at boot, while every interactive terminal stays focused on local work without spawning ghost entries in the web UI.
2. Auto-Deriving Projects Without Hardcoding (agy-project.py)
At first I considered writing a case "$PWD" lookup table in .zshrc to assign --project per repository. Two lines in, I scrapped it—updating .zshrc every time you clone a repo is pure maintenance tax.
A better design derives the Project ID from the working directory and lazily creates the Project file only when missing:
- Run
git -C <cwd> rev-parse --show-toplevelfirst so launchingagyrfrom any subdirectory normalizes to the same Git root. - Outside a Git repo, fall back to
realpath(cwd). - Explicitly exclude
/,$HOME,/tmp, and/tmp/*so shared scratch directories never spawn junk Projects. - Sanitize the directory basename into a valid slug, falling back to an 8-character SHA-256 hash prefix of the path if it collides with reserved IDs (empty string or
default-cli-project). - Create
~/.gemini/config/projects/<slug>.jsonatomically viaos.open(..., O_WRONLY | O_CREAT | O_EXCL)so concurrent terminal launches never clobber each other or write truncated JSON.
The implementation lives at ~/.gemini/bin/agy-project.py:
1 | #!/usr/bin/env python3 |
You can also run python3 ~/.gemini/bin/agy-project.py --dry-run in any directory to preview the derived Project ID before writing anything to disk.
3. A Directory-Scoped Session Picker (agy-pick.py)
Project isolation alone is not enough—the native resume picker can still surface conversations from other workspaces. To eliminate cross-project noise completely, I wrote a zero-dependency Python TUI picker (~/.gemini/bin/agy-pick.py) that queries the underlying SQLite index directly and filters strictly to sessions belonging to the current directory or repository.
Core Filtering Logic
1 | DB_PATH = os.path.expanduser("~/.gemini/antigravity-cli/conversation_summaries.db") |
Four hard-won details make this picker reliable in day-to-day use:
- Read-only mode +
.dbexistence check:conversation_summaries.dbruns in WAL mode, so opening it withmode=roguarantees zero write contention. Checking thatconversations/<cid>.dbstill exists also filters out orphaned index rows left behind after pruning old sessions. - Exclude subagents and empty sessions:
step_count > 0drops abandoned sessions closed immediately after launch, andCOALESCE(parent_conversation_id, '') = ''strips background subagent entries, keeping the list clean. - Render the TUI directly against
/dev/tty: Becauseagyr()captures the chosen ID via command substitution (picked="$(python3 agy-pick.py ...)"),stdoutis redirected into a shell variable. The interactive TUI reads and draws straight to/dev/tty, writing only the selectedconversation_id(or__NEW__) tostdouton exit. - Wide-character alignment + dual default ordering: Truncating titles using
unicodedata.east_asian_widthprevents CJK characters from wrapping the right-alignedsteps / agecolumns. Bareagyrpasses--new-firstso+ New sessionsits on row 1 (press Enter to start fresh immediately), whereasagyr -rputs the most recent session first (press Enter to resume immediately).
4. 5-Color Terminal Title + Unfocused Desktop Notifications (hooks.json + title.sh)
agy lets you configure a title command in settings.json to update the terminal title dynamically, but the real-time JSON payload it pipes in only exposes agent_state and tool_confirmation_pending. That covers idle, running, awaiting tool approval, and error—but has no way to distinguish “the Agent called ask_question and is waiting for you to pick an option.”
In practice, ask_question is the #1 silent stall: the window title still shows “running”, you assume the agent is busy writing code, and ten minutes later you tab back to find it has been waiting for you to choose A or B the whole time.
End-to-End State Pipeline
A lightweight flag file in /tmp bridges Hooks and title.sh:
sequenceDiagram
participant A as Gemini Agent
participant H as hooks.json<br/>(ask-question-state.py)
participant F as /tmp/agy-waiting-choice/
participant T as title.sh (periodic refresh)
participant D as Linux Desktop (xdotool / notify-send)
A->>H: PreToolUse (matcher: ask_question)
H->>F: Write conv-<sha256[:24]>.flag
H->>D: xdotool confirms terminal unfocused -> notify-send 🔵 Waiting for choice
T->>F: Detect .flag present and state != idle
T-->>T: Set title bar to 🔵 dir | title | branch
Note over A,D: User returns to terminal and selects an option
A->>H: PostToolUse (matcher: ask_question)
H->>F: Delete .flag; title switches back to 🟣 Running
A->>H: Stop (NO_TOOL_CALL / ERROR)
H->>F: Clean stale .flag + check 15s cooldown
H->>D: If unfocused, send 🟢 Completed or 🔴 Error
1. Hooks Configuration (~/.gemini/config/hooks.json)
1 | { |
2. State Tracking and Anti-Spam Notification Script (ask-question-state.py)
Firing a desktop toast on every single stop gets noisy fast when you are already staring at the terminal. The script adds three anti-spam guardrails:
- Active-window focus check: Queries
xdotool getactivewindow getwindowclassname. If the focused window matches any terminal class in the allowlist (Terminator, Kitty, Alacritty, WezTerm, Ghostty, etc.), it stays silent. - 15-second cooldown: Tracks per-session timestamps in
notify-<key>.tsso back-to-backStopevents never spam notifications. - Escape hatch + non-blocking allow: Set
AGY_NO_NOTIFY=1to mute everything during screen recordings or demos. OnPreToolUse, the script must print{"decision": "allow"}so it never blocks the tool call.
1 | #!/usr/bin/env python3 |
3. 5-Color Terminal Title Script (~/.gemini/antigravity-cli/title.sh)
One classic Bash pitfall from writing status bars showed up here too: parsing multiple fields with IFS=$'\t' read collapses consecutive whitespace whenever branch or title is empty, shifting every subsequent variable to the left. Using a single jq call that emits one field per line into mapfile -t eliminates field-shift bugs altogether:
1 |
|
5. Two-Line Powerline Status Bar (agy-powerline) and settings.json Wiring
The window title gives you glanceable status when you tab away or juggle split panes. For the bottom bar of your active terminal, I use the community agy-powerline package—far less maintenance than a hand-rolled shell status bar, with built-in width adaptation and quota pacing meters.
My ~/.agy-powerline/statusline.config.json splits widgets across two rows—location/code status on row 1, resource/quota telemetry on row 2:
| Row | Enabled Widgets | What It Shows |
|---|---|---|
| Row 1 | cwd(depth:2) · agentState · git(gitLink) · gitFiles · gitChanges · gitStash · gitWorktree · model · contextTokens(warn:65, crit:85) · mode |
Current repo, working tree state, active model, and context budget pressure |
| Row 2 | title(maxWidth:24) · tasks(alwaysShow) · queue · cacheHit · fiveHourPct · fiveHourReset · weeklyPct · weeklyReset · sessionTime · tokensToday |
Background tasks and queued prompts, prompt cache hit rate, and remaining 5-hour/weekly quota |
Finally, wire both statusLine and title into ~/.gemini/antigravity-cli/settings.json:
1 | { |
If you enable enableTerminalSandbox: true, double-check permissions.deny in settings.json: read_file(...) entries must specify exact directory paths (such as read_file(/home/user/.ssh)), never /** wildcards. Otherwise sandbox validation fails outright and blocks every sandboxed command.
Full Script Inventory
Every piece of this setup lives in user-level directories and leaves project repositories untouched:
| File | Responsibility |
|---|---|
~/.zshrc (agyr) |
SSH keyring reuse, picker launch on bare/-r invocation, subcommand passthrough, automatic --project injection |
~/.gemini/bin/agy-project.py |
Derives Project ID from Git root and atomically creates ~/.gemini/config/projects/<slug>.json on demand |
~/.gemini/bin/agy-pick.py |
Queries conversation_summaries.db read-only and filters sessions strictly to the current directory/repo |
~/.config/systemd/user/antigravity-cli-daemon.service |
Runs a single persistent agy remote-control serve instance (see Part 12 of the Field Guide for Remote Control internals and loginctl enable-linger) |
~/.gemini/config/hooks.json + hooks/ask-question-state.py |
Tracks ask_question waiting flags and sends unfocused desktop notifications |
~/.gemini/antigravity-cli/title.sh |
Parses live session JSON in a single jq pass and renders the 5-color terminal title |
~/.agy-powerline/statusline.config.json |
Two-line powerline status bar at the bottom of the terminal |









