Python
Merge branch 'main' into feature/memory
Rohit Pf21c53dd29b5
diff --cc coworker/server/manager.pyindex c838ea39,6ab60cd3..66a51ecc--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@@ -3667,53 -3799,177 +3819,217 @@@ class SessionManagerdef list_agents(self) -> list[dict[str, Any]]:return _list_agents()- def list_skills(self) -> list[dict[str, Any]]:- loader = SkillLoader([state_dir() / "skills"])- return loader.catalog()+ # -- skills (SKILLS-SPEC §4.4) ------------------------------------------------+ def list_skills(self, workspace: Optional[str] = None) -> list[dict[str, Any]]:+ """Enriched rows for the Settings screen (scope/source/enabled). Optional workspace+ adds that project's skills, with project copies shadowing same-named global ones."""+ return self.skill_store.rows(workspace or None)++ def reveal_skill(+ self, name: str, workspace: Optional[str] = None+ ) -> dict[str, Any]:+ """Open the skill's folder in the OS file manager (§6 "Show folder" — the power-user+ window into folder-is-truth). Same local-machine rationale as reveal_artifact."""+ import subprocess+ import sys++ try:+ folder, _scope = self.skill_store.find(name, workspace or None)+ except ValueError as exc:+ return {"ok": False, "error": str(exc)}+ try:+ if sys.platform == "darwin":+ subprocess.Popen(+ ["open", str(folder)],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ elif sys.platform == "win32":+ import os++ os.startfile(str(folder)) # type: ignore[attr-defined]+ else:+ subprocess.Popen(+ ["xdg-open", str(folder)],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ except OSError as exc:+ return {"ok": False, "error": str(exc)}+ return {"ok": True}++ def effective_skill_names(+ self, session_id: str, workspace: Optional[str | Path] = None+ ) -> set[str]:+ """The session's skill menu (§3): merged scopes − Settings disables − session mutes.+ The single resolver behind the engine catalog, the rail list, and the composer popup."""+ dirs = [self.skill_store.global_dir]+ if workspace:+ dirs.append(self.skill_store.project_dir(workspace))+ loader = SkillLoader(dirs)+ return effective_skills(+ names=set(loader.names()),+ disabled=self.skill_store.disabled_names(),+ session_overrides=self.session_skills.get(session_id),+ )++ def session_skills_view(+ self, session_id: str, workspace: Optional[str] = None+ ) -> dict[str, Any]:+ """The rail payload: every in-scope, Settings-enabled skill with its mute state."""+ disabled = self.skill_store.disabled_names()+ overrides = self.session_skills.get(session_id)+ rows = [+ {+ "name": r["name"],+ "description": r["description"],+ "scope": r["scope"],+ "enabled": overrides.get(r["name"], True),+ }+ for r in self.skill_store.rows(workspace or None)+ if r["name"] not in disabled+ ]+ return {"skills": rows}++ def _scratch_workspace_error(self, workspace: Any) -> Optional[dict[str, Any]]:+ """Refuse skill WRITES into a per-conversation scratch dir — a skill saved there is+ stranded in a throwaway folder. Backend chokepoint: guards every entry path (UI,+ REST, future import), not just the flows the GUI happens to gate."""+ if not workspace:+ return None+ try:+ ws = Path(str(workspace)).expanduser().resolve()+ if ws.is_relative_to(self.scratch_base().resolve()):+ return {+ "ok": False,+ "error": (+ "That folder is a temporary session space — skills saved there "+ "would be lost. Save it globally or pick a real project."+ ),+ }+ except OSError:+ pass+ return None++ def create_skill(self, body: dict[str, Any]) -> dict[str, Any]:+ blocked = self._scratch_workspace_error(body.get("workspace"))+ if blocked:+ return blocked+ try:+ created = self.skill_store.create(+ name=str(body.get("name", "")),+ description=str(body.get("description", "")),+ instructions=str(body.get("instructions", "")),+ scope=str(body.get("scope", "global") or "global"),+ workspace=body.get("workspace") or None,+ )+ except ValueError as exc:+ return {"ok": False, "error": str(exc)}+ return {"ok": True, "skill": created}++ def update_skill(self, name: str, body: dict[str, Any]) -> dict[str, Any]:+ try:+ if "enabled" in body:+ self.skill_store.set_enabled(name, bool(body["enabled"]))+ if body.get("description") is not None or body.get("instructions") is not None:+ self.skill_store.update(+ name,+ description=body.get("description"),+ instructions=body.get("instructions"),+ workspace=body.get("workspace") or None,+ )+ except ValueError as exc:+ return {"ok": False, "error": str(exc)}+ return {"ok": True}++ def delete_skill(self, name: str, workspace: Optional[str] = None) -> dict[str, Any]:+ try:+ self.skill_store.delete(name, workspace or None)+ except ValueError as exc:+ return {"ok": False, "error": str(exc)}+ return {"ok": True}++ def move_skill(self, name: str, body: dict[str, Any]) -> dict[str, Any]:+ # Moving INTO project scope must not target a scratch dir (moving OUT is fine —+ # that's the rescue path for already-stranded skills).+ if str(body.get("scope", "")) == "project":+ blocked = self._scratch_workspace_error(body.get("workspace"))+ if blocked:+ return blocked+ try:+ moved = self.skill_store.move(+ name,+ to_scope=str(body.get("scope", "")),+ workspace=body.get("workspace") or None,+ )+ except ValueError as exc:+ return {"ok": False, "error": str(exc)}+ return {"ok": True, "skill": moved}++ def stage_skill_upload(self, data: bytes, filename: str = "") -> dict[str, Any]:+ try:+ preview = self.skill_store.stage_upload(data, filename)+ except ValueError as exc:+ return {"ok": False, "error": str(exc)}+ return {"ok": True, **preview}++ def confirm_skill_upload(self, body: dict[str, Any]) -> dict[str, Any]:+ blocked = self._scratch_workspace_error(body.get("workspace"))+ if blocked:+ return blocked+ try:+ saved = self.skill_store.confirm_upload(+ str(body.get("token", "")),+ scope=str(body.get("scope", "global") or "global"),+ workspace=body.get("workspace") or None,+ )+ except ValueError as exc:+ return {"ok": False, "error": str(exc)}+ return {"ok": True, "skill": saved}+ def _memory_saved_notifier(self, session_id: str):+ """MEMORY-SPEC §5.1: push the memory_saved event that powers the GUI's save+ toast ("I'll remember that — … [Undo]"). Best-effort by design: `remember` may+ run with no socket attached (background runs) or off the loop thread — a lost+ toast never fails the save."""+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ loop = None++ def notify(item, previous=None) -> None:+ if loop is None or not loop.is_running():+ return+ payload = {+ "type": "memory_saved",+ "data": {+ "id": item.id,+ "scope": item.scope.value,+ "summary": item.summary or "",+ "content": item.content,+ # Set when this was an EDIT of an existing memory: the surface says+ # "I've updated what I remember" and Undo restores this text.+ "previous": previous or "",+ },+ }+ try:+ asyncio.run_coroutine_threadsafe(+ self.broadcast_session(session_id, payload), loop+ )+ except RuntimeError:+ pass++ return notify+def list_memory(self) -> list[dict[str, Any]]:return [- {"id": m.id, "scope": m.scope.value, "content": m.content}+ {+ "id": m.id,+ "scope": m.scope.value,+ "content": m.content,+ "summary": m.summary or "",+ "created_at": m.created_at or "",+ }for m in self.memory_store.list()]diff --cc surfaces/gui/src/App.tsxindex ecca5bf7,c2df912b..972abd9a--- a/surfaces/gui/src/App.tsx+++ b/surfaces/gui/src/App.tsx@@@ -207,10 -211,12 +214,12 @@@ export function App()const [scheduledOpenId, setScheduledOpenId] = useState<string | null>(null);const [gateCreate, setGateCreate] = useState(false);// Which Settings section the full-page Settings surface opens on (§ Settings-as-page).- const [settingsTab, setSettingsTab] = useState<"appearance" | "models" | "voice" | "memory" | "personas">(- "appearance",- );- const openSettings = (tab: "appearance" | "models" | "voice" | "memory" | "personas" = "appearance") => {+ const [settingsTab, setSettingsTab] = useState<- "appearance" | "models" | "skills" | "voice" | "personas"++ "appearance" | "models" | "skills" | "voice" | "memory" | "personas"+ >("appearance");+ const openSettings = (- tab: "appearance" | "models" | "skills" | "voice" | "personas" = "appearance",++ tab: "appearance" | "models" | "skills" | "voice" | "memory" | "personas" = "appearance",+ ) => {setSettingsTab(tab);setSurface("settings");};@@@ -712,24 -727,14 +730,32 @@@if (d.model) setModel(d.model);setItems((p) => [...p, { kind: "notice", tone: "info", text: d.text || "Model switched" }]);break;+ case "memory_saved":+ // §5.1 save notice — inline in the transcript, where the user is already+ // looking and where it keeps until they act (a corner toast disappeared+ // before it could be read or undone — owner-hit 2026-07-28). Summary is the+ // friendly one-liner; content is the fallback when the model skipped it.+ setItems((p) => [+ ...p,+ {+ kind: "memory",+ id: Number(d.id),+ text: String(d.summary || d.content || ""),+ // Present when an existing memory was edited rather than added — the+ // notice says so, and Undo restores this text instead of deleting.+ ...(d.previous ? { previous: String(d.previous) } : {}),+ },+ ]);+ announceMemoryChanged(); // Settings ▸ Memory, if open, is now stale+ break;+ case "compacting":+ setCompacting(true);+ break;+ case "compacted":+ // Auto-compaction marker (OPE-27): outbound-only — the transcript stays intact,+ // this divider just shows where the model's memory was summarized.+ setItems((p) => [...p, { kind: "notice", tone: "info", text: d.text || "Context compacted" }]);+ break;case "interrupted":flushPartialStream();setItems((p) => [...p, { kind: "notice", tone: "warn", text: "Interrupted." }]);diff --cc surfaces/gui/src/components/SettingsView.tsxindex 5221b72a,8a722f12..ac2ef488--- a/surfaces/gui/src/components/SettingsView.tsx+++ b/surfaces/gui/src/components/SettingsView.tsx@@@ -36,9 -39,9 +39,10 @@@ import { useThemePref } from "../theme"import { Icon } from "./Icon";import { PanelHead } from "./IntegrationsView";import { ModelsTab } from "./ManageTabs";+import { MemorySection } from "./MemorySection";import { GalleryModal } from "./GalleryModal";import { PersonasTab } from "./PersonasTab";+ import { SkillsTab } from "./SkillsTab";import { showPersonas } from "../flags";// Settings, restructured (Option 2) into a full-page surface that mirrors IntegrationsView's shell:@@@ -48,7 -51,7 +52,7 @@@// Models + Personas host the existing tab components inside the page shell (field re-skin to follow).// "appearance" is the General tab's stable key — callers deep-link with it, so the// rename (UX-021) changed only the label. "files" folded into General as a card.- type SetTab = "appearance" | "models" | "voice" | "memory" | "personas";-type SetTab = "appearance" | "models" | "skills" | "voice" | "personas";++type SetTab = "appearance" | "models" | "skills" | "voice" | "memory" | "personas";const CARD = "rounded-xl2 border border-line bg-panel";const FIELD_LABEL = "text-[12.5px] font-medium text-ink";@@@ -59,11 -62,11 +63,16 @@@ const BTN_ACCENT = "text-[12.5px] px-3const BTN_BORDERED ="text-[12.5px] px-3 py-2 rounded-lg border border-line bg-paper hover:border-lineStrong shrink-0";- const SET_TABS: { key: SetTab; label: string; icon: "sliders" | "code" | "mic" | "archive" | "sparkle" }[] = [-const SET_TABS: { key: SetTab; label: string; icon: "sliders" | "code" | "mic" | "sparkle" | "book" }[] = [++const SET_TABS: {++ key: SetTab;++ label: string;++ icon: "sliders" | "code" | "mic" | "archive" | "sparkle" | "book";++}[] = [{ key: "appearance", label: "General", icon: "sliders" },{ key: "models", label: "Models", icon: "code" },+ { key: "skills", label: "Skills", icon: "book" },{ key: "voice", label: "Voice input", icon: "mic" },+ { key: "memory", label: "Memory", icon: "archive" },{ key: "personas", label: "Personas", icon: "sparkle" },];@@@ -120,12 -127,13 +133,15 @@@ export function SettingsView(not under General. */}<div className="mt-6"><TokenSavingsCard />+ <CompactionCard /></div></section>+ ) : tab === "skills" ? (+ <SkillsTab onCreateSkill={onCreateSkill} />) : tab === "voice" ? (<VoiceInputSection />+ ) : tab === "memory" ? (+ <MemorySection />) : (<PersonasSection onOpenPersona={onOpenPersona} />)}diff --cc surfaces/gui/src/types.tsindex cb8c23fd,412a3490..02f81276--- a/surfaces/gui/src/types.ts+++ b/surfaces/gui/src/types.ts@@@ -18,7 -18,8 +18,9 @@@ export type EventType| "input_rejected"| "interrupted"| "model_changed"+ | "memory_saved"+ | "compacting"+ | "compacted"| "turn_done";export interface WsEvent {@@@ -132,15 -133,29 +134,35 @@@ export type Item// A live ask_user prompt (attended sessions answer inline; unattended ones route to the Inbox).kind: "question";question: string;- options?: string[];+ options?: QuestionOption[];allow_text?: boolean;multi?: boolean;+ header?: string;+ questions?: GroupedQuestion[];resolved?: string;}- | { kind: "notice"; tone: "info" | "warn"; text: string; retriable?: boolean };+ | { kind: "notice"; tone: "info" | "warn"; text: string; retriable?: boolean }+ // MEMORY-SPEC §5.1: the save notice, inline in the conversation where the user is+ // already looking (a corner toast vanished before it could be read or undone —+ // owner-hit 2026-07-28). Stays put. `previous` is set when an existing memory was+ // EDITED rather than a new one added (the update-don't-duplicate rule sends many+ // saves that way) — Undo restores that text instead of deleting the memory.+ | { kind: "memory"; id: number; text: string; previous?: string; undone?: boolean };++ // -- ask_user question metadata (OPE-51) --------------------------------------+ // An option is a plain string (renders as today's pill) or a rich object: `label` is the answer+ // value, `description` renders under it, `recommended` adds the green tag, `preview` is monospace+ // text shown in the side pane (≥1 preview switches the card to the two-pane layout).+ export type QuestionOption =+ | string+ | { label: string; description?: string; recommended?: boolean; preview?: string };++ // One step of a grouped ask_user call (up to 4, rendered as a stepper). The answer map is keyed+ // by `header` (falling back to `question`).+ export interface GroupedQuestion {+ question: string;+ header?: string;+ options?: QuestionOption[];+ allow_text?: boolean;+ multi?: boolean;+ }