deskc 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- deskc/__init__.py +3 -0
- deskc/cli.py +32 -0
- deskc/mcp_server.py +102 -0
- deskc/py.typed +0 -0
- deskc/server.py +161 -0
- deskc/static/index.html +384 -0
- deskc/store.py +256 -0
- deskc-0.1.0.dist-info/METADATA +132 -0
- deskc-0.1.0.dist-info/RECORD +12 -0
- deskc-0.1.0.dist-info/WHEEL +4 -0
- deskc-0.1.0.dist-info/entry_points.txt +2 -0
- deskc-0.1.0.dist-info/licenses/LICENSE +21 -0
deskc/__init__.py
ADDED
deskc/cli.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""The ``deskc`` command: ``deskc serve`` (the board page) and ``deskc mcp`` (the agent's tools)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main(argv: list[str] | None = None) -> None:
|
|
11
|
+
"""Run a ``deskc`` subcommand."""
|
|
12
|
+
parser = argparse.ArgumentParser(prog="deskc", description=__doc__)
|
|
13
|
+
parser.add_argument(
|
|
14
|
+
"--root", type=Path, default=None, help="folder that holds product/ (default: cwd)"
|
|
15
|
+
)
|
|
16
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
17
|
+
serve = sub.add_parser("serve", help="serve the board in a browser")
|
|
18
|
+
serve.add_argument("--port", type=int, default=8765)
|
|
19
|
+
sub.add_parser("mcp", help="serve the agent's tools over MCP (stdio)")
|
|
20
|
+
args = parser.parse_args(argv)
|
|
21
|
+
|
|
22
|
+
# The store reads its root when it is first imported, so set it before the import below.
|
|
23
|
+
if args.root is not None:
|
|
24
|
+
os.environ["DESKC_ROOT"] = str(args.root.resolve())
|
|
25
|
+
if args.command == "serve":
|
|
26
|
+
from deskc.server import serve as run_server
|
|
27
|
+
|
|
28
|
+
run_server(args.port)
|
|
29
|
+
else:
|
|
30
|
+
from deskc.mcp_server import run
|
|
31
|
+
|
|
32
|
+
run()
|
deskc/mcp_server.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""MCP server for the demo board: the agent's tools on the same files the page shows.
|
|
2
|
+
|
|
3
|
+
Run on stdio: ``deskc mcp``. The web server (``deskc serve``) watches the files, so
|
|
4
|
+
everything written here appears on every open page at once.
|
|
5
|
+
|
|
6
|
+
The agent proposes options and writes documents. It never chooses an option: that is the
|
|
7
|
+
person's decision, and ``choose`` is not a tool here.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Generator
|
|
13
|
+
from contextlib import contextmanager
|
|
14
|
+
from dataclasses import asdict
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from mcp.server.mcpserver import MCPServer
|
|
18
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
19
|
+
from mcp.types import ToolAnnotations
|
|
20
|
+
|
|
21
|
+
from deskc import store
|
|
22
|
+
|
|
23
|
+
INSTRUCTIONS = """\
|
|
24
|
+
A shared board of design options and documents. People watch it live in a browser.
|
|
25
|
+
- Propose design options as complete HTML pages (inline CSS, no external files). Give each
|
|
26
|
+
option a short note that says what is different from the others.
|
|
27
|
+
- Write documents as markdown. Start with a '# Title' line.
|
|
28
|
+
- Read get_choices before you change a design: a person may have chosen or rejected options.
|
|
29
|
+
- Never ask to choose an option for the person. You cannot.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
_READ = ToolAnnotations(read_only_hint=True, open_world_hint=False)
|
|
33
|
+
_WRITE = ToolAnnotations(read_only_hint=False, destructive_hint=False, open_world_hint=False)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@contextmanager
|
|
37
|
+
def refuse_bad_input() -> Generator[None]:
|
|
38
|
+
"""Turn a store error into a tool error, so the agent reads the reason."""
|
|
39
|
+
try:
|
|
40
|
+
yield
|
|
41
|
+
except (ValueError, KeyError, FileNotFoundError) as exc:
|
|
42
|
+
raise ToolError(str(exc) or exc.__class__.__name__) from exc
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
server = MCPServer("design-demo", version="0.0.0", instructions=INSTRUCTIONS)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@server.tool(annotations=_READ)
|
|
49
|
+
def list_artifacts() -> dict[str, Any]:
|
|
50
|
+
"""The designs (with their options) and the documents on the board."""
|
|
51
|
+
return {
|
|
52
|
+
"designs": [asdict(d) for d in store.load_designs()],
|
|
53
|
+
"documents": [asdict(d) for d in store.load_documents()],
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@server.tool(annotations=_READ)
|
|
58
|
+
def get_choices() -> list[dict[str, Any]]:
|
|
59
|
+
"""For each design: the option a person chose (or None) and the state of every option."""
|
|
60
|
+
return [
|
|
61
|
+
{"design": d.slug, "chosen": d.chosen, "states": {o.id: o.state for o in d.options}}
|
|
62
|
+
for d in store.load_designs()
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@server.tool(annotations=_READ)
|
|
67
|
+
def read_document(slug: str) -> str:
|
|
68
|
+
"""The markdown of one document."""
|
|
69
|
+
with refuse_bad_input():
|
|
70
|
+
return store.read_document(slug)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@server.tool(annotations=_WRITE)
|
|
74
|
+
def write_document(slug: str, markdown: str, title: str | None = None) -> str:
|
|
75
|
+
"""Create or replace a document. Its place on the canvas is kept."""
|
|
76
|
+
with refuse_bad_input():
|
|
77
|
+
store.write_document(slug, markdown, title)
|
|
78
|
+
return f"wrote document {slug}"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@server.tool(annotations=_WRITE)
|
|
82
|
+
def propose_option( # noqa: PLR0913, PLR0917 (the tool's arguments)
|
|
83
|
+
design: str,
|
|
84
|
+
option_id: str,
|
|
85
|
+
html: str,
|
|
86
|
+
note: str,
|
|
87
|
+
serves: list[str] | None = None,
|
|
88
|
+
view: str | None = None,
|
|
89
|
+
title: str | None = None,
|
|
90
|
+
) -> str:
|
|
91
|
+
"""Add or replace one design option as a full HTML page.
|
|
92
|
+
|
|
93
|
+
Pass ``view`` (for example ``web:/sales/invoices``) and ``title`` to create a new design.
|
|
94
|
+
"""
|
|
95
|
+
with refuse_bad_input():
|
|
96
|
+
store.propose_option(design, option_id, html, note, tuple(serves or ()), view, title)
|
|
97
|
+
return f"wrote option {option_id} of design {design}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def run() -> None:
|
|
101
|
+
"""Serve the tools on stdio."""
|
|
102
|
+
server.run("stdio")
|
deskc/py.typed
ADDED
|
File without changes
|
deskc/server.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Demo server: design options and documents on a shared canvas, with live updates.
|
|
2
|
+
|
|
3
|
+
Run: ``deskc serve`` then open http://127.0.0.1:8765 in one or more browsers.
|
|
4
|
+
|
|
5
|
+
- The server watches ``product/designs/`` and ``product/docs/``. A changed file is pushed to every
|
|
6
|
+
open page, whoever changed it: a person on the page, or an agent through the MCP server.
|
|
7
|
+
- Cursors and card drags are relayed live to every page (not saved). A dropped card is saved as
|
|
8
|
+
``x`` and ``y`` in its file.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import queue
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
from dataclasses import asdict
|
|
19
|
+
from http import HTTPStatus
|
|
20
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from deskc import store
|
|
25
|
+
|
|
26
|
+
STATIC = Path(__file__).parent / "static"
|
|
27
|
+
POLL_SECONDS = 0.25
|
|
28
|
+
KEEPALIVE_SECONDS = 15
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Hub:
|
|
32
|
+
"""Send each message to every open page."""
|
|
33
|
+
|
|
34
|
+
def __init__(self) -> None:
|
|
35
|
+
self._lock = threading.Lock()
|
|
36
|
+
self._subscribers: list[queue.Queue[dict[str, Any]]] = []
|
|
37
|
+
|
|
38
|
+
def subscribe(self) -> queue.Queue[dict[str, Any]]:
|
|
39
|
+
q: queue.Queue[dict[str, Any]] = queue.Queue()
|
|
40
|
+
with self._lock:
|
|
41
|
+
self._subscribers.append(q)
|
|
42
|
+
return q
|
|
43
|
+
|
|
44
|
+
def unsubscribe(self, q: queue.Queue[dict[str, Any]]) -> None:
|
|
45
|
+
with self._lock:
|
|
46
|
+
self._subscribers.remove(q)
|
|
47
|
+
|
|
48
|
+
def publish(self, message: dict[str, Any]) -> None:
|
|
49
|
+
with self._lock:
|
|
50
|
+
for q in self._subscribers:
|
|
51
|
+
q.put(message)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
HUB = Hub()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def watch_files() -> None:
|
|
58
|
+
"""Publish a ``file`` message each time a watched file changes."""
|
|
59
|
+
seen = store.snapshot()
|
|
60
|
+
while True:
|
|
61
|
+
time.sleep(POLL_SECONDS)
|
|
62
|
+
now = store.snapshot()
|
|
63
|
+
for name in sorted(now.keys() | seen.keys()):
|
|
64
|
+
if now.get(name) != seen.get(name):
|
|
65
|
+
HUB.publish({"type": "file", "path": name})
|
|
66
|
+
seen = now
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Handler(BaseHTTPRequestHandler):
|
|
70
|
+
def log_message(self, format: str, *args: object) -> None: # noqa: A002
|
|
71
|
+
"""Silence the per-request log line."""
|
|
72
|
+
del format, args
|
|
73
|
+
|
|
74
|
+
def _send(self, status: int, body: bytes, content_type: str) -> None:
|
|
75
|
+
self.send_response(status)
|
|
76
|
+
self.send_header("Content-Type", content_type)
|
|
77
|
+
self.send_header("Content-Length", str(len(body)))
|
|
78
|
+
self.send_header("Cache-Control", "no-store")
|
|
79
|
+
self.end_headers()
|
|
80
|
+
self.wfile.write(body)
|
|
81
|
+
|
|
82
|
+
def _json(self, status: int, payload: object) -> None:
|
|
83
|
+
self._send(status, json.dumps(payload).encode(), "application/json")
|
|
84
|
+
|
|
85
|
+
def _not_found(self) -> None:
|
|
86
|
+
self._send(HTTPStatus.NOT_FOUND, b"not found", "text/plain")
|
|
87
|
+
|
|
88
|
+
def do_GET(self) -> None:
|
|
89
|
+
path = self.path.split("?")[0]
|
|
90
|
+
if path == "/":
|
|
91
|
+
self._send(200, (STATIC / "index.html").read_bytes(), "text/html; charset=utf-8")
|
|
92
|
+
elif path == "/api/designs":
|
|
93
|
+
self._json(200, [asdict(d) for d in store.load_designs()])
|
|
94
|
+
elif path == "/api/docs":
|
|
95
|
+
self._json(200, [asdict(d) for d in store.load_documents()])
|
|
96
|
+
elif path == "/events":
|
|
97
|
+
self._events()
|
|
98
|
+
elif path.startswith("/files/"):
|
|
99
|
+
target = (store.DESIGNS / path.removeprefix("/files/")).resolve()
|
|
100
|
+
if store.DESIGNS not in target.parents or not target.is_file():
|
|
101
|
+
self._not_found()
|
|
102
|
+
else:
|
|
103
|
+
self._send(200, target.read_bytes(), "text/html; charset=utf-8")
|
|
104
|
+
elif path.startswith("/docs/") and path.endswith(".html"):
|
|
105
|
+
try:
|
|
106
|
+
page = store.render_document(path.removeprefix("/docs/").removesuffix(".html"))
|
|
107
|
+
except (ValueError, FileNotFoundError):
|
|
108
|
+
self._not_found()
|
|
109
|
+
else:
|
|
110
|
+
self._send(200, page.encode(), "text/html; charset=utf-8")
|
|
111
|
+
else:
|
|
112
|
+
self._not_found()
|
|
113
|
+
|
|
114
|
+
def do_POST(self) -> None:
|
|
115
|
+
if self.path not in ("/api/choose", "/api/move", "/api/presence"):
|
|
116
|
+
self._not_found()
|
|
117
|
+
return
|
|
118
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0"))))
|
|
119
|
+
try:
|
|
120
|
+
if self.path == "/api/choose":
|
|
121
|
+
store.choose(body["design"], body["option"])
|
|
122
|
+
elif self.path == "/api/move" and body.get("kind") == "doc":
|
|
123
|
+
store.move_document(body["slug"], round(body["x"]), round(body["y"]))
|
|
124
|
+
elif self.path == "/api/move":
|
|
125
|
+
store.move_option(
|
|
126
|
+
body["design"], body["option"], round(body["x"]), round(body["y"])
|
|
127
|
+
)
|
|
128
|
+
else:
|
|
129
|
+
HUB.publish({"type": "presence", **body})
|
|
130
|
+
except (KeyError, ValueError, FileNotFoundError):
|
|
131
|
+
self._json(400, {"error": "unknown or invalid name"})
|
|
132
|
+
return
|
|
133
|
+
self._json(200, {"ok": True})
|
|
134
|
+
|
|
135
|
+
def _events(self) -> None:
|
|
136
|
+
self.send_response(200)
|
|
137
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
138
|
+
self.send_header("Cache-Control", "no-store")
|
|
139
|
+
self.end_headers()
|
|
140
|
+
q = HUB.subscribe()
|
|
141
|
+
try:
|
|
142
|
+
while True:
|
|
143
|
+
try:
|
|
144
|
+
line = f"data: {json.dumps(q.get(timeout=KEEPALIVE_SECONDS))}\n\n"
|
|
145
|
+
except queue.Empty:
|
|
146
|
+
line = ": keepalive\n\n"
|
|
147
|
+
self.wfile.write(line.encode())
|
|
148
|
+
self.wfile.flush()
|
|
149
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
150
|
+
return
|
|
151
|
+
finally:
|
|
152
|
+
HUB.unsubscribe(q)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def serve(port: int = 8765) -> None:
|
|
156
|
+
"""Serve the board on ``127.0.0.1`` until interrupted."""
|
|
157
|
+
server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
|
|
158
|
+
server.daemon_threads = True
|
|
159
|
+
threading.Thread(target=watch_files, daemon=True).start()
|
|
160
|
+
sys.stdout.write(f"http://127.0.0.1:{port}\n")
|
|
161
|
+
server.serve_forever()
|
deskc/static/index.html
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<meta charset="utf-8">
|
|
3
|
+
<title>Design board</title>
|
|
4
|
+
<style>
|
|
5
|
+
:root { --line:#e3e6ec; --ink:#1d2433; --mute:#5b6477; --accent:#2f5bea; }
|
|
6
|
+
* { box-sizing: border-box; }
|
|
7
|
+
html, body { height:100%; margin:0; overflow:hidden; font:14px system-ui; color:var(--ink); }
|
|
8
|
+
header { position:fixed; inset:0 0 auto 0; z-index:10; height:48px; background:#fff;
|
|
9
|
+
border-bottom:1px solid var(--line); padding:0 16px; display:flex; gap:12px; align-items:center; }
|
|
10
|
+
header h1 { font-size:16px; margin:0; flex:1; }
|
|
11
|
+
#people { display:flex; gap:6px; }
|
|
12
|
+
.chip { font-size:12px; color:#fff; padding:2px 9px; border-radius:99px; }
|
|
13
|
+
#live { font-size:12px; color:var(--mute); }
|
|
14
|
+
#live.on::before { content:"● "; color:#2e9e5b; }
|
|
15
|
+
#live.off::before { content:"● "; color:#d64545; }
|
|
16
|
+
button { font:inherit; border:1px solid var(--accent); color:var(--accent); background:#fff;
|
|
17
|
+
border-radius:6px; padding:4px 10px; cursor:pointer; }
|
|
18
|
+
button:hover { background:var(--accent); color:#fff; }
|
|
19
|
+
#viewport { position:absolute; inset:48px 0 0 0; background:#f5f6f9 radial-gradient(#d5d9e2 1px, transparent 1px) 0 0/24px 24px;
|
|
20
|
+
cursor:grab; touch-action:none; }
|
|
21
|
+
#viewport.panning { cursor:grabbing; }
|
|
22
|
+
#viewport, #viewport * { user-select:none; -webkit-user-select:none; }
|
|
23
|
+
#world { position:absolute; left:0; top:0; transform-origin:0 0; will-change:transform; }
|
|
24
|
+
.label { position:absolute; left:0; top:0; font-weight:600; font-size:15px; white-space:nowrap; }
|
|
25
|
+
.label small { display:block; font:12px ui-monospace,monospace; color:var(--mute); font-weight:400; }
|
|
26
|
+
.card { position:absolute; left:0; top:0; width:420px; background:#fff; border:2px solid var(--line); border-radius:12px;
|
|
27
|
+
box-shadow:0 2px 8px #0001; }
|
|
28
|
+
.card.chosen { border-color:#2e9e5b; }
|
|
29
|
+
.card.rejected .frame { opacity:.5; }
|
|
30
|
+
.card.flash { border-color:var(--accent); }
|
|
31
|
+
.card.mine { box-shadow:0 10px 28px #0003; }
|
|
32
|
+
.meta { padding:10px 12px; display:flex; gap:8px; align-items:center; cursor:move; user-select:none; }
|
|
33
|
+
.meta b { font-size:15px; }
|
|
34
|
+
.meta .note { color:var(--mute); flex:1; }
|
|
35
|
+
.badge { font-size:11px; padding:2px 8px; border-radius:99px; background:#e8eaf0; color:var(--mute); }
|
|
36
|
+
.chosen .badge { background:#dff5e6; color:#17663a; }
|
|
37
|
+
.serves { padding:0 12px 8px; color:var(--mute); font-size:12px; min-height:22px; }
|
|
38
|
+
.frame { height:300px; border-top:1px solid var(--line); border-radius:0 0 10px 10px; overflow:hidden; }
|
|
39
|
+
.frame iframe { border:0; width:100%; height:100%; background:#fff; pointer-events:none; }
|
|
40
|
+
.card.interactive .frame iframe { pointer-events:auto; }
|
|
41
|
+
.card.doc { width:520px; border-color:#c9ced9; }
|
|
42
|
+
.card.doc .frame { height:360px; }
|
|
43
|
+
.card.doc .badge { background:#e8eaf0; }
|
|
44
|
+
.cursor { position:absolute; pointer-events:none; z-index:5; transition:transform .06s linear; }
|
|
45
|
+
.cursor svg { display:block; }
|
|
46
|
+
.cursor span { position:absolute; left:14px; top:14px; color:#fff; font-size:11px; padding:1px 6px;
|
|
47
|
+
border-radius:6px; white-space:nowrap; }
|
|
48
|
+
#hint { position:fixed; left:16px; bottom:12px; font-size:12px; color:var(--mute); z-index:10; }
|
|
49
|
+
</style>
|
|
50
|
+
<header>
|
|
51
|
+
<h1>Design board</h1>
|
|
52
|
+
<div id="people"></div>
|
|
53
|
+
<button id="fit">Fit</button>
|
|
54
|
+
<span id="live" class="off">connecting</span>
|
|
55
|
+
</header>
|
|
56
|
+
<div id="viewport"><div id="world"></div></div>
|
|
57
|
+
<div id="hint">Drag a card by its header. Drag the background to pan. Scroll to zoom. Double-click a card to use its page.</div>
|
|
58
|
+
<script>
|
|
59
|
+
const viewport = document.getElementById("viewport");
|
|
60
|
+
const world = document.getElementById("world");
|
|
61
|
+
const live = document.getElementById("live");
|
|
62
|
+
const people = document.getElementById("people");
|
|
63
|
+
|
|
64
|
+
const PALETTE = ["#e5484d", "#2f5bea", "#2e9e5b", "#c47a00", "#8e4ec6", "#0e8f8f"];
|
|
65
|
+
const me = {
|
|
66
|
+
id: Math.random().toString(36).slice(2, 8),
|
|
67
|
+
name: "Guest-" + Math.random().toString(36).slice(2, 5),
|
|
68
|
+
color: PALETTE[Math.floor(Math.random() * PALETTE.length)],
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const view = { x: 40, y: 20, z: 1 };
|
|
72
|
+
let designs = [];
|
|
73
|
+
let docs = [];
|
|
74
|
+
const cards = new Map(); // "slug/id" -> { el, d, o }
|
|
75
|
+
const labels = new Map(); // slug -> element
|
|
76
|
+
const users = new Map(); // id -> { name, color, x, y, seen, el }
|
|
77
|
+
let drag = null; // { key, dx, dy }
|
|
78
|
+
let pan = null; // { sx, sy, vx, vy }
|
|
79
|
+
let pointer = { x: 0, y: 0 };
|
|
80
|
+
|
|
81
|
+
const key = (d, o) => `${d.slug}/${o.id}`;
|
|
82
|
+
const defaultPos = (i, j) => ({ x: 40 + j * 460, y: 70 + i * 470 });
|
|
83
|
+
|
|
84
|
+
function applyView() {
|
|
85
|
+
world.style.transform = `translate(${view.x}px, ${view.y}px) scale(${view.z})`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function toWorld(clientX, clientY) {
|
|
89
|
+
const r = viewport.getBoundingClientRect();
|
|
90
|
+
return { x: (clientX - r.left - view.x) / view.z, y: (clientY - r.top - view.y) / view.z };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ---------- model -> DOM (keyed, so an update never reloads a page) ----------
|
|
94
|
+
async function refresh() {
|
|
95
|
+
[designs, docs] = await Promise.all([
|
|
96
|
+
fetch("/api/designs").then(r => r.json()),
|
|
97
|
+
fetch("/api/docs").then(r => r.json()),
|
|
98
|
+
]);
|
|
99
|
+
sync();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function sync() {
|
|
103
|
+
const seen = new Set();
|
|
104
|
+
designs.forEach((d, i) => d.options.forEach((o, j) => {
|
|
105
|
+
const k = key(d, o);
|
|
106
|
+
seen.add(k);
|
|
107
|
+
let c = cards.get(k);
|
|
108
|
+
if (!c) { c = { el: makeCard(d, o), d, o }; cards.set(k, c); world.append(c.el); }
|
|
109
|
+
c.d = d; c.o = o;
|
|
110
|
+
updateCard(c, i, j);
|
|
111
|
+
}));
|
|
112
|
+
docs.forEach((doc, k) => {
|
|
113
|
+
const kk = "doc/" + doc.slug;
|
|
114
|
+
seen.add(kk);
|
|
115
|
+
let c = cards.get(kk);
|
|
116
|
+
if (!c) { c = { el: makeDocCard(doc), doc, kind: "doc", w: 524 }; cards.set(kk, c); world.append(c.el); }
|
|
117
|
+
c.doc = doc;
|
|
118
|
+
updateDocCard(c, k);
|
|
119
|
+
});
|
|
120
|
+
for (const [k, c] of cards) if (!seen.has(k)) { c.el.remove(); cards.delete(k); }
|
|
121
|
+
layoutLabels();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function makeCard(d, o) {
|
|
125
|
+
const el = document.createElement("div");
|
|
126
|
+
el.innerHTML = `<div class="meta"><b></b><span class="note"></span><span class="badge"></span><button>Choose</button></div>
|
|
127
|
+
<div class="serves"></div><div class="frame"><iframe sandbox="allow-scripts"></iframe></div>`;
|
|
128
|
+
el.querySelector("iframe").src = `/files/${o.file}?v=${Date.now()}`;
|
|
129
|
+
el.querySelector("button").onclick = () =>
|
|
130
|
+
post("/api/choose", { design: d.slug, option: o.id });
|
|
131
|
+
el.querySelector(".meta").addEventListener("pointerdown", (e) => startDrag(e, key(d, o)));
|
|
132
|
+
el.querySelector(".frame").addEventListener("dblclick", () => {
|
|
133
|
+
document.querySelectorAll(".card.interactive").forEach(x => x.classList.remove("interactive"));
|
|
134
|
+
el.classList.add("interactive");
|
|
135
|
+
});
|
|
136
|
+
return el;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function updateCard(c, i, j) {
|
|
140
|
+
const { el, d, o } = c;
|
|
141
|
+
const k = key(d, o);
|
|
142
|
+
const keepInteractive = el.classList.contains("interactive");
|
|
143
|
+
el.className = `card ${o.state}` + (keepInteractive ? " interactive" : "") + (drag && drag.key === k ? " mine" : "");
|
|
144
|
+
el.querySelector("b").textContent = o.id.toUpperCase();
|
|
145
|
+
el.querySelector(".note").textContent = o.note;
|
|
146
|
+
el.querySelector(".badge").textContent = o.state;
|
|
147
|
+
el.querySelector(".serves").textContent = o.serves.length ? "serves " + o.serves.join(", ") : "";
|
|
148
|
+
if (!(drag && drag.key === k)) {
|
|
149
|
+
const p = o.x == null ? defaultPos(i, j) : { x: o.x, y: o.y };
|
|
150
|
+
c.x = p.x; c.y = p.y;
|
|
151
|
+
el.style.transform = `translate(${p.x}px, ${p.y}px)`;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function makeDocCard(doc) {
|
|
156
|
+
const el = document.createElement("div");
|
|
157
|
+
el.innerHTML = `<div class="meta"><b></b><span class="note"></span><span class="badge">document</span></div>
|
|
158
|
+
<div class="frame"><iframe sandbox=""></iframe></div>`;
|
|
159
|
+
el.querySelector("iframe").src = `/docs/${doc.slug}.html?v=${Date.now()}`;
|
|
160
|
+
el.querySelector(".meta").addEventListener("pointerdown", (e) => startDrag(e, "doc/" + doc.slug));
|
|
161
|
+
el.querySelector(".frame").addEventListener("dblclick", () => {
|
|
162
|
+
document.querySelectorAll(".card.interactive").forEach(x => x.classList.remove("interactive"));
|
|
163
|
+
el.classList.add("interactive");
|
|
164
|
+
});
|
|
165
|
+
return el;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function updateDocCard(c, k) {
|
|
169
|
+
const { el, doc } = c;
|
|
170
|
+
const kk = "doc/" + doc.slug;
|
|
171
|
+
const keepInteractive = el.classList.contains("interactive");
|
|
172
|
+
el.className = "card doc" + (keepInteractive ? " interactive" : "") + (drag && drag.key === kk ? " mine" : "");
|
|
173
|
+
el.querySelector("b").textContent = doc.title;
|
|
174
|
+
if (!(drag && drag.key === kk)) {
|
|
175
|
+
const p = doc.x == null ? { x: 40 + k * 560, y: 70 + designs.length * 470 } : { x: doc.x, y: doc.y };
|
|
176
|
+
c.x = p.x; c.y = p.y;
|
|
177
|
+
el.style.transform = `translate(${p.x}px, ${p.y}px)`;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function reloadDoc(slug) {
|
|
182
|
+
const c = cards.get("doc/" + slug);
|
|
183
|
+
if (!c) return;
|
|
184
|
+
c.el.querySelector("iframe").src = `/docs/${slug}.html?v=${Date.now()}`;
|
|
185
|
+
c.el.classList.add("flash");
|
|
186
|
+
setTimeout(() => c.el.classList.remove("flash"), 600);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function layoutLabels() {
|
|
190
|
+
for (const d of designs) {
|
|
191
|
+
let el = labels.get(d.slug);
|
|
192
|
+
if (!el) {
|
|
193
|
+
el = document.createElement("div");
|
|
194
|
+
el.className = "label";
|
|
195
|
+
el.innerHTML = "<span></span><small></small>";
|
|
196
|
+
world.append(el);
|
|
197
|
+
labels.set(d.slug, el);
|
|
198
|
+
}
|
|
199
|
+
if (el.firstChild.textContent !== d.title) el.firstChild.textContent = d.title;
|
|
200
|
+
if (el.lastChild.textContent !== d.view) el.lastChild.textContent = d.view;
|
|
201
|
+
const cs = d.options.map(o => cards.get(key(d, o))).filter(Boolean);
|
|
202
|
+
if (!cs.length) continue;
|
|
203
|
+
el.style.transform = `translate(${Math.min(...cs.map(c => c.x))}px, ${Math.min(...cs.map(c => c.y)) - 42}px)`;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function setCardPos(c, x, y) {
|
|
208
|
+
c.x = x; c.y = y;
|
|
209
|
+
c.el.style.transform = `translate(${x}px, ${y}px)`;
|
|
210
|
+
if (c.kind !== "doc") c.o = { ...c.o, x, y };
|
|
211
|
+
layoutLabels();
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function reloadFrame(file) {
|
|
215
|
+
for (const c of cards.values()) {
|
|
216
|
+
if (!c.o || c.o.file !== file) continue;
|
|
217
|
+
c.el.querySelector("iframe").src = `/files/${file}?v=${Date.now()}`;
|
|
218
|
+
c.el.classList.add("flash");
|
|
219
|
+
setTimeout(() => c.el.classList.remove("flash"), 600);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ---------- talking to the server ----------
|
|
224
|
+
function post(url, body) {
|
|
225
|
+
return fetch(url, { method: "POST", body: JSON.stringify(body), keepalive: true });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
let lastSent = 0;
|
|
229
|
+
function sendPresence(force) {
|
|
230
|
+
const t = performance.now();
|
|
231
|
+
if (!force && t - lastSent < 40) return;
|
|
232
|
+
lastSent = t;
|
|
233
|
+
const c = drag && cards.get(drag.key);
|
|
234
|
+
post("/api/presence", {
|
|
235
|
+
id: me.id, name: me.name, color: me.color, x: pointer.x, y: pointer.y,
|
|
236
|
+
drag: c ? { key: drag.key, x: c.x, y: c.y } : null,
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ---------- interaction: drag a card, pan, zoom ----------
|
|
241
|
+
function startDrag(e, k) {
|
|
242
|
+
if (e.target.tagName === "BUTTON" || e.button !== 0) return;
|
|
243
|
+
e.stopPropagation();
|
|
244
|
+
e.preventDefault();
|
|
245
|
+
const c = cards.get(k);
|
|
246
|
+
const w = toWorld(e.clientX, e.clientY);
|
|
247
|
+
drag = { key: k, dx: w.x - c.x, dy: w.y - c.y };
|
|
248
|
+
c.el.classList.add("mine");
|
|
249
|
+
viewport.setPointerCapture(e.pointerId);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
viewport.addEventListener("pointerdown", (e) => {
|
|
253
|
+
document.querySelectorAll(".card.interactive").forEach(x => x.classList.remove("interactive"));
|
|
254
|
+
if (drag || e.button !== 0) return;
|
|
255
|
+
e.preventDefault();
|
|
256
|
+
pan = { sx: e.clientX, sy: e.clientY, vx: view.x, vy: view.y };
|
|
257
|
+
viewport.classList.add("panning");
|
|
258
|
+
viewport.setPointerCapture(e.pointerId);
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
viewport.addEventListener("pointermove", (e) => {
|
|
262
|
+
pointer = toWorld(e.clientX, e.clientY);
|
|
263
|
+
if (drag) {
|
|
264
|
+
const c = cards.get(drag.key);
|
|
265
|
+
setCardPos(c, Math.round(pointer.x - drag.dx), Math.round(pointer.y - drag.dy));
|
|
266
|
+
} else if (pan) {
|
|
267
|
+
view.x = pan.vx + (e.clientX - pan.sx);
|
|
268
|
+
view.y = pan.vy + (e.clientY - pan.sy);
|
|
269
|
+
applyView();
|
|
270
|
+
}
|
|
271
|
+
sendPresence(false);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
function endPointer() {
|
|
275
|
+
if (drag) {
|
|
276
|
+
const c = cards.get(drag.key);
|
|
277
|
+
sendPresence(true);
|
|
278
|
+
post("/api/move", c.kind === "doc"
|
|
279
|
+
? { kind: "doc", slug: c.doc.slug, x: c.x, y: c.y }
|
|
280
|
+
: { design: c.d.slug, option: c.o.id, x: c.x, y: c.y });
|
|
281
|
+
c.el.classList.remove("mine");
|
|
282
|
+
drag = null;
|
|
283
|
+
sendPresence(true);
|
|
284
|
+
}
|
|
285
|
+
pan = null;
|
|
286
|
+
viewport.classList.remove("panning");
|
|
287
|
+
}
|
|
288
|
+
viewport.addEventListener("pointerup", endPointer);
|
|
289
|
+
viewport.addEventListener("pointercancel", endPointer);
|
|
290
|
+
|
|
291
|
+
viewport.addEventListener("wheel", (e) => {
|
|
292
|
+
e.preventDefault();
|
|
293
|
+
const r = viewport.getBoundingClientRect();
|
|
294
|
+
const mx = e.clientX - r.left, my = e.clientY - r.top;
|
|
295
|
+
const z = Math.min(2, Math.max(0.2, view.z * Math.exp(-e.deltaY * 0.0015)));
|
|
296
|
+
view.x = mx - (mx - view.x) * (z / view.z);
|
|
297
|
+
view.y = my - (my - view.y) * (z / view.z);
|
|
298
|
+
view.z = z;
|
|
299
|
+
applyView();
|
|
300
|
+
}, { passive: false });
|
|
301
|
+
|
|
302
|
+
function fit() {
|
|
303
|
+
const cs = [...cards.values()];
|
|
304
|
+
if (!cs.length) return;
|
|
305
|
+
const x0 = Math.min(...cs.map(c => c.x)), y0 = Math.min(...cs.map(c => c.y)) - 50;
|
|
306
|
+
const x1 = Math.max(...cs.map(c => c.x + (c.w ?? 424))), y1 = Math.max(...cs.map(c => c.y + 440));
|
|
307
|
+
const r = viewport.getBoundingClientRect();
|
|
308
|
+
const z = Math.min(1, r.width / (x1 - x0 + 80), r.height / (y1 - y0 + 80));
|
|
309
|
+
view.z = z;
|
|
310
|
+
view.x = (r.width - (x1 - x0) * z) / 2 - x0 * z;
|
|
311
|
+
view.y = (r.height - (y1 - y0) * z) / 2 - y0 * z;
|
|
312
|
+
applyView();
|
|
313
|
+
}
|
|
314
|
+
document.getElementById("fit").onclick = fit;
|
|
315
|
+
|
|
316
|
+
// ---------- other people: cursors and live drags ----------
|
|
317
|
+
function onPresence(m) {
|
|
318
|
+
if (m.id === me.id) return;
|
|
319
|
+
let u = users.get(m.id);
|
|
320
|
+
if (!u) {
|
|
321
|
+
const el = document.createElement("div");
|
|
322
|
+
el.className = "cursor";
|
|
323
|
+
el.innerHTML = `<svg width="16" height="16" viewBox="0 0 16 16"><path d="M1 1l5 13 2-5 5-2z" fill="${m.color}" stroke="#fff"/></svg><span style="background:${m.color}"></span>`;
|
|
324
|
+
el.querySelector("span").textContent = m.name;
|
|
325
|
+
world.append(el);
|
|
326
|
+
u = { el };
|
|
327
|
+
users.set(m.id, u);
|
|
328
|
+
}
|
|
329
|
+
Object.assign(u, { name: m.name, color: m.color, seen: Date.now() });
|
|
330
|
+
u.el.style.transform = `translate(${m.x}px, ${m.y}px)`;
|
|
331
|
+
if (m.drag) {
|
|
332
|
+
const c = cards.get(m.drag.key);
|
|
333
|
+
if (c && !(drag && drag.key === m.drag.key)) {
|
|
334
|
+
setCardPos(c, m.drag.x, m.drag.y);
|
|
335
|
+
c.el.style.outline = `3px solid ${m.color}`;
|
|
336
|
+
u.dragging = m.drag.key;
|
|
337
|
+
}
|
|
338
|
+
} else if (u.dragging) {
|
|
339
|
+
const c = cards.get(u.dragging);
|
|
340
|
+
if (c) c.el.style.outline = "";
|
|
341
|
+
u.dragging = null;
|
|
342
|
+
}
|
|
343
|
+
renderPeople();
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function renderPeople() {
|
|
347
|
+
const all = [{ name: me.name + " (you)", color: me.color }, ...users.values()];
|
|
348
|
+
people.replaceChildren(...all.map(u => {
|
|
349
|
+
const s = document.createElement("span");
|
|
350
|
+
s.className = "chip";
|
|
351
|
+
s.style.background = u.color;
|
|
352
|
+
s.textContent = u.name;
|
|
353
|
+
return s;
|
|
354
|
+
}));
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
setInterval(() => {
|
|
358
|
+
let changed = false;
|
|
359
|
+
for (const [id, u] of users) {
|
|
360
|
+
if (Date.now() - u.seen > 8000) { u.el.remove(); users.delete(id); changed = true; }
|
|
361
|
+
}
|
|
362
|
+
if (changed) renderPeople();
|
|
363
|
+
}, 2000);
|
|
364
|
+
|
|
365
|
+
// ---------- live connection ----------
|
|
366
|
+
function connect() {
|
|
367
|
+
const es = new EventSource("/events");
|
|
368
|
+
es.onopen = () => { live.textContent = "live"; live.className = "on"; };
|
|
369
|
+
es.onerror = () => { live.textContent = "reconnecting"; live.className = "off"; };
|
|
370
|
+
es.onmessage = (e) => {
|
|
371
|
+
const m = JSON.parse(e.data);
|
|
372
|
+
if (m.type === "presence") onPresence(m);
|
|
373
|
+
else if (m.type === "file") {
|
|
374
|
+
if (m.path.startsWith("designs/") && m.path.endsWith(".html")) reloadFrame(m.path.slice(8));
|
|
375
|
+
else if (m.path.startsWith("docs/")) { reloadDoc(m.path.slice(5).replace(/\.md$/, "")); refresh(); }
|
|
376
|
+
else refresh();
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
applyView();
|
|
382
|
+
renderPeople();
|
|
383
|
+
refresh().then(() => { fit(); connect(); sendPresence(true); });
|
|
384
|
+
</script>
|
deskc/store.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""The data layer of the demo: design options and documents, as files.
|
|
2
|
+
|
|
3
|
+
Both the web server (``serve.py``) and the MCP server (``mcp_server.py``) use this module.
|
|
4
|
+
Files are the source of truth. Every write goes through a function here, which checks the input.
|
|
5
|
+
|
|
6
|
+
- Design: ``product/designs/<slug>.yaml`` plus one HTML file per option.
|
|
7
|
+
- Document: ``product/docs/<slug>.md``, markdown with an optional front matter (``title``, ``x``, ``y``).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import html
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import markdown
|
|
20
|
+
import yaml
|
|
21
|
+
|
|
22
|
+
ROOT = Path(os.environ.get("DESKC_ROOT", Path.cwd())).resolve()
|
|
23
|
+
PRODUCT = ROOT / "product"
|
|
24
|
+
DESIGNS = PRODUCT / "designs"
|
|
25
|
+
DOCS = PRODUCT / "docs"
|
|
26
|
+
|
|
27
|
+
NAME = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")
|
|
28
|
+
FRONT_MATTER = re.compile(r"\A---\n(.*?)\n---\n?", re.DOTALL)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Option:
|
|
33
|
+
id: str
|
|
34
|
+
file: str
|
|
35
|
+
note: str
|
|
36
|
+
state: str
|
|
37
|
+
serves: tuple[str, ...]
|
|
38
|
+
x: int | None = None
|
|
39
|
+
y: int | None = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Design:
|
|
44
|
+
slug: str
|
|
45
|
+
view: str
|
|
46
|
+
title: str
|
|
47
|
+
chosen: str | None
|
|
48
|
+
options: tuple[Option, ...]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Document:
|
|
53
|
+
slug: str
|
|
54
|
+
title: str
|
|
55
|
+
x: int | None = None
|
|
56
|
+
y: int | None = None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def check_name(kind: str, value: str) -> str:
|
|
60
|
+
"""Return ``value`` if it is a safe file name part. Raise ``ValueError`` if not."""
|
|
61
|
+
if not NAME.match(value):
|
|
62
|
+
raise ValueError(f"{kind} must be lowercase letters, digits and dashes: {value!r}")
|
|
63
|
+
return value
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def write_atomic(path: Path, text: str) -> None:
|
|
67
|
+
"""Write a file in one step, so a reader never sees half a file."""
|
|
68
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
tmp = path.with_name(f".{path.name}.tmp")
|
|
70
|
+
tmp.write_text(text)
|
|
71
|
+
tmp.replace(path)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ---------- designs ----------
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def design_path(slug: str) -> Path:
|
|
78
|
+
return DESIGNS / f"{check_name('design', slug)}.yaml"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def load_design(path: Path) -> Design:
|
|
82
|
+
"""Read one design YAML file into a ``Design``."""
|
|
83
|
+
raw = yaml.safe_load(path.read_text())
|
|
84
|
+
options = tuple(
|
|
85
|
+
Option(
|
|
86
|
+
id=o["id"],
|
|
87
|
+
file=o["file"],
|
|
88
|
+
note=o.get("note", ""),
|
|
89
|
+
state="chosen" if raw.get("chosen") == o["id"] else o.get("state", "proposed"),
|
|
90
|
+
serves=tuple(o.get("serves", ())),
|
|
91
|
+
x=o.get("x"),
|
|
92
|
+
y=o.get("y"),
|
|
93
|
+
)
|
|
94
|
+
for o in raw["options"]
|
|
95
|
+
)
|
|
96
|
+
return Design(path.stem, raw["view"], raw.get("title", path.stem), raw.get("chosen"), options)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def load_designs() -> list[Design]:
|
|
100
|
+
return [load_design(p) for p in sorted(DESIGNS.glob("*.yaml"))]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _save_design(slug: str, raw: dict[str, Any]) -> None:
|
|
104
|
+
write_atomic(design_path(slug), yaml.safe_dump(raw, sort_keys=False))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def choose(slug: str, option_id: str) -> None:
|
|
108
|
+
"""Record the person's choice: ``chosen`` and the state of every option."""
|
|
109
|
+
raw = yaml.safe_load(design_path(slug).read_text())
|
|
110
|
+
if option_id not in [o["id"] for o in raw["options"]]:
|
|
111
|
+
raise KeyError(option_id)
|
|
112
|
+
raw["chosen"] = option_id
|
|
113
|
+
for o in raw["options"]:
|
|
114
|
+
o["state"] = "chosen" if o["id"] == option_id else "rejected"
|
|
115
|
+
_save_design(slug, raw)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def move_option(slug: str, option_id: str, x: int, y: int) -> None:
|
|
119
|
+
"""Write the canvas position of one option."""
|
|
120
|
+
raw = yaml.safe_load(design_path(slug).read_text())
|
|
121
|
+
for o in raw["options"]:
|
|
122
|
+
if o["id"] == option_id:
|
|
123
|
+
o["x"], o["y"] = x, y
|
|
124
|
+
_save_design(slug, raw)
|
|
125
|
+
return
|
|
126
|
+
raise KeyError(option_id)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def propose_option( # noqa: PLR0913, PLR0917 (mirrors the tool's arguments)
|
|
130
|
+
slug: str,
|
|
131
|
+
option_id: str,
|
|
132
|
+
page: str,
|
|
133
|
+
note: str,
|
|
134
|
+
serves: tuple[str, ...] = (),
|
|
135
|
+
view: str | None = None,
|
|
136
|
+
title: str | None = None,
|
|
137
|
+
) -> None:
|
|
138
|
+
"""Add or replace one option of a design: write its HTML page and its YAML entry.
|
|
139
|
+
|
|
140
|
+
``view`` and ``title`` are required when the design does not exist yet. The state of an
|
|
141
|
+
option is ``proposed`` here: only a person chooses.
|
|
142
|
+
"""
|
|
143
|
+
check_name("option id", option_id)
|
|
144
|
+
if "<" not in page:
|
|
145
|
+
raise ValueError("page must be HTML")
|
|
146
|
+
path = design_path(slug)
|
|
147
|
+
raw: dict[str, Any]
|
|
148
|
+
if path.exists():
|
|
149
|
+
raw = yaml.safe_load(path.read_text())
|
|
150
|
+
elif view:
|
|
151
|
+
raw = {"view": view, "title": title or slug, "chosen": None, "options": []}
|
|
152
|
+
else:
|
|
153
|
+
raise ValueError(f"design {slug!r} does not exist: pass view (and title) to create it")
|
|
154
|
+
file = f"{slug}/{option_id}.html"
|
|
155
|
+
write_atomic(DESIGNS / file, page)
|
|
156
|
+
entry = {
|
|
157
|
+
"id": option_id,
|
|
158
|
+
"file": file,
|
|
159
|
+
"note": note,
|
|
160
|
+
"state": "proposed",
|
|
161
|
+
"serves": list(serves),
|
|
162
|
+
}
|
|
163
|
+
for i, o in enumerate(raw["options"]):
|
|
164
|
+
if o["id"] == option_id:
|
|
165
|
+
entry.update({k: o[k] for k in ("x", "y") if k in o})
|
|
166
|
+
entry["state"] = o.get("state", "proposed")
|
|
167
|
+
raw["options"][i] = entry
|
|
168
|
+
break
|
|
169
|
+
else:
|
|
170
|
+
raw["options"].append(entry)
|
|
171
|
+
_save_design(slug, raw)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# ---------- documents ----------
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def doc_path(slug: str) -> Path:
|
|
178
|
+
return DOCS / f"{check_name('document', slug)}.md"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def split_front_matter(text: str) -> tuple[dict[str, Any], str]:
|
|
182
|
+
"""Return the front matter (as a dict) and the body of a document."""
|
|
183
|
+
m = FRONT_MATTER.match(text)
|
|
184
|
+
if not m:
|
|
185
|
+
return {}, text
|
|
186
|
+
return yaml.safe_load(m.group(1)) or {}, text[m.end() :]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def join_front_matter(meta: dict[str, Any], body: str) -> str:
|
|
190
|
+
if not meta:
|
|
191
|
+
return body
|
|
192
|
+
return f"---\n{yaml.safe_dump(meta, sort_keys=False).strip()}\n---\n{body}"
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def load_document(path: Path) -> Document:
|
|
196
|
+
meta, body = split_front_matter(path.read_text())
|
|
197
|
+
first = next((ln[2:].strip() for ln in body.splitlines() if ln.startswith("# ")), path.stem)
|
|
198
|
+
return Document(path.stem, meta.get("title", first), meta.get("x"), meta.get("y"))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def load_documents() -> list[Document]:
|
|
202
|
+
return [load_document(p) for p in sorted(DOCS.glob("*.md"))]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def read_document(slug: str) -> str:
|
|
206
|
+
"""Return the markdown body of a document."""
|
|
207
|
+
return split_front_matter(doc_path(slug).read_text())[1]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def write_document(slug: str, body: str, title: str | None = None) -> None:
|
|
211
|
+
"""Create or replace a document. The position (``x``, ``y``) of an existing one is kept."""
|
|
212
|
+
if not body.strip():
|
|
213
|
+
raise ValueError("document is empty")
|
|
214
|
+
path = doc_path(slug)
|
|
215
|
+
meta = split_front_matter(path.read_text())[0] if path.exists() else {}
|
|
216
|
+
if title:
|
|
217
|
+
meta["title"] = title
|
|
218
|
+
write_atomic(path, join_front_matter(meta, body))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def move_document(slug: str, x: int, y: int) -> None:
|
|
222
|
+
"""Write the canvas position of a document into its front matter."""
|
|
223
|
+
path = doc_path(slug)
|
|
224
|
+
meta, body = split_front_matter(path.read_text())
|
|
225
|
+
meta["x"], meta["y"] = x, y
|
|
226
|
+
write_atomic(path, join_front_matter(meta, body))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
PAGE = """<!doctype html><meta charset="utf-8"><style>
|
|
230
|
+
body{{font:15px/1.55 Georgia,serif;color:#1d2433;margin:0;padding:24px 28px;background:#fff}}
|
|
231
|
+
h1,h2,h3{{font-family:system-ui;line-height:1.2}} h1{{font-size:24px}} h2{{font-size:18px}}
|
|
232
|
+
code{{background:#f0f2f6;padding:1px 4px;border-radius:4px}} pre{{background:#f0f2f6;padding:10px;overflow:auto}}
|
|
233
|
+
table{{border-collapse:collapse}} td,th{{border:1px solid #d5d9e2;padding:4px 8px}}
|
|
234
|
+
blockquote{{margin:0;padding-left:12px;border-left:3px solid #d5d9e2;color:#5b6477}}
|
|
235
|
+
</style>{body}"""
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def render_document(slug: str) -> str:
|
|
239
|
+
"""Return a document as a full HTML page. Raw HTML in the markdown is escaped."""
|
|
240
|
+
text = html.escape(read_document(slug), quote=False)
|
|
241
|
+
body = markdown.markdown(text.replace(">", ">"), extensions=["tables", "fenced_code"])
|
|
242
|
+
return PAGE.format(body=body)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# ---------- watching ----------
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def snapshot() -> dict[str, float]:
|
|
249
|
+
"""Return the modification time of every file under ``product/designs`` and ``product/docs``."""
|
|
250
|
+
out: dict[str, float] = {}
|
|
251
|
+
for base in (DESIGNS, DOCS):
|
|
252
|
+
if base.exists():
|
|
253
|
+
for p in base.rglob("*"):
|
|
254
|
+
if p.is_file() and not p.name.startswith("."):
|
|
255
|
+
out[f"{base.name}/{p.relative_to(base)}"] = p.stat().st_mtime
|
|
256
|
+
return out
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: deskc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Local live board where an agent proposes design options and documents and people choose and move them
|
|
5
|
+
Project-URL: Homepage, https://gitlab.com/cardona-oss/deskc
|
|
6
|
+
Project-URL: Repository, https://gitlab.com/cardona-oss/deskc
|
|
7
|
+
Project-URL: Documentation, https://cardona-oss.gitlab.io/deskc/
|
|
8
|
+
Project-URL: Changelog, https://gitlab.com/cardona-oss/deskc/-/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://gitlab.com/cardona-oss/deskc/-/issues
|
|
10
|
+
Author-email: Jorge Cardona <jorgeecardona@gmail.com>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: agent,canvas,design,live,mcp,whiteboard
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Software Development :: User Interfaces
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.12
|
|
22
|
+
Requires-Dist: markdown>=3.6
|
|
23
|
+
Requires-Dist: mcp<3,>=2
|
|
24
|
+
Requires-Dist: pyyaml>=6
|
|
25
|
+
Provides-Extra: docs
|
|
26
|
+
Requires-Dist: mkdocs-llmstxt>=0.5; extra == 'docs'
|
|
27
|
+
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
|
|
28
|
+
Requires-Dist: mkdocs>=1.6; extra == 'docs'
|
|
29
|
+
Requires-Dist: mkdocstrings[python]>=0.27; extra == 'docs'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
<h1 align="center">deskc</h1>
|
|
33
|
+
|
|
34
|
+
<p align="center"><strong>Open a local board, ask your agent for design options, then choose and move them yourself.</strong></p>
|
|
35
|
+
|
|
36
|
+
<p align="center">
|
|
37
|
+
<a href="https://pypi.org/project/deskc/"><img alt="PyPI" src="https://img.shields.io/pypi/v/deskc?style=flat-square"></a>
|
|
38
|
+
<a href="https://pypi.org/project/deskc/"><img alt="Python versions" src="https://img.shields.io/pypi/pyversions/deskc?style=flat-square"></a>
|
|
39
|
+
<a href="https://cardona-oss.gitlab.io/deskc/"><img alt="Docs" src="https://img.shields.io/badge/docs-cardona--oss.gitlab.io%2Fdeskc-blue?style=flat-square"></a>
|
|
40
|
+
<a href="https://gitlab.com/cardona-oss/deskc/-/pipelines"><img alt="Pipeline" src="https://img.shields.io/gitlab/pipeline-status/cardona-oss%2Fdeskc?branch=main&style=flat-square"></a>
|
|
41
|
+
<a href="https://gitlab.com/cardona-oss/deskc/-/blob/main/LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-blue?style=flat-square"></a>
|
|
42
|
+
</p>
|
|
43
|
+
|
|
44
|
+
<p align="center">
|
|
45
|
+
<a href="https://cardona-oss.gitlab.io/deskc/">Docs</a> ·
|
|
46
|
+
<a href="https://gitlab.com/cardona-oss/deskc/-/blob/main/CHANGELOG.md">Changelog</a>
|
|
47
|
+
</p>
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Overview
|
|
52
|
+
|
|
53
|
+
deskc shows design options and documents on one canvas in your browser. The files are the source of
|
|
54
|
+
truth: an agent writes them (through an MCP server or by editing files), and every open page
|
|
55
|
+
updates at once. You drag cards, zoom, and pick an option. Your pick is saved in the file.
|
|
56
|
+
|
|
57
|
+
Use it to compare alternative pages or visual designs side by side while an agent works.
|
|
58
|
+
|
|
59
|
+
Status: alpha. Design options and markdown documents work. Sheets and decks are not built.
|
|
60
|
+
|
|
61
|
+
## Install
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
uv tool install deskc
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Python 3.12 or later. Linux, macOS, Windows (not tested on the last two).
|
|
68
|
+
|
|
69
|
+
## Quickstart
|
|
70
|
+
|
|
71
|
+
1. From a clone of this repo, copy the sample into a folder and serve it:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
cp -r examples/product ./product
|
|
75
|
+
deskc serve
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
2. Open http://127.0.0.1:8765. Drag a card by its header. Double-click a page to interact with it.
|
|
79
|
+
3. Give your agent the MCP server. Put this in `.mcp.json`:
|
|
80
|
+
|
|
81
|
+
```json
|
|
82
|
+
{"mcpServers": {"deskc": {"command": "deskc", "args": ["mcp"]}}}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
4. Ask the agent for a new option. It calls `propose_option` and the card appears on the page.
|
|
86
|
+
|
|
87
|
+
## Files
|
|
88
|
+
|
|
89
|
+
```text
|
|
90
|
+
product/designs/<design>.yaml view, title, chosen, options (id, file, note, state, x, y)
|
|
91
|
+
product/designs/<design>/<id>.html one full HTML page per option
|
|
92
|
+
product/docs/<document>.md markdown, optional front matter: title, x, y
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`--root DIR` sets the folder that holds `product/` (default: the current folder).
|
|
96
|
+
|
|
97
|
+
## Agent tools
|
|
98
|
+
|
|
99
|
+
- `list_artifacts`: the designs, their options and the documents.
|
|
100
|
+
- `get_choices`: what a person chose, and the state of every option.
|
|
101
|
+
- `propose_option`: add or replace one option as a full HTML page.
|
|
102
|
+
- `read_document`, `write_document`: markdown documents.
|
|
103
|
+
|
|
104
|
+
There is no tool to choose an option. Only a person chooses.
|
|
105
|
+
|
|
106
|
+
## Key features
|
|
107
|
+
|
|
108
|
+
- Live updates: a changed file reaches every open page in under half a second.
|
|
109
|
+
- Live cursors and drags between people on the same server.
|
|
110
|
+
- Pan, zoom, fit, and a sandboxed frame for each page.
|
|
111
|
+
- Writes are atomic and names are checked, so an agent cannot write outside `product/`.
|
|
112
|
+
|
|
113
|
+
## Limits
|
|
114
|
+
|
|
115
|
+
- One server on `127.0.0.1`. Remote collaborators need a tunnel. There is no login.
|
|
116
|
+
- Saving a design rewrites its YAML file and drops its comments.
|
|
117
|
+
- Last write wins. No undo.
|
|
118
|
+
- Many live pages on screen at a low zoom can be slow.
|
|
119
|
+
|
|
120
|
+
## Links
|
|
121
|
+
|
|
122
|
+
- Docs: https://cardona-oss.gitlab.io/deskc/
|
|
123
|
+
- Source: https://gitlab.com/cardona-oss/deskc
|
|
124
|
+
- Changelog: https://gitlab.com/cardona-oss/deskc/-/blob/main/CHANGELOG.md
|
|
125
|
+
|
|
126
|
+
## Contributing
|
|
127
|
+
|
|
128
|
+
`uv sync && make install-hooks`, then `make check`. See [CONTRIBUTING.md](https://gitlab.com/cardona-oss/deskc/-/blob/main/CONTRIBUTING.md).
|
|
129
|
+
|
|
130
|
+
## License
|
|
131
|
+
|
|
132
|
+
MIT © 2026 Jorge Cardona (see [LICENSE](https://gitlab.com/cardona-oss/deskc/-/blob/main/LICENSE)).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
deskc/__init__.py,sha256=tHjwunOLKj419ptI9Cf6-SwyROk6wmWVd4MpPsYJOls,123
|
|
2
|
+
deskc/cli.py,sha256=AyjO6gpBMLLT56D2Vam8A8vEOxMJOHieuLNhuDjbXL0,1142
|
|
3
|
+
deskc/mcp_server.py,sha256=kVOBIAFyK2Iw-OojmFZ6xMqbBN1jn3qEE5K2wWgyc_8,3527
|
|
4
|
+
deskc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
deskc/server.py,sha256=DjmYw4NMulEUcyXd-bYuOh3DfQD4P2Feg798VKvWFyA,5880
|
|
6
|
+
deskc/store.py,sha256=Ju8io3AfK8H4o1zFcpxmGwimppm7DQUk0w38RXOxjvs,8282
|
|
7
|
+
deskc/static/index.html,sha256=h9ZDYm9oThBRTUIZvx5_rBNPs8Cix32yEro8vuMyBko,15182
|
|
8
|
+
deskc-0.1.0.dist-info/METADATA,sha256=fn0OElX5th2T6zjysNojoZKhx9Bs95M8yik9WaUDZjg,5288
|
|
9
|
+
deskc-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
deskc-0.1.0.dist-info/entry_points.txt,sha256=_nYPJ2y52CtkLQD-vD9lc_rle__D43PYFW6CPAn5oQU,41
|
|
11
|
+
deskc-0.1.0.dist-info/licenses/LICENSE,sha256=6dP7w8m4xJH1IQumkEnTTCY4BJO16jnKEG-xPIj9y90,1070
|
|
12
|
+
deskc-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jorge Cardona
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|