Files
dssc/dsflow/ui/app.py
T
lucioandClaude Opus 5.5 60532a4043 Rebuild the UI on vendored Textual; make the checkout self-contained
The internal servers have no access to outside package repositories and
run Python 3.8/3.9, so the UI moves from hand-drawn curses to Textual
6.2.1 (the last release supporting 3.8.1), vendored with its pure-Python
dependencies in vendor/. The launcher puts vendor/ first on sys.path, so a
plain checkout runs with no pip and no network.

- dsflow/: the single script split into a package (pure moves of the
  backend sections); action rules moved to ops.py, free of Textual
- dsflow/ui/: tabs, detail pane, live sanity-run panel, log viewer,
  modal dialogs, filter, themes, mouse support
- tests/test_ui.py: headless UI tests through Textual's pilot
- tools/vendor.py (refresh vendor/), tools/screenshots.py (README images)
- README, CLAUDE.md, TODO and the feature doc updated for the new layout,
  the Python 3.8.1 floor and the vendoring rules

Verified: 11 tests green on Python 3.12 and 3.8.20; the shipped file set
runs under `python -I -S` on both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-24 03:24:21 -07:00

546 lines
25 KiB
Python

"""The Textual application: layout, key bindings, polling the job file, and the actions behind each key."""
import os
import threading
import time
from textual import work
from textual.app import App
from textual.binding import Binding
from textual.screen import ModalScreen
from textual.widgets import Footer, Header, Input, Static, TabbedContent, TabPane
from .. import ops
from ..common import JOB_FILE, ME, RUNNER_LOG, VERSION, fmt_ago, job_state, norm, read_json
from ..flow import Snapshot
from ..runner import new_job, runner_alive, spawn_runner
from .dialogs import (AddFilesDialog, CheckinDialog, ConfirmDialog, HelpDialog, MessageDialog, SanityDialog,
TagDialog, file_notes)
from .widgets import DetailPane, FilePane, FileTable, LogPanel, RunPanel, run_bar
FILE_TABS = ("changes", "locks", "checkout")
TAB_LABELS = {"changes": "Changes", "locks": "Locks", "checkout": "Checked-out", "sanity": "Sanity run",
"logs": "Logs"}
# which file actions make sense on which tab; everything else is global
TAB_ACTIONS = {
"changes": {"toggle_mark", "mark_all", "sanity", "checkin", "tag", "add_new", "rebase", "filter"},
"locks": {"toggle_mark", "mark_all", "lock", "unlock", "tag", "filter"},
"checkout": {"toggle_mark", "mark_all", "lock", "tag", "filter"},
"sanity": {"checkin"},
"logs": set(),
}
FILE_ACTIONS = set().union(*TAB_ACTIONS.values())
class DsflowApp(App):
"""dsflow_tui's main screen."""
CSS_PATH = "styles.tcss"
TITLE = "dsflow"
ENABLE_COMMAND_PALETTE = True
AUTO_FOCUS = "#table-changes" # never the hidden filter input
BINDINGS = [
Binding("space", "toggle_mark", "Mark"),
Binding("s", "sanity", "Sanity"),
Binding("c", "checkin", "Check in"),
Binding("t", "tag", "Tag"),
Binding("l", "lock", "Lock"),
Binding("u", "unlock", "Unlock"),
Binding("x", "cancel_run", "Cancel run"),
Binding("slash", "filter", "Filter"),
Binding("r", "refresh", "Refresh"),
Binding("question_mark", "help", "Help"),
Binding("q", "quit", "Quit"),
Binding("a", "mark_all", "Mark all", show=False),
Binding("n", "add_new", "Add new", show=False),
Binding("m", "rebase", "Rebase", show=False),
Binding("escape", "clear", "Clear", show=False),
] + [Binding(str(i + 1), "show_tab('%s')" % tab, TAB_LABELS[tab], show=False)
for i, tab in enumerate(("changes", "locks", "checkout", "sanity", "logs"))]
def __init__(self, flow, auto_refresh=0, theme="tokyo-night"):
super().__init__()
self.flow = flow
self.refresh_every = auto_refresh # not `auto_refresh`: that name is Textual's repaint interval
self.start_theme = theme
self.snap = None
self.marks = set()
self.text_filter = ""
self.job, self.jstate, self.jmtime, self.locks_seen = None, "none", None, None
self.activity = []
self.busy = None
self.refreshing = False
self.last_refresh = 0.0
self.last_msg = ""
# -- layout ---------------------------------------------------------------
def compose(self):
yield Header(show_clock=True, icon="◆")
yield Input(placeholder="filter by path… (esc to close)", id="filter")
with TabbedContent(id="tabs", initial="changes"):
for tab in FILE_TABS:
with TabPane(TAB_LABELS[tab], id=tab):
yield FilePane(tab)
with TabPane(TAB_LABELS["sanity"], id="sanity"):
yield RunPanel()
with TabPane(TAB_LABELS["logs"], id="logs"):
yield LogPanel(self.log_sources, self.activity)
yield Static(id="runbar")
yield Footer()
def on_mount(self):
# direct references: events that arrive during teardown must not need a DOM query
self.tabs = self.query_one("#tabs", TabbedContent)
self.tables = dict((t, self.query_one("#table-" + t, FileTable)) for t in FILE_TABS)
self.details = dict((t, self.query_one("#detail-" + t, DetailPane)) for t in FILE_TABS)
self.runbar = self.query_one("#runbar", Static)
self.run_panel = self.query_one(RunPanel)
self.log_panel = self.query_one(LogPanel)
try:
self.theme = self.start_theme
except Exception: # noqa - an unknown --theme name just keeps the default
self.notify("unknown theme %r" % self.start_theme, severity="warning")
home = os.path.expanduser("~")
ws = "~" + self.flow.ws[len(home):] if self.flow.ws.startswith(home) else self.flow.ws
self.sub_title = "%s · %s · %s · green tag %s" % (ws, ME, self.flow.trunk, self.flow.working_tag)
for tab in FILE_TABS:
self.table(tab).loading = True
self.refresh_snapshot()
self.poll()
self.set_interval(0.25, self.poll)
# -- helpers --------------------------------------------------------------
def table(self, tab):
return self.tables[tab]
def tab(self):
return self.tabs.active
def log_sources(self):
cfgs = (self.job or {}).get("configs") or self.flow.configs
return ([("activity", None)] + [(c, self.flow.path("sanity_%s.log" % c)) for c in cfgs]
+ [("runner", self.flow.path(RUNNER_LOG))])
def run_files(self):
if self.jstate != "active":
return set()
return set(self.job.get("files", []) + self.job.get("new_files", []))
def to_ui(self, fn, *args, **kw):
"""call_from_thread that is a no-op once the app is shutting down (a worker can outlive it)."""
if self._closing or self._closed: # MessagePump state; pinned Textual, see vendor/requirements.txt
return
try:
self.call_from_thread(fn, *args, **kw)
except RuntimeError:
pass
def say(self, text, severity="information"):
"""A toast plus an entry in the activity log; safe from worker threads."""
self.activity.append((time.time(), severity, text))
if threading.current_thread() is threading.main_thread():
self.notify(text, severity=severity, timeout=6)
else:
self.to_ui(self.notify, text, severity=severity, timeout=6)
def log_line(self, text):
self.activity.append((time.time(), "log", text))
def check_action(self, action, parameters):
if isinstance(self.screen, ModalScreen):
return False
if action == "cancel_run":
return self.jstate in ("active", "orphaned")
if action in FILE_ACTIONS:
return action in TAB_ACTIONS.get(self.tab(), set())
return True
# -- state: snapshot and job ------------------------------------------------
def action_refresh(self):
self.refresh_snapshot()
@work(thread=True, exclusive=True, group="refresh")
def refresh_snapshot(self):
self.refreshing = True
self.last_refresh = time.time()
self.to_ui(self.show_title)
try:
snap = self.flow.snapshot()
except Exception as e: # noqa - a failed query is shown, never fatal
snap = Snapshot()
snap.err = str(e)
self.to_ui(self.apply_snapshot, snap)
def show_title(self):
if self.refreshing:
self.title = "dsflow · querying DesignSync…"
elif self.snap is not None:
self.title = "dsflow · updated %s (%.1fs)" % (time.strftime("%H:%M:%S", time.localtime(self.snap.ts)),
self.snap.took)
def apply_snapshot(self, snap):
self.snap = snap
self.refreshing = False
known = set(r["path"] for r in snap.changes + snap.locks + snap.checkout)
self.marks &= known
self.render_tables()
self.show_title()
if self.focused is None and self.tab() in FILE_TABS:
self.table(self.tab()).focus() # a loading table can't take focus at mount
if snap.err:
self.say("refresh failed: %s" % snap.err, "error")
def render_tables(self):
if self.snap is None:
return
tabs = self.tabs
counts = {"changes": len(self.snap.changes), "locks": len([r for r in self.snap.locks if r["holder"] == ME]),
"checkout": len(self.snap.checkout)}
for tab in FILE_TABS:
table = self.table(tab)
table.loading = False
table.show(getattr(self.snap, tab), self.marks, self.run_files(), self.text_filter)
tabs.get_tab(tab).label = "%s %d" % (TAB_LABELS[tab], counts[tab])
self.show_detail(tab)
def show_detail(self, tab):
table = self.table(tab)
row = table.current()
self.details[tab].show(tab, row, self.flow.ws,
bool(row) and row["path"] in self.run_files())
def on_data_table_row_highlighted(self, event):
if isinstance(event.data_table, FileTable):
self.show_detail(event.data_table.kind)
def on_data_table_row_selected(self, event):
if isinstance(event.data_table, FileTable) and event.data_table.selection_toggles():
self.action_toggle_mark(advance=False)
def poll(self):
path = self.flow.path(JOB_FILE)
try:
mtime = os.stat(path).st_mtime
except OSError:
mtime = None
if mtime != self.jmtime:
self.jmtime = mtime
job = read_json(path) if mtime else None
if job or mtime is None:
self.job = job
prev, self.jstate = self.jstate, job_state(self.job)
if prev != self.jstate:
self.refresh_bindings()
self.render_tables()
if self.jstate == "active" and self.locks_seen != self.job["id"] and \
any(s["key"] == "lock" and s["status"] == "done" for s in self.job["steps"]):
self.locks_seen = self.job["id"]
self.refresh_snapshot() # show the run's locks as soon as it has them
if prev == "active" and self.jstate == "done":
self.run_finished()
if self.refresh_every and not self.refreshing and time.time() - self.last_refresh > self.refresh_every:
self.refresh_snapshot()
self.runbar.update(run_bar(self.job, self.jstate, len(self.marks)))
self.run_panel.show(self.job, self.jstate)
self.log_panel.sync_sources()
self.log_panel.tick()
glyph = {"active": " ⟳", "orphaned": " ▲", "none": ""}.get(
self.jstate, " ✔" if (self.job or {}).get("status") == "passed" else " ✘")
tab = self.tabs.get_tab("sanity")
if str(tab.label) != TAB_LABELS["sanity"] + glyph:
tab.label = TAB_LABELS["sanity"] + glyph
def run_finished(self):
st = self.job.get("status")
if self.job.get("checked_in"):
self.marks -= set(self.job["files"] + self.job["new_files"])
self.say("sanity %s: %s" % (st.upper(), self.job.get("summary", "")),
"information" if st == "passed" else "error")
self.bell()
self.refresh_snapshot()
# -- tabs, marks, filter ------------------------------------------------------
def on_tabbed_content_tab_activated(self, event):
self.refresh_bindings()
if self.tab() in FILE_TABS:
self.table(self.tab()).focus()
PANE_FOCUS = {"sanity": "#run-log", "logs": "#log-view"}
def action_show_tab(self, tab):
# focus moves into the pane too: TabbedContent follows focus, so a stale focus would switch back
self.tabs.active = tab
self.query_one(self.PANE_FOCUS.get(tab, "#table-" + tab)).focus()
self.refresh_bindings()
def action_toggle_mark(self, advance=True):
if self.tab() not in FILE_TABS:
return
table = self.table(self.tab())
row = table.current()
if row is None:
return
self.marks ^= {row["path"]}
for tab in FILE_TABS:
self.table(tab).refresh_marks(self.marks)
if advance:
table.action_cursor_down()
def action_mark_all(self):
paths = set(r["path"] for r in self.table(self.tab()).file_rows)
self.marks = self.marks - paths if paths <= self.marks else self.marks | paths
for tab in FILE_TABS:
self.table(tab).refresh_marks(self.marks)
def action_clear(self):
flt = self.query_one("#filter", Input)
if flt.has_focus or flt.display:
flt.value, self.text_filter = "", ""
flt.display = False
self.render_tables()
if self.tab() in FILE_TABS:
self.table(self.tab()).focus()
return
if self.marks:
self.marks.clear()
for tab in FILE_TABS:
self.table(tab).refresh_marks(self.marks)
def action_filter(self):
flt = self.query_one("#filter", Input)
flt.display = True
flt.focus()
def on_input_changed(self, event):
if event.input.id == "filter":
self.text_filter = event.value
self.render_tables()
def on_input_submitted(self, event):
if event.input.id == "filter":
if not event.value:
event.input.display = False
self.table(self.tab()).focus()
# -- picking rows ---------------------------------------------------------------
def need_snap(self):
if self.snap is None:
self.say("still reading the workspace - one moment", "warning")
return False
return True
def pick(self, rows, use_cursor=True):
"""Marked rows among `rows`; with no marks, the highlighted row if it is one of them."""
chosen = [r for r in rows if r["path"] in self.marks]
if chosen or not use_cursor or self.tab() not in FILE_TABS:
return chosen
cur = self.table(self.tab()).current()
return [r for r in rows if cur is not None and r["path"] == cur["path"]]
def background(self, label, fn):
if self.busy:
self.say("busy: %s - wait for it to finish" % self.busy, "warning")
return
self.busy = label
self.log_line(label + " …")
self.notify(label + " …", timeout=3)
self.run_background(label, fn)
@work(thread=True, group="actions")
def run_background(self, label, fn):
try:
ok, msg = fn()
except Exception as e: # noqa - any failure becomes a toast instead of killing the UI
ok, msg = False, "%s failed: %s" % (label, e)
self.busy = None
self.say(msg, "information" if ok else "error")
self.to_ui(self.refresh_snapshot)
# -- actions --------------------------------------------------------------------
def action_sanity(self):
if not self.need_snap():
return
if self.jstate == "active":
return self.say("a sanity run is already in progress (x cancels it)", "warning")
if self.jstate == "orphaned":
return self.say("the previous runner died holding locks - press x to release them first", "error")
if runner_alive(self.flow):
return self.say("another runner still holds the job lock in this workspace", "error")
rows = self.pick(self.snap.changes, use_cursor=self.tab() == "changes")
if not rows:
return self.say("mark files in Changes (space) first", "warning")
blockers = ops.sanity_blockers(rows)
if blockers:
return self.push_screen(MessageDialog("Can't start sanity", [("Fix these first:", "bold")]
+ [(" " + b, "bad") for b in blockers]))
if not self.flow.configs:
return self.push_screen(MessageDialog("No sanity configs",
[("SANITY_CONFIGS is empty in %s" % self.flow.conf, "bad")]))
mods, news = ops.split_kinds(rows)
chosen = set(mods + news)
others = [r["path"] for r in self.snap.changes if r["path"] not in chosen]
notes = [("%d file(s) are locked while sanity runs and released when it ends." % len(rows), "bold")]
notes += file_notes(mods + news, 6)
if others:
notes.append(("▲ %d other local change(s) are not marked. They stay in the workspace, so sanity tests "
"them too, but they won't be checked in." % len(others), "warn"))
if any(r["unknown"] and r["kind"] == "M" for r in rows):
notes.append(("▲ couldn't read base/latest versions for some files; freshness is unverified.", "warn"))
if self.flow.sanity_cmd:
notes.append(("sanity command: %s" % self.flow.sanity_cmd, "dim"))
def launch(values):
if not values:
return
self.last_msg = values["msg"]
job = new_job(self.flow, mods, news, values["configs"], values["mode"], values["msg"], values["tag"],
values["refresh"])
try:
spawn_runner(self.flow, job)
except OSError as e:
return self.say("could not start the runner: %s" % e, "error")
self.jmtime = None
self.say("sanity started on %s for %d file(s)" % (" ".join(job["configs"]), len(rows)))
self.call_after_refresh(self.action_show_tab, "sanity") # after the dialog hands focus back
self.push_screen(SanityDialog(notes, self.flow.configs, self.flow.tags, self.flow.trunk, self.last_msg),
launch)
def action_cancel_run(self):
job = self.job
if self.jstate == "active":
def confirmed(yes):
if yes:
ops.request_cancel(self.flow)
self.say("cancel requested - the runner is cleaning up")
self.push_screen(ConfirmDialog("Cancel sanity run?", [
("Stops the running sanity, then releases the %d lock(s) the run took. Nothing is checked in."
% len(job.get("locked_by_job", [])), "")], yes="Cancel run"), confirmed)
elif self.jstate == "orphaned":
def confirmed(yes):
if yes:
self.background("releasing the lost runner's locks", lambda: ops.release_orphan(self.flow, job))
self.push_screen(ConfirmDialog("Release the lost runner's locks?", [
("The runner stopped sending heartbeats. Stop its simulation and release the lock(s) it took?", "")]
+ file_notes(job.get("locked_by_job", [])), yes="Release"), confirmed)
else:
self.say("no sanity run in progress")
def action_checkin(self):
if not self.need_snap():
return
if self.jstate == "active":
return self.say("wait for the sanity run to finish - it may check these in itself", "warning")
rows = self.pick(self.snap.changes, use_cursor=self.tab() == "changes")
if not rows:
return self.say("mark files in Changes (space) first", "warning")
stale = [r["path"] for r in rows if r["stale"]]
if stale:
return self.push_screen(MessageDialog("Can't check in", [
("Went stale on Trunk - rebase (m), then rerun sanity:", "bad")] + file_notes(stale)))
probs = ops.stamp_problems(self.flow, self.job, rows)
if probs:
return self.push_screen(MessageDialog("Sanity required", [
("These files need a passing sanity run first:", "bold")] + [(" " + p, "warn") for p in probs]
+ [("", ""), ("Press s and pick 'Check in' to test and check in in one go.", "dim")]))
mods, news = ops.split_kinds(rows)
job = self.job
def go(values):
if values:
self.last_msg = values["msg"]
self.background("checking in %d file(s)" % len(rows), lambda: ops.checkin_now(
self.flow, job, rows, values["msg"], values["tag"], self.log_line))
self.push_screen(CheckinDialog(
"Check in %d file(s)" % len(rows),
[("Sanity passed %s on %s." % (fmt_ago(job["sanity_epoch"]), " ".join(job["configs"])), "good")]
+ file_notes(mods + news), self.flow.tags, job.get("msg") or self.last_msg), go)
def action_tag(self):
if not self.need_snap():
return
rows = self.pick(self.table(self.tab()).file_rows)
if not rows:
return self.say("mark files (space) first", "warning")
paths = [r["path"] for r in rows if r.get("kind") != "A"]
if not paths:
return self.say("new files aren't in the vault yet - check them in before tagging", "warning")
if not self.flow.tags:
return self.say("no tags configured (DSFLOW_TAGS in dsflow.conf)", "error")
edited = [r for r in rows if r.get("kind") == "M" or r.get("modified")]
notes = [("Tag %d file(s) in one batch:" % len(paths), "bold")] + file_notes(paths, 6)
if edited:
notes.append(("▲ %d file(s) have local edits. The tag goes on the vault version your copy is based on, "
"not on your edits. Check in first to tag your changes." % len(edited), "warn"))
if len(paths) < len(rows):
notes.append(("skipping %d new (unmanaged) file(s)" % (len(rows) - len(paths)), "dim"))
def go(tag):
if tag:
self.background("tagging %d file(s) %s" % (len(paths), tag),
lambda: ops.run_action(self.flow, "ds_tag", paths, "tag " + tag, self.log_line,
lead=[tag]))
self.push_screen(TagDialog(notes, self.flow.tags), go)
def action_lock(self):
if not self.need_snap():
return
rows = [r for r in self.pick(self.table(self.tab()).file_rows) if r.get("kind") != "A"]
paths = [r["path"] for r in rows if not r["holder"]]
theirs = [r for r in rows if r["holder"] and r["holder"] != ME]
if theirs:
self.say("skipping %d file(s) locked by others" % len(theirs), "warning")
if not paths:
return self.say("nothing to lock - mark unlocked files first", "warning")
self.background("locking %d file(s)" % len(paths),
lambda: ops.run_action(self.flow, "ds_lock", paths, "lock", self.log_line))
def action_unlock(self):
if not self.need_snap():
return
in_run = set(self.job.get("locked_by_job", [])) if self.jstate == "active" else set()
rows = self.pick(self.table(self.tab()).file_rows)
paths = [r["path"] for r in rows if r["holder"] == ME and r["path"] not in in_run]
if any(r["path"] in in_run for r in rows):
self.say("files locked by the running sanity are released when it ends", "warning")
if not paths:
return self.say("none of the marked files are locked by you", "warning")
def confirmed(yes):
if yes:
self.background("unlocking %d file(s)" % len(paths),
lambda: ops.run_action(self.flow, "ds_unlock", paths, "unlock", self.log_line))
self.push_screen(ConfirmDialog("Release %d lock(s)?" % len(paths),
file_notes(paths) + [("", ""), ("Local edits are kept.", "dim")],
yes="Release"), confirmed)
def action_add_new(self):
def added(paths):
if not paths:
return
paths = [norm(os.path.relpath(self.flow.wpath(p), self.flow.ws)) for p in paths]
self.flow.add_new(paths)
self.marks |= set(paths)
self.say("registered %d new file(s)" % len(paths))
self.refresh_snapshot()
self.push_screen(AddFilesDialog(self.flow.ws), added)
def action_rebase(self):
if not self.need_snap():
return
paths = [r["path"] for r in self.pick(self.snap.changes, use_cursor=self.tab() == "changes") if r["stale"]]
if not paths:
return self.say("none of the marked files are stale")
def confirmed(yes):
if yes:
def work_fn():
ok, msg = ops.run_action(self.flow, "ds_rebase", paths, "merge", self.log_line)
self.flow.drop_stamp()
return ok, msg + (" - check for conflicts, then rerun sanity" if ok else "")
self.background("merging %d file(s)" % len(paths), work_fn)
self.push_screen(ConfirmDialog("Merge %s into %d file(s)?" % (self.flow.trunk, len(paths)), file_notes(paths) + [
("", ""), ("Runs ds_rebase (dssc pop -merge). Resolve any conflict markers, then rerun sanity.", "dim")],
yes="Merge"), confirmed)
def action_help(self):
self.push_screen(HelpDialog(VERSION, self.flow.conf))