desky-agent 0.3.10 → 0.3.12

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.
package/ui/app.html CHANGED
@@ -1,1625 +1,1666 @@
1
- <!doctype html>
2
- <html lang="uk">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>Desky Agent</title>
7
- <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect x='2' y='3' width='12' height='9' fill='%23D9774B'/%3E%3Crect x='5' y='5' width='2' height='3' fill='%23222'/%3E%3Crect x='9' y='5' width='2' height='3' fill='%23222'/%3E%3Crect x='0' y='6' width='2' height='3' fill='%23D9774B'/%3E%3Crect x='14' y='6' width='2' height='3' fill='%23D9774B'/%3E%3Crect x='3' y='12' width='2' height='3' fill='%23D9774B'/%3E%3Crect x='11' y='12' width='2' height='3' fill='%23D9774B'/%3E%3C/svg%3E">
8
- <link rel="preconnect" href="https://fonts.googleapis.com">
9
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
- <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Unbounded:wght@500;600&family=Onest:wght@400;500;600&family=JetBrains+Mono:wght@400;500;800&display=swap">
11
- <script type="importmap">{ "imports": { "three": "/vendor/three.module.min.js" } }</script>
12
- <script type="module" src="/clawd3d.js"></script>
13
- <style>
14
- /* Desky's control app, served by the agent daemon. Left: Desky's face and state, the pages, the link and Stop.
15
- Right: the page: overview, moves, calibration, settings, monitor. Over everything: the setup wizard. */
16
- :root {
17
- --bg: #F4F2EE; --side: #EDEAE5; --card: #FFFFFF; --sunk: #F6F4F1; --ink: #1F1D1A; --muted: #736E68; --faint: #A7A19A;
18
- --line: #E6E2DC; --line2: #D6D1CA;
19
- --clawd: #D9774B; --clawd-hi: #C4643A; --clawd-ink: #FFFFFF; --clawd-soft: #FBEDE5; --clawd-glow: rgba(217, 119, 75, .22);
20
- --ok: #3C8A55; --ok-soft: #E6F3EA; --bad: #C2462A; --bad-soft: #FBE9E4; --desk: #2A2826;
21
- --term: #1E1C1A; --termfg: #E6E1DA; --termdim: #8E877F;
22
- --shadow: 0 1px 2px rgba(40, 30, 20, .05), 0 2px 10px rgba(40, 30, 20, .045);
23
- --shadow-lg: 0 24px 80px rgba(40, 25, 10, .22), 0 4px 16px rgba(40, 25, 10, .08);
24
- --r: 14px; --rc: 9px; --h: 36px;
25
- --f-display: "Unbounded", "Segoe UI", system-ui, sans-serif;
26
- --f-body: "Onest", "Segoe UI", system-ui, sans-serif;
27
- --f-mono: "JetBrains Mono", Consolas, monospace;
28
- }
29
- @media (prefers-color-scheme: dark) { :root {
30
- --bg: #151413; --side: #1A1918; --card: #211F1D; --sunk: #1A1917; --ink: #EDEAE5; --muted: #A29C94; --faint: #6F6A64;
31
- --line: #2D2A27; --line2: #3B3733;
32
- --clawd: #E3825A; --clawd-hi: #EC9167; --clawd-ink: #1A0F0A; --clawd-soft: #33231B; --clawd-glow: rgba(227, 130, 90, .2);
33
- --ok: #6BBF86; --ok-soft: #1C2E22; --bad: #E56A4C; --bad-soft: #3A1F18; --desk: #4A4744;
34
- --term: #100F0E; --shadow: none; --shadow-lg: 0 24px 80px rgba(0, 0, 0, .55); color-scheme: dark } }
35
- * { box-sizing: border-box; }
36
- [hidden] { display: none !important; }
37
- html, body { height: 100%; }
38
- body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.5 var(--f-body); -webkit-font-smoothing: antialiased; }
39
- h1, h2, h3, p { margin: 0; }
40
- .mono { font-family: var(--f-mono); }
41
-
42
- /* ---------------------------------------------------------------- shell */
43
- .app { display: grid; grid-template-columns: 260px minmax(0, 1fr); min-height: 100%; }
44
- aside { background: var(--side); border-right: 1px solid var(--line); padding: 20px 16px; display: flex; flex-direction: column; gap: 18px;
45
- position: sticky; top: 0; height: 100vh; overflow-y: auto; }
46
- .brand { display: flex; align-items: center; gap: 10px; padding: 0 8px; font: 600 17px var(--f-display); letter-spacing: -.01em; }
47
- .brand { gap: 8px; }
48
- .brand svg.head { width: 34px; height: auto; margin-right: 2px; }
49
- .brand svg.chev { width: 10px; height: 16px; }
50
- .brand svg.chev path { fill: none; stroke: var(--clawd); stroke-width: 3; stroke-linecap: square; }
51
- .brand .wm { font: 800 19px/1 var(--f-mono, 'JetBrains Mono', monospace); letter-spacing: -.01em; margin-left: -3px; }
52
- .brand .cur { width: 9px; height: 17px; background: var(--clawd); margin-left: -4px; animation: blink 1.1s steps(1) infinite; }
53
- @keyframes blink { 50% { opacity: 0; } }
54
- @media (prefers-reduced-motion: reduce) { .brand .cur { animation: none; } }
55
- .who { background: var(--card); border: 1px solid var(--line); border-radius: var(--r); padding: 18px 16px 16px; display: grid; justify-items: center;
56
- gap: 4px; text-align: center; box-shadow: var(--shadow); }
57
- .who svg { width: 136px; height: 102px; margin-bottom: 10px; border-radius: 12px; box-shadow: 0 8px 24px var(--clawd-glow); }
58
- .who .k { font-size: 11px; letter-spacing: .08em; text-transform: uppercase; color: var(--faint); }
59
- .who .s { font: 600 18px var(--f-display); letter-spacing: -.01em; }
60
- .who .w { font-size: 12.5px; color: var(--muted); line-height: 1.4; }
61
- nav { display: grid; gap: 2px; }
62
- nav button, .wizlink { all: unset; display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: var(--rc); cursor: pointer;
63
- color: var(--muted); font-weight: 500; }
64
- nav button svg, .wizlink svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; flex: none; }
65
- nav button:hover, .wizlink:hover { color: var(--ink); background: rgba(127, 110, 90, .08); }
66
- nav button[aria-selected="true"] { color: var(--ink); background: var(--card); box-shadow: var(--shadow); }
67
- nav button[aria-selected="true"] svg { color: var(--clawd); }
68
- nav button:focus-visible, .wizlink:focus-visible { outline: 2px solid var(--clawd); outline-offset: 1px; }
69
- .wizlink { color: var(--clawd-hi); border: 1px dashed color-mix(in srgb, var(--clawd) 45%, transparent); justify-content: center; }
70
- .wizlink:hover { color: var(--clawd-hi); background: var(--clawd-soft); }
71
- .links { margin-top: auto; display: grid; gap: 0; border-top: 1px solid var(--line); padding-top: 12px; }
72
- .lk { display: flex; align-items: center; gap: 8px; padding: 5px 8px; font-size: 13px; color: var(--muted); }
73
- .lk span:last-child { margin-left: auto; color: var(--ink); font-weight: 500; text-align: right; }
74
- .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); flex: none; }
75
- .dot.on { background: var(--ok); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ok) 18%, transparent); }
76
- .dot.bad { background: var(--bad); }
77
- .dot.warn { background: var(--clawd); }
78
-
79
- main { padding: 28px 32px 48px; display: grid; gap: 20px; align-content: start; max-width: 1100px; width: 100%; }
80
- .page { display: grid; gap: 20px; align-content: start; animation: fadein .25s ease; }
81
- @keyframes fadein { from { opacity: 0; transform: translateY(4px); } }
82
- .title { display: flex; align-items: end; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
83
- .title h1 { font: 600 23px var(--f-display); letter-spacing: -.015em; }
84
- .title p { color: var(--muted); margin-top: 4px; }
85
-
86
- /* ---------------------------------------------------------------- cards and controls */
87
- .cols { display: grid; gap: 20px; grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: stretch; }
88
- .cols.wide { grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); }
89
- .card { background: var(--card); border: 1px solid var(--line); border-radius: var(--r); box-shadow: var(--shadow); padding: 20px; display: flex;
90
- flex-direction: column; gap: 16px; min-width: 0; }
91
- .card > .hd { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 30px; }
92
- .card h2 { font-size: 15px; font-weight: 600; }
93
- .card .sub { color: var(--muted); font-size: 13px; margin-top: -10px; }
94
- .muted { color: var(--muted); }
95
- .small { font-size: 12.5px; }
96
-
97
- button { font: 500 13.5px var(--f-body); color: var(--ink); background: var(--card); border: 1px solid var(--line2); border-radius: var(--rc);
98
- height: var(--h); padding: 0 14px; cursor: pointer; white-space: nowrap; transition: background .12s, border-color .12s, color .12s, box-shadow .12s; }
99
- button:hover:not(:disabled) { background: var(--sunk); border-color: var(--faint); }
100
- button:active:not(:disabled) { transform: translateY(1px); }
101
- button:disabled { opacity: .4; cursor: default; }
102
- button:focus-visible, input:focus-visible { outline: 2px solid var(--clawd); outline-offset: 2px; }
103
- button.pri { background: var(--clawd); border-color: var(--clawd); color: var(--clawd-ink); }
104
- button.pri:hover:not(:disabled) { background: var(--clawd-hi); border-color: var(--clawd-hi); box-shadow: 0 4px 14px var(--clawd-glow); }
105
- button.ghost { background: none; border-color: transparent; color: var(--muted); }
106
- button.ghost:hover:not(:disabled) { color: var(--ink); background: var(--sunk); border-color: transparent; }
107
- button.sm { height: 30px; padding: 0 10px; font-size: 13px; }
108
- button.lg { height: 44px; padding: 0 22px; font-size: 14.5px; font-weight: 600; border-radius: 11px; }
109
- button[aria-pressed="true"] { background: var(--clawd-soft); border-color: var(--clawd); }
110
- button.stop { width: 100%; height: 40px; background: var(--bad); border-color: var(--bad); color: #fff; font-weight: 600; }
111
- button.stop:hover:not(:disabled) { background: var(--bad); border-color: var(--bad); filter: brightness(1.08); }
112
-
113
- .btns { display: grid; gap: 8px; grid-template-columns: repeat(3, minmax(0, 1fr)); }
114
- .btns button { width: 100%; padding: 0 6px; }
115
- .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
116
- .row.end { justify-content: flex-end; }
117
-
118
- input.num, input.text, .raw input { font: 13.5px var(--f-mono); height: var(--h); padding: 0 10px; border: 1px solid var(--line2); border-radius: var(--rc);
119
- background: var(--card); color: var(--ink); min-width: 0; }
120
- input.num { width: 76px; text-align: right; }
121
- input.num.s { width: 60px; height: 30px; }
122
- input.text { width: 100%; }
123
- input[type=checkbox] { accent-color: var(--clawd); width: 15px; height: 15px; margin: 0; }
124
- .check { display: inline-flex; align-items: center; gap: 8px; color: var(--muted); cursor: pointer; font-size: 13px; user-select: none; }
125
-
126
- /* range: one look in Edge and Firefox */
127
- input[type=range] { -webkit-appearance: none; appearance: none; width: 100%; height: 22px; background: none; margin: 0; cursor: pointer; }
128
- input[type=range]::-webkit-slider-runnable-track { height: 6px; border-radius: 3px;
129
- background: linear-gradient(var(--clawd), var(--clawd)) 0 / var(--p, 50%) 100% no-repeat, var(--line); }
130
- input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 18px; height: 18px; margin-top: -6px; border-radius: 50%;
131
- background: var(--card); border: 2px solid var(--clawd); box-shadow: 0 1px 3px rgba(0, 0, 0, .2); }
132
- input[type=range]::-moz-range-track { height: 6px; border-radius: 3px; background: var(--line); }
133
- input[type=range]::-moz-range-progress { height: 6px; border-radius: 3px; background: var(--clawd); }
134
- input[type=range]::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%; background: var(--card); border: 2px solid var(--clawd); }
135
- input[type=range]:disabled { opacity: .5; }
136
-
137
- /* the centre dial: a range that fills from the middle, with a tick at zero */
138
- .dial { display: grid; gap: 8px; }
139
- .dial .track { position: relative; }
140
- .dial .track::before { content: ""; position: absolute; left: 50%; top: -3px; bottom: -3px; width: 2px; margin-left: -1px; border-radius: 1px; background: var(--line2); pointer-events: none; }
141
- .dial input[type=range] { height: 30px; position: relative; }
142
- .dial input[type=range]::-webkit-slider-runnable-track { height: 8px; border-radius: 4px;
143
- background: linear-gradient(90deg, transparent var(--a, 50%), var(--clawd) var(--a, 50%), var(--clawd) var(--b, 50%), transparent var(--b, 50%)), var(--line); }
144
- .dial input[type=range]::-webkit-slider-thumb { width: 24px; height: 24px; margin-top: -8px; border-width: 3px; }
145
- .dial input[type=range]::-moz-range-progress { background: transparent; }
146
- .dial input[type=range]::-moz-range-thumb { width: 18px; height: 18px; border-width: 3px; }
147
- .dial .ends { display: flex; justify-content: space-between; font-size: 12px; color: var(--muted); }
148
- .dial .ends b { color: var(--ink); font: 600 15px var(--f-mono); font-variant-numeric: tabular-nums; }
149
- .dial .fine { display: flex; gap: 6px; align-items: center; justify-content: center; }
150
- .dial .fine button { min-width: 44px; font-family: var(--f-mono); }
151
- .dial .fine button[data-z] { font-family: var(--f-body); }
152
- .dial.warn input[type=range]::-webkit-slider-thumb { border-color: var(--bad); }
153
- .hint { font-size: 12.5px; color: var(--muted); line-height: 1.45; }
154
- .hint.warn { color: var(--bad); }
155
-
156
- /* banners */
157
- .banner { display: flex; align-items: center; gap: 16px; padding: 12px 14px 12px 16px; border-radius: var(--r); background: var(--clawd-soft);
158
- border: 1px solid color-mix(in srgb, var(--clawd) 35%, transparent); }
159
- .banner p { flex: 1; }
160
- .banner b { font-weight: 600; }
161
- .banner.bad { background: var(--bad-soft); border-color: color-mix(in srgb, var(--bad) 35%, transparent); }
162
- .banner.ok { background: var(--card); border-color: var(--line); }
163
- .banner .acts { display: flex; gap: 8px; }
164
- .lk.btn { all: unset; display: flex; align-items: center; gap: 8px; padding: 5px 8px; font-size: 13px; color: var(--muted); border-radius: 6px; }
165
- .lk.btn:not(:disabled) { cursor: pointer; }
166
- .lk.btn:not(:disabled):hover { background: rgba(127, 110, 90, .08); }
167
- .lk.btn:focus-visible { outline: 2px solid var(--clawd); outline-offset: 1px; }
168
-
169
- /* toast */
170
- .toast { position: fixed; left: 50%; bottom: 24px; transform: translate(-50%, 20px); opacity: 0; pointer-events: none; z-index: 60;
171
- background: var(--ink); color: var(--bg); padding: 10px 16px; border-radius: 999px; font-weight: 500; font-size: 13.5px;
172
- box-shadow: var(--shadow-lg); transition: opacity .2s, transform .2s; max-width: calc(100% - 32px); }
173
- .toast.on { opacity: 1; transform: translate(-50%, 0); }
174
- .toast.bad { background: var(--bad); color: #fff; }
175
-
176
- /* ---------------------------------------------------------------- the 3D stage (ui/clawd3d.js) */
177
- .scene3d { position: relative; min-height: 240px; border-radius: var(--r); overflow: hidden; display: grid; place-items: center;
178
- background: radial-gradient(70% 60% at 50% 62%, color-mix(in srgb, var(--clawd) 16%, transparent), transparent 70%),
179
- radial-gradient(circle at 1px 1px, color-mix(in srgb, var(--ink) 9%, transparent) 1px, transparent 1.4px) 0 0 / 18px 18px,
180
- linear-gradient(180deg, var(--sunk), var(--card)); }
181
- .scene3d canvas.c3d { position: absolute; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none;
182
- animation: c3in .6s ease both; }
183
- .scene3d canvas.c3d:active { cursor: grabbing; }
184
- @keyframes c3in { from { opacity: 0; transform: scale(.97); } }
185
- .scene3d .tip3d { position: absolute; right: 12px; bottom: 10px; font-size: 11.5px; color: var(--faint); pointer-events: none;
186
- display: none; align-items: center; gap: 6px; opacity: 0; transition: opacity .2s; }
187
- .scene3d:hover .tip3d { opacity: 1; }
188
- .scene3d .tip3d svg { width: 14px; height: 14px; stroke: currentColor; fill: none; stroke-width: 1.8; stroke-linecap: round; }
189
- body.has3d .scene3d .tip3d { display: flex; }
190
- body.has3d .scene3d > .flat { display: none; }
191
- body:not(.has3d) #moveScene { display: none; }
192
- body.has3d .sketches { display: none; }
193
- #moveScene { height: 300px; }
194
-
195
- /* ---------------------------------------------------------------- overview */
196
- .herocard { padding: 0; display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); overflow: hidden; gap: 0; }
197
- .herocard .scene3d { min-height: 340px; border-radius: 0; }
198
- .herocard .scene3d > .flat { width: 200px; height: 150px; border-radius: 18px; box-shadow: 0 16px 40px var(--clawd-glow); }
199
- .herocard .info { padding: 28px 28px 24px; display: flex; flex-direction: column; gap: 6px; border-left: 1px solid var(--line); }
200
- .herocard .k { font-size: 11px; letter-spacing: .08em; text-transform: uppercase; color: var(--faint); }
201
- .herocard .s { font: 600 30px/1.15 var(--f-display); letter-spacing: -.025em; }
202
- .herocard .w { color: var(--muted); font-size: 14.5px; }
203
- .herocard .quiet { align-self: flex-start; margin-top: 8px; font-size: 12.5px; color: var(--muted); display: inline-flex; gap: 6px; align-items: center; }
204
- .herocard .quiet svg { width: 14px; height: 14px; stroke: currentColor; fill: none; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
205
- .herocard .ses { margin-top: auto; padding-top: 22px; display: grid; gap: 8px; }
206
- .herocard .ses .hd { font-size: 12px; color: var(--faint); display: flex; justify-content: space-between; }
207
- .herocard .ses .list { border-radius: 10px; }
208
- .herocard .ses .li { height: 38px; padding: 0 10px 0 12px; }
209
- .herocard .ses .empty { padding: 16px 12px; border-radius: 10px; font-size: 13px; }
210
- .list { display: grid; border: 1px solid var(--line); border-radius: var(--rc); overflow: hidden; }
211
- .li { display: flex; align-items: center; gap: 12px; padding: 0 14px; height: 44px; border-top: 1px solid var(--line); }
212
- .li:first-child { border-top: 0; }
213
- .li .mono { color: var(--muted); font-size: 12.5px; }
214
- .badge { margin-left: auto; font-size: 12.5px; font-weight: 500; padding: 2px 10px; border-radius: 999px; background: var(--sunk); border: 1px solid var(--line); }
215
- .badge.ask { background: var(--clawd-soft); border-color: transparent; color: var(--clawd-hi); }
216
- .empty { display: grid; place-items: center; text-align: center; gap: 4px; padding: 24px 16px; border: 1px dashed var(--line2); border-radius: var(--rc); color: var(--muted); }
217
- .empty b { color: var(--ink); font-weight: 500; }
218
- .facts { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0; border: 1px solid var(--line); border-radius: var(--rc); }
219
- .fact { padding: 12px 14px; border-left: 1px solid var(--line); }
220
- .fact:first-child { border-left: 0; }
221
- .fact .k { font-size: 12px; color: var(--muted); }
222
- .fact .v { font-weight: 600; margin-top: 2px; }
223
-
224
- /* ---------------------------------------------------------------- moves */
225
- .fader { display: grid; grid-template-columns: 128px minmax(0, 1fr) 52px; gap: 16px; align-items: center; }
226
- .fader label { font-weight: 500; line-height: 1.3; }
227
- .fader label small { display: block; font-weight: 400; color: var(--muted); font-size: 12px; }
228
- .fader output { font: 500 13.5px var(--f-mono); text-align: right; font-variant-numeric: tabular-nums; }
229
- .sketches { display: grid; grid-template-columns: 3fr 2fr; gap: 12px; }
230
- .sketches figure, .fig { margin: 0; background: var(--sunk); border: 1px solid var(--line); border-radius: var(--rc); padding: 8px 8px 6px; }
231
- .sketches svg, .fig svg { width: 100%; height: auto; display: block; }
232
- .sketches figcaption, .fig figcaption { font-size: 12px; color: var(--muted); text-align: center; }
233
- .sep { height: 1px; background: var(--line); margin: 0 -20px; }
234
- .opt { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
235
- .opt small { display: block; color: var(--muted); font-size: 12.5px; }
236
-
237
- /* ---------------------------------------------------------------- calibration */
238
- .calhero { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 20px; align-items: center;
239
- background: linear-gradient(120deg, var(--clawd-soft), var(--card) 70%); }
240
- .calhero h2 { font: 600 17px var(--f-display); letter-spacing: -.01em; }
241
- .calhero p { color: var(--muted); margin-top: 4px; max-width: 560px; }
242
- .joints { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; }
243
- .joint .hd small { display: block; color: var(--muted); font: 12px var(--f-mono); }
244
- .joint .pic { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
245
- .joint .fig svg { height: 112px; }
246
- .joint .dir { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding-top: 12px; border-top: 1px solid var(--line); }
247
- .joint .dir span { margin-right: auto; font-size: 13px; color: var(--muted); }
248
- .joint .dir span b { color: var(--ink); font-weight: 500; }
249
- .tog { display: grid; gap: 0; }
250
- .tog .field { padding: 12px 0; }
251
- .savebar { position: sticky; bottom: 16px; display: flex; align-items: center; gap: 8px; padding: 10px 10px 10px 20px; background: var(--card);
252
- border: 1px solid var(--line); border-radius: var(--r); box-shadow: 0 6px 24px rgba(40, 30, 20, .08); }
253
- .savebar p { margin-right: auto; color: var(--muted); font-size: 13px; }
254
- .savebar p.ok { color: var(--ok); }
255
- .savebar p.bad { color: var(--bad); }
256
- .savebar.dirty { border-color: var(--clawd); box-shadow: 0 6px 24px var(--clawd-glow); }
257
- .savebar.dirty p { color: var(--clawd-hi); font-weight: 500; }
258
-
259
- /* ---------------------------------------------------------------- Desky's colour */
260
- .swatches { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 10px; }
261
- .swatch { height: auto; padding: 12px 6px 10px; display: grid; justify-items: center; gap: 8px; border-radius: 14px; white-space: normal;
262
- line-height: 1.2; font-size: 13px; }
263
- .swatch .chip { width: 52px; height: 39px; border-radius: 8px; background: var(--c); position: relative;
264
- box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .1), 0 6px 16px color-mix(in srgb, var(--c) 35%, transparent);
265
- transition: transform .2s cubic-bezier(.2, .8, .2, 1); }
266
- .swatch .chip::before, .swatch .chip::after { content: ""; position: absolute; top: 12px; width: 7px; height: 14px; background: var(--e); }
267
- .swatch .chip::before { left: 11px; }
268
- .swatch .chip::after { right: 11px; }
269
- .swatch:hover:not(:disabled) .chip { transform: translateY(-2px) rotate(-3deg); }
270
- .swatch[aria-checked="true"] { border-color: var(--clawd); background: var(--clawd-soft); box-shadow: 0 0 0 3px var(--clawd-glow); }
271
- .swatch[aria-checked="true"] .chip { transform: scale(1.06); }
272
- .swatch small { display: block; color: var(--muted); font-size: 11.5px; }
273
- .colorcard .hint { margin-top: -6px; }
274
- .wiz .swatches { grid-template-columns: repeat(3, minmax(0, 1fr)); }
275
-
276
- /* ---------------------------------------------------------------- settings */
277
- .set { display: grid; }
278
- .field { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 14px 0; border-top: 1px solid var(--line); }
279
- .field:first-child { border-top: 0; padding-top: 0; }
280
- .field:last-child { padding-bottom: 0; }
281
- .field label { font-weight: 500; }
282
- .field label small { display: block; color: var(--muted); font-size: 12.5px; font-weight: 400; }
283
- .field .in { display: flex; align-items: center; gap: 8px; }
284
- .field .unit { font-size: 12.5px; color: var(--muted); width: 84px; }
285
- .field.col { grid-template-columns: 1fr; gap: 8px; }
286
-
287
- /* ---------------------------------------------------------------- monitor */
288
- .term { background: var(--term); border-radius: var(--r); overflow: hidden; display: grid; grid-template-rows: auto 1fr auto; height: calc(100vh - 190px); min-height: 360px; }
289
- .term .bar { display: flex; align-items: center; gap: 16px; padding: 10px 14px; border-bottom: 1px solid rgba(255, 255, 255, .07); color: var(--termdim); font-size: 12.5px; }
290
- .term .bar .check { color: var(--termdim); }
291
- .term .bar button { margin-left: auto; color: var(--termdim); }
292
- .term .bar button:hover:not(:disabled) { background: rgba(255, 255, 255, .06); color: var(--termfg); }
293
- .legend { display: flex; gap: 14px; }
294
- .legend i { display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 6px; }
295
- .log { padding: 12px 14px; font: 12.5px/1.6 var(--f-mono); color: var(--termfg); overflow: auto; white-space: pre-wrap; }
296
- .log .me { color: #F2B48F; }
297
- .log .agent { color: #9FC6F0; }
298
- .log .info, .log .dim { color: var(--termdim); }
299
- .raw { display: flex; gap: 8px; padding: 10px; border-top: 1px solid rgba(255, 255, 255, .07); }
300
- .raw input { flex: 1; background: rgba(255, 255, 255, .05); border-color: rgba(255, 255, 255, .1); color: var(--termfg); }
301
- .raw input::placeholder { color: var(--termdim); }
302
- .raw button { background: rgba(255, 255, 255, .08); border-color: transparent; color: var(--termfg); }
303
- .raw button:hover:not(:disabled) { background: rgba(255, 255, 255, .14); border-color: transparent; }
304
-
305
- /* ---------------------------------------------------------------- the face: blinks while alive */
306
- svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: blink 5.2s infinite; }
307
- @keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 95.5% { transform: scaleY(.1); } }
308
- @media (prefers-reduced-motion: reduce) { svg.alive .eye { animation: none; } .page, .wiz .step { animation: none !important; } }
309
-
310
- /* ---------------------------------------------------------------- a new version: dialog over the window */
311
- .upd { position: fixed; inset: 0; z-index: 60; display: grid; place-items: center; padding: 24px;
312
- background: color-mix(in srgb, var(--bg) 80%, transparent); backdrop-filter: blur(3px); }
313
- .upd .card { width: min(440px, 100%); padding: 28px 28px 22px; border-radius: 22px; box-shadow: var(--shadow-lg);
314
- display: grid; gap: 14px; justify-items: center; text-align: center; animation: stepin .3s cubic-bezier(.2, .8, .2, 1); }
315
- .upd svg.big { width: 112px; height: 84px; }
316
- .upd h2 { font-size: 21px; margin: 0; }
317
- .upd p { margin: 0; color: var(--muted); line-height: 1.5; }
318
- .upd .ver { font-family: var(--f-mono, ui-monospace, monospace); font-size: 13px; padding: 4px 10px; border-radius: 99px;
319
- background: var(--clawd-soft); color: var(--clawd-hi); }
320
- .upd .cmd { display: flex; gap: 8px; align-items: center; width: 100%; padding: 8px 8px 8px 12px; border-radius: 10px;
321
- background: var(--sunk); font-family: var(--f-mono, ui-monospace, monospace); font-size: 13px; text-align: left; }
322
- .upd .cmd span { flex: 1; }
323
- .upd .acts { display: flex; gap: 10px; justify-content: center; width: 100%; margin-top: 4px; }
324
- .upd .acts .pri { flex: 1; }
325
- .lk.btn.new { background: var(--clawd); color: var(--clawd-ink); font-weight: 600; }
326
- .lk.btn.new span:last-child { color: inherit; }
327
- .lk.btn.new .dot { background: var(--clawd-ink); }
328
-
329
- /* ---------------------------------------------------------------- setup wizard */
330
- .wiz { position: fixed; inset: 0; z-index: 50; display: grid; place-items: center; padding: 24px;
331
- background: color-mix(in srgb, var(--bg) 88%, transparent); }
332
- .wiz .panel { width: min(960px, 100%); max-height: calc(100vh - 48px); background: var(--card); border: 1px solid var(--line); border-radius: 22px;
333
- box-shadow: var(--shadow-lg); display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden; }
334
- .wiz .top { display: flex; align-items: center; gap: 16px; padding: 16px 18px 14px 24px; border-bottom: 1px solid var(--line); }
335
- .wiz .top .brand { padding: 0; font-size: 15px; }
336
- .prog { flex: 1; display: grid; gap: 6px; }
337
- .prog .bars { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 4px; }
338
- .prog .bars i { height: 4px; border-radius: 2px; background: var(--line); transition: background .3s; }
339
- .prog .bars i.done { background: var(--clawd); }
340
- .prog .bars i.now { background: linear-gradient(90deg, var(--clawd) 50%, var(--line) 50%); }
341
- .prog .lbl { font-size: 12px; color: var(--muted); }
342
- .prog .lbl b { color: var(--ink); font-weight: 500; }
343
- .wiz .x { width: 34px; height: 34px; padding: 0; display: grid; place-items: center; border-radius: 50%; }
344
- .wiz .x svg { width: 16px; height: 16px; stroke: currentColor; stroke-width: 2; fill: none; stroke-linecap: round; }
345
- .wiz .body { overflow-y: auto; overflow-x: hidden; }
346
- .wiz .step { display: grid; grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); min-height: 460px; animation: stepin .35s cubic-bezier(.2, .8, .2, 1); }
347
- @keyframes stepin { from { opacity: 0; transform: translateX(14px); } }
348
- .wiz .stage { background: radial-gradient(120% 90% at 50% 40%, var(--clawd-soft), var(--sunk) 70%); border-right: 1px solid var(--line);
349
- display: grid; place-items: center; padding: 28px; gap: 12px; align-content: center; }
350
- .wiz .stage .views { display: grid; gap: 12px; width: 100%; max-width: 380px; }
351
- .wiz .stage .views.two { grid-template-columns: 1fr 1fr; max-width: 440px; }
352
- .wiz .stage .views:not(.two) { max-width: 280px; }
353
- .wiz .stage .fig { background: var(--card); }
354
- .wiz .stage .big { width: min(300px, 80%); height: auto; border-radius: 22px; box-shadow: 0 20px 50px var(--clawd-glow); }
355
- .wiz .stage .cap { font-size: 12.5px; color: var(--muted); text-align: center; }
356
- .wiz .stage.s3 { padding: 0; display: block; position: relative; }
357
- .wiz .stage.s3 .scene3d { position: absolute; inset: 0; border-radius: 0; background: radial-gradient(70% 60% at 50% 60%, color-mix(in srgb, var(--clawd) 20%, transparent), transparent 70%), radial-gradient(circle at 1px 1px, color-mix(in srgb, var(--ink) 9%, transparent) 1px, transparent 1.4px) 0 0 / 18px 18px, var(--sunk); }
358
- .wiz .stage.s3 .cap3 { position: absolute; left: 16px; top: 14px; z-index: 1; padding: 5px 11px; border-radius: 999px; font-size: 12px; font-weight: 600;
359
- background: color-mix(in srgb, var(--card) 85%, transparent); border: 1px solid var(--line); color: var(--ink); }
360
- .wiz .stage.s3 .cap3 i { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--clawd); margin-right: 7px; animation: pulse 1.4s ease-in-out infinite; }
361
- .wiz .content { padding: 32px 32px 24px; display: flex; flex-direction: column; gap: 16px; min-width: 0; }
362
- .wiz .kick { font-size: 11.5px; letter-spacing: .08em; text-transform: uppercase; color: var(--clawd-hi); font-weight: 600; }
363
- .wiz h2 { font: 600 24px/1.2 var(--f-display); letter-spacing: -.02em; }
364
- .wiz .lead { color: var(--muted); font-size: 14.5px; line-height: 1.55; }
365
- .wiz .lead b { color: var(--ink); font-weight: 500; }
366
- .wiz .foot { margin-top: auto; display: flex; gap: 8px; align-items: center; padding-top: 16px; }
367
- .wiz .foot .sp { margin-right: auto; }
368
- .checks { display: grid; gap: 8px; }
369
- .ck { display: flex; align-items: center; gap: 12px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; background: var(--sunk); }
370
- .ck .ic { width: 26px; height: 26px; border-radius: 50%; display: grid; place-items: center; flex: none; background: var(--line); color: var(--muted); }
371
- .ck .ic svg { width: 14px; height: 14px; stroke: currentColor; stroke-width: 2.4; fill: none; stroke-linecap: round; stroke-linejoin: round; }
372
- .ck.ok .ic { background: var(--ok); color: #fff; }
373
- .ck.wait .ic { background: none; border: 2px solid var(--line2); border-top-color: var(--clawd); animation: spin 1s linear infinite; }
374
- .ck.bad .ic { background: var(--bad); color: #fff; }
375
- @keyframes spin { to { transform: rotate(360deg); } }
376
- .ck div { flex: 1; min-width: 0; }
377
- .ck b { display: block; font-weight: 500; }
378
- .ck small { color: var(--muted); font-size: 12.5px; }
379
- .choices { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
380
- .choice { height: auto; padding: 14px 12px 12px; display: grid; justify-items: center; gap: 8px; border-radius: 14px; white-space: normal; text-align: center; line-height: 1.3; }
381
- .choice svg { width: 100%; max-width: 150px; height: auto; border-radius: 8px; background: var(--sunk); }
382
- .choice:hover:not(:disabled) { border-color: var(--clawd); background: var(--clawd-soft); }
383
- .choice.yes { border-color: color-mix(in srgb, var(--ok) 50%, var(--line2)); }
384
- .choice.yes:hover:not(:disabled) { border-color: var(--ok); background: var(--ok-soft); }
385
- .note { padding: 10px 14px; border-radius: 12px; background: var(--clawd-soft); color: var(--clawd-hi); font-size: 13px; font-weight: 500; }
386
- .note.bad { background: var(--bad-soft); color: var(--bad); }
387
- .note.ok { background: var(--ok-soft); color: var(--ok); }
388
- .watch { display: flex; align-items: center; gap: 10px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; }
389
- .watch .pulse { width: 10px; height: 10px; border-radius: 50%; background: var(--clawd); animation: pulse 1.2s ease-in-out infinite; flex: none; }
390
- @keyframes pulse { 50% { box-shadow: 0 0 0 7px var(--clawd-glow); } }
391
- .confetti { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
392
- .confetti i { position: absolute; top: -12px; width: 8px; height: 12px; border-radius: 2px; animation: fall 2.4s ease-in forwards; }
393
- @keyframes fall { to { transform: translateY(560px) rotate(540deg); opacity: 0; } }
394
-
395
- /* ---------------------------------------------------------------- narrow windows */
396
- @media (max-width: 1100px) { .cols.wide { grid-template-columns: 1fr; } .joints { grid-template-columns: 1fr; } }
397
- @media (max-width: 900px) {
398
- .app { grid-template-columns: 1fr; }
399
- aside { position: static; height: auto; border-right: 0; border-bottom: 1px solid var(--line); padding: 16px; gap: 14px; }
400
- .who { grid-template-columns: auto 1fr; justify-items: start; text-align: left; column-gap: 14px; padding: 12px; }
401
- .who svg { width: 72px; height: 54px; margin: 0; grid-row: 1 / 4; }
402
- nav { grid-auto-flow: column; justify-content: start; overflow-x: auto; scrollbar-width: none; }
403
- nav::-webkit-scrollbar { display: none; }
404
- .links { margin-top: 0; grid-template-columns: 1fr 1fr; column-gap: 16px; }
405
- main { padding: 20px 16px 40px; }
406
- .cols { grid-template-columns: 1fr; }
407
- .wiz { padding: 0; }
408
- .wiz .panel { max-height: 100vh; height: 100%; border-radius: 0; }
409
- .wiz .step { grid-template-columns: 1fr; }
410
- .wiz .stage { border-right: 0; border-bottom: 1px solid var(--line); padding: 20px; }
411
- .wiz .stage.s3 { height: 300px; }
412
- .wiz .content { padding: 22px 18px 18px; }
413
- .herocard { grid-template-columns: 1fr; }
414
- .herocard .info { border-left: 0; border-top: 1px solid var(--line); }
415
- }
416
- @media (max-width: 600px) {
417
- .btns { grid-template-columns: repeat(2, minmax(0, 1fr)); }
418
- .fader { grid-template-columns: minmax(0, 1fr) 52px; gap: 6px 12px; }
419
- .fader input { grid-column: 1 / -1; grid-row: 2; }
420
- .facts { grid-template-columns: 1fr; }
421
- .fact { border-left: 0; border-top: 1px solid var(--line); }
422
- .fact:first-child { border-top: 0; }
423
- .banner { flex-wrap: wrap; }
424
- .calhero { grid-template-columns: 1fr; }
425
- .choices { grid-template-columns: 1fr; }
426
- .swatches { grid-template-columns: repeat(3, minmax(0, 1fr)); }
427
- .tog .field { grid-template-columns: 1fr; gap: 10px; }
428
- }
429
- </style>
430
- </head>
431
- <body>
432
- <div class="app">
433
- <aside>
434
- <div class="brand" aria-label="Desky Agent"><svg class="head" viewBox="-8 0 80 48" aria-hidden="true" id="logo" data-head="1"></svg><svg class="chev" viewBox="0 0 10 16" aria-hidden="true"><path d="M1.5 2 L8 8 L1.5 14"/></svg><span class="wm">desky</span><span class="cur"></span></div>
435
- <nav role="tablist">
436
- <button type="button" role="tab" data-tab="home" aria-selected="true"><svg viewBox="0 0 24 24"><path d="M4 11l8-7 8 7v8.5a.5.5 0 0 1-.5.5H15v-6H9v6H4.5a.5.5 0 0 1-.5-.5z"/></svg>Огляд</button>
437
- <button type="button" role="tab" data-tab="move"><svg viewBox="0 0 24 24"><path d="M4 7h9M19 7h1M4 17h3M13 17h7"/><circle cx="16" cy="7" r="2.5"/><circle cx="10" cy="17" r="2.5"/></svg>Рухи</button>
438
- <button type="button" role="tab" data-tab="cal"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7.5"/><circle cx="12" cy="12" r="2.5"/><path d="M12 2.5v3M12 18.5v3M2.5 12h3M18.5 12h3"/></svg>Калібрування</button>
439
- <button type="button" role="tab" data-tab="cfg"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16"/><circle cx="9" cy="6" r="1.8" fill="currentColor"/><circle cx="15" cy="12" r="1.8" fill="currentColor"/><circle cx="7" cy="18" r="1.8" fill="currentColor"/></svg>Налаштування</button>
440
- <button type="button" role="tab" data-tab="mon"><svg viewBox="0 0 24 24"><rect x="3" y="4.5" width="18" height="15" rx="2.5"/><path d="M7.5 9.5l3 2.5-3 2.5M13 15h3.5"/></svg>Монітор</button>
441
- </nav>
442
- <button type="button" class="wizlink" id="openWiz"><svg viewBox="0 0 24 24"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z"/><path d="M19 16l.7 2 2 .7-2 .7-.7 2-.7-2-2-.7 2-.7z"/></svg>Майстер налаштування</button>
443
- <div class="links">
444
- <div class="lk"><span class="dot" id="dC3"></span><span>Плата</span><span id="sC3">…</span></div>
445
- <div class="lk" id="rowServo" hidden><span class="dot" id="dServo"></span><span>Серво</span><span id="health">—</span></div>
446
- <button type="button" class="lk btn" id="verRow" title="версія програми Desky Agent" disabled><span class="dot on" id="dVer"></span><span>Версія</span><span id="sVer" class="mono">—</span></button>
447
- </div>
448
- <button type="button" class="stop" id="stop" title="зупинити будь-який рух">Стоп</button>
449
- </aside>
450
-
451
- <main>
452
- <div class="banner bad" id="downbox" hidden><p><b>Desky не відповідає.</b> Відкрий застосунок ще раз.</p></div>
453
- <div class="banner" id="updbox" hidden><p id="updText"></p><div class="acts"><button type="button" class="ghost sm" id="updLater">Пізніше</button><button type="button" class="pri sm" id="updGo">Оновити</button></div></div>
454
- <div class="banner bad" id="nocbox" hidden><p><b>Плату не під'єднано.</b> Під'єднай Desky кабелем USB.</p></div>
455
- <div class="banner" id="manualbox" hidden><p><b>Ручне керування.</b> Агент на паузі.</p><button type="button" class="pri sm" id="toAgent">Повернути агенту</button></div>
456
- <div class="banner" id="limpbox" hidden><p><b>Серво відпущені.</b></p><button type="button" class="pri sm" data-cmd="on">Тримати позу</button></div>
457
-
458
- <!-- ============================================================ overview -->
459
- <section data-page="home" class="page">
460
- <div class="card herocard">
461
- <div class="scene3d" id="homeScene"><svg id="bigface" class="alive flat" viewBox="0 0 64 48" aria-hidden="true"></svg>
462
- <div class="tip3d"><svg viewBox="0 0 16 16"><path d="M13 8a5 5 0 1 1-1.5-3.5M13 2.5V5h-2.5"/></svg>потягни, щоб покрутити</div></div>
463
- <div class="info">
464
- <div class="k" id="hKicker" hidden>Агент зараз</div><div class="s" id="hState">—</div><div class="w" id="hWhat"></div>
465
- <div class="quiet" id="hQuiet" hidden><svg viewBox="0 0 16 16"><path d="M3 6h2.5L9 3v10L5.5 10H3zM11.5 6l3 4M14.5 6l-3 4"/></svg><span></span></div>
466
- <div class="ses"><div class="hd"><span>Сесії агентів</span><span id="sessCount"></span></div><div id="sessions"></div></div>
467
- </div>
468
- </div>
469
- <div class="cols">
470
- <div class="card">
471
- <div class="hd"><h2>Стани</h2></div>
472
- <div class="btns" id="statesRow"></div>
473
- </div>
474
- <div class="card">
475
- <div class="hd"><h2>Звуки</h2></div>
476
- <div class="btns" id="soundsRow"></div>
477
- </div>
478
- </div>
479
- </section>
480
-
481
- <!-- ============================================================ moves -->
482
- <section data-page="move" class="page" hidden>
483
- <div class="title"><div><h1>Рухи</h1></div></div>
484
- <div class="cols wide">
485
- <div class="card">
486
- <div class="hd"><h2>Суглоби</h2><label class="check"><input type="checkbox" id="live" checked> рухати одразу</label></div>
487
- <div class="scene3d" id="moveScene"><div class="tip3d"><svg viewBox="0 0 16 16"><path d="M13 8a5 5 0 1 1-1.5-3.5M13 2.5V5h-2.5"/></svg>потягни, щоб покрутити</div></div>
488
- <div class="sketches">
489
- <figure><svg id="side" viewBox="0 0 240 170" role="img" aria-label="Вигляд збоку: нахил і руки"></svg><figcaption>збоку, стіл праворуч</figcaption></figure>
490
- <figure><svg id="topv" viewBox="0 0 160 170" role="img" aria-label="Вигляд згори: поворот"></svg><figcaption>згори, стіл угорі</figcaption></figure>
491
- </div>
492
- <div class="fader"><label for="f0">Поворот<small>J1 · ±45°</small></label><input type="range" id="f0" min="-45" max="45" step="1" value="0"><output id="o0">0°</output></div>
493
- <div class="fader"><label for="f1">Нахил<small>J2 · + уперед</small></label><input type="range" id="f1" min="-10" max="25" step="1" value="0"><output id="o1">0°</output></div>
494
- <div class="fader"><label for="f2">Права рука<small>J3 · 0° висить</small></label><input type="range" id="f2" min="-30" max="160" step="1" value="65"><output id="o2">65°</output></div>
495
- <div class="fader"><label for="f3">Ліва рука<small>J4 · 0° висить</small></label><input type="range" id="f3" min="-30" max="160" step="1" value="65"><output id="o3">65°</output></div>
496
- <div class="row">
497
- <button type="button" id="home">У центр</button>
498
- <button type="button" id="mirror" aria-pressed="false" title="права й ліва рука рухаються разом">Руки разом</button>
499
- <button type="button" class="pri" id="send" hidden>Поїхали</button>
500
- <button type="button" class="ghost" data-cmd="where" title="запитати в плати, де зараз суглоби" style="margin-left:auto">Оновити позу</button>
501
- </div>
502
- </div>
503
-
504
- <div class="card">
505
- <div class="hd"><h2>Сценки</h2></div>
506
- <div class="btns">
507
- <button type="button" data-cmd="type">Друкує</button>
508
- <button type="button" data-cmd="wave">Махає</button>
509
- <button type="button" data-cmd="look">Озирається</button>
510
- <button type="button" data-cmd="nod">Киває</button>
511
- <button type="button" data-cmd="happy">Радіє</button>
512
- <button type="button" data-cmd="sleep">Спить</button>
513
- </div>
514
- <div class="fader"><label for="spd">Швидкість рук</label><input type="range" id="spd" min="10" max="150" step="5" value="60"><output id="ospd">60°/с</output></div>
515
- <div class="sep"></div>
516
- <div class="hd"><h2>Серво</h2></div>
517
- <div class="btns">
518
- <button type="button" data-cmd="on">Тримати</button>
519
- <button type="button" data-cmd="off" title="зняти струм: Desky обм'якне, його можна повернути рукою">Відпустити</button>
520
- <button type="button" data-cmd="beep">Пискнути</button>
521
- </div>
522
- <div class="opt"><div>Ворушиться в спокої<small>дрібні рухи, коли нічого не відбувається</small></div><button type="button" class="sm" data-cmd="idle">увімк / вимк</button></div>
523
- <div class="opt"><div>Тримати після руху<small>інакше відпускає за 0,6 с</small></div><button type="button" class="sm" data-cmd="hold">увімк / вимк</button></div>
524
- </div>
525
- </div>
526
- </section>
527
-
528
- <!-- ============================================================ calibration -->
529
- <section data-page="cal" class="page" hidden>
530
- <div class="title"><div><h1>Калібрування</h1></div>
531
- <button type="button" class="ghost" data-cmd="cal">Оновити з плати</button></div>
532
- <div class="card calhero">
533
- <div><h2>Покроковий майстер</h2><p>Desky показує кожен рух, ти підтверджуєш. Близько 3 хвилин.</p></div>
534
- <button type="button" class="pri lg" id="calWiz">Почати калібрування</button>
535
- </div>
536
- <div class="joints" id="joints"></div>
537
- <div class="card">
538
- <div class="hd"><h2>Проводи й екран</h2></div>
539
- <div class="set tog">
540
- <div class="field"><label>Поворот і нахил переплутані<small>Повзунок повороту нахиляє Desky, а нахилу — крутить? Серво під'єднані навпаки. <span id="swapV"></span></small></label>
541
- <button type="button" class="sm" id="swapYP">Поміняти місцями</button></div>
542
- <div class="field"><label>Екран догори дриґом<small>Очі-галочки «^ ^» мають дивитися кутиками вгору. <span id="flipV"></span></small></label>
543
- <span class="in"><button type="button" class="sm ghost" id="faceTest">Показати «^ ^»</button><button type="button" class="sm" id="flipScr">Перевернути</button></span></div>
544
- </div>
545
- </div>
546
- <div class="savebar" id="calbar"><p id="calMsg">Збережи, щоб зміни пережили перезапуск плати.</p><button type="button" class="pri" id="calSave">Зберегти в платі</button></div>
547
- </section>
548
-
549
- <!-- ============================================================ settings -->
550
- <section data-page="cfg" class="page" hidden>
551
- <div class="title"><div><h1>Налаштування</h1></div></div>
552
- <div class="card colorcard">
553
- <div class="hd"><h2>Колір Desky</h2><span class="muted small" id="colorNow"></span></div>
554
- <div class="swatches" id="cfgSwatches" role="radiogroup" aria-label="Колір Desky"></div>
555
- </div>
556
- <div class="cols">
557
- <div class="card">
558
- <div class="hd"><h2>Звук</h2></div>
559
- <div class="set">
560
- <div class="field"><label for="qh0">Тихі години<small>без звуку, лише рухи</small></label>
561
- <span class="in"><input class="num s" type="number" id="qh0" min="0" max="24"><span class="muted">–</span><input class="num s" type="number" id="qh1" min="0" max="24"><span class="unit">год</span></span></div>
562
- <div class="field"><label for="ask_times">Пищати «чекає»<small>разом із першим разом</small></label>
563
- <span class="in"><input class="num" type="number" id="ask_times" min="0"><span class="unit">разів</span></span></div>
564
- <div class="field"><label for="ask_repeat_secs">Повтор трелі</label>
565
- <span class="in"><input class="num" type="number" id="ask_repeat_secs" min="0"><span class="unit" data-for="ask_repeat_secs"></span></span></div>
566
- </div>
567
- </div>
568
- <div class="card">
569
- <div class="hd"><h2>Час</h2></div>
570
- <div class="set">
571
- <div class="field"><label for="done_secs">«Закінчив» триває<small>потім «нічого не робить»</small></label>
572
- <span class="in"><input class="num" type="number" id="done_secs" min="0"><span class="unit" data-for="done_secs"></span></span></div>
573
- <div class="field"><label for="sleep_secs">Засинає через<small>якщо немає подій</small></label>
574
- <span class="in"><input class="num" type="number" id="sleep_secs" min="0"><span class="unit" data-for="sleep_secs"></span></span></div>
575
- </div>
576
- </div>
577
- <div class="card">
578
- <div class="hd"><h2>Забувати сесію</h2></div>
579
- <div class="set">
580
- <div class="field"><label for="session_ttl_secs">Мовчить<small>після «закінчив» або простою</small></label>
581
- <span class="in"><input class="num" type="number" id="session_ttl_secs" min="0"><span class="unit" data-for="session_ttl_secs"></span></span></div>
582
- <div class="field"><label for="busy_ttl_secs">Працювала й зникла<small>термінал закрили; довше 10 хв команди не йдуть</small></label>
583
- <span class="in"><input class="num" type="number" id="busy_ttl_secs" min="0"><span class="unit" data-for="busy_ttl_secs"></span></span></div>
584
- <div class="field"><label for="ask_ttl_secs">Питання без відповіді</label>
585
- <span class="in"><input class="num" type="number" id="ask_ttl_secs" min="0"><span class="unit" data-for="ask_ttl_secs"></span></span></div>
586
- </div>
587
- </div>
588
- <div class="card">
589
- <div class="hd"><h2>«Читає» чи «працює»</h2></div>
590
- <div class="set">
591
- <div class="field col"><label for="read_tools">Інструменти для «читає»<small>через кому; решта — «працює»</small></label>
592
- <input class="text" type="text" id="read_tools"></div>
593
- </div>
594
- </div>
595
- </div>
596
- <div class="savebar"><p id="cfgMsg"></p><button type="button" class="ghost" id="defCfg">За замовчуванням</button><button type="button" class="pri" id="saveCfg">Зберегти</button></div>
597
- </section>
598
-
599
- <!-- ============================================================ monitor -->
600
- <section data-page="mon" class="page" hidden>
601
- <div class="title"><div><h1>Монітор</h1></div></div>
602
- <div class="term">
603
- <div class="bar">
604
- <span class="legend"><span><i style="background:#F2B48F"></i>ти</span><span><i style="background:#9FC6F0"></i>агент</span><span><i style="background:#E6E1DA"></i>плата</span></span>
605
- <label class="check"><input type="checkbox" id="showAgent" checked> команди агента</label>
606
- <button type="button" class="ghost sm" id="clearLog">Очистити</button>
607
- </div>
608
- <div class="log" id="log" aria-live="polite"></div>
609
- <form class="raw" id="rawf"><input id="raw" placeholder="pose 0 10 80 80 · state ask · help" autocomplete="off"><button type="button" id="helpBtn">help</button><button type="submit">Надіслати</button></form>
610
- </div>
611
- </section>
612
- </main>
613
- </div>
614
-
615
- <!-- ============================================================ setup wizard -->
616
- <div class="upd" id="updModal" hidden role="dialog" aria-modal="true" aria-labelledby="updTitle">
617
- <div class="card">
618
- <svg class="big alive" id="updFace" viewBox="0 0 64 48" aria-hidden="true"></svg>
619
- <span class="ver" id="updVer"></span>
620
- <h2 id="updTitle">Вийшла нова версія Desky</h2>
621
- <p id="updLead"></p>
622
- <div class="cmd" id="updCmd" hidden><span>npx desky-agent@latest</span><button type="button" class="sm" id="updCopy">Копіювати</button></div>
623
- <div class="acts"><button type="button" class="ghost" id="updSkip">Пізніше</button><button type="button" class="pri lg" id="updNow">Оновити зараз</button></div>
624
- </div>
625
- </div>
626
-
627
- <div class="wiz" id="wiz" hidden role="dialog" aria-modal="true" aria-labelledby="wizTitle">
628
- <div class="panel">
629
- <div class="top">
630
- <div class="brand" aria-label="Desky Agent"><svg class="head" viewBox="-8 0 80 48" aria-hidden="true" id="wizLogo" data-head="1"></svg><svg class="chev" viewBox="0 0 10 16" aria-hidden="true"><path d="M1.5 2 L8 8 L1.5 14"/></svg><span class="wm">desky</span><span class="cur"></span></div>
631
- <div class="prog"><div class="bars" id="wizBars"></div><div class="lbl" id="wizLbl"></div></div>
632
- <button type="button" class="ghost x" id="wizClose" title="закрити майстер"><svg viewBox="0 0 16 16"><path d="M3.5 3.5l9 9M12.5 3.5l-9 9"/></svg></button>
633
- </div>
634
- <div class="body" id="wizBody"></div>
635
- </div>
636
- </div>
637
- <div class="toast" id="toast" role="status"></div>
638
-
639
- <script>
640
- (() => {
641
- const $ = id => document.getElementById(id);
642
- const css = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
643
- const wait = ms => new Promise(r => setTimeout(r, ms));
644
- const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
645
- wait: 'чекає на фонову задачу', limit: 'скінчилися ліміти', error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
646
- const WHAT = { wake: 'Щойно прокинувся', listen: 'Почув твоє повідомлення', work: 'Агент пише код або запускає команди',
647
- read: 'Агент читає файли', ask: 'Агент чекає на відповідь',
648
- wait: 'Агент чекає, поки допрацює запущене у фоні', limit: 'Скінчилися ліміти, чекає на скидання', error: 'Інструмент повернув помилку',
649
- done: 'Задачу виконано', idle: '', sleep: 'Давно не було подій' };
650
- const SOUNDS = { wake: 'прокинувся', tick: 'тік', ask: 'трель', error: 'помилка', done: 'готово', sleep: 'засинає', limit: 'ліміти' };
651
- // The colours Desky is printed in (src/core.js COLORS). body and eye: his plastic and the face on his screen (the
652
- // board keeps them, "color"); a and d: the app's accent, hover and text on it, for light and dark windows
653
- const PALETTE = {
654
- orange: { name: 'Помаранчевий', body: '#D9774B', eye: '#000000', a: ['#D9774B', '#C4643A', '#FFFFFF'], d: ['#E3825A', '#EC9167', '#1A0F0A'] },
655
- white: { name: 'Білий', body: '#ECE8E1', eye: '#000000', a: ['#8A7D6B', '#73675A', '#FFFFFF'], d: ['#D6CEC2', '#E6DFD5', '#1A1712'] },
656
- mint: { name: 'М\'ятний', body: '#7CC4A4', eye: '#000000', a: ['#3E9A75', '#2F8263', '#FFFFFF'], d: ['#6CC49E', '#88D3B2', '#0D1F17'] },
657
- blue: { name: 'Блакитний', body: '#6FA3D8', eye: '#000000', a: ['#3B7BC2', '#2D66A8', '#FFFFFF'], d: ['#6FA7E0', '#8BBAEA', '#0D1824'] },
658
- graphite: { name: 'Графіт', body: '#3D3B39', eye: '#F2EFEA', a: ['#3D3B39', '#2A2826', '#FFFFFF'], d: ['#BDB7AF', '#D3CDC5', '#1A1917'] },
659
- };
660
- let COLOR = 'orange', boardColor = null, boardFw = null, colorAsked = false;
661
- const canColor = () => { const v = String(boardFw || '').split('.').map(Number); return v.length === 3 && (v[0] > 0 || v[1] > 2 || (v[1] === 2 && v[2] >= 4)); };
662
- let CFG = null;
663
-
664
- // ---------------------------------------------------------------- toast
665
- function toast(text, bad) {
666
- const t = $('toast'); t.textContent = text; t.className = 'toast on' + (bad ? ' bad' : '');
667
- clearTimeout(toast.t); toast.t = setTimeout(() => { t.className = 'toast' + (bad ? ' bad' : ''); }, 3200);
668
- }
669
-
670
- // ---------------------------------------------------------------- pages
671
- const TABS = document.querySelectorAll('nav button');
672
- let curTab = 'home', C3 = null;
673
- function showTab(name) {
674
- curTab = name;
675
- TABS.forEach(b => b.setAttribute('aria-selected', String(b.dataset.tab === name)));
676
- document.querySelectorAll('[data-page]').forEach(p => { p.hidden = p.dataset.page !== name; });
677
- try { localStorage.setItem('clawd.tab', name); } catch (e) {}
678
- if (name === 'mon') logEl.scrollTop = logEl.scrollHeight;
679
- place3d();
680
- }
681
- // one 3D Desky: on the overview he plays the agent's state, on "Рухи" he follows the sliders, in the wizard the step
682
- function place3d() {
683
- if (!C3 || !$('wiz').hidden) return;
684
- C3.glow(null);
685
- if (curTab === 'home') { C3.mount($('homeScene'), 'hero'); C3.state(lastState || 'idle'); }
686
- else if (curTab === 'move') { C3.mount($('moveScene'), 'moves'); C3.pose(pose()); }
687
- else C3.mount(null);
688
- }
689
- addEventListener('clawd3d', () => { C3 = window.Clawd3D; C3.colors(PALETTE[COLOR].body, PALETTE[COLOR].eye); document.body.classList.add('has3d'); place3d(); if (!$('wiz').hidden && W.step) go(W.step, W.sub); });
690
- TABS.forEach(b => b.onclick = () => showTab(b.dataset.tab));
691
-
692
- // ---------------------------------------------------------------- talking to the daemon
693
- let up = false, connected = false, manual = false, beat = null;
694
- // "on" powers the servos one by one, 400 ms each (play.cpp attachAll), and the board reads nothing meanwhile: a move
695
- // sent behind it waits, and the "home" that ends a demo is already queued and cuts that move off at once. So "on"
696
- // goes only when the servos are let go (the heartbeat says so), and the next command waits until the board is back.
697
- // a move the wizard waits for: any line that reaches the board mid-move stops that move (play.cpp pollStop), so a
698
- // demo's "home", then its move, then "home" again only work one after another. Done on the board's "ok <cmd>",
699
- // refused on "Нельзя"/"err", and 4 s at most whatever happens (an old firmware, a lost line).
700
- const waiters = [];
701
- function move(cmd, ms = 4000) {
702
- const word = cmd.trim().split(/\s+/)[0].toLowerCase();
703
- return new Promise(resolve => {
704
- const w = { word };
705
- w.done = ok => { clearTimeout(w.t); const i = waiters.indexOf(w); if (i >= 0) waiters.splice(i, 1); resolve(ok); };
706
- w.t = setTimeout(() => w.done(false), ms);
707
- waiters.push(w);
708
- send(cmd);
709
- });
710
- }
711
- // a test move, twice there and back: one small twitch is easy to miss, on a video too
712
- async function demoMove(line) {
713
- await move('home');
714
- for (let i = 0; i < 2; i++) { await move(line); await wait(700); await move('home'); await wait(300); }
715
- }
716
- let onUntil = 0; // until then the board is still busy with the last "on" (any page sends it)
717
- async function servosOn() {
718
- if (!beat || /отпущены/.test(beat)) await send('on');
719
- await wait(Math.max(0, onUntil - Date.now()));
720
- }
721
- async function api(path, body) {
722
- const r = await fetch(path, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
723
- if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || r.status);
724
- return r.json();
725
- }
726
- function showMode() {
727
- $('manualbox').hidden = !manual || !$('wiz').hidden;
728
- // in manual mode Desky shows what the app says, not this: call it the agent's state then
729
- $('hKicker').hidden = !manual;
730
- }
731
- async function setManual(on, hold) {
732
- try { manual = (await api('/manual', { on, hold: Boolean(hold) })).manual; } catch (e) {}
733
- if (!manual) atRef = null;
734
- showMode();
735
- }
736
- // every hand command takes Desky from the agent; the daemon gives him back 15 s after the last keep-alive
737
- // calibration writes the board's memory: the firmware takes it only after "factory on" (docs/firmware_contract.md)
738
- const FACTORY = ['trim', 'inv', 'here', 'save', 'swap', 'flip', 'probe', 'hold', 'yawhold', 'sn', 'calset', 'face'];
739
- async function send(cmd, quiet) {
740
- if (FACTORY.includes(cmd.trim().split(/\s+/)[0].toLowerCase())) await api('/cmd', { line: 'factory on', hand: false }).catch(() => {});
741
- if (cmd === 'on') onUntil = Date.now() + 1800;
742
- if (!quiet) { lastHand = Date.now(); manual = true; showMode(); if (!/^trim /.test(cmd)) atRef = null; }
743
- try { await api('/cmd', { line: cmd, hand: !quiet }); } catch (e) { log('не надіслано: ' + e.message, 'dim'); }
744
- }
745
- let lastHand = 0;
746
- let atRef = null; // the "pose" line a centre was set in; any other hand move, or the agent taking over, clears it
747
- setInterval(() => {
748
- // the wizard and the calibration page hold Desky for as long as they are open: back with the agent, he would
749
- // stand in the agent's pose (arms at 65) while the page asks for the zero one (arms straight down)
750
- const hold = connected && (!$('wiz').hidden || curTab === 'cal');
751
- if (hold) lastHand = Date.now();
752
- if (manual && Date.now() - lastHand < 60000) setManual(true, hold);
753
- }, 5000);
754
- $('toAgent').onclick = () => { lastHand = 0; manual = false; setManual(false); };
755
-
756
- // ---------------------------------------------------------------- monitor
757
- const logEl = $('log');
758
- function log(text, cls) {
759
- if (cls === 'agent' && !$('showAgent').checked) return;
760
- const s = document.createElement('span'); if (cls) s.className = cls;
761
- s.textContent = (cls === 'me' || cls === 'agent' ? '> ' : '') + text + '\n';
762
- const stick = logEl.scrollTop + logEl.clientHeight >= logEl.scrollHeight - 20;
763
- logEl.appendChild(s);
764
- while (logEl.childNodes.length > 500) logEl.removeChild(logEl.firstChild);
765
- if (stick) logEl.scrollTop = logEl.scrollHeight;
766
- }
767
- $('clearLog').onclick = () => { logEl.innerHTML = ''; };
768
- let since = 0, primed = false;
769
- async function pollLines() {
770
- try {
771
- const lines = await api('/lines?since=' + since);
772
- for (const l of lines) {
773
- since = l.n;
774
- log(l.text, l.kind === 'c3' ? '' : l.kind);
775
- if (l.kind === 'c3') onLine(l.text);
776
- }
777
- if (!primed) { primed = true; send('cal', true); send('where', true); }
778
- } catch (e) {}
779
- }
780
- setInterval(pollLines, 300);
781
-
782
- // ---------------------------------------------------------------- status
783
- const dur = s => s < 120 ? Math.round(s) + ' с' : s < 7200 ? Math.round(s / 60) + ' хв' : (s / 3600).toFixed(1).replace('.0', '').replace('.', ',') + ' год';
784
- const plural = (n, a, b, c) => { const m = n % 10, h = n % 100; return m === 1 && h !== 11 ? a : m >= 2 && m <= 4 && (h < 12 || h > 14) ? b : c; };
785
- let firstStatus = true, port = '', lastState = null;
786
- async function pollStatus() {
787
- let st;
788
- try { st = await api('/status'); up = true; } catch (e) { up = false; }
789
- $('downbox').hidden = up;
790
- if (!up) { connected = false; beat = null; $('nocbox').hidden = true; enable(); wizTick(); return; }
791
- const was = connected;
792
- connected = st.connected; port = st.port || '';
793
- if (connected && !was) { boardColor = null; colorAsked = false; send('cal', true); }
794
- boardFw = connected && st.board ? st.board.fw : null;
795
- if (connected && canColor() && !colorAsked) { colorAsked = true; send('color', true); }
796
- $('dC3').className = 'dot ' + (connected ? 'on' : 'bad');
797
- $('sC3').textContent = connected ? st.port : 'немає';
798
- $('nocbox').hidden = connected;
799
- $('rowServo').hidden = !connected;
800
- beat = connected && st.heartbeat && st.heartbeat_age < 8 ? st.heartbeat : null;
801
- if (beat) {
802
- const limp = /отпущены/.test(beat);
803
- $('dServo').className = 'dot ' + (limp ? 'warn' : 'on');
804
- $('health').textContent = limp ? 'відпущені' : 'тримають';
805
- $('limpbox').hidden = !limp;
806
- } else {
807
- $('dServo').className = 'dot' + (connected ? ' bad' : ''); $('health').textContent = connected ? 'мовчать' : '—';
808
- $('limpbox').hidden = true;
809
- }
810
- manual = st.manual; if (!manual) atRef = null; showMode();
811
- showUpdate(st.app_update);
812
-
813
- $('hState').textContent = NAMES[st.state] || st.state;
814
- $('hWhat').textContent = WHAT[st.state] || '';
815
- $('hQuiet').hidden = !st.quiet_now;
816
- if (st.quiet_now) $('hQuiet').querySelector('span').textContent = 'Тихі години' + (CFG ? ' до ' + CFG.quiet_hours[1] + ':00' : '');
817
-
818
- const ses = Object.entries(st.by_session || {}), host = $('sessions');
819
- $('sessCount').textContent = ses.length || '';
820
- host.innerHTML = '';
821
- if (!ses.length) host.innerHTML = '<div class="empty">Запусти Claude Code або Codex — Desky прокинеться.</div>';
822
- else {
823
- const list = document.createElement('div'); list.className = 'list';
824
- for (const [sid, s] of ses) {
825
- const r = document.createElement('div'); r.className = 'li';
826
- r.innerHTML = '<span class="mono"></span><span class="badge"></span>';
827
- r.querySelector('.mono').textContent = sid;
828
- const b = r.querySelector('.badge'); b.textContent = NAMES[s] || s; if (s === 'ask') b.classList.add('ask');
829
- list.appendChild(r);
830
- }
831
- host.appendChild(list);
832
- }
833
- if (st.state !== lastState) {
834
- lastState = st.state; ['logo', 'bigface'].forEach(id => drawFace($(id), st.state));
835
- if (C3 && curTab === 'home' && $('wiz').hidden) C3.state(st.state);
836
- }
837
- enable();
838
- wizTick();
839
- if (firstStatus) {
840
- firstStatus = false;
841
- let seen = false; try { seen = !!localStorage.getItem('clawd.onboarded'); } catch (e) { seen = true; }
842
- if (!seen) wizOpen();
843
- }
844
- }
845
- // ---------------------------------------------------------------- new versions of the app
846
- // the dialog comes back every time the window opens until the update is in; "Пізніше" closes it for this window only
847
- let modalSkipped = '';
848
- let updSeen = ''; // a done or failed text closed with "Сховати"
849
- let au = {}, updErr = ''; // updErr: the button's own failure, kept until the next try
850
- function showUpdate(a) {
851
- au = a || {};
852
- if (updErr && au.state !== 'updating') au = { ...au, state: 'failed', text: updErr };
853
- const box = $('updbox'), p = $('updText'), go = $('updGo'), later = $('updLater');
854
- $('sVer').textContent = au.version ? (au.available ? au.version + ' → ' + au.latest : au.version) : '—';
855
- $('dVer').className = 'dot ' + (au.state === 'failed' ? 'bad' : au.available ? 'warn' : 'on');
856
- $('verRow').disabled = !au.available;
857
- $('verRow').classList.toggle('new', Boolean(au.available && au.state !== 'updating'));
858
- if (au.available && au.state !== 'updating') $('sVer').textContent = 'оновити до ' + au.latest;
859
- $('verRow').title = au.available ? 'стоїть ' + au.version + ', вийшла ' + au.latest + ': оновити' : 'версія програми Desky Agent';
860
- showModal();
861
- let show = false;
862
- box.classList.remove('bad', 'ok');
863
- p.textContent = '';
864
- const b = t => { const e = document.createElement('b'); e.textContent = t; return e; };
865
- if (au.state === 'updating') {
866
- show = true;
867
- p.append(b('Оновлюю Desky до ' + au.latest + '.'), ' Це займе хвилину: вікно закриється й відкриється знову вже з новою версією.');
868
- go.hidden = false; go.disabled = true; go.textContent = 'Оновлюю…'; later.hidden = true;
869
- } else if ((au.state === 'failed' || au.state === 'done') && au.text !== updSeen) {
870
- show = true;
871
- box.classList.add(au.state === 'failed' ? 'bad' : 'ok');
872
- p.append(b(au.state === 'failed' ? 'Оновлення не вдалося. ' : 'Готово. '), au.text);
873
- go.hidden = !(au.state === 'failed' && au.available && au.can); go.disabled = false; go.textContent = 'Ще раз';
874
- later.hidden = false; later.textContent = 'Сховати';
875
- } else if (au.available) {
876
- show = true;
877
- p.append(b('Вийшла версія ' + au.latest + '.'), ' Зараз стоїть ' + au.version + '. ');
878
- if (au.can) p.append('Оновлення займе хвилину, налаштування й калібрування залишаться.');
879
- else { p.append('Онови з термінала: '); const c = document.createElement('span'); c.className = 'mono'; c.textContent = 'npx desky-agent@latest'; p.append(c); }
880
- go.hidden = !au.can; go.disabled = false; go.textContent = 'Оновити';
881
- later.hidden = true;
882
- }
883
- box.hidden = !show;
884
- }
885
- $('updGo').onclick = async () => {
886
- $('updGo').disabled = true; updErr = '';
887
- try { showUpdate({ ...au, ...(await api('/app-update', {})) }); }
888
- catch (e) { updErr = e.message; showUpdate(au); }
889
- };
890
- $('updLater').onclick = () => {
891
- if (au.state === 'failed' || au.state === 'done') { updSeen = au.text; updErr = ''; }
892
- showUpdate(au);
893
- };
894
- $('verRow').onclick = () => { modalSkipped = ''; updSeen = ''; showUpdate(au); };
895
-
896
- // the dialog: not over the wizard (he is mid-calibration), back after it closes
897
- function showModal() {
898
- const m = $('updModal');
899
- const want = Boolean(au.available && au.state !== 'updating' && modalSkipped !== au.latest && $('wiz').hidden);
900
- if (want && m.hidden) {
901
- drawFace($('updFace'), 'happy');
902
- $('updVer').textContent = au.version + ' → ' + au.latest;
903
- $('updLead').textContent = au.can
904
- ? 'Оновлення займе хвилину: вікно закриється й відкриється знову. Налаштування й калібрування залишаться, плату не від\'єднуй.'
905
- : 'Онови з термінала або попроси свого агента виконати цю команду. Налаштування й калібрування залишаться.';
906
- $('updCmd').hidden = Boolean(au.can);
907
- $('updNow').textContent = au.can ? 'Оновити зараз' : 'Зрозуміло';
908
- setTimeout(() => $('updNow').focus(), 50);
909
- }
910
- m.hidden = !want;
911
- }
912
- $('updSkip').onclick = () => { modalSkipped = au.latest; showModal(); };
913
- $('updNow').onclick = () => {
914
- modalSkipped = au.latest;
915
- showModal();
916
- if (au.can) $('updGo').click();
917
- };
918
- $('updCopy').onclick = async () => {
919
- try { await navigator.clipboard.writeText('npx desky-agent@latest'); $('updCopy').textContent = 'Скопійовано'; } catch (e) {}
920
- };
921
- document.addEventListener('keydown', e => { if (e.key === 'Escape' && !$('updModal').hidden) $('updSkip').click(); });
922
-
923
- function enable() {
924
- document.querySelectorAll('[data-cmd], #send, #home, #stop, #swapYP, #flipScr, #faceTest, #calSave, #rawf button, #joints button, #joints input, #statesRow button, #soundsRow button')
925
- .forEach(b => { b.disabled = !connected; });
926
- F.forEach(f => { f.disabled = !connected; });
927
- }
928
- setInterval(pollStatus, 1000);
929
-
930
- // a small picture of the face the state shows, as the firmware draws it: orange face, black eyes
931
- function drawFace(s, state) {
932
- s.innerHTML = '';
933
- const c = PALETTE[COLOR].eye, add = (x, y, w, h, cls) => { const r = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
934
- r.setAttribute('x', x); r.setAttribute('y', y); r.setAttribute('width', w); r.setAttribute('height', h); r.setAttribute('fill', c);
935
- if (cls) r.setAttribute('class', cls); s.appendChild(r); };
936
- const bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
937
- bg.setAttribute('width', 64); bg.setAttribute('height', 48); bg.setAttribute('rx', s.dataset.head ? 8 : 4); bg.setAttribute('fill', PALETTE[COLOR].body); s.appendChild(bg);
938
- // the logo: the head from the brand sheet, a servo ear on each side of the screen
939
- if (s.dataset.head) for (const x of [-8, 64]) { const e = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
940
- e.setAttribute('x', x); e.setAttribute('y', 15); e.setAttribute('width', 8); e.setAttribute('height', 18); e.setAttribute('rx', 2);
941
- e.setAttribute('fill', PALETTE[COLOR].body); s.appendChild(e); }
942
- const eyes = { work: [9, 7, 0, 6], read: [7, 8, -4, 6], ask: [13, 13, 0, 0], sleep: [11, 2, 0, 4], idle: [8, 14, 0, 0],
943
- wait: [8, 11, 0, 3], limit: [11, 3, 0, 4],
944
- wake: [8, 14, 0, 0], listen: [8, 14, 0, 0] }[state];
945
- if (state === 'done' || state === 'happy') { for (const x of [16, 48]) for (let i = 0; i < 6; i++) { add(x - 6 + i, 26 - i, 2, 2); add(x + i, 21 + i, 2, 2); } return; }
946
- if (state === 'sad') { for (const x of [16, 48]) for (let i = 0; i < 6; i++) { add(x - 6 + i, 20 + i, 2, 2); add(x + i, 25 - i, 2, 2); } return; }
947
- if (state === 'error') { for (const [x, d] of [[16, 1], [48, -1]]) for (let i = 0; i < 6; i++) { add(x - d * 6 + d * i, 18 + i, 2, 2); add(x - d * 6 + d * i, 30 - i, 2, 2); } return; }
948
- const [w, h, dx, dy] = eyes || [8, 14, 0, 0];
949
- for (const x of [16, 48]) add(x - w / 2 + dx, 24 - h / 2 + dy, w, h, state === 'sleep' ? '' : 'eye');
950
- if (state === 'sleep') add(54, 4, 5, 2), add(57, 6, 2, 2), add(54, 8, 5, 2);
951
- if (state === 'limit') { add(26, 3, 12, 1); add(26, 9, 12, 1); add(26, 3, 1, 7); add(37, 3, 1, 7); add(38, 5, 1, 3); add(28, 5, 2, 3); }
952
- }
953
-
954
- // ---------------------------------------------------------------- previews
955
- for (const [k, v] of Object.entries(NAMES)) {
956
- const b = document.createElement('button'); b.type = 'button'; b.textContent = v; b.onclick = () => send('state ' + k); $('statesRow').appendChild(b);
957
- }
958
- for (const [k, v] of Object.entries(SOUNDS)) {
959
- const b = document.createElement('button'); b.type = 'button'; b.textContent = v; b.onclick = () => send('sound ' + k, true); $('soundsRow').appendChild(b);
960
- }
961
-
962
- // ---------------------------------------------------------------- settings
963
- const NUMS = ['done_secs', 'sleep_secs', 'ask_repeat_secs', 'ask_times', 'session_ttl_secs', 'busy_ttl_secs', 'ask_ttl_secs'];
964
- let DEF = null;
965
- // "600" means little at a glance: show it as minutes or hours next to the box
966
- const human = s => !(s >= 0) ? '' : s < 60 ? s + ' с' : s % 3600 === 0 ? s / 3600 + ' год' : s % 60 === 0 ? s / 60 + ' хв'
967
- : (s / 60).toFixed(1).replace('.', ',') + ' хв';
968
- function units() { document.querySelectorAll('.unit[data-for]').forEach(u => { const v = $(u.dataset.for).value; u.textContent = v === '' ? 'с' : 'с · ' + human(+v); }); }
969
- NUMS.forEach(k => $(k).addEventListener('input', units));
970
- function fillCfg(c) {
971
- CFG = c;
972
- if (c.color && c.color !== COLOR) applyColor(c.color);
973
- reconcileColor();
974
- $('qh0').value = c.quiet_hours[0]; $('qh1').value = c.quiet_hours[1];
975
- NUMS.forEach(k => { $(k).value = c[k]; });
976
- $('read_tools').value = c.read_tools.join(', ');
977
- units();
978
- }
979
- async function loadCfg() { try { const r = await api('/config'); DEF = r.defaults; fillCfg(r.config); } catch (e) {} }
980
- const say = (t, cls) => { const m = $('cfgMsg'); m.className = cls || ''; m.textContent = t;
981
- clearTimeout(say.t); say.t = setTimeout(() => { m.className = ''; m.textContent = 'Час — у секундах.'; }, 4000); };
982
- $('saveCfg').onclick = async () => {
983
- const body = { quiet_hours: [+$('qh0').value, +$('qh1').value], read_tools: $('read_tools').value.split(',').map(s => s.trim()).filter(Boolean) };
984
- NUMS.forEach(k => { body[k] = +$(k).value; });
985
- try { fillCfg((await api('/config', body)).config); say('Збережено', 'ok'); }
986
- catch (e) { say(e.message, 'bad'); }
987
- };
988
- $('defCfg').onclick = () => { if (DEF) { const keep = CFG; fillCfg(DEF); CFG = keep; } say('Підставлено значення за замовчуванням — збережи, щоб застосувати'); };
989
- loadCfg();
990
-
991
- // ---------------------------------------------------------------- Desky's colour
992
- function applyColor(name) {
993
- COLOR = PALETTE[name] ? name : 'orange';
994
- const c = PALETTE[COLOR], dark = matchMedia('(prefers-color-scheme: dark)').matches, [a, hi, ink] = dark ? c.d : c.a;
995
- const st = document.documentElement.style;
996
- st.setProperty('--clawd', a); st.setProperty('--clawd-hi', hi); st.setProperty('--clawd-ink', ink);
997
- st.setProperty('--clawd-soft', `color-mix(in srgb, ${a} ${dark ? 18 : 12}%, var(--card))`);
998
- st.setProperty('--clawd-glow', `color-mix(in srgb, ${a} 24%, transparent)`);
999
- ['logo', 'bigface', 'wizLogo'].forEach(id => $(id) && drawFace($(id), id === 'wizLogo' ? 'done' : lastState || 'idle'));
1000
- if (C3) C3.colors(c.body, c.eye);
1001
- document.querySelectorAll('.swatch').forEach(b => b.setAttribute('aria-checked', String(b.dataset.color === COLOR)));
1002
- $('colorNow').textContent = c.name;
1003
- buildJoints();
1004
- }
1005
- const colorLine = n => 'color ' + PALETTE[n].body.slice(1).toLowerCase() + ' ' + PALETTE[n].eye.slice(1).toLowerCase();
1006
- // chosen here: the app takes it at once, the config keeps it, the board repaints his face and keeps it too
1007
- // fromBoard: the board already shows that colour, it only goes into the config (sending it back made the board
1008
- // answer again, and every answer that came before the config was saved sent it once more)
1009
- async function pickColor(name, fromBoard) {
1010
- applyColor(name);
1011
- if (CFG) CFG.color = COLOR;
1012
- if (fromBoard) boardColor = COLOR;
1013
- else if (connected && canColor()) { boardColor = COLOR; send(colorLine(COLOR), true); }
1014
- try { CFG = (await api('/config', { color: COLOR })).config; } catch (e) {}
1015
- }
1016
- // the board and the config disagree: a board left at the factory orange takes the chosen colour, any other colour on
1017
- // the board is the robot's own (printed and set at the factory) and wins
1018
- function reconcileColor() {
1019
- if (!CFG || !boardColor || boardColor === 'other' || boardColor === CFG.color) return;
1020
- if (boardColor === 'orange') { if (connected && canColor()) send(colorLine(CFG.color), true); boardColor = CFG.color; }
1021
- else pickColor(boardColor, true);
1022
- }
1023
- function swatches(host) {
1024
- host.innerHTML = '';
1025
- for (const [k, c] of Object.entries(PALETTE)) {
1026
- const b = document.createElement('button'); b.type = 'button'; b.className = 'swatch'; b.dataset.color = k;
1027
- b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', String(k === COLOR));
1028
- b.innerHTML = `<span class="chip" style="--c:${c.body};--e:${c.eye}"></span><span>${c.name}${k === 'orange' ? '<small>основний</small>' : ''}</span>`;
1029
- b.onclick = () => pickColor(k);
1030
- host.appendChild(b);
1031
- }
1032
- return host;
1033
- }
1034
- swatches($('cfgSwatches'));
1035
-
1036
- // ---------------------------------------------------------------- what the board prints back (firmware text, Russian)
1037
- const CAL = [{ dir: 1, trim: 0 }, { dir: 1, trim: 0 }, { dir: 1, trim: 0 }, { dir: -1, trim: 0 }];
1038
- let SWAP = null, FLIP = null;
1039
- const touched = [0, 0, 0, 0]; // when this window last moved a joint's trim: ignore echoes then
1040
- function onLine(line) {
1041
- const ok = line.match(/^ok (\S+)/);
1042
- if (ok) { const w = waiters.find(x => x.word === ok[1]); if (w) w.done(true); }
1043
- else if (/^(Нельзя|err )/.test(line) && waiters.length) waiters[0].done(false);
1044
- if (/^Серво отпущены/i.test(line)) $('limpbox').hidden = false;
1045
- if (/^Нельзя:/.test(line)) toast('Desky так не стане: зачепить стіл або ноутбук', true);
1046
- let m = line.match(/поза: J1 ([+-]?\d+)\s+J2 ([+-]?\d+)\s+J3 (-?\d+)\s+J4 (-?\d+)/);
1047
- if (m && !dragging) setFaders([+m[1], +m[2], +m[3], +m[4]]);
1048
- m = line.match(/J([1-4]) [^:]+: направление ([+-]\d)/);
1049
- if (m) { CAL[+m[1] - 1].dir = +m[2]; calChanged(+m[1] - 1); }
1050
- m = line.match(/J([1-4]) [^:]+:.*подстройка ([+-]\d+) us/);
1051
- if (m && Date.now() - touched[+m[1] - 1] > 900) { CAL[+m[1] - 1].trim = +m[2]; calChanged(+m[1] - 1); }
1052
- // firmware's cal: "поворот на GPIO1, наклон на GPIO2; экран как есть" as wired in docs/pinout.html
1053
- m = line.match(/поворот на GPIO(\d+), наклон на GPIO(\d+)(?:; экран (.+))?/);
1054
- if (m) {
1055
- SWAP = +m[1] > +m[2]; $('swapV').textContent = SWAP ? 'Зараз: поміняні місцями.' : 'Зараз: як на схемі.';
1056
- if (m[3]) { FLIP = /перев/.test(m[3]); $('flipV').textContent = FLIP ? 'Зараз: перевернутий.' : 'Зараз: як є.'; }
1057
- }
1058
- if (/^сохранено/.test(line)) { calDirty(false); }
1059
- m = line.match(/^цвет ([0-9a-f]{6}) ([0-9a-f]{6})/i);
1060
- // only fresh answers: the first poll replays the monitor's history, old colours included (each one sent ours back)
1061
- if (m && primed) { boardColor = Object.keys(PALETTE).find(k => PALETTE[k].body.slice(1).toLowerCase() === m[1].toLowerCase()) || 'other'; reconcileColor(); }
1062
- if (/^err (trim|inv|here|save|swap|flip|face)/.test(line)) toast('Плата не прийняла команду: ' + line.slice(4), true);
1063
- wizLine(line);
1064
- }
1065
-
1066
- // ---------------------------------------------------------------- faders
1067
- const F = [0, 1, 2, 3].map(i => $('f' + i)), O = [0, 1, 2, 3].map(i => $('o' + i));
1068
- const fill = f => f.style.setProperty('--p', (f.value - f.min) / (f.max - f.min) * 100 + '%');
1069
- const pose = () => F.map(f => +f.value);
1070
- let dragging = false, lastSent = 0, timer = null;
1071
- function setFaders(P) { P.forEach((v, i) => { F[i].value = v; }); refresh(); }
1072
- function refresh() {
1073
- const P = pose();
1074
- P.forEach((v, i) => { O[i].textContent = (i < 2 && v > 0 ? '+' : '') + v + '°'; fill(F[i]); });
1075
- drawSide($('side'), P); drawTop($('topv'), P[0], true);
1076
- if (C3 && curTab === 'move' && $('wiz').hidden) C3.pose(P);
1077
- }
1078
- const sendPose = () => send('pose ' + pose().join(' '));
1079
- function queueLive() {
1080
- if (!$('live').checked || !connected) return;
1081
- clearTimeout(timer);
1082
- const wt = Math.max(0, 180 - (Date.now() - lastSent));
1083
- timer = setTimeout(() => { lastSent = Date.now(); sendPose(); }, wt);
1084
- }
1085
- F.forEach((f, i) => {
1086
- f.addEventListener('pointerdown', () => { dragging = true; });
1087
- f.addEventListener('pointerup', () => { dragging = false; });
1088
- f.addEventListener('input', () => {
1089
- if ($('mirror').getAttribute('aria-pressed') === 'true' && i >= 2) F[5 - i].value = f.value;
1090
- refresh(); queueLive();
1091
- });
1092
- });
1093
- $('mirror').onclick = () => {
1094
- const on = $('mirror').getAttribute('aria-pressed') !== 'true';
1095
- $('mirror').setAttribute('aria-pressed', String(on));
1096
- if (on) { F[3].value = F[2].value; refresh(); queueLive(); }
1097
- };
1098
- $('live').onchange = () => { $('send').hidden = $('live').checked; };
1099
- $('send').onclick = sendPose;
1100
- $('home').onclick = () => { setFaders([0, 0, 65, 65]); send('home'); };
1101
- $('stop').onclick = () => send('stop');
1102
- document.querySelectorAll('[data-cmd]').forEach(b => b.onclick = () => send(b.dataset.cmd, ['where', 'cal'].includes(b.dataset.cmd)));
1103
- const spd = $('spd');
1104
- spd.oninput = () => { $('ospd').textContent = spd.value + '°/с'; fill(spd); };
1105
- spd.onchange = () => send('speed ' + spd.value);
1106
- fill(spd);
1107
- $('rawf').onsubmit = e => { e.preventDefault(); const v = $('raw').value.trim(); if (v) { send(v, /^(where|cal|help|who|ping|sound )/.test(v)); $('raw').value = ''; } };
1108
- $('helpBtn').onclick = () => send('help', true);
1109
-
1110
- // ---------------------------------------------------------------- joints: what each one is and how to judge it
1111
- // as factory/clawd_factory/calibrate.py: direction first, then the centre (an arm's trim counts along its direction)
1112
- const US_PER_DEG = 1000 / 90; // MG90S, as the firmware: about 1000 us per 90 deg
1113
- const J = [
1114
- { n: 1, name: 'Поворот голови', short: 'Поворот', base: 0, plus: 25, ref: 0,
1115
- plusText: 'Голова повернулася <b>праворуч</b>, якщо дивитися Desky в обличчя.',
1116
- refText: 'голова дивиться <b>прямо вперед</b>, рівно на ноутбук', lo: 'ліворуч', hi: 'праворуч' },
1117
- { n: 2, name: 'Нахил голови', short: 'Нахил', base: 0, plus: 15, ref: 0,
1118
- plusText: 'Голова нахилилася <b>вперед</b>, до ноутбука.',
1119
- refText: 'голова стоїть <b>рівно</b>: не нахилена ні вперед, ні назад', lo: 'назад', hi: 'вперед' },
1120
- { n: 3, name: 'Права рука', short: 'Права рука', base: 65, plus: 40, ref: 65, pic: 0,
1121
- plusText: 'Права рука Desky <b>піднялася вперед</b>. Це та, що в тебе <b>зліва</b>, коли дивишся йому в обличчя.',
1122
- refText: 'права рука <b>висить рівно вниз</b>', lo: 'назад', hi: 'вперед' },
1123
- { n: 4, name: 'Ліва рука', short: 'Ліва рука', base: 65, plus: 40, ref: 65, pic: 0,
1124
- plusText: 'Ліва рука Desky <b>піднялася вперед</b>. Це та, що в тебе <b>справа</b>, коли дивишся йому в обличчя.',
1125
- refText: 'ліва рука <b>висить рівно вниз</b>', lo: 'назад', hi: 'вперед' },
1126
- ];
1127
- const HOME = [0, 0, 65, 65];
1128
- // ref: the angle the centre is set at (sent to the board). An arm hangs straight down at the servo centre, home's
1129
- // 65 (the horn goes on hanging), so its centre is set there; pic: how the pictures draw that pose (0 = hanging).
1130
- const refPic = j => poseWith(j, J[j].pic ?? J[j].ref);
1131
- const FACTORY_DIR = [1, 1, 1, -1]; // play.cpp dirOf: the arms are mirror images
1132
- const poseWith = (j, v) => { const p = HOME.slice(); p[j] = v; return p; };
1133
- const trimToDeg = j => CAL[j].trim * CAL[j].dir / US_PER_DEG;
1134
- const degToTrim = (j, d) => Math.max(-500, Math.min(500, Math.round(d * US_PER_DEG * CAL[j].dir)));
1135
- const fmtDeg = d => (d > 0.04 ? '+' : d < -0.04 ? '−' : '') + Math.abs(d).toFixed(1).replace('.', ',') + '°';
1136
-
1137
- // a live trim: the firmware moves the servo at once (play.cpp, "trim"); at most one line per 110 ms, the last one always
1138
- const trimQ = [null, null, null, null], trimT = [0, 0, 0, 0], trimTimer = [];
1139
- function sendTrim(j, us) {
1140
- CAL[j].trim = us; touched[j] = Date.now(); calDirty(true);
1141
- trimQ[j] = us;
1142
- if (trimTimer[j]) return;
1143
- const go = () => {
1144
- trimTimer[j] = null;
1145
- if (trimQ[j] === null) return;
1146
- const v = trimQ[j]; trimQ[j] = null; trimT[j] = Date.now();
1147
- send('trim j' + (j + 1) + ' ' + (v >= 0 ? '+' : '') + v);
1148
- trimTimer[j] = setTimeout(go, 110);
1149
- };
1150
- const wt = Math.max(0, 110 - (Date.now() - trimT[j]));
1151
- trimTimer[j] = setTimeout(go, wt);
1152
- }
1153
-
1154
- // the centre dial in degrees (±45° = ±500 us), filled from the middle; fine steps of 0.5° and the arrow keys
1155
- function toRef(j) {
1156
- const line = 'pose ' + poseWith(j, J[j].ref).join(' ');
1157
- if (atRef === line && manual) return Promise.resolve();
1158
- clearTimeout(trimTimer[j]); trimTimer[j] = null;
1159
- trimT[j] = Date.now() + 1500; // an arm from 65 to 0 at 60 deg/s; a trim sent sooner stops the move
1160
- const sent = send(line);
1161
- atRef = line;
1162
- return sent;
1163
- }
1164
-
1165
- function makeDial(j, onMove) {
1166
- const d = document.createElement('div'); d.className = 'dial';
1167
- d.innerHTML = `<div class="ends"><span>← ${J[j].lo}</span><b></b><span>${J[j].hi} →</span></div>
1168
- <div class="track"><input type="range" min="-45" max="45" step="0.1" aria-label="центр: ${J[j].short}"></div>
1169
- <div class="fine"><button type="button" class="sm" data-d="-2">−2°</button><button type="button" class="sm" data-d="-0.5">−½°</button>
1170
- <button type="button" class="sm ghost" data-z>у нуль</button>
1171
- <button type="button" class="sm" data-d="0.5">+½°</button><button type="button" class="sm" data-d="2">+2°</button></div>
1172
- <div class="hint"></div>`;
1173
- const r = d.querySelector('input'), b = d.querySelector('.ends b'), hint = d.querySelector('.hint');
1174
- const paint = () => {
1175
- const v = +r.value, p = (v + 45) / 90 * 100;
1176
- r.style.setProperty('--a', Math.min(50, p) + '%'); r.style.setProperty('--b', Math.max(50, p) + '%');
1177
- b.textContent = fmtDeg(v);
1178
- const us = Math.abs(degToTrim(j, v)), big = us > 200;
1179
- d.classList.toggle('warn', big);
1180
- hint.className = 'hint' + (big ? ' warn' : '');
1181
- hint.innerHTML = big ? 'Зсув понад 18°: ходу в один бік стане менше. Краще переставити качалку серво на сусідній зубець і почати з нуля.'
1182
- : 'Стрілки ← → на клавіатурі рухають на 0,1°. Зсув ' + (us ? '≈ ' + us + ' мкс' : 'нульовий') + '.';
1183
- };
1184
- const set = (v, push) => { r.value = Math.max(-45, Math.min(45, Math.round(v * 10) / 10)); paint(); if (push) { toRef(j); sendTrim(j, degToTrim(j, +r.value)); onMove && onMove(); } };
1185
- r.addEventListener('input', () => set(+r.value, true));
1186
- d.querySelectorAll('[data-d]').forEach(x => x.onclick = () => set(+r.value + +x.dataset.d, true));
1187
- d.querySelector('[data-z]').onclick = () => set(0, true);
1188
- d.sync = () => { if (Date.now() - touched[j] > 900 && document.activeElement !== r) set(trimToDeg(j), false); };
1189
- set(trimToDeg(j), false);
1190
- return d;
1191
- }
1192
-
1193
- // ---------------------------------------------------------------- calibration page
1194
- const dials = [];
1195
- function buildJoints() {
1196
- const host = $('joints'); host.innerHTML = '';
1197
- J.forEach((jj, j) => {
1198
- const c = document.createElement('div'); c.className = 'card joint';
1199
- c.innerHTML = `<div class="hd"><div><h2>${jj.name}</h2><small>J${jj.n}</small></div><button type="button" class="sm ghost" data-goref>Поставити в нуль</button></div>
1200
- <div class="pic"><figure class="fig"><svg viewBox="0 0 160 120"></svg><figcaption>в обличчя</figcaption></figure>
1201
- <figure class="fig"><svg viewBox="0 0 240 170"></svg><figcaption>${j === 0 ? 'згори' : 'збоку'}</figcaption></figure></div>
1202
- <p class="hint">Центр: ${jj.refText}.</p>`;
1203
- const dial = makeDial(j); dials[j] = dial; c.appendChild(dial);
1204
- const dir = document.createElement('div'); dir.className = 'dir';
1205
- dir.innerHTML = '<span>Напрямок: <b></b></span><button type="button" class="sm" data-test>Перевірити</button><button type="button" class="sm ghost" data-inv>Розвернути</button>';
1206
- c.appendChild(dir);
1207
- const [front, other] = c.querySelectorAll('svg');
1208
- c.draw = () => {
1209
- const P = refPic(j);
1210
- drawFront(front, P, j);
1211
- if (j === 0) { other.setAttribute('viewBox', '0 0 160 170'); drawTop(other, 0); } else drawSide(other, P, j);
1212
- dir.querySelector('b').textContent = CAL[j].dir === FACTORY_DIR[j] ? 'як із заводу' : 'розвернутий';
1213
- };
1214
- c.querySelector('[data-goref]').onclick = () => { atRef = null; toRef(j); };
1215
- dir.querySelector('[data-test]').onclick = async () => {
1216
- await servosOn(); await demoMove('j' + jj.n + ' ' + (jj.base + jj.plus));
1217
- toast(jj.plusText.replace(/<[^>]+>/g, '') + ' Якщо ні — «Розвернути».');
1218
- };
1219
- dir.querySelector('[data-inv]').onclick = async () => { await send('inv j' + jj.n); calDirty(true); await send('cal', true); };
1220
- c.draw();
1221
- host.appendChild(c);
1222
- });
1223
- }
1224
- function calChanged(j) {
1225
- const c = $('joints').children[j]; if (c && c.draw) c.draw();
1226
- if (dials[j]) dials[j].sync();
1227
- wizCal(j);
1228
- }
1229
- let dirty = false;
1230
- function calDirty(on) {
1231
- dirty = on; $('calbar').classList.toggle('dirty', on);
1232
- $('calMsg').textContent = on ? 'Є незбережені зміни. Desky уже рухається з ними, але після перезапуску плати вони зникнуть.'
1233
- : 'Усе збережено в платі.';
1234
- }
1235
- $('calSave').onclick = async () => { await send('save'); toast('Збережено в платі'); };
1236
- $('swapYP').onclick = async () => { await send('swap'); await send('cal', true); };
1237
- $('flipScr').onclick = async () => { await send('flip'); await send('face happy'); await send('cal', true); };
1238
- $('faceTest').onclick = async () => { await send('face happy'); await wait(2500); await send('face eyes'); };
1239
- $('calWiz').onclick = () => wizOpen('wires');
1240
-
1241
- // ---------------------------------------------------------------- sketches (as firmware/panel.html)
1242
- const NS = 'http://www.w3.org/2000/svg';
1243
- function el(svg, tag, a) { const e = document.createElementNS(NS, tag); for (const k in a) e.setAttribute(k, a[k]); svg.appendChild(e); return e; }
1244
- // side view, desk to the right. hl: the joint to pick out (1: the head, 2/3: an arm), the rest fades
1245
- function drawSide(side, P, hl) {
1246
- const [, pitch, aR, aL] = P;
1247
- side.innerHTML = '';
1248
- const ink = css('--ink'), cl = css('--clawd'), desk = css('--desk');
1249
- const ox = 70, oy = 150, J2 = [0, 46.5];
1250
- const pt = (y, z) => [ox + y * 1.1, oy - z * 1.1];
1251
- const pp = (y, z) => { const r = -pitch * Math.PI / 180, dy = y - J2[0], dz = z - J2[1];
1252
- return pt(J2[0] + dy * Math.cos(r) - dz * Math.sin(r), J2[1] + dy * Math.sin(r) + dz * Math.cos(r)); };
1253
- const poly = (pts, fill, op = 1) => el(side, 'polygon', { points: pts.map(p => p.join(',')).join(' '), fill, opacity: op });
1254
- poly([pt(29, 57), pt(79, 57), pt(79, 61), pt(29, 61)], desk);
1255
- poly([pt(33, 61), pt(71, 61), pt(71, 67), pt(33, 67)], desk, .7);
1256
- poly([pt(-22, 0), pt(30, 0), pt(30, 29), pt(-22, 29)], desk, .5);
1257
- poly([pt(-26, 29.5), pt(26, 29.5), pt(26, 33.5), pt(-26, 33.5)], desk, .8);
1258
- poly([pp(-18, 64.5), pp(18, 64.5), pp(18, 116.5), pp(-18, 116.5)], cl, hl >= 2 ? .45 : 1);
1259
- poly([pp(-18, 35.5), pp(11, 35.5), pp(11, 64.5), pp(-18, 64.5)], cl, hl >= 2 ? .35 : .7);
1260
- const sh = [-2.2, 90];
1261
- [[aR, 2], [aL, 3]].forEach(([a, k]) => {
1262
- const op = hl >= 2 ? (hl === k ? 1 : .18) : k === 2 ? 1 : .55;
1263
- const r = a * Math.PI / 180, tip = [sh[0] + 26 * Math.sin(r), sh[1] - 26 * Math.cos(r)];
1264
- const p0 = pp(...sh), p1 = pp(...tip);
1265
- el(side, 'line', { x1: p0[0], y1: p0[1], x2: p1[0], y2: p1[1], stroke: hl === k ? cl : ink, 'stroke-width': 7, 'stroke-linecap': 'round', opacity: op,
1266
- ...(hl === k ? { filter: 'drop-shadow(0 0 2px rgba(0,0,0,.35))' } : {}) });
1267
- });
1268
- if (hl === 1) { // the arc the head travels
1269
- const c = pt(...J2);
1270
- el(side, 'path', { d: `M ${c[0] + 6} ${c[1] - 82} A 82 82 0 0 1 ${c[0] + 50} ${c[1] - 66}`, fill: 'none', stroke: cl, 'stroke-width': 2, 'stroke-dasharray': '4 4', opacity: .8 });
1271
- }
1272
- }
1273
- // top view, desk at the top; + yaw turns the head to Desky's left, which is your right when you face him
1274
- function drawTop(top, yaw, label) {
1275
- top.innerHTML = '';
1276
- const ink = css('--ink'), cl = css('--clawd'), desk = css('--desk'), mut = css('--muted');
1277
- const tx = 80, ty = 115;
1278
- el(top, 'rect', { x: 14, y: 8, width: 132, height: 52, rx: 3, fill: desk, opacity: .6 });
1279
- const g = el(top, 'g', { transform: `rotate(${-yaw} ${tx} ${ty})` });
1280
- el(g, 'rect', { x: tx - 32, y: ty - 18, width: 64, height: 34, rx: 2, fill: cl });
1281
- el(g, 'polygon', { points: `${tx - 8},${ty - 18} ${tx + 8},${ty - 18} ${tx},${ty - 30}`, fill: ink });
1282
- if (label) el(top, 'text', { x: 80, y: 162, 'text-anchor': 'middle', fill: mut, 'font-size': 11, 'font-family': 'JetBrains Mono, monospace' }).textContent = (yaw > 0 ? '+' : '') + Math.round(yaw) + '°';
1283
- }
1284
- // front view: you face Desky, so his right arm is on your left. Yaw slides the eyes, pitch shrinks the head, an arm
1285
- // raised forward looks shorter (cos), and past 90° it points up
1286
- function drawFront(svg, P, hl) {
1287
- const [yaw, pitch, aR, aL] = P;
1288
- svg.innerHTML = '';
1289
- const ink = css('--ink'), cl = css('--clawd'), desk = css('--desk');
1290
- const cx = 80;
1291
- el(svg, 'rect', { x: 20, y: 104, width: 120, height: 10, rx: 2, fill: desk, opacity: .55 });
1292
- el(svg, 'rect', { x: cx - 26, y: 72, width: 52, height: 32, rx: 4, fill: cl, opacity: hl >= 2 ? .5 : .75 });
1293
- const hh = 46 * Math.cos(pitch * Math.PI / 180) - 4 * Math.sin(pitch * Math.PI / 180);
1294
- const shift = Math.sin(yaw * Math.PI / 180) * 14, sq = Math.cos(yaw * Math.PI / 180);
1295
- const hw = 60 * (0.82 + 0.18 * sq);
1296
- el(svg, 'rect', { x: cx - hw / 2, y: 72 - hh, width: hw, height: hh, rx: 5, fill: cl, opacity: hl >= 2 ? .5 : 1 });
1297
- for (const ex of [-13, 13]) el(svg, 'rect', { x: cx + ex * sq + shift - 3.5, y: 72 - hh / 2 - 7 + pitch * .25, width: 7, height: 14, fill: '#000', opacity: hl >= 2 ? .5 : 1 });
1298
- [[aR, 2, -1], [aL, 3, 1]].forEach(([a, k, side]) => {
1299
- const sx = cx + side * 31, sy = 80, L = 26 * Math.cos(a * Math.PI / 180);
1300
- const on = hl === k, op = hl >= 2 ? (on ? 1 : .2) : .8;
1301
- el(svg, 'line', { x1: sx, y1: sy, x2: sx + side * 3, y2: sy + L, stroke: on ? cl : ink, 'stroke-width': 7, 'stroke-linecap': 'round', opacity: op });
1302
- el(svg, 'circle', { cx: sx + side * 3, cy: sy + L, r: 4.5, fill: on ? cl : ink, opacity: op });
1303
- });
1304
- }
1305
-
1306
- // a pose moving on a loop between two poses, for pictures that show what is about to happen
1307
- function animate(draws, A, B) {
1308
- let t0 = performance.now(), id = 0, alive = true;
1309
- const ease = u => u < .5 ? 2 * u * u : 1 - Math.pow(-2 * u + 2, 2) / 2;
1310
- const frame = now => {
1311
- if (!alive) return;
1312
- const T = 3000, u = ((now - t0) % T) / T;
1313
- const k = u < .15 ? 0 : u < .45 ? ease((u - .15) / .3) : u < .7 ? 1 : u < 1 ? 1 - ease((u - .7) / .3) : 0;
1314
- const P = A.map((a, i) => a + (B[i] - a) * k);
1315
- draws.forEach(f => f(P));
1316
- id = requestAnimationFrame(frame);
1317
- };
1318
- // drawn at once, so the picture is there before the first animation frame; without motion: the end pose, still
1319
- if (matchMedia('(prefers-reduced-motion: reduce)').matches) { draws.forEach(f => f(B)); return () => {}; }
1320
- t0 -= 3000 * .55; // start on the moved pose: what to look for comes first
1321
- frame(performance.now());
1322
- return () => { alive = false; cancelAnimationFrame(id); };
1323
- }
1324
-
1325
- // ---------------------------------------------------------------- setup wizard
1326
- const STEPS = ['hello', 'connect', 'color', 'check', 'wires', 'screen', 'j0', 'j1', 'j2', 'j3', 'done'];
1327
- const STEP_NAMES = { hello: 'Привіт', connect: 'Підключення', color: 'Колір', check: 'Перевірка', wires: 'Проводи', screen: 'Екран',
1328
- j0: 'Поворот', j1: 'Нахил', j2: 'Права рука', j3: 'Ліва рука', done: 'Готово' };
1329
- const W = { step: null, sub: null, stop: null, retried: false, orig: null, onTick: null, onLine: null, onCal: null };
1330
- const IC_OK = '<svg viewBox="0 0 16 16"><path d="M3.5 8.5l3 3 6-7"/></svg>', IC_BAD = '<svg viewBox="0 0 16 16"><path d="M4.5 4.5l7 7M11.5 4.5l-7 7"/></svg>';
1331
-
1332
- function wizOpen(from) {
1333
- $('wiz').hidden = false; showMode();
1334
- drawFace($('wizLogo'), 'done');
1335
- go(from || 'hello');
1336
- setTimeout(() => { const b = $('wizBody').querySelector('button.pri'); b && b.focus(); }, 50);
1337
- }
1338
- async function wizClose(finished) {
1339
- if (W.stop) W.stop();
1340
- revertCentre();
1341
- W.step = null; W.onTick = W.onLine = W.onCal = null;
1342
- $('wiz').hidden = true; showMode();
1343
- place3d();
1344
- try { localStorage.setItem('clawd.onboarded', '1'); } catch (e) {}
1345
- if (connected) send('home');
1346
- if (finished) showTab('home');
1347
- }
1348
- $('openWiz').onclick = () => wizOpen();
1349
- $('wizClose').onclick = () => wizClose(false);
1350
- document.addEventListener('keydown', e => { if (e.key === 'Escape' && !$('wiz').hidden) wizClose(false); });
1351
-
1352
- function progress(name) {
1353
- const i = STEPS.indexOf(name);
1354
- $('wizBars').innerHTML = STEPS.map((s, k) => `<i class="${k < i || name === 'done' ? 'done' : k === i ? 'now' : ''}" title="${STEP_NAMES[s]}"></i>`).join('');
1355
- $('wizLbl').innerHTML = `Крок ${i + 1} з ${STEPS.length} · <b>${STEP_NAMES[name]}</b>`;
1356
- }
1357
-
1358
- // one step: a stage on the left (pictures), the words and buttons on the right
1359
- const SHOT3 = ['yaw', 'side', 'armR', 'armL'];
1360
- function frame({ kick, title, lead, stage, scene, cap, body, foot }) {
1361
- if (W.stop) { W.stop(); W.stop = null; }
1362
- W.onTick = W.onLine = W.onCal = null;
1363
- const s = document.createElement('div'); s.className = 'step';
1364
- s.innerHTML = `<div class="stage"></div><div class="content"><div class="kick"></div><h2 id="wizTitle"></h2><p class="lead"></p><div class="slot"></div><div class="foot"></div></div>`;
1365
- s.querySelector('.kick').textContent = kick || '';
1366
- s.querySelector('h2').textContent = title;
1367
- s.querySelector('.lead').innerHTML = lead || '';
1368
- const stg = s.querySelector('.stage');
1369
- let host = null;
1370
- if (C3 && scene) {
1371
- host = h('<div class="scene3d"><div class="tip3d"><svg viewBox="0 0 16 16"><path d="M13 8a5 5 0 1 1-1.5-3.5M13 2.5V5h-2.5"/></svg>потягни, щоб покрутити</div></div>');
1372
- stg.classList.add('s3'); stg.appendChild(host);
1373
- if (cap) { const c = h('<div class="cap3"><i></i></div>'); c.append(cap); stg.appendChild(c); }
1374
- } else if (stage) stg.append(...[].concat(stage));
1375
- if (body) s.querySelector('.slot').append(...[].concat(body));
1376
- const f = s.querySelector('.foot');
1377
- (foot || []).forEach(b => f.appendChild(b));
1378
- $('wizBody').innerHTML = ''; $('wizBody').appendChild(s); $('wizBody').scrollTop = 0;
1379
- if (C3) C3.glow(null);
1380
- if (host) { C3.mount(host, scene.shot); if (scene.glow != null) C3.glow(scene.glow); if (scene.run) scene.run(C3); }
1381
- return s;
1382
- }
1383
- function btn(text, cls, onclick) { const b = document.createElement('button'); b.type = 'button'; b.className = cls || ''; b.innerHTML = text; b.onclick = onclick; return b; }
1384
- function spacer() { const s = document.createElement('span'); s.className = 'sp'; return s; }
1385
- function h(html) { const d = document.createElement('div'); d.innerHTML = html.trim(); return d.firstElementChild; }
1386
- function bigFace(state) { const s = document.createElementNS(NS, 'svg'); s.setAttribute('viewBox', '0 0 64 48'); s.setAttribute('class', 'big alive'); drawFace(s, state); return s; }
1387
- function fig(viewBox, caption) {
1388
- const f = document.createElement('figure'); f.className = 'fig';
1389
- const s = document.createElementNS(NS, 'svg'); s.setAttribute('viewBox', viewBox); f.appendChild(s);
1390
- if (caption) { const c = document.createElement('figcaption'); c.textContent = caption; f.appendChild(c); }
1391
- return [f, s];
1392
- }
1393
- function views(...figs) { const v = document.createElement('div'); v.className = 'views' + (figs.length > 1 ? ' two' : ''); figs.forEach(f => v.appendChild(f)); return v; }
1394
- function back(to) { return btn('Назад', 'ghost', () => go(to)); }
1395
- const busy = async (b, fn) => { const all = [...$('wizBody').querySelectorAll('button')]; all.forEach(x => x.disabled = true); try { await fn(); } finally { all.forEach(x => x.disabled = false); W.onTick && W.onTick(); } };
1396
-
1397
- // a centre the user moved but did not confirm ("Назад", closing): give the joint back what it had
1398
- function revertCentre() {
1399
- if (W.orig !== null && W.step && W.step[0] === 'j' && W.sub === 'centre') sendTrim(+W.step[1], W.orig);
1400
- W.orig = null;
1401
- }
1402
- function go(name, sub) {
1403
- revertCentre();
1404
- W.step = name; W.sub = sub || null; W.retried = false;
1405
- progress(name);
1406
- const fixed = { hello: stHello, connect: stConnect, color: stColor, check: stCheck, wires: stWires, screen: stScreen, done: stDone }[name];
1407
- if (fixed) fixed(); else if (sub === 'centre') stCentre(+name[1]); else stDir(+name[1]);
1408
- }
1409
- function wizTick() { if (!$('wiz').hidden && W.onTick) W.onTick(); }
1410
- function wizLine(line) { if (!$('wiz').hidden && W.onLine) W.onLine(line); }
1411
- function wizCal(j) { if (!$('wiz').hidden && W.onCal) W.onCal(j); }
1412
-
1413
- // ---- 1. hello
1414
- function stHello() {
1415
- frame({
1416
- kick: 'Ласкаво просимо до Desky Agent', title: 'Привіт! Я Desky',
1417
- lead: 'Я сиджу біля ноутбука й показую, що зараз робить <b>Claude Code</b> або <b>Codex</b>: пише код, читає файли, чекає на твою відповідь або вже закінчив.<br><br>Налаштуймо мене разом: під\'єднаємо плату, перевіримо рухи й за потреби відкалібруємо. Це займе кілька хвилин.',
1418
- stage: [bigFace('idle'), h('<div class="cap">Desky · робот, який живе поруч із Claude Code і Codex</div>')],
1419
- scene: { shot: 'hero', run: c => c.state('idle', true) }, cap: 'Desky за роботою',
1420
- foot: [btn('Пропустити', 'ghost', () => wizClose(false)), spacer(), btn('Почнімо', 'pri lg', () => go('connect'))],
1421
- });
1422
- }
1423
-
1424
- // ---- 2. the cable
1425
- function stConnect() {
1426
- const rows = h(`<div class="checks">
1427
- <div class="ck" data-k="app"><span class="ic"></span><div><b>Програма Desky Agent</b><small></small></div></div>
1428
- <div class="ck" data-k="board"><span class="ic"></span><div><b>Плата</b><small></small></div></div>
1429
- <div class="ck" data-k="servo"><span class="ic"></span><div><b>Серво</b><small></small></div></div></div>`);
1430
- const next = btn('Далі', 'pri lg', () => go('color'));
1431
- const face = bigFace('sleep');
1432
- frame({
1433
- kick: 'Підключення', title: 'Під\'єднай Desky',
1434
- lead: 'Встав кабель <b>USB-C</b> у Desky і в комп\'ютер. Програма знайде плату сама, нічого обирати не треба.',
1435
- stage: [face, h('<div class="cap">Чекаю на плату…</div>')], body: rows,
1436
- scene: { shot: 'front', run: c => c.state(connected ? 'wake' : 'sleep', true) }, cap: 'Чекаю на плату…',
1437
- foot: [back('hello'), spacer(), next],
1438
- });
1439
- const cap = $('wizBody').querySelector('.cap') || $('wizBody').querySelector('.cap3');
1440
- let woke = false;
1441
- W.onTick = () => {
1442
- const set = (k, cls, text) => { const r = rows.querySelector(`[data-k="${k}"]`); r.className = 'ck ' + cls; r.querySelector('small').textContent = text;
1443
- r.querySelector('.ic').innerHTML = cls === 'ok' ? IC_OK : cls === 'bad' ? IC_BAD : ''; };
1444
- set('app', up ? 'ok' : 'bad', up ? 'працює на цьому комп\'ютері' : 'не відповідає: відкрий застосунок Desky ще раз');
1445
- set('board', connected ? 'ok' : up ? 'wait' : '', connected ? 'на зв\'язку · ' + port : 'шукаю… перевір кабель (потрібен кабель з даними, не лише для заряджання)');
1446
- const limp = beat && /отпущены/.test(beat);
1447
- set('servo', beat ? 'ok' : connected ? 'wait' : '', beat ? (limp ? 'відпущені — натисну «тримати»' : 'тримають позу') : connected ? 'чекаю відповіді плати…' : '—');
1448
- next.disabled = !connected;
1449
- const say3 = t => { cap.lastChild.textContent = t; };
1450
- if (connected && !woke) { woke = true; drawFace(face, 'idle'); say3('Плата на зв\'язку!'); C3 && C3.state('wake'); send('on'); }
1451
- if (!connected && woke) { woke = false; drawFace(face, 'sleep'); say3('Чекаю на плату…'); C3 && C3.state('sleep'); }
1452
- };
1453
- W.onTick();
1454
- }
1455
-
1456
- // ---- 3. which Desky is this: his colour
1457
- function stColor() {
1458
- const sw = swatches(h('<div class="swatches" role="radiogroup" aria-label="Колір Desky"></div>'));
1459
- frame({
1460
- kick: 'Колір', title: 'Якого кольору твій Desky?',
1461
- lead: 'Обери колір корпусу. Під нього підлаштується застосунок, а Desky одразу перефарбує обличчя на своєму екрані.',
1462
- stage: [bigFace('idle')], scene: { shot: 'hero', run: c => c.state('wake', true) }, cap: 'покрути його мишкою',
1463
- body: [sw, h('<p class="hint">Колір можна змінити будь-коли в «Налаштуваннях».</p>')],
1464
- foot: [back('connect'), spacer(), btn('Далі', 'pri lg', () => go('check'))],
1465
- });
1466
- }
1467
-
1468
- // ---- 4. is everything fine already? (Desky leaves the factory calibrated)
1469
- function stCheck() {
1470
- const [f1, s1] = fig('0 0 160 120', 'в обличчя');
1471
- W.stop = animate([P => drawFront(s1, P)], HOME, [0, 0, 150, 65]);
1472
- const watch = h('<div class="watch"><span class="pulse"></span><span>Подивись на Desky: він помахає й стане рівно.</span></div>');
1473
- const replay = btn('Показати ще раз', 'ghost', () => busy(replay, demo));
1474
- const ok = btn('Так, усе рівно', 'pri', () => go('done'));
1475
- const fix = btn('Ні, налаштуймо', '', () => go('wires'));
1476
- frame({
1477
- kick: 'Перевірка', title: 'Усе на своїх місцях?',
1478
- lead: 'Desky калібрують ще на виробництві, тож зазвичай усе вже гаразд. Перевір: <b>голова дивиться прямо</b>, не нахилена, <b>руки висять рівно</b>, а помах був плавний.',
1479
- stage: views(f1), body: [watch, h('<div class="row"></div>')],
1480
- scene: { shot: 'front' }, cap: 'так має бути',
1481
- foot: [back('color'), spacer(), fix, ok],
1482
- });
1483
- $('wizBody').querySelector('.slot .row').appendChild(replay);
1484
- async function demo() { C3 && C3.state('wave', true); await servosOn(); await move('home'); await move('wave', 8000); await move('home'); }
1485
- busy(replay, demo);
1486
- }
1487
-
1488
- // ---- 4. yaw and pitch on each other's pins? (calibrate.py, check_swap)
1489
- function stWires() {
1490
- const [fa, sa] = fig('0 0 160 120'), [fb, sb] = fig('0 0 240 170');
1491
- const ca = btn('', 'choice yes', () => answer(true)), cb = btn('', 'choice', () => answer(false));
1492
- ca.append(fa.firstChild, document.createTextNode('Повернув голову вбік'));
1493
- cb.append(fb.firstChild, document.createTextNode('Кивнув уперед'));
1494
- const stopA = animate([P => drawFront(sa, P)], HOME, [22, 0, 65, 65]);
1495
- const stopB = animate([P => drawSide(sb, P, 1)], HOME, [0, 14, 65, 65]);
1496
- const [ft, st] = fig('0 0 160 170', 'згори: має бути так');
1497
- const stopT = animate([P => drawTop(st, P[0])], HOME, [22, 0, 65, 65]);
1498
- W.stop = () => { stopA(); stopB(); stopT(); };
1499
- const note = h('<div class="note" hidden></div>');
1500
- const replay = btn('Показати ще раз', 'ghost', () => busy(replay, show));
1501
- frame({
1502
- kick: 'Калібрування · проводи', title: 'Поворот чи кивок?',
1503
- lead: 'Desky спробує <b>повернути голову вбік</b>. Якщо серво поворота й нахилу під\'єднані навпаки, замість цього він кивне. Що він зробив?',
1504
- stage: views(ft), body: [h('<div class="choices"></div>'), note, replay],
1505
- scene: { shot: 'yaw', glow: 0, run: c => c.loop(HOME, [22, 0, 65, 65]) }, cap: 'має бути так: поворот убік',
1506
- foot: [back('check'), spacer(), btn('Пропустити крок', 'ghost', () => go('screen'))],
1507
- });
1508
- const ch = $('wizBody').querySelector('.choices'); ch.append(ca, cb);
1509
- async function show() { await servosOn(); await demoMove('j1 25'); }
1510
- async function answer(ok) {
1511
- if (ok) { go('screen'); return; }
1512
- if (W.retried) { note.hidden = false; note.className = 'note bad';
1513
- note.textContent = 'Голова не повертається й після перестановки. Перевір серво J1 і J2 та їхні роз\'єми, потім пройди майстер ще раз.'; return; }
1514
- W.retried = true;
1515
- await busy(ca, async () => { await send('swap'); note.hidden = false; note.className = 'note'; note.textContent = 'Поміняв поворот і нахил місцями й зберіг. Дивись ще раз!'; await show(); });
1516
- }
1517
- busy(replay, show);
1518
- }
1519
-
1520
- // ---- 5. the screen upside down? (calibrate.py, check_flip)
1521
- function stScreen() {
1522
- const P = PALETTE[COLOR];
1523
- const up = (cls, d) => `<svg viewBox="0 0 64 40" class="${cls}"><rect width="64" height="40" rx="4" fill="${P.body}"/><g fill="${P.eye}">${
1524
- [16, 48].map(x => [0, 1, 2, 3, 4, 5].map(i => `<rect x="${x - 6 + i}" y="${d ? 22 - i : 16 + i}" width="2" height="2"/><rect x="${x + i}" y="${d ? 17 + i : 21 - i}" width="2" height="2"/>`).join('')).join('')}</g></svg>`;
1525
- const ca = btn(up('', true) + 'Кутиками вгору «^ ^»', 'choice yes', () => answer(true));
1526
- const cb = btn(up('', false) + 'Кутиками вниз «v v»', 'choice', () => answer(false));
1527
- const note = h('<div class="note" hidden></div>');
1528
- frame({
1529
- kick: 'Калібрування · екран', title: 'Подивись на екран',
1530
- lead: 'Зараз на екрані Desky <b>усміхнені очі-галочки</b>. Якщо вони перевернуті, екран стоїть догори дриґом. Як вони виглядають?',
1531
- stage: [bigFace('happy'), h('<div class="cap">так має бути</div>')], body: [h('<div class="choices"></div>'), note],
1532
- scene: { shot: 'face', run: c => { c.pose(HOME); c.face('HAPPY'); } }, cap: 'так має бути',
1533
- foot: [back('wires'), spacer(), btn('Пропустити крок', 'ghost', () => { send('face eyes'); go('j0'); })],
1534
- });
1535
- $('wizBody').querySelector('.choices').append(ca, cb);
1536
- send('face happy');
1537
- async function answer(ok) {
1538
- if (ok) { await send('face eyes'); go('j0'); return; }
1539
- if (W.retried) { note.hidden = false; note.className = 'note bad'; note.textContent = 'Екран і досі перевернутий? Перевір, чи на ньому взагалі щось видно, і спробуй ще раз.'; return; }
1540
- W.retried = true;
1541
- await busy(ca, async () => { await send('flip'); await send('face happy'); note.hidden = false; note.className = 'note'; note.textContent = 'Перевернув екран і зберіг. А тепер?'; });
1542
- }
1543
- }
1544
-
1545
- // ---- 6. a joint's direction (calibrate.py, direction)
1546
- function stDir(j) {
1547
- const jj = J[j], A = HOME, B = poseWith(j, jj.base + jj.plus);
1548
- const [f1, s1] = fig('0 0 160 120', 'в обличчя');
1549
- const [f2, s2] = j === 0 ? fig('0 0 160 170', 'згори') : fig('0 0 240 170', 'збоку');
1550
- W.stop = animate([P => drawFront(s1, P, j), P => j === 0 ? drawTop(s2, P[0]) : drawSide(s2, P, j)], A, B);
1551
- const note = h('<div class="note" hidden></div>');
1552
- const replay = btn('Показати ще раз', 'ghost', () => busy(replay, show));
1553
- const yes = btn('Так, саме так', 'choice yes', () => answer(true)), no = btn('Ні, в інший бік', 'choice', () => answer(false));
1554
- frame({
1555
- kick: `Калібрування · ${jj.short} · напрямок`, title: `${jj.name}: куди рухається?`,
1556
- lead: `Desky зробить невеликий рух, як на малюнку. ${jj.plusText}`,
1557
- stage: views(f1, f2), body: [h('<div class="choices"></div>'), note, replay],
1558
- scene: { shot: SHOT3[j], glow: j, run: c => c.loop(A, B) }, cap: 'має бути так',
1559
- foot: [back(j === 0 ? 'screen' : 'j' + (j - 1)), spacer(), btn('Пропустити суглоб', 'ghost', () => go(j < 3 ? 'j' + (j + 1) : 'done'))],
1560
- });
1561
- $('wizBody').querySelector('.choices').append(yes, no);
1562
- async function show() { await servosOn(); await demoMove('j' + jj.n + ' ' + (jj.base + jj.plus)); }
1563
- async function answer(ok) {
1564
- if (ok) { await send('home'); go('j' + j, 'centre'); return; }
1565
- if (W.retried) { note.hidden = false; note.className = 'note bad';
1566
- note.textContent = `${jj.name} і після розвороту рухається не туди. Можливо, рухається не той суглоб: перевір роз'єми серво.`; return; }
1567
- W.retried = true;
1568
- await busy(yes, async () => { await send('inv j' + jj.n); calDirty(true); note.hidden = false; note.className = 'note'; note.textContent = 'Розвернув напрямок. Дивись ще раз!'; await show(); });
1569
- }
1570
- busy(replay, show);
1571
- }
1572
-
1573
- // ---- 7. a joint's centre, live on a dial
1574
- function stCentre(j) {
1575
- const jj = J[j];
1576
- const [f1, s1] = fig('0 0 160 120', 'в обличчя: має бути так');
1577
- const [f2, s2] = j === 0 ? fig('0 0 160 170', 'згори') : fig('0 0 240 170', 'збоку');
1578
- const ref = refPic(j);
1579
- drawFront(s1, ref, j); j === 0 ? drawTop(s2, 0) : drawSide(s2, ref, j);
1580
- W.orig = CAL[j].trim;
1581
- const dial = makeDial(j);
1582
- const done = btn('Рівно, далі', 'pri lg', async () => {
1583
- await busy(done, async () => { await send('save'); calDirty(false); W.orig = null; await send('home'); });
1584
- go(j < 3 ? 'j' + (j + 1) : 'done');
1585
- });
1586
- frame({
1587
- kick: `Калібрування · ${jj.short} · центр`, title: 'Виставимо нуль',
1588
- lead: `Desky став у нульове положення. Тягни повзунок, поки ${jj.refText}. Desky рухається разом із повзунком.`,
1589
- stage: views(f1, f2), body: [dial],
1590
- scene: { shot: j === 0 ? 'front' : SHOT3[j], glow: j, run: c => c.pose(ref) }, cap: 'нуль: має бути так',
1591
- foot: [back('j' + j), spacer(), done],
1592
- });
1593
- W.onCal = k => { if (k === j) dial.sync(); };
1594
- (async () => { await servosOn(); await toRef(j); await send('cal', true); })();
1595
- setTimeout(() => dial.querySelector('input').focus(), 80);
1596
- }
1597
-
1598
- // ---- 8. done
1599
- function stDone() {
1600
- const face = bigFace('happy');
1601
- const conf = document.createElement('div'); conf.className = 'confetti';
1602
- const colors = [PALETTE[COLOR].body, css('--clawd'), '#F2B48F', '#3C8A55', '#9FC6F0', '#E6C15A'];
1603
- for (let i = 0; i < 46; i++) { const c = document.createElement('i'); c.style.left = Math.random() * 100 + '%'; c.style.background = colors[i % colors.length];
1604
- c.style.animationDelay = Math.random() * .8 + 's'; c.style.transform = `rotate(${Math.random() * 180}deg)`; conf.appendChild(c); }
1605
- const s = frame({
1606
- kick: 'Готово', title: 'Desky готовий до роботи!',
1607
- lead: 'Усе збережено в платі. Тепер просто працюй у <b>Claude Code</b> або <b>Codex</b>, а Desky показуватиме, що відбувається: працює, читає, чекає на тебе.<br><br>Майстер завжди можна відкрити знову в боковій панелі.',
1608
- stage: [face], scene: { shot: 'hero', run: c => c.state('done', true) }, cap: 'Desky радіє',
1609
- foot: [spacer(), btn('Відкрити пульт', 'pri lg', () => wizClose(true))],
1610
- });
1611
- s.querySelector('.stage').style.position = 'relative'; s.querySelector('.stage').appendChild(conf);
1612
- if (connected) (async () => { if (dirty) await send('save'); calDirty(false); await send('home'); await send('happy'); await send('sound done', true); })();
1613
- }
1614
-
1615
- let tab = 'home';
1616
- try { tab = localStorage.getItem('clawd.tab') || 'home'; } catch (e) {}
1617
- if (location.hash) tab = location.hash.slice(1);
1618
- showTab(document.querySelector('[data-page="' + tab + '"]') ? tab : 'home');
1619
- ['logo', 'bigface'].forEach(id => drawFace($(id), 'idle'));
1620
- buildJoints(); calDirty(false); showMode(); refresh(); pollStatus(); pollLines();
1621
- window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { applyColor(COLOR); refresh(); buildJoints(); });
1622
- })();
1623
- </script>
1624
- </body>
1625
- </html>
1
+ <!doctype html>
2
+ <html lang="uk">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Desky Agent</title>
7
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect x='2' y='3' width='12' height='9' fill='%23D9774B'/%3E%3Crect x='5' y='5' width='2' height='3' fill='%23222'/%3E%3Crect x='9' y='5' width='2' height='3' fill='%23222'/%3E%3Crect x='0' y='6' width='2' height='3' fill='%23D9774B'/%3E%3Crect x='14' y='6' width='2' height='3' fill='%23D9774B'/%3E%3Crect x='3' y='12' width='2' height='3' fill='%23D9774B'/%3E%3Crect x='11' y='12' width='2' height='3' fill='%23D9774B'/%3E%3C/svg%3E">
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Unbounded:wght@500;600&family=Onest:wght@400;500;600&family=JetBrains+Mono:wght@400;500;800&display=swap">
11
+ <script type="importmap">{ "imports": { "three": "/vendor/three.module.min.js" } }</script>
12
+ <script type="module" src="/clawd3d.js"></script>
13
+ <style>
14
+ /* Desky's control app, served by the agent daemon. Left: Desky's face and state, the pages, the link and Stop.
15
+ Right: the page: overview, moves, calibration, settings, monitor. Over everything: the setup wizard. */
16
+ :root {
17
+ --bg: #F4F2EE; --side: #EDEAE5; --card: #FFFFFF; --sunk: #F6F4F1; --ink: #1F1D1A; --muted: #736E68; --faint: #A7A19A;
18
+ --line: #E6E2DC; --line2: #D6D1CA;
19
+ --clawd: #D9774B; --clawd-hi: #C4643A; --clawd-ink: #FFFFFF; --clawd-soft: #FBEDE5; --clawd-glow: rgba(217, 119, 75, .22);
20
+ --ok: #3C8A55; --ok-soft: #E6F3EA; --bad: #C2462A; --bad-soft: #FBE9E4; --desk: #2A2826;
21
+ --term: #1E1C1A; --termfg: #E6E1DA; --termdim: #8E877F;
22
+ --shadow: 0 1px 2px rgba(40, 30, 20, .05), 0 2px 10px rgba(40, 30, 20, .045);
23
+ --shadow-lg: 0 24px 80px rgba(40, 25, 10, .22), 0 4px 16px rgba(40, 25, 10, .08);
24
+ --r: 14px; --rc: 9px; --h: 36px;
25
+ --f-display: "Unbounded", "Segoe UI", system-ui, sans-serif;
26
+ --f-body: "Onest", "Segoe UI", system-ui, sans-serif;
27
+ --f-mono: "JetBrains Mono", Consolas, monospace;
28
+ }
29
+ @media (prefers-color-scheme: dark) { :root {
30
+ --bg: #151413; --side: #1A1918; --card: #211F1D; --sunk: #1A1917; --ink: #EDEAE5; --muted: #A29C94; --faint: #6F6A64;
31
+ --line: #2D2A27; --line2: #3B3733;
32
+ --clawd: #E3825A; --clawd-hi: #EC9167; --clawd-ink: #1A0F0A; --clawd-soft: #33231B; --clawd-glow: rgba(227, 130, 90, .2);
33
+ --ok: #6BBF86; --ok-soft: #1C2E22; --bad: #E56A4C; --bad-soft: #3A1F18; --desk: #4A4744;
34
+ --term: #100F0E; --shadow: none; --shadow-lg: 0 24px 80px rgba(0, 0, 0, .55); color-scheme: dark } }
35
+ * { box-sizing: border-box; }
36
+ [hidden] { display: none !important; }
37
+ html, body { height: 100%; }
38
+ body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.5 var(--f-body); -webkit-font-smoothing: antialiased; }
39
+ h1, h2, h3, p { margin: 0; }
40
+ .mono { font-family: var(--f-mono); }
41
+
42
+ /* ---------------------------------------------------------------- shell */
43
+ .app { display: grid; grid-template-columns: 260px minmax(0, 1fr); min-height: 100%; }
44
+ aside { background: var(--side); border-right: 1px solid var(--line); padding: 20px 16px; display: flex; flex-direction: column; gap: 18px;
45
+ position: sticky; top: 0; height: 100vh; overflow-y: auto; }
46
+ .brand { display: flex; align-items: center; gap: 10px; padding: 0 8px; font: 600 17px var(--f-display); letter-spacing: -.01em; }
47
+ .brand { gap: 8px; }
48
+ .brand svg.head { width: 34px; height: auto; margin-right: 2px; }
49
+ .brand svg.chev { width: 10px; height: 16px; }
50
+ .brand svg.chev path { fill: none; stroke: var(--clawd); stroke-width: 3; stroke-linecap: square; }
51
+ .brand .wm { font: 800 19px/1 var(--f-mono, 'JetBrains Mono', monospace); letter-spacing: -.01em; margin-left: -3px; }
52
+ .brand .cur { width: 9px; height: 17px; background: var(--clawd); margin-left: -4px; animation: blink 1.1s steps(1) infinite; }
53
+ @keyframes blink { 50% { opacity: 0; } }
54
+ @media (prefers-reduced-motion: reduce) { .brand .cur { animation: none; } }
55
+ .who { background: var(--card); border: 1px solid var(--line); border-radius: var(--r); padding: 18px 16px 16px; display: grid; justify-items: center;
56
+ gap: 4px; text-align: center; box-shadow: var(--shadow); }
57
+ .who svg { width: 136px; height: 102px; margin-bottom: 10px; border-radius: 12px; box-shadow: 0 8px 24px var(--clawd-glow); }
58
+ .who .k { font-size: 11px; letter-spacing: .08em; text-transform: uppercase; color: var(--faint); }
59
+ .who .s { font: 600 18px var(--f-display); letter-spacing: -.01em; }
60
+ .who .w { font-size: 12.5px; color: var(--muted); line-height: 1.4; }
61
+ nav { display: grid; gap: 2px; }
62
+ nav button, .wizlink { all: unset; display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: var(--rc); cursor: pointer;
63
+ color: var(--muted); font-weight: 500; }
64
+ nav button svg, .wizlink svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; flex: none; }
65
+ nav button:hover, .wizlink:hover { color: var(--ink); background: rgba(127, 110, 90, .08); }
66
+ nav button[aria-selected="true"] { color: var(--ink); background: var(--card); box-shadow: var(--shadow); }
67
+ nav button[aria-selected="true"] svg { color: var(--clawd); }
68
+ nav button:focus-visible, .wizlink:focus-visible { outline: 2px solid var(--clawd); outline-offset: 1px; }
69
+ .wizlink { color: var(--clawd-hi); border: 1px dashed color-mix(in srgb, var(--clawd) 45%, transparent); justify-content: center; }
70
+ .wizlink:hover { color: var(--clawd-hi); background: var(--clawd-soft); }
71
+ .links { margin-top: auto; display: grid; gap: 0; border-top: 1px solid var(--line); padding-top: 12px; }
72
+ .lk { display: flex; align-items: center; gap: 8px; padding: 5px 8px; font-size: 13px; color: var(--muted); }
73
+ .lk span:last-child { margin-left: auto; color: var(--ink); font-weight: 500; text-align: right; }
74
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); flex: none; }
75
+ .dot.on { background: var(--ok); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ok) 18%, transparent); }
76
+ .dot.bad { background: var(--bad); }
77
+ .dot.warn { background: var(--clawd); }
78
+
79
+ main { padding: 28px 32px 48px; display: grid; gap: 20px; align-content: start; max-width: 1100px; width: 100%; }
80
+ .page { display: grid; gap: 20px; align-content: start; animation: fadein .25s ease; }
81
+ @keyframes fadein { from { opacity: 0; transform: translateY(4px); } }
82
+ .title { display: flex; align-items: end; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
83
+ .title h1 { font: 600 23px var(--f-display); letter-spacing: -.015em; }
84
+ .title p { color: var(--muted); margin-top: 4px; }
85
+
86
+ /* ---------------------------------------------------------------- cards and controls */
87
+ .cols { display: grid; gap: 20px; grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: stretch; }
88
+ .cols.wide { grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); }
89
+ .card { background: var(--card); border: 1px solid var(--line); border-radius: var(--r); box-shadow: var(--shadow); padding: 20px; display: flex;
90
+ flex-direction: column; gap: 16px; min-width: 0; }
91
+ .card > .hd { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 30px; }
92
+ .card h2 { font-size: 15px; font-weight: 600; }
93
+ .card .sub { color: var(--muted); font-size: 13px; margin-top: -10px; }
94
+ .muted { color: var(--muted); }
95
+ .small { font-size: 12.5px; }
96
+
97
+ button { font: 500 13.5px var(--f-body); color: var(--ink); background: var(--card); border: 1px solid var(--line2); border-radius: var(--rc);
98
+ height: var(--h); padding: 0 14px; cursor: pointer; white-space: nowrap; transition: background .12s, border-color .12s, color .12s, box-shadow .12s; }
99
+ button:hover:not(:disabled) { background: var(--sunk); border-color: var(--faint); }
100
+ button:active:not(:disabled) { transform: translateY(1px); }
101
+ button:disabled { opacity: .4; cursor: default; }
102
+ button:focus-visible, input:focus-visible { outline: 2px solid var(--clawd); outline-offset: 2px; }
103
+ button.pri { background: var(--clawd); border-color: var(--clawd); color: var(--clawd-ink); }
104
+ button.pri:hover:not(:disabled) { background: var(--clawd-hi); border-color: var(--clawd-hi); box-shadow: 0 4px 14px var(--clawd-glow); }
105
+ button.ghost { background: none; border-color: transparent; color: var(--muted); }
106
+ button.ghost:hover:not(:disabled) { color: var(--ink); background: var(--sunk); border-color: transparent; }
107
+ button.sm { height: 30px; padding: 0 10px; font-size: 13px; }
108
+ button.lg { height: 44px; padding: 0 22px; font-size: 14.5px; font-weight: 600; border-radius: 11px; }
109
+ button[aria-pressed="true"] { background: var(--clawd-soft); border-color: var(--clawd); }
110
+ button.stop { width: 100%; height: 40px; background: var(--bad); border-color: var(--bad); color: #fff; font-weight: 600; }
111
+ button.stop:hover:not(:disabled) { background: var(--bad); border-color: var(--bad); filter: brightness(1.08); }
112
+
113
+ .btns { display: grid; gap: 8px; grid-template-columns: repeat(3, minmax(0, 1fr)); }
114
+ .btns button { width: 100%; padding: 0 6px; }
115
+ .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
116
+ .row.end { justify-content: flex-end; }
117
+
118
+ input.num, input.text, .raw input { font: 13.5px var(--f-mono); height: var(--h); padding: 0 10px; border: 1px solid var(--line2); border-radius: var(--rc);
119
+ background: var(--card); color: var(--ink); min-width: 0; }
120
+ input.num { width: 76px; text-align: right; }
121
+ input.num.s { width: 60px; height: 30px; }
122
+ input.text { width: 100%; }
123
+ input[type=checkbox] { accent-color: var(--clawd); width: 15px; height: 15px; margin: 0; }
124
+ .check { display: inline-flex; align-items: center; gap: 8px; color: var(--muted); cursor: pointer; font-size: 13px; user-select: none; }
125
+
126
+ /* range: one look in Edge and Firefox */
127
+ input[type=range] { -webkit-appearance: none; appearance: none; width: 100%; height: 22px; background: none; margin: 0; cursor: pointer; }
128
+ input[type=range]::-webkit-slider-runnable-track { height: 6px; border-radius: 3px;
129
+ background: linear-gradient(var(--clawd), var(--clawd)) 0 / var(--p, 50%) 100% no-repeat, var(--line); }
130
+ input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 18px; height: 18px; margin-top: -6px; border-radius: 50%;
131
+ background: var(--card); border: 2px solid var(--clawd); box-shadow: 0 1px 3px rgba(0, 0, 0, .2); }
132
+ input[type=range]::-moz-range-track { height: 6px; border-radius: 3px; background: var(--line); }
133
+ input[type=range]::-moz-range-progress { height: 6px; border-radius: 3px; background: var(--clawd); }
134
+ input[type=range]::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%; background: var(--card); border: 2px solid var(--clawd); }
135
+ input[type=range]:disabled { opacity: .5; }
136
+
137
+ /* the centre dial: a range that fills from the middle, with a tick at zero */
138
+ .dial { display: grid; gap: 8px; }
139
+ .dial .track { position: relative; }
140
+ .dial .track::before { content: ""; position: absolute; left: 50%; top: -3px; bottom: -3px; width: 2px; margin-left: -1px; border-radius: 1px; background: var(--line2); pointer-events: none; }
141
+ .dial input[type=range] { height: 30px; position: relative; }
142
+ .dial input[type=range]::-webkit-slider-runnable-track { height: 8px; border-radius: 4px;
143
+ background: linear-gradient(90deg, transparent var(--a, 50%), var(--clawd) var(--a, 50%), var(--clawd) var(--b, 50%), transparent var(--b, 50%)), var(--line); }
144
+ .dial input[type=range]::-webkit-slider-thumb { width: 24px; height: 24px; margin-top: -8px; border-width: 3px; }
145
+ .dial input[type=range]::-moz-range-progress { background: transparent; }
146
+ .dial input[type=range]::-moz-range-thumb { width: 18px; height: 18px; border-width: 3px; }
147
+ .dial .ends { display: flex; justify-content: space-between; font-size: 12px; color: var(--muted); }
148
+ .dial .ends b { color: var(--ink); font: 600 15px var(--f-mono); font-variant-numeric: tabular-nums; }
149
+ .dial .fine { display: flex; gap: 6px; align-items: center; justify-content: center; }
150
+ .dial .fine button { min-width: 44px; font-family: var(--f-mono); }
151
+ .dial .fine button[data-z] { font-family: var(--f-body); }
152
+ .dial.warn input[type=range]::-webkit-slider-thumb { border-color: var(--bad); }
153
+ .hint { font-size: 12.5px; color: var(--muted); line-height: 1.45; }
154
+ .hint.warn { color: var(--bad); }
155
+
156
+ /* banners */
157
+ .banner { display: flex; align-items: center; gap: 16px; padding: 12px 14px 12px 16px; border-radius: var(--r); background: var(--clawd-soft);
158
+ border: 1px solid color-mix(in srgb, var(--clawd) 35%, transparent); }
159
+ .banner p { flex: 1; }
160
+ .banner b { font-weight: 600; }
161
+ .banner.bad { background: var(--bad-soft); border-color: color-mix(in srgb, var(--bad) 35%, transparent); }
162
+ .banner.ok { background: var(--card); border-color: var(--line); }
163
+ .banner .acts { display: flex; gap: 8px; }
164
+ .lk.btn { all: unset; display: flex; align-items: center; gap: 8px; padding: 5px 8px; font-size: 13px; color: var(--muted); border-radius: 6px; }
165
+ .lk.btn:not(:disabled) { cursor: pointer; }
166
+ .lk.btn:not(:disabled):hover { background: rgba(127, 110, 90, .08); }
167
+ .lk.btn:focus-visible { outline: 2px solid var(--clawd); outline-offset: 1px; }
168
+
169
+ /* toast */
170
+ .toast { position: fixed; left: 50%; bottom: 24px; transform: translate(-50%, 20px); opacity: 0; pointer-events: none; z-index: 60;
171
+ background: var(--ink); color: var(--bg); padding: 10px 16px; border-radius: 999px; font-weight: 500; font-size: 13.5px;
172
+ box-shadow: var(--shadow-lg); transition: opacity .2s, transform .2s; max-width: calc(100% - 32px); }
173
+ .toast.on { opacity: 1; transform: translate(-50%, 0); }
174
+ .toast.bad { background: var(--bad); color: #fff; }
175
+
176
+ /* ---------------------------------------------------------------- the 3D stage (ui/clawd3d.js) */
177
+ .scene3d { position: relative; min-height: 240px; border-radius: var(--r); overflow: hidden; display: grid; place-items: center;
178
+ background: radial-gradient(70% 60% at 50% 62%, color-mix(in srgb, var(--clawd) 16%, transparent), transparent 70%),
179
+ radial-gradient(circle at 1px 1px, color-mix(in srgb, var(--ink) 9%, transparent) 1px, transparent 1.4px) 0 0 / 18px 18px,
180
+ linear-gradient(180deg, var(--sunk), var(--card)); }
181
+ .scene3d canvas.c3d { position: absolute; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none;
182
+ animation: c3in .6s ease both; }
183
+ .scene3d canvas.c3d:active { cursor: grabbing; }
184
+ @keyframes c3in { from { opacity: 0; transform: scale(.97); } }
185
+ .scene3d .tip3d { position: absolute; right: 12px; bottom: 10px; font-size: 11.5px; color: var(--faint); pointer-events: none;
186
+ display: none; align-items: center; gap: 6px; opacity: 0; transition: opacity .2s; }
187
+ .scene3d:hover .tip3d { opacity: 1; }
188
+ .scene3d .tip3d svg { width: 14px; height: 14px; stroke: currentColor; fill: none; stroke-width: 1.8; stroke-linecap: round; }
189
+ body.has3d .scene3d .tip3d { display: flex; }
190
+ body.has3d .scene3d > .flat { display: none; }
191
+ body:not(.has3d) #moveScene { display: none; }
192
+ body.has3d .sketches { display: none; }
193
+ #moveScene { height: 300px; }
194
+
195
+ /* ---------------------------------------------------------------- overview */
196
+ .herocard { padding: 0; display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); overflow: hidden; gap: 0; }
197
+ .herocard .scene3d { min-height: 340px; border-radius: 0; }
198
+ .herocard .scene3d > .flat { width: 200px; height: 150px; border-radius: 18px; box-shadow: 0 16px 40px var(--clawd-glow); }
199
+ .herocard .info { padding: 28px 28px 24px; display: flex; flex-direction: column; gap: 6px; border-left: 1px solid var(--line); }
200
+ .herocard .k { font-size: 11px; letter-spacing: .08em; text-transform: uppercase; color: var(--faint); }
201
+ .herocard .s { font: 600 30px/1.15 var(--f-display); letter-spacing: -.025em; }
202
+ .herocard .w { color: var(--muted); font-size: 14.5px; }
203
+ .herocard .quiet { align-self: flex-start; margin-top: 8px; font-size: 12.5px; color: var(--muted); display: inline-flex; gap: 6px; align-items: center; }
204
+ .herocard .quiet svg { width: 14px; height: 14px; stroke: currentColor; fill: none; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
205
+ .herocard .ses { margin-top: auto; padding-top: 22px; display: grid; gap: 8px; }
206
+ .herocard .ses .hd { font-size: 12px; color: var(--faint); display: flex; justify-content: space-between; }
207
+ .herocard .ses .list { border-radius: 10px; }
208
+ .herocard .ses .li { height: 38px; padding: 0 10px 0 12px; }
209
+ .herocard .ses .empty { padding: 16px 12px; border-radius: 10px; font-size: 13px; }
210
+ .list { display: grid; border: 1px solid var(--line); border-radius: var(--rc); overflow: hidden; }
211
+ .li { display: flex; align-items: center; gap: 12px; padding: 0 14px; height: 44px; border-top: 1px solid var(--line); }
212
+ .li:first-child { border-top: 0; }
213
+ .li .mono { color: var(--muted); font-size: 12.5px; }
214
+ .badge { margin-left: auto; font-size: 12.5px; font-weight: 500; padding: 2px 10px; border-radius: 999px; background: var(--sunk); border: 1px solid var(--line); }
215
+ .badge.ask { background: var(--clawd-soft); border-color: transparent; color: var(--clawd-hi); }
216
+ .empty { display: grid; place-items: center; text-align: center; gap: 4px; padding: 24px 16px; border: 1px dashed var(--line2); border-radius: var(--rc); color: var(--muted); }
217
+ .empty b { color: var(--ink); font-weight: 500; }
218
+ .facts { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0; border: 1px solid var(--line); border-radius: var(--rc); }
219
+ .fact { padding: 12px 14px; border-left: 1px solid var(--line); }
220
+ .fact:first-child { border-left: 0; }
221
+ .fact .k { font-size: 12px; color: var(--muted); }
222
+ .fact .v { font-weight: 600; margin-top: 2px; }
223
+
224
+ /* ---------------------------------------------------------------- moves */
225
+ .fader { display: grid; grid-template-columns: 128px minmax(0, 1fr) 52px; gap: 16px; align-items: center; }
226
+ .fader label { font-weight: 500; line-height: 1.3; }
227
+ .fader label small { display: block; font-weight: 400; color: var(--muted); font-size: 12px; }
228
+ .fader output { font: 500 13.5px var(--f-mono); text-align: right; font-variant-numeric: tabular-nums; }
229
+ .sketches { display: grid; grid-template-columns: 3fr 2fr; gap: 12px; }
230
+ .sketches figure, .fig { margin: 0; background: var(--sunk); border: 1px solid var(--line); border-radius: var(--rc); padding: 8px 8px 6px; }
231
+ .sketches svg, .fig svg { width: 100%; height: auto; display: block; }
232
+ .sketches figcaption, .fig figcaption { font-size: 12px; color: var(--muted); text-align: center; }
233
+ .sep { height: 1px; background: var(--line); margin: 0 -20px; }
234
+ .opt { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
235
+ .opt small { display: block; color: var(--muted); font-size: 12.5px; }
236
+
237
+ /* ---------------------------------------------------------------- calibration */
238
+ .calhero { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 20px; align-items: center;
239
+ background: linear-gradient(120deg, var(--clawd-soft), var(--card) 70%); }
240
+ .calhero h2 { font: 600 17px var(--f-display); letter-spacing: -.01em; }
241
+ .calhero p { color: var(--muted); margin-top: 4px; max-width: 560px; }
242
+ .joints { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; }
243
+ .joint .hd small { display: block; color: var(--muted); font: 12px var(--f-mono); }
244
+ .joint .pic { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
245
+ .joint .fig svg { height: 112px; }
246
+ .joint .dir { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding-top: 12px; border-top: 1px solid var(--line); }
247
+ .joint .dir span { margin-right: auto; font-size: 13px; color: var(--muted); }
248
+ .joint .dir span b { color: var(--ink); font-weight: 500; }
249
+ .tog { display: grid; gap: 0; }
250
+ .tog .field { padding: 12px 0; }
251
+ .savebar { position: sticky; bottom: 16px; display: flex; align-items: center; gap: 8px; padding: 10px 10px 10px 20px; background: var(--card);
252
+ border: 1px solid var(--line); border-radius: var(--r); box-shadow: 0 6px 24px rgba(40, 30, 20, .08); }
253
+ .savebar p { margin-right: auto; color: var(--muted); font-size: 13px; }
254
+ .savebar p.ok { color: var(--ok); }
255
+ .savebar p.bad { color: var(--bad); }
256
+ .savebar.dirty { border-color: var(--clawd); box-shadow: 0 6px 24px var(--clawd-glow); }
257
+ .savebar.dirty p { color: var(--clawd-hi); font-weight: 500; }
258
+
259
+ /* ---------------------------------------------------------------- Desky's colour */
260
+ .swatches { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 10px; }
261
+ .swatch { height: auto; padding: 12px 6px 10px; display: grid; justify-items: center; gap: 8px; border-radius: 14px; white-space: normal;
262
+ line-height: 1.2; font-size: 13px; }
263
+ .swatch .chip { width: 52px; height: 39px; border-radius: 8px; background: var(--c); position: relative;
264
+ box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .1), 0 6px 16px color-mix(in srgb, var(--c) 35%, transparent);
265
+ transition: transform .2s cubic-bezier(.2, .8, .2, 1); }
266
+ .swatch .chip::before, .swatch .chip::after { content: ""; position: absolute; top: 12px; width: 7px; height: 14px; background: var(--e); }
267
+ .swatch .chip::before { left: 11px; }
268
+ .swatch .chip::after { right: 11px; }
269
+ .swatch:hover:not(:disabled) .chip { transform: translateY(-2px) rotate(-3deg); }
270
+ .swatch[aria-checked="true"] { border-color: var(--clawd); background: var(--clawd-soft); box-shadow: 0 0 0 3px var(--clawd-glow); }
271
+ .swatch[aria-checked="true"] .chip { transform: scale(1.06); }
272
+ .swatch small { display: block; color: var(--muted); font-size: 11.5px; }
273
+ .colorcard .hint { margin-top: -6px; }
274
+ .wiz .swatches { grid-template-columns: repeat(3, minmax(0, 1fr)); }
275
+
276
+ /* ---------------------------------------------------------------- settings */
277
+ .set { display: grid; }
278
+ .field { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 14px 0; border-top: 1px solid var(--line); }
279
+ .field:first-child { border-top: 0; padding-top: 0; }
280
+ .field:last-child { padding-bottom: 0; }
281
+ .field label { font-weight: 500; }
282
+ .field label small { display: block; color: var(--muted); font-size: 12.5px; font-weight: 400; }
283
+ .field .in { display: flex; align-items: center; gap: 8px; }
284
+ .field .unit { font-size: 12.5px; color: var(--muted); width: 84px; }
285
+ .field.col { grid-template-columns: 1fr; gap: 8px; }
286
+
287
+ /* ---------------------------------------------------------------- monitor */
288
+ .term { background: var(--term); border-radius: var(--r); overflow: hidden; display: grid; grid-template-rows: auto 1fr auto; height: calc(100vh - 190px); min-height: 360px; }
289
+ .term .bar { display: flex; align-items: center; gap: 16px; padding: 10px 14px; border-bottom: 1px solid rgba(255, 255, 255, .07); color: var(--termdim); font-size: 12.5px; }
290
+ .term .bar .check { color: var(--termdim); }
291
+ .term .bar button { margin-left: auto; color: var(--termdim); }
292
+ .term .bar button:hover:not(:disabled) { background: rgba(255, 255, 255, .06); color: var(--termfg); }
293
+ .legend { display: flex; gap: 14px; }
294
+ .legend i { display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 6px; }
295
+ .log { padding: 12px 14px; font: 12.5px/1.6 var(--f-mono); color: var(--termfg); overflow: auto; white-space: pre-wrap; }
296
+ .log .me { color: #F2B48F; }
297
+ .log .agent { color: #9FC6F0; }
298
+ .log .info, .log .dim { color: var(--termdim); }
299
+ .raw { display: flex; gap: 8px; padding: 10px; border-top: 1px solid rgba(255, 255, 255, .07); }
300
+ .raw input { flex: 1; background: rgba(255, 255, 255, .05); border-color: rgba(255, 255, 255, .1); color: var(--termfg); }
301
+ .raw input::placeholder { color: var(--termdim); }
302
+ .raw button { background: rgba(255, 255, 255, .08); border-color: transparent; color: var(--termfg); }
303
+ .raw button:hover:not(:disabled) { background: rgba(255, 255, 255, .14); border-color: transparent; }
304
+
305
+ /* ---------------------------------------------------------------- the face: blinks while alive */
306
+ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: blink 5.2s infinite; }
307
+ @keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 95.5% { transform: scaleY(.1); } }
308
+ @media (prefers-reduced-motion: reduce) { svg.alive .eye { animation: none; } .page, .wiz .step { animation: none !important; } }
309
+
310
+ /* ---------------------------------------------------------------- a new version: dialog over the window */
311
+ .upd { position: fixed; inset: 0; z-index: 60; display: grid; place-items: center; padding: 24px;
312
+ background: color-mix(in srgb, var(--bg) 80%, transparent); backdrop-filter: blur(3px); }
313
+ .upd .card { width: min(440px, 100%); padding: 28px 28px 22px; border-radius: 22px; box-shadow: var(--shadow-lg);
314
+ display: grid; gap: 14px; justify-items: center; text-align: center; animation: stepin .3s cubic-bezier(.2, .8, .2, 1); }
315
+ .upd svg.big { width: 112px; height: 84px; }
316
+ .upd h2 { font-size: 21px; margin: 0; }
317
+ .upd p { margin: 0; color: var(--muted); line-height: 1.5; }
318
+ .upd .ver { font-family: var(--f-mono, ui-monospace, monospace); font-size: 13px; padding: 4px 10px; border-radius: 99px;
319
+ background: var(--clawd-soft); color: var(--clawd-hi); }
320
+ .upd .cmd { display: flex; gap: 8px; align-items: center; width: 100%; padding: 8px 8px 8px 12px; border-radius: 10px;
321
+ background: var(--sunk); font-family: var(--f-mono, ui-monospace, monospace); font-size: 13px; text-align: left; }
322
+ .upd .cmd span { flex: 1; }
323
+ .upd .acts { display: flex; gap: 10px; justify-content: center; width: 100%; margin-top: 4px; }
324
+ .upd .acts .pri { flex: 1; }
325
+ .lk.btn.new { background: var(--clawd); color: var(--clawd-ink); font-weight: 600; }
326
+ .lk.btn.new span:last-child { color: inherit; }
327
+ .lk.btn.new .dot { background: var(--clawd-ink); }
328
+
329
+ /* ---------------------------------------------------------------- setup wizard */
330
+ .wiz { position: fixed; inset: 0; z-index: 50; display: grid; place-items: center; padding: 24px;
331
+ background: color-mix(in srgb, var(--bg) 88%, transparent); }
332
+ .wiz .panel { width: min(960px, 100%); max-height: calc(100vh - 48px); background: var(--card); border: 1px solid var(--line); border-radius: 22px;
333
+ box-shadow: var(--shadow-lg); display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden; }
334
+ .wiz .top { display: flex; align-items: center; gap: 16px; padding: 16px 18px 14px 24px; border-bottom: 1px solid var(--line); }
335
+ .wiz .top .brand { padding: 0; font-size: 15px; }
336
+ .prog { flex: 1; display: grid; gap: 6px; }
337
+ .prog .bars { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 4px; }
338
+ .prog .bars i { height: 4px; border-radius: 2px; background: var(--line); transition: background .3s; }
339
+ .prog .bars i.done { background: var(--clawd); }
340
+ .prog .bars i.now { background: linear-gradient(90deg, var(--clawd) 50%, var(--line) 50%); }
341
+ .prog .lbl { font-size: 12px; color: var(--muted); }
342
+ .prog .lbl b { color: var(--ink); font-weight: 500; }
343
+ .wiz .x { width: 34px; height: 34px; padding: 0; display: grid; place-items: center; border-radius: 50%; }
344
+ .wiz .x svg { width: 16px; height: 16px; stroke: currentColor; stroke-width: 2; fill: none; stroke-linecap: round; }
345
+ .wiz .body { overflow-y: auto; overflow-x: hidden; }
346
+ .wiz .step { display: grid; grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); min-height: 460px; animation: stepin .35s cubic-bezier(.2, .8, .2, 1); }
347
+ @keyframes stepin { from { opacity: 0; transform: translateX(14px); } }
348
+ .wiz .stage { background: radial-gradient(120% 90% at 50% 40%, var(--clawd-soft), var(--sunk) 70%); border-right: 1px solid var(--line);
349
+ display: grid; place-items: center; padding: 28px; gap: 12px; align-content: center; }
350
+ .wiz .stage .views { display: grid; gap: 12px; width: 100%; max-width: 380px; }
351
+ .wiz .stage .views.two { grid-template-columns: 1fr 1fr; max-width: 440px; }
352
+ .wiz .stage .views:not(.two) { max-width: 280px; }
353
+ .wiz .stage .fig { background: var(--card); }
354
+ .wiz .stage .big { width: min(300px, 80%); height: auto; border-radius: 22px; box-shadow: 0 20px 50px var(--clawd-glow); }
355
+ .wiz .stage .cap { font-size: 12.5px; color: var(--muted); text-align: center; }
356
+ .wiz .stage.s3 { padding: 0; display: block; position: relative; }
357
+ .wiz .stage.s3 .scene3d { position: absolute; inset: 0; border-radius: 0; background: radial-gradient(70% 60% at 50% 60%, color-mix(in srgb, var(--clawd) 20%, transparent), transparent 70%), radial-gradient(circle at 1px 1px, color-mix(in srgb, var(--ink) 9%, transparent) 1px, transparent 1.4px) 0 0 / 18px 18px, var(--sunk); }
358
+ .wiz .stage.s3 .cap3 { position: absolute; left: 16px; top: 14px; z-index: 1; padding: 5px 11px; border-radius: 999px; font-size: 12px; font-weight: 600;
359
+ background: color-mix(in srgb, var(--card) 85%, transparent); border: 1px solid var(--line); color: var(--ink); }
360
+ .wiz .stage.s3 .cap3 i { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--clawd); margin-right: 7px; animation: pulse 1.4s ease-in-out infinite; }
361
+ .wiz .content { padding: 32px 32px 24px; display: flex; flex-direction: column; gap: 16px; min-width: 0; }
362
+ .wiz .kick { font-size: 11.5px; letter-spacing: .08em; text-transform: uppercase; color: var(--clawd-hi); font-weight: 600; }
363
+ .wiz h2 { font: 600 24px/1.2 var(--f-display); letter-spacing: -.02em; }
364
+ .wiz .lead { color: var(--muted); font-size: 14.5px; line-height: 1.55; }
365
+ .wiz .lead b { color: var(--ink); font-weight: 500; }
366
+ .wiz .foot { margin-top: auto; display: flex; gap: 8px; align-items: center; padding-top: 16px; }
367
+ .wiz .foot .sp { margin-right: auto; }
368
+ .checks { display: grid; gap: 8px; }
369
+ .ck { display: flex; align-items: center; gap: 12px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; background: var(--sunk); }
370
+ .ck .ic { width: 26px; height: 26px; border-radius: 50%; display: grid; place-items: center; flex: none; background: var(--line); color: var(--muted); }
371
+ .ck .ic svg { width: 14px; height: 14px; stroke: currentColor; stroke-width: 2.4; fill: none; stroke-linecap: round; stroke-linejoin: round; }
372
+ .ck.ok .ic { background: var(--ok); color: #fff; }
373
+ .ck.wait .ic { background: none; border: 2px solid var(--line2); border-top-color: var(--clawd); animation: spin 1s linear infinite; }
374
+ .ck.bad .ic { background: var(--bad); color: #fff; }
375
+ @keyframes spin { to { transform: rotate(360deg); } }
376
+ .ck div { flex: 1; min-width: 0; }
377
+ .ck b { display: block; font-weight: 500; }
378
+ .ck small { color: var(--muted); font-size: 12.5px; }
379
+ .choices { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
380
+ .choice { height: auto; padding: 14px 12px 12px; display: grid; justify-items: center; gap: 8px; border-radius: 14px; white-space: normal; text-align: center; line-height: 1.3; }
381
+ .choice svg { width: 100%; max-width: 150px; height: auto; border-radius: 8px; background: var(--sunk); }
382
+ .choice:hover:not(:disabled) { border-color: var(--clawd); background: var(--clawd-soft); }
383
+ .choice.yes { border-color: color-mix(in srgb, var(--ok) 50%, var(--line2)); }
384
+ .choice.yes:hover:not(:disabled) { border-color: var(--ok); background: var(--ok-soft); }
385
+ .note { padding: 10px 14px; border-radius: 12px; background: var(--clawd-soft); color: var(--clawd-hi); font-size: 13px; font-weight: 500; }
386
+ .note.bad { background: var(--bad-soft); color: var(--bad); }
387
+ .note.ok { background: var(--ok-soft); color: var(--ok); }
388
+ .watch { display: flex; align-items: center; gap: 10px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; }
389
+ .watch .pulse { width: 10px; height: 10px; border-radius: 50%; background: var(--clawd); animation: pulse 1.2s ease-in-out infinite; flex: none; }
390
+ @keyframes pulse { 50% { box-shadow: 0 0 0 7px var(--clawd-glow); } }
391
+ .confetti { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
392
+ .confetti i { position: absolute; top: -12px; width: 8px; height: 12px; border-radius: 2px; animation: fall 2.4s ease-in forwards; }
393
+ @keyframes fall { to { transform: translateY(560px) rotate(540deg); opacity: 0; } }
394
+
395
+ /* ---------------------------------------------------------------- narrow windows */
396
+ @media (max-width: 1100px) { .cols.wide { grid-template-columns: 1fr; } .joints { grid-template-columns: 1fr; } }
397
+ @media (max-width: 900px) {
398
+ .app { grid-template-columns: 1fr; }
399
+ aside { position: static; height: auto; border-right: 0; border-bottom: 1px solid var(--line); padding: 16px; gap: 14px; }
400
+ .who { grid-template-columns: auto 1fr; justify-items: start; text-align: left; column-gap: 14px; padding: 12px; }
401
+ .who svg { width: 72px; height: 54px; margin: 0; grid-row: 1 / 4; }
402
+ nav { grid-auto-flow: column; justify-content: start; overflow-x: auto; scrollbar-width: none; }
403
+ nav::-webkit-scrollbar { display: none; }
404
+ .links { margin-top: 0; grid-template-columns: 1fr 1fr; column-gap: 16px; }
405
+ main { padding: 20px 16px 40px; }
406
+ .cols { grid-template-columns: 1fr; }
407
+ .wiz { padding: 0; }
408
+ .wiz .panel { max-height: 100vh; height: 100%; border-radius: 0; }
409
+ .wiz .step { grid-template-columns: 1fr; }
410
+ .wiz .stage { border-right: 0; border-bottom: 1px solid var(--line); padding: 20px; }
411
+ .wiz .stage.s3 { height: 300px; }
412
+ .wiz .content { padding: 22px 18px 18px; }
413
+ .herocard { grid-template-columns: 1fr; }
414
+ .herocard .info { border-left: 0; border-top: 1px solid var(--line); }
415
+ }
416
+ @media (max-width: 600px) {
417
+ .btns { grid-template-columns: repeat(2, minmax(0, 1fr)); }
418
+ .fader { grid-template-columns: minmax(0, 1fr) 52px; gap: 6px 12px; }
419
+ .fader input { grid-column: 1 / -1; grid-row: 2; }
420
+ .facts { grid-template-columns: 1fr; }
421
+ .fact { border-left: 0; border-top: 1px solid var(--line); }
422
+ .fact:first-child { border-top: 0; }
423
+ .banner { flex-wrap: wrap; }
424
+ .calhero { grid-template-columns: 1fr; }
425
+ .choices { grid-template-columns: 1fr; }
426
+ .swatches { grid-template-columns: repeat(3, minmax(0, 1fr)); }
427
+ .tog .field { grid-template-columns: 1fr; gap: 10px; }
428
+ }
429
+ </style>
430
+ </head>
431
+ <body>
432
+ <div class="app">
433
+ <aside>
434
+ <div class="brand" aria-label="Desky Agent"><svg class="head" viewBox="-8 0 80 48" aria-hidden="true" id="logo" data-head="1"></svg><svg class="chev" viewBox="0 0 10 16" aria-hidden="true"><path d="M1.5 2 L8 8 L1.5 14"/></svg><span class="wm">desky</span><span class="cur"></span></div>
435
+ <nav role="tablist">
436
+ <button type="button" role="tab" data-tab="home" aria-selected="true"><svg viewBox="0 0 24 24"><path d="M4 11l8-7 8 7v8.5a.5.5 0 0 1-.5.5H15v-6H9v6H4.5a.5.5 0 0 1-.5-.5z"/></svg>Огляд</button>
437
+ <button type="button" role="tab" data-tab="move"><svg viewBox="0 0 24 24"><path d="M4 7h9M19 7h1M4 17h3M13 17h7"/><circle cx="16" cy="7" r="2.5"/><circle cx="10" cy="17" r="2.5"/></svg>Рухи</button>
438
+ <button type="button" role="tab" data-tab="cal"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7.5"/><circle cx="12" cy="12" r="2.5"/><path d="M12 2.5v3M12 18.5v3M2.5 12h3M18.5 12h3"/></svg>Калібрування</button>
439
+ <button type="button" role="tab" data-tab="cfg"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16"/><circle cx="9" cy="6" r="1.8" fill="currentColor"/><circle cx="15" cy="12" r="1.8" fill="currentColor"/><circle cx="7" cy="18" r="1.8" fill="currentColor"/></svg>Налаштування</button>
440
+ <button type="button" role="tab" data-tab="mon"><svg viewBox="0 0 24 24"><rect x="3" y="4.5" width="18" height="15" rx="2.5"/><path d="M7.5 9.5l3 2.5-3 2.5M13 15h3.5"/></svg>Монітор</button>
441
+ </nav>
442
+ <button type="button" class="wizlink" id="openWiz"><svg viewBox="0 0 24 24"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z"/><path d="M19 16l.7 2 2 .7-2 .7-.7 2-.7-2-2-.7 2-.7z"/></svg>Майстер налаштування</button>
443
+ <div class="links">
444
+ <button type="button" class="lk btn" id="boardRow" title="плата Desky"><span class="dot" id="dC3"></span><span>Плата</span><span id="sC3">…</span></button>
445
+ <div class="lk" id="rowServo" hidden><span class="dot" id="dServo"></span><span>Серво</span><span id="health">—</span></div>
446
+ <button type="button" class="lk btn" id="verRow" title="версія програми Desky Agent" disabled><span class="dot on" id="dVer"></span><span>Версія</span><span id="sVer" class="mono">—</span></button>
447
+ </div>
448
+ <button type="button" class="stop" id="stop" title="зупинити будь-який рух">Стоп</button>
449
+ </aside>
450
+
451
+ <main>
452
+ <div class="banner bad" id="downbox" hidden><p><b>Desky не відповідає.</b> Відкрий застосунок ще раз.</p></div>
453
+ <div class="banner" id="updbox" hidden><p id="updText"></p><div class="acts"><button type="button" class="ghost sm" id="updLater">Пізніше</button><button type="button" class="pri sm" id="updGo">Оновити</button></div></div>
454
+ <div class="banner bad" id="nocbox" hidden><p><b>Плату не під'єднано.</b> Під'єднай Desky кабелем USB.</p></div>
455
+ <div class="banner" id="manualbox" hidden><p><b>Ручне керування.</b> Агент на паузі.</p><button type="button" class="pri sm" id="toAgent">Повернути агенту</button></div>
456
+ <div class="banner" id="limpbox" hidden><p><b>Серво відпущені.</b></p><button type="button" class="pri sm" data-cmd="on">Тримати позу</button></div>
457
+
458
+ <!-- ============================================================ overview -->
459
+ <section data-page="home" class="page">
460
+ <div class="card herocard">
461
+ <div class="scene3d" id="homeScene"><svg id="bigface" class="alive flat" viewBox="0 0 64 48" aria-hidden="true"></svg>
462
+ <div class="tip3d"><svg viewBox="0 0 16 16"><path d="M13 8a5 5 0 1 1-1.5-3.5M13 2.5V5h-2.5"/></svg>потягни, щоб покрутити</div></div>
463
+ <div class="info">
464
+ <div class="k" id="hKicker" hidden>Агент зараз</div><div class="s" id="hState">—</div><div class="w" id="hWhat"></div>
465
+ <div class="quiet" id="hQuiet" hidden><svg viewBox="0 0 16 16"><path d="M3 6h2.5L9 3v10L5.5 10H3zM11.5 6l3 4M14.5 6l-3 4"/></svg><span></span></div>
466
+ <div class="ses"><div class="hd"><span>Сесії агентів</span><span id="sessCount"></span></div><div id="sessions"></div></div>
467
+ </div>
468
+ </div>
469
+ <div class="cols">
470
+ <div class="card">
471
+ <div class="hd"><h2>Стани</h2></div>
472
+ <div class="btns" id="statesRow"></div>
473
+ </div>
474
+ <div class="card">
475
+ <div class="hd"><h2>Звуки</h2></div>
476
+ <div class="btns" id="soundsRow"></div>
477
+ </div>
478
+ </div>
479
+ </section>
480
+
481
+ <!-- ============================================================ moves -->
482
+ <section data-page="move" class="page" hidden>
483
+ <div class="title"><div><h1>Рухи</h1></div></div>
484
+ <div class="cols wide">
485
+ <div class="card">
486
+ <div class="hd"><h2>Суглоби</h2><label class="check"><input type="checkbox" id="live" checked> рухати одразу</label></div>
487
+ <div class="scene3d" id="moveScene"><div class="tip3d"><svg viewBox="0 0 16 16"><path d="M13 8a5 5 0 1 1-1.5-3.5M13 2.5V5h-2.5"/></svg>потягни, щоб покрутити</div></div>
488
+ <div class="sketches">
489
+ <figure><svg id="side" viewBox="0 0 240 170" role="img" aria-label="Вигляд збоку: нахил і руки"></svg><figcaption>збоку, стіл праворуч</figcaption></figure>
490
+ <figure><svg id="topv" viewBox="0 0 160 170" role="img" aria-label="Вигляд згори: поворот"></svg><figcaption>згори, стіл угорі</figcaption></figure>
491
+ </div>
492
+ <div class="fader"><label for="f0">Поворот<small>J1 · ±45°</small></label><input type="range" id="f0" min="-45" max="45" step="1" value="0"><output id="o0">0°</output></div>
493
+ <div class="fader"><label for="f1">Нахил<small>J2 · + уперед</small></label><input type="range" id="f1" min="-10" max="25" step="1" value="0"><output id="o1">0°</output></div>
494
+ <div class="fader"><label for="f2">Права рука<small>J3 · 0° висить</small></label><input type="range" id="f2" min="-30" max="160" step="1" value="65"><output id="o2">65°</output></div>
495
+ <div class="fader"><label for="f3">Ліва рука<small>J4 · 0° висить</small></label><input type="range" id="f3" min="-30" max="160" step="1" value="65"><output id="o3">65°</output></div>
496
+ <div class="row">
497
+ <button type="button" id="home">У центр</button>
498
+ <button type="button" id="mirror" aria-pressed="false" title="права й ліва рука рухаються разом">Руки разом</button>
499
+ <button type="button" class="pri" id="send" hidden>Поїхали</button>
500
+ <button type="button" class="ghost" data-cmd="where" title="запитати в плати, де зараз суглоби" style="margin-left:auto">Оновити позу</button>
501
+ </div>
502
+ </div>
503
+
504
+ <div class="card">
505
+ <div class="hd"><h2>Сценки</h2></div>
506
+ <div class="btns">
507
+ <button type="button" data-cmd="type">Друкує</button>
508
+ <button type="button" data-cmd="wave">Махає</button>
509
+ <button type="button" data-cmd="look">Озирається</button>
510
+ <button type="button" data-cmd="nod">Киває</button>
511
+ <button type="button" data-cmd="happy">Радіє</button>
512
+ <button type="button" data-cmd="sleep">Спить</button>
513
+ </div>
514
+ <div class="fader"><label for="spd">Швидкість рук</label><input type="range" id="spd" min="10" max="150" step="5" value="60"><output id="ospd">60°/с</output></div>
515
+ <div class="sep"></div>
516
+ <div class="hd"><h2>Серво</h2></div>
517
+ <div class="btns">
518
+ <button type="button" data-cmd="on">Тримати</button>
519
+ <button type="button" data-cmd="off" title="зняти струм: Desky обм'якне, його можна повернути рукою">Відпустити</button>
520
+ <button type="button" data-cmd="beep">Пискнути</button>
521
+ </div>
522
+ <div class="opt"><div>Ворушиться в спокої<small>дрібні рухи, коли нічого не відбувається</small></div><button type="button" class="sm" data-cmd="idle">увімк / вимк</button></div>
523
+ <div class="opt"><div>Тримати після руху<small>інакше відпускає за 0,6 с</small></div><button type="button" class="sm" data-cmd="hold">увімк / вимк</button></div>
524
+ </div>
525
+ </div>
526
+ </section>
527
+
528
+ <!-- ============================================================ calibration -->
529
+ <section data-page="cal" class="page" hidden>
530
+ <div class="title"><div><h1>Калібрування</h1></div>
531
+ <button type="button" class="ghost" data-cmd="cal">Оновити з плати</button></div>
532
+ <div class="card calhero">
533
+ <div><h2>Покроковий майстер</h2><p>Desky показує кожен рух, ти підтверджуєш. Близько 3 хвилин.</p></div>
534
+ <button type="button" class="pri lg" id="calWiz">Почати калібрування</button>
535
+ </div>
536
+ <div class="joints" id="joints"></div>
537
+ <div class="card">
538
+ <div class="hd"><h2>Проводи й екран</h2></div>
539
+ <div class="set tog">
540
+ <div class="field"><label>Поворот і нахил переплутані<small>Повзунок повороту нахиляє Desky, а нахилу — крутить? Серво під'єднані навпаки. <span id="swapV"></span></small></label>
541
+ <button type="button" class="sm" id="swapYP">Поміняти місцями</button></div>
542
+ <div class="field"><label>Руки переплутані<small>Повзунок правої руки рухає ліву? Серво рук під'єднані навпаки. <span id="armsV"></span></small></label>
543
+ <button type="button" class="sm" id="swapArms">Поміняти руки</button></div>
544
+ <div class="field"><label>Екран догори дриґом<small>Очі-галочки «^ ^» мають дивитися кутиками вгору. <span id="flipV"></span></small></label>
545
+ <span class="in"><button type="button" class="sm ghost" id="faceTest">Показати «^ ^»</button><button type="button" class="sm" id="flipScr">Перевернути</button></span></div>
546
+ </div>
547
+ </div>
548
+ <div class="savebar" id="calbar"><p id="calMsg">Збережи, щоб зміни пережили перезапуск плати.</p><button type="button" class="pri" id="calSave">Зберегти в платі</button></div>
549
+ </section>
550
+
551
+ <!-- ============================================================ settings -->
552
+ <section data-page="cfg" class="page" hidden>
553
+ <div class="title"><div><h1>Налаштування</h1></div></div>
554
+ <div class="card colorcard">
555
+ <div class="hd"><h2>Колір Desky</h2><span class="muted small" id="colorNow"></span></div>
556
+ <div class="swatches" id="cfgSwatches" role="radiogroup" aria-label="Колір Desky"></div>
557
+ </div>
558
+ <div class="cols">
559
+ <div class="card">
560
+ <div class="hd"><h2>Звук</h2></div>
561
+ <div class="set">
562
+ <div class="field"><label for="qh0">Тихі години<small>без звуку, лише рухи</small></label>
563
+ <span class="in"><input class="num s" type="number" id="qh0" min="0" max="24"><span class="muted">–</span><input class="num s" type="number" id="qh1" min="0" max="24"><span class="unit">год</span></span></div>
564
+ <div class="field"><label for="ask_times">Пищати «чекає»<small>разом із першим разом</small></label>
565
+ <span class="in"><input class="num" type="number" id="ask_times" min="0"><span class="unit">разів</span></span></div>
566
+ <div class="field"><label for="ask_repeat_secs">Повтор трелі</label>
567
+ <span class="in"><input class="num" type="number" id="ask_repeat_secs" min="0"><span class="unit" data-for="ask_repeat_secs"></span></span></div>
568
+ </div>
569
+ </div>
570
+ <div class="card">
571
+ <div class="hd"><h2>Час</h2></div>
572
+ <div class="set">
573
+ <div class="field"><label for="done_secs">«Закінчив» триває<small>потім «нічого не робить»</small></label>
574
+ <span class="in"><input class="num" type="number" id="done_secs" min="0"><span class="unit" data-for="done_secs"></span></span></div>
575
+ <div class="field"><label for="sleep_secs">Засинає через<small>якщо немає подій</small></label>
576
+ <span class="in"><input class="num" type="number" id="sleep_secs" min="0"><span class="unit" data-for="sleep_secs"></span></span></div>
577
+ </div>
578
+ </div>
579
+ <div class="card">
580
+ <div class="hd"><h2>Забувати сесію</h2></div>
581
+ <div class="set">
582
+ <div class="field"><label for="session_ttl_secs">Мовчить<small>після «закінчив» або простою</small></label>
583
+ <span class="in"><input class="num" type="number" id="session_ttl_secs" min="0"><span class="unit" data-for="session_ttl_secs"></span></span></div>
584
+ <div class="field"><label for="busy_ttl_secs">Працювала й зникла<small>термінал закрили; довше 10 хв команди не йдуть</small></label>
585
+ <span class="in"><input class="num" type="number" id="busy_ttl_secs" min="0"><span class="unit" data-for="busy_ttl_secs"></span></span></div>
586
+ <div class="field"><label for="ask_ttl_secs">Питання без відповіді</label>
587
+ <span class="in"><input class="num" type="number" id="ask_ttl_secs" min="0"><span class="unit" data-for="ask_ttl_secs"></span></span></div>
588
+ </div>
589
+ </div>
590
+ <div class="card">
591
+ <div class="hd"><h2>«Читає» чи «працює»</h2></div>
592
+ <div class="set">
593
+ <div class="field col"><label for="read_tools">Інструменти для «читає»<small>через кому; решта — «працює»</small></label>
594
+ <input class="text" type="text" id="read_tools"></div>
595
+ </div>
596
+ </div>
597
+ </div>
598
+ <div class="savebar"><p id="cfgMsg"></p><button type="button" class="ghost" id="defCfg">За замовчуванням</button><button type="button" class="pri" id="saveCfg">Зберегти</button></div>
599
+ </section>
600
+
601
+ <!-- ============================================================ monitor -->
602
+ <section data-page="mon" class="page" hidden>
603
+ <div class="title"><div><h1>Монітор</h1></div></div>
604
+ <div class="term">
605
+ <div class="bar">
606
+ <span class="legend"><span><i style="background:#F2B48F"></i>ти</span><span><i style="background:#9FC6F0"></i>агент</span><span><i style="background:#E6E1DA"></i>плата</span></span>
607
+ <label class="check"><input type="checkbox" id="showAgent" checked> команди агента</label>
608
+ <button type="button" class="ghost sm" id="clearLog">Очистити</button>
609
+ </div>
610
+ <div class="log" id="log" aria-live="polite"></div>
611
+ <form class="raw" id="rawf"><input id="raw" placeholder="pose 0 10 80 80 · state ask · help" autocomplete="off"><button type="button" id="helpBtn">help</button><button type="submit">Надіслати</button></form>
612
+ </div>
613
+ </section>
614
+ </main>
615
+ </div>
616
+
617
+ <!-- ============================================================ setup wizard -->
618
+ <div class="upd" id="updModal" hidden role="dialog" aria-modal="true" aria-labelledby="updTitle">
619
+ <div class="card">
620
+ <svg class="big alive" id="updFace" viewBox="0 0 64 48" aria-hidden="true"></svg>
621
+ <span class="ver" id="updVer"></span>
622
+ <h2 id="updTitle">Вийшла нова версія Desky</h2>
623
+ <p id="updLead"></p>
624
+ <div class="cmd" id="updCmd" hidden><span>npx desky-agent@latest</span><button type="button" class="sm" id="updCopy">Копіювати</button></div>
625
+ <div class="acts"><button type="button" class="ghost" id="updSkip">Пізніше</button><button type="button" class="pri lg" id="updNow">Оновити зараз</button></div>
626
+ </div>
627
+ </div>
628
+
629
+ <div class="wiz" id="wiz" hidden role="dialog" aria-modal="true" aria-labelledby="wizTitle">
630
+ <div class="panel">
631
+ <div class="top">
632
+ <div class="brand" aria-label="Desky Agent"><svg class="head" viewBox="-8 0 80 48" aria-hidden="true" id="wizLogo" data-head="1"></svg><svg class="chev" viewBox="0 0 10 16" aria-hidden="true"><path d="M1.5 2 L8 8 L1.5 14"/></svg><span class="wm">desky</span><span class="cur"></span></div>
633
+ <div class="prog"><div class="bars" id="wizBars"></div><div class="lbl" id="wizLbl"></div></div>
634
+ <button type="button" class="ghost x" id="wizClose" title="закрити майстер"><svg viewBox="0 0 16 16"><path d="M3.5 3.5l9 9M12.5 3.5l-9 9"/></svg></button>
635
+ </div>
636
+ <div class="body" id="wizBody"></div>
637
+ </div>
638
+ </div>
639
+ <div class="toast" id="toast" role="status"></div>
640
+
641
+ <script>
642
+ (() => {
643
+ const $ = id => document.getElementById(id);
644
+ const css = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
645
+ const wait = ms => new Promise(r => setTimeout(r, ms));
646
+ const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
647
+ wait: 'чекає на фонову задачу', limit: 'скінчилися ліміти', error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
648
+ const WHAT = { wake: 'Щойно прокинувся', listen: 'Почув твоє повідомлення', work: 'Агент пише код або запускає команди',
649
+ read: 'Агент читає файли', ask: 'Агент чекає на відповідь',
650
+ wait: 'Агент чекає, поки допрацює запущене у фоні', limit: 'Скінчилися ліміти, чекає на скидання', error: 'Інструмент повернув помилку',
651
+ done: 'Задачу виконано', idle: '', sleep: 'Давно не було подій' };
652
+ const SOUNDS = { wake: 'прокинувся', tick: 'тік', ask: 'трель', error: 'помилка', done: 'готово', sleep: 'засинає', limit: 'ліміти' };
653
+ // The colours Desky is printed in (src/core.js COLORS). body and eye: his plastic and the face on his screen (the
654
+ // board keeps them, "color"); a and d: the app's accent, hover and text on it, for light and dark windows
655
+ const PALETTE = {
656
+ orange: { name: 'Помаранчевий', body: '#D9774B', eye: '#000000', a: ['#D9774B', '#C4643A', '#FFFFFF'], d: ['#E3825A', '#EC9167', '#1A0F0A'] },
657
+ white: { name: 'Білий', body: '#ECE8E1', eye: '#000000', a: ['#8A7D6B', '#73675A', '#FFFFFF'], d: ['#D6CEC2', '#E6DFD5', '#1A1712'] },
658
+ mint: { name: 'М\'ятний', body: '#7CC4A4', eye: '#000000', a: ['#3E9A75', '#2F8263', '#FFFFFF'], d: ['#6CC49E', '#88D3B2', '#0D1F17'] },
659
+ blue: { name: 'Блакитний', body: '#6FA3D8', eye: '#000000', a: ['#3B7BC2', '#2D66A8', '#FFFFFF'], d: ['#6FA7E0', '#8BBAEA', '#0D1824'] },
660
+ graphite: { name: 'Графіт', body: '#3D3B39', eye: '#F2EFEA', a: ['#3D3B39', '#2A2826', '#FFFFFF'], d: ['#BDB7AF', '#D3CDC5', '#1A1917'] },
661
+ };
662
+ let COLOR = 'orange', boardColor = null, boardFw = null, colorAsked = false, boardText = '';
663
+ $('boardRow').onclick = async () => {
664
+ if (!boardText) return;
665
+ try { await navigator.clipboard.writeText(boardText); toast('Скопійовано: ' + boardText); } catch (e) {}
666
+ };
667
+ const canColor = () => { const v = String(boardFw || '').split('.').map(Number); return v.length === 3 && (v[0] > 0 || v[1] > 2 || (v[1] === 2 && v[2] >= 4)); };
668
+ let CFG = null;
669
+
670
+ // ---------------------------------------------------------------- toast
671
+ function toast(text, bad) {
672
+ const t = $('toast'); t.textContent = text; t.className = 'toast on' + (bad ? ' bad' : '');
673
+ clearTimeout(toast.t); toast.t = setTimeout(() => { t.className = 'toast' + (bad ? ' bad' : ''); }, 3200);
674
+ }
675
+
676
+ // ---------------------------------------------------------------- pages
677
+ const TABS = document.querySelectorAll('nav button');
678
+ let curTab = 'home', C3 = null;
679
+ function showTab(name) {
680
+ curTab = name;
681
+ TABS.forEach(b => b.setAttribute('aria-selected', String(b.dataset.tab === name)));
682
+ document.querySelectorAll('[data-page]').forEach(p => { p.hidden = p.dataset.page !== name; });
683
+ try { localStorage.setItem('clawd.tab', name); } catch (e) {}
684
+ if (name === 'mon') logEl.scrollTop = logEl.scrollHeight;
685
+ place3d();
686
+ }
687
+ // one 3D Desky: on the overview he plays the agent's state, on "Рухи" he follows the sliders, in the wizard the step
688
+ function place3d() {
689
+ if (!C3 || !$('wiz').hidden) return;
690
+ C3.glow(null);
691
+ if (curTab === 'home') { C3.mount($('homeScene'), 'hero'); C3.state(lastState || 'idle'); }
692
+ else if (curTab === 'move') { C3.mount($('moveScene'), 'moves'); C3.pose(pose()); }
693
+ else C3.mount(null);
694
+ }
695
+ addEventListener('clawd3d', () => { C3 = window.Clawd3D; C3.colors(PALETTE[COLOR].body, PALETTE[COLOR].eye); document.body.classList.add('has3d'); place3d(); if (!$('wiz').hidden && W.step) go(W.step, W.sub); });
696
+ TABS.forEach(b => b.onclick = () => showTab(b.dataset.tab));
697
+
698
+ // ---------------------------------------------------------------- talking to the daemon
699
+ let up = false, connected = false, manual = false, beat = null;
700
+ // "on" powers the servos one by one, 400 ms each (play.cpp attachAll), and the board reads nothing meanwhile: a move
701
+ // sent behind it waits, and the "home" that ends a demo is already queued and cuts that move off at once. So "on"
702
+ // goes only when the servos are let go (the heartbeat says so), and the next command waits until the board is back.
703
+ // a move the wizard waits for: any line that reaches the board mid-move stops that move (play.cpp pollStop), so a
704
+ // demo's "home", then its move, then "home" again only work one after another. Done on the board's "ok <cmd>",
705
+ // refused on "Нельзя"/"err", and 4 s at most whatever happens (an old firmware, a lost line).
706
+ const waiters = [];
707
+ function move(cmd, ms = 4000) {
708
+ const word = cmd.trim().split(/\s+/)[0].toLowerCase();
709
+ return new Promise(resolve => {
710
+ const w = { word };
711
+ w.done = ok => { clearTimeout(w.t); const i = waiters.indexOf(w); if (i >= 0) waiters.splice(i, 1); resolve(ok); };
712
+ w.t = setTimeout(() => w.done(false), ms);
713
+ waiters.push(w);
714
+ send(cmd);
715
+ });
716
+ }
717
+ // a test move, twice there and back: one small twitch is easy to miss, on a video too
718
+ async function demoMove(line) {
719
+ await move('home');
720
+ for (let i = 0; i < 2; i++) { await move(line); await wait(700); await move('home'); await wait(300); }
721
+ }
722
+ let onUntil = 0; // until then the board is still busy with the last "on" (any page sends it)
723
+ async function servosOn() {
724
+ if (!beat || /отпущены/.test(beat)) await send('on');
725
+ await wait(Math.max(0, onUntil - Date.now()));
726
+ }
727
+ async function api(path, body) {
728
+ const r = await fetch(path, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
729
+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || r.status);
730
+ return r.json();
731
+ }
732
+ function showMode() {
733
+ $('manualbox').hidden = !manual || !$('wiz').hidden;
734
+ // in manual mode Desky shows what the app says, not this: call it the agent's state then
735
+ $('hKicker').hidden = !manual;
736
+ }
737
+ async function setManual(on, hold) {
738
+ try { manual = (await api('/manual', { on, hold: Boolean(hold) })).manual; } catch (e) {}
739
+ if (!manual) atRef = null;
740
+ showMode();
741
+ }
742
+ // every hand command takes Desky from the agent; the daemon gives him back 15 s after the last keep-alive
743
+ // calibration writes the board's memory: the firmware takes it only after "factory on" (docs/firmware_contract.md)
744
+ const FACTORY = ['trim', 'inv', 'here', 'save', 'swap', 'aswap', 'flip', 'probe', 'hold', 'yawhold', 'sn', 'calset', 'face'];
745
+ async function send(cmd, quiet) {
746
+ if (FACTORY.includes(cmd.trim().split(/\s+/)[0].toLowerCase())) await api('/cmd', { line: 'factory on', hand: false }).catch(() => {});
747
+ if (cmd === 'on') onUntil = Date.now() + 1800;
748
+ if (!quiet) { lastHand = Date.now(); manual = true; showMode(); if (!/^trim /.test(cmd)) atRef = null; }
749
+ try { await api('/cmd', { line: cmd, hand: !quiet }); } catch (e) { log('не надіслано: ' + e.message, 'dim'); }
750
+ }
751
+ let lastHand = 0;
752
+ let atRef = null; // the "pose" line a centre was set in; any other hand move, or the agent taking over, clears it
753
+ setInterval(() => {
754
+ // the wizard and the calibration page hold Desky for as long as they are open: back with the agent, he would
755
+ // stand in the agent's pose (arms at 65) while the page asks for the zero one (arms straight down)
756
+ const hold = connected && (!$('wiz').hidden || curTab === 'cal');
757
+ if (hold) lastHand = Date.now();
758
+ if (manual && Date.now() - lastHand < 60000) setManual(true, hold);
759
+ }, 5000);
760
+ $('toAgent').onclick = () => { lastHand = 0; manual = false; setManual(false); };
761
+
762
+ // ---------------------------------------------------------------- monitor
763
+ const logEl = $('log');
764
+ function log(text, cls) {
765
+ if (cls === 'agent' && !$('showAgent').checked) return;
766
+ const s = document.createElement('span'); if (cls) s.className = cls;
767
+ s.textContent = (cls === 'me' || cls === 'agent' ? '> ' : '') + text + '\n';
768
+ const stick = logEl.scrollTop + logEl.clientHeight >= logEl.scrollHeight - 20;
769
+ logEl.appendChild(s);
770
+ while (logEl.childNodes.length > 500) logEl.removeChild(logEl.firstChild);
771
+ if (stick) logEl.scrollTop = logEl.scrollHeight;
772
+ }
773
+ $('clearLog').onclick = () => { logEl.innerHTML = ''; };
774
+ let since = 0, primed = false;
775
+ async function pollLines() {
776
+ try {
777
+ const lines = await api('/lines?since=' + since);
778
+ for (const l of lines) {
779
+ since = l.n;
780
+ log(l.text, l.kind === 'c3' ? '' : l.kind);
781
+ if (l.kind === 'c3') onLine(l.text);
782
+ }
783
+ if (!primed) { primed = true; send('cal', true); send('where', true); }
784
+ } catch (e) {}
785
+ }
786
+ setInterval(pollLines, 300);
787
+
788
+ // ---------------------------------------------------------------- status
789
+ const dur = s => s < 120 ? Math.round(s) + ' с' : s < 7200 ? Math.round(s / 60) + ' хв' : (s / 3600).toFixed(1).replace('.0', '').replace('.', ',') + ' год';
790
+ const plural = (n, a, b, c) => { const m = n % 10, h = n % 100; return m === 1 && h !== 11 ? a : m >= 2 && m <= 4 && (h < 12 || h > 14) ? b : c; };
791
+ let firstStatus = true, port = '', lastState = null;
792
+ async function pollStatus() {
793
+ let st;
794
+ try { st = await api('/status'); up = true; } catch (e) { up = false; }
795
+ $('downbox').hidden = up;
796
+ if (!up) { connected = false; beat = null; $('nocbox').hidden = true; enable(); wizTick(); return; }
797
+ const was = connected;
798
+ connected = st.connected; port = st.port || '';
799
+ if (connected && !was) { boardColor = null; colorAsked = false; send('cal', true); }
800
+ boardFw = connected && st.board ? st.board.fw : null;
801
+ if (connected && canColor() && !colorAsked) { colorAsked = true; send('color', true); }
802
+ $('dC3').className = 'dot ' + (connected ? 'on' : 'bad');
803
+ const bd = connected && st.board ? st.board : {};
804
+ $('sC3').textContent = connected ? (bd.sn || st.port) : 'немає';
805
+ boardText = connected ? ['Desky ' + (bd.sn || 'без серійного номера'), bd.id && 'ID ' + bd.id, bd.fw && 'прошивка ' + bd.fw, st.port]
806
+ .filter(Boolean).join(' · ') : '';
807
+ $('boardRow').title = connected ? boardText + '\nнатисни, щоб скопіювати (для підтримки)' : 'плату не під\'єднано';
808
+ $('boardRow').disabled = !connected;
809
+ $('nocbox').hidden = connected;
810
+ $('rowServo').hidden = !connected;
811
+ beat = connected && st.heartbeat && st.heartbeat_age < 8 ? st.heartbeat : null;
812
+ if (beat) {
813
+ const limp = /отпущены/.test(beat);
814
+ $('dServo').className = 'dot ' + (limp ? 'warn' : 'on');
815
+ $('health').textContent = limp ? 'відпущені' : 'тримають';
816
+ $('limpbox').hidden = !limp;
817
+ } else {
818
+ $('dServo').className = 'dot' + (connected ? ' bad' : ''); $('health').textContent = connected ? 'мовчать' : '—';
819
+ $('limpbox').hidden = true;
820
+ }
821
+ manual = st.manual; if (!manual) atRef = null; showMode();
822
+ showUpdate(st.app_update);
823
+
824
+ $('hState').textContent = NAMES[st.state] || st.state;
825
+ $('hWhat').textContent = WHAT[st.state] || '';
826
+ $('hQuiet').hidden = !st.quiet_now;
827
+ if (st.quiet_now) $('hQuiet').querySelector('span').textContent = 'Тихі години' + (CFG ? ' до ' + CFG.quiet_hours[1] + ':00' : '');
828
+
829
+ const ses = Object.entries(st.by_session || {}), host = $('sessions');
830
+ $('sessCount').textContent = ses.length || '';
831
+ host.innerHTML = '';
832
+ if (!ses.length) host.innerHTML = '<div class="empty">Запусти Claude Code або Codex — Desky прокинеться.</div>';
833
+ else {
834
+ const list = document.createElement('div'); list.className = 'list';
835
+ for (const [sid, s] of ses) {
836
+ const r = document.createElement('div'); r.className = 'li';
837
+ r.innerHTML = '<span class="mono"></span><span class="badge"></span>';
838
+ r.querySelector('.mono').textContent = sid;
839
+ const b = r.querySelector('.badge'); b.textContent = NAMES[s] || s; if (s === 'ask') b.classList.add('ask');
840
+ list.appendChild(r);
841
+ }
842
+ host.appendChild(list);
843
+ }
844
+ if (st.state !== lastState) {
845
+ lastState = st.state; ['logo', 'bigface'].forEach(id => drawFace($(id), st.state));
846
+ if (C3 && curTab === 'home' && $('wiz').hidden) C3.state(st.state);
847
+ }
848
+ enable();
849
+ wizTick();
850
+ if (firstStatus) {
851
+ firstStatus = false;
852
+ let seen = false; try { seen = !!localStorage.getItem('clawd.onboarded'); } catch (e) { seen = true; }
853
+ if (!seen) wizOpen();
854
+ }
855
+ }
856
+ // ---------------------------------------------------------------- new versions of the app
857
+ // the dialog comes back every time the window opens until the update is in; "Пізніше" closes it for this window only
858
+ let modalSkipped = '';
859
+ let updSeen = ''; // a done or failed text closed with "Сховати"
860
+ let au = {}, updErr = ''; // updErr: the button's own failure, kept until the next try
861
+ function showUpdate(a) {
862
+ au = a || {};
863
+ if (updErr && au.state !== 'updating') au = { ...au, state: 'failed', text: updErr };
864
+ const box = $('updbox'), p = $('updText'), go = $('updGo'), later = $('updLater');
865
+ $('sVer').textContent = au.version ? (au.available ? au.version + ' → ' + au.latest : au.version) : '—';
866
+ $('dVer').className = 'dot ' + (au.state === 'failed' ? 'bad' : au.available ? 'warn' : 'on');
867
+ $('verRow').disabled = !au.available;
868
+ $('verRow').classList.toggle('new', Boolean(au.available && au.state !== 'updating'));
869
+ if (au.available && au.state !== 'updating') $('sVer').textContent = 'оновити до ' + au.latest;
870
+ $('verRow').title = au.available ? 'стоїть ' + au.version + ', вийшла ' + au.latest + ': оновити' : 'версія програми Desky Agent';
871
+ showModal();
872
+ let show = false;
873
+ box.classList.remove('bad', 'ok');
874
+ p.textContent = '';
875
+ const b = t => { const e = document.createElement('b'); e.textContent = t; return e; };
876
+ if (au.state === 'updating') {
877
+ show = true;
878
+ p.append(b('Оновлюю Desky до ' + au.latest + '.'), ' Це займе хвилину: вікно закриється й відкриється знову вже з новою версією.');
879
+ go.hidden = false; go.disabled = true; go.textContent = 'Оновлюю…'; later.hidden = true;
880
+ } else if ((au.state === 'failed' || au.state === 'done') && au.text !== updSeen) {
881
+ show = true;
882
+ box.classList.add(au.state === 'failed' ? 'bad' : 'ok');
883
+ p.append(b(au.state === 'failed' ? 'Оновлення не вдалося. ' : 'Готово. '), au.text);
884
+ go.hidden = !(au.state === 'failed' && au.available && au.can); go.disabled = false; go.textContent = 'Ще раз';
885
+ later.hidden = false; later.textContent = 'Сховати';
886
+ } else if (au.available) {
887
+ show = true;
888
+ p.append(b('Вийшла версія ' + au.latest + '.'), ' Зараз стоїть ' + au.version + '. ');
889
+ if (au.can) p.append('Оновлення займе хвилину, налаштування й калібрування залишаться.');
890
+ else { p.append('Онови з термінала: '); const c = document.createElement('span'); c.className = 'mono'; c.textContent = 'npx desky-agent@latest'; p.append(c); }
891
+ go.hidden = !au.can; go.disabled = false; go.textContent = 'Оновити';
892
+ later.hidden = true;
893
+ }
894
+ box.hidden = !show;
895
+ }
896
+ $('updGo').onclick = async () => {
897
+ $('updGo').disabled = true; updErr = '';
898
+ try { showUpdate({ ...au, ...(await api('/app-update', {})) }); }
899
+ catch (e) { updErr = e.message; showUpdate(au); }
900
+ };
901
+ $('updLater').onclick = () => {
902
+ if (au.state === 'failed' || au.state === 'done') { updSeen = au.text; updErr = ''; }
903
+ showUpdate(au);
904
+ };
905
+ $('verRow').onclick = () => { modalSkipped = ''; updSeen = ''; showUpdate(au); };
906
+
907
+ // the dialog: not over the wizard (he is mid-calibration), back after it closes
908
+ function showModal() {
909
+ const m = $('updModal');
910
+ const want = Boolean(au.available && au.state !== 'updating' && modalSkipped !== au.latest && $('wiz').hidden);
911
+ if (want && m.hidden) {
912
+ drawFace($('updFace'), 'happy');
913
+ $('updVer').textContent = au.version + ' → ' + au.latest;
914
+ $('updLead').textContent = au.can
915
+ ? 'Оновлення займе хвилину: вікно закриється й відкриється знову. Налаштування й калібрування залишаться, плату не від\'єднуй.'
916
+ : 'Онови з термінала або попроси свого агента виконати цю команду. Налаштування й калібрування залишаться.';
917
+ $('updCmd').hidden = Boolean(au.can);
918
+ $('updNow').textContent = au.can ? 'Оновити зараз' : 'Зрозуміло';
919
+ setTimeout(() => $('updNow').focus(), 50);
920
+ }
921
+ m.hidden = !want;
922
+ }
923
+ $('updSkip').onclick = () => { modalSkipped = au.latest; showModal(); };
924
+ $('updNow').onclick = () => {
925
+ modalSkipped = au.latest;
926
+ showModal();
927
+ if (au.can) $('updGo').click();
928
+ };
929
+ $('updCopy').onclick = async () => {
930
+ try { await navigator.clipboard.writeText('npx desky-agent@latest'); $('updCopy').textContent = 'Скопійовано'; } catch (e) {}
931
+ };
932
+ document.addEventListener('keydown', e => { if (e.key === 'Escape' && !$('updModal').hidden) $('updSkip').click(); });
933
+
934
+ function enable() {
935
+ document.querySelectorAll('[data-cmd], #send, #home, #stop, #swapYP, #swapArms, #flipScr, #faceTest, #calSave, #rawf button, #joints button, #joints input, #statesRow button, #soundsRow button')
936
+ .forEach(b => { b.disabled = !connected; });
937
+ F.forEach(f => { f.disabled = !connected; });
938
+ }
939
+ setInterval(pollStatus, 1000);
940
+
941
+ // a small picture of the face the state shows, as the firmware draws it: orange face, black eyes
942
+ function drawFace(s, state) {
943
+ s.innerHTML = '';
944
+ const c = PALETTE[COLOR].eye, add = (x, y, w, h, cls) => { const r = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
945
+ r.setAttribute('x', x); r.setAttribute('y', y); r.setAttribute('width', w); r.setAttribute('height', h); r.setAttribute('fill', c);
946
+ if (cls) r.setAttribute('class', cls); s.appendChild(r); };
947
+ const bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
948
+ bg.setAttribute('width', 64); bg.setAttribute('height', 48); bg.setAttribute('rx', s.dataset.head ? 8 : 4); bg.setAttribute('fill', PALETTE[COLOR].body); s.appendChild(bg);
949
+ // the logo: the head from the brand sheet, a servo ear on each side of the screen
950
+ if (s.dataset.head) for (const x of [-8, 64]) { const e = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
951
+ e.setAttribute('x', x); e.setAttribute('y', 15); e.setAttribute('width', 8); e.setAttribute('height', 18); e.setAttribute('rx', 2);
952
+ e.setAttribute('fill', PALETTE[COLOR].body); s.appendChild(e); }
953
+ const eyes = { work: [9, 7, 0, 6], read: [7, 8, -4, 6], ask: [13, 13, 0, 0], sleep: [11, 2, 0, 4], idle: [8, 14, 0, 0],
954
+ wait: [8, 11, 0, 3], limit: [11, 3, 0, 4],
955
+ wake: [8, 14, 0, 0], listen: [8, 14, 0, 0] }[state];
956
+ if (state === 'done' || state === 'happy') { for (const x of [16, 48]) for (let i = 0; i < 6; i++) { add(x - 6 + i, 26 - i, 2, 2); add(x + i, 21 + i, 2, 2); } return; }
957
+ if (state === 'sad') { for (const x of [16, 48]) for (let i = 0; i < 6; i++) { add(x - 6 + i, 20 + i, 2, 2); add(x + i, 25 - i, 2, 2); } return; }
958
+ if (state === 'error') { for (const [x, d] of [[16, 1], [48, -1]]) for (let i = 0; i < 6; i++) { add(x - d * 6 + d * i, 18 + i, 2, 2); add(x - d * 6 + d * i, 30 - i, 2, 2); } return; }
959
+ const [w, h, dx, dy] = eyes || [8, 14, 0, 0];
960
+ for (const x of [16, 48]) add(x - w / 2 + dx, 24 - h / 2 + dy, w, h, state === 'sleep' ? '' : 'eye');
961
+ if (state === 'sleep') add(54, 4, 5, 2), add(57, 6, 2, 2), add(54, 8, 5, 2);
962
+ if (state === 'limit') { add(26, 3, 12, 1); add(26, 9, 12, 1); add(26, 3, 1, 7); add(37, 3, 1, 7); add(38, 5, 1, 3); add(28, 5, 2, 3); }
963
+ }
964
+
965
+ // ---------------------------------------------------------------- previews
966
+ for (const [k, v] of Object.entries(NAMES)) {
967
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = v; b.onclick = () => send('state ' + k); $('statesRow').appendChild(b);
968
+ }
969
+ for (const [k, v] of Object.entries(SOUNDS)) {
970
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = v; b.onclick = () => send('sound ' + k, true); $('soundsRow').appendChild(b);
971
+ }
972
+
973
+ // ---------------------------------------------------------------- settings
974
+ const NUMS = ['done_secs', 'sleep_secs', 'ask_repeat_secs', 'ask_times', 'session_ttl_secs', 'busy_ttl_secs', 'ask_ttl_secs'];
975
+ let DEF = null;
976
+ // "600" means little at a glance: show it as minutes or hours next to the box
977
+ const human = s => !(s >= 0) ? '' : s < 60 ? s + ' с' : s % 3600 === 0 ? s / 3600 + ' год' : s % 60 === 0 ? s / 60 + ' хв'
978
+ : (s / 60).toFixed(1).replace('.', ',') + ' хв';
979
+ function units() { document.querySelectorAll('.unit[data-for]').forEach(u => { const v = $(u.dataset.for).value; u.textContent = v === '' ? 'с' : 'с · ' + human(+v); }); }
980
+ NUMS.forEach(k => $(k).addEventListener('input', units));
981
+ function fillCfg(c) {
982
+ CFG = c;
983
+ if (c.color && c.color !== COLOR) applyColor(c.color);
984
+ reconcileColor();
985
+ $('qh0').value = c.quiet_hours[0]; $('qh1').value = c.quiet_hours[1];
986
+ NUMS.forEach(k => { $(k).value = c[k]; });
987
+ $('read_tools').value = c.read_tools.join(', ');
988
+ units();
989
+ }
990
+ async function loadCfg() { try { const r = await api('/config'); DEF = r.defaults; fillCfg(r.config); } catch (e) {} }
991
+ const say = (t, cls) => { const m = $('cfgMsg'); m.className = cls || ''; m.textContent = t;
992
+ clearTimeout(say.t); say.t = setTimeout(() => { m.className = ''; m.textContent = 'Час — у секундах.'; }, 4000); };
993
+ $('saveCfg').onclick = async () => {
994
+ const body = { quiet_hours: [+$('qh0').value, +$('qh1').value], read_tools: $('read_tools').value.split(',').map(s => s.trim()).filter(Boolean) };
995
+ NUMS.forEach(k => { body[k] = +$(k).value; });
996
+ try { fillCfg((await api('/config', body)).config); say('Збережено', 'ok'); }
997
+ catch (e) { say(e.message, 'bad'); }
998
+ };
999
+ $('defCfg').onclick = () => { if (DEF) { const keep = CFG; fillCfg(DEF); CFG = keep; } say('Підставлено значення за замовчуванням — збережи, щоб застосувати'); };
1000
+ loadCfg();
1001
+
1002
+ // ---------------------------------------------------------------- Desky's colour
1003
+ function applyColor(name) {
1004
+ COLOR = PALETTE[name] ? name : 'orange';
1005
+ const c = PALETTE[COLOR], dark = matchMedia('(prefers-color-scheme: dark)').matches, [a, hi, ink] = dark ? c.d : c.a;
1006
+ const st = document.documentElement.style;
1007
+ st.setProperty('--clawd', a); st.setProperty('--clawd-hi', hi); st.setProperty('--clawd-ink', ink);
1008
+ st.setProperty('--clawd-soft', `color-mix(in srgb, ${a} ${dark ? 18 : 12}%, var(--card))`);
1009
+ st.setProperty('--clawd-glow', `color-mix(in srgb, ${a} 24%, transparent)`);
1010
+ ['logo', 'bigface', 'wizLogo'].forEach(id => $(id) && drawFace($(id), id === 'wizLogo' ? 'done' : lastState || 'idle'));
1011
+ if (C3) C3.colors(c.body, c.eye);
1012
+ document.querySelectorAll('.swatch').forEach(b => b.setAttribute('aria-checked', String(b.dataset.color === COLOR)));
1013
+ $('colorNow').textContent = c.name;
1014
+ buildJoints();
1015
+ }
1016
+ const colorLine = n => 'color ' + PALETTE[n].body.slice(1).toLowerCase() + ' ' + PALETTE[n].eye.slice(1).toLowerCase();
1017
+ // chosen here: the app takes it at once, the config keeps it, the board repaints his face and keeps it too
1018
+ // fromBoard: the board already shows that colour, it only goes into the config (sending it back made the board
1019
+ // answer again, and every answer that came before the config was saved sent it once more)
1020
+ async function pickColor(name, fromBoard) {
1021
+ applyColor(name);
1022
+ if (CFG) CFG.color = COLOR;
1023
+ if (fromBoard) boardColor = COLOR;
1024
+ else if (connected && canColor()) { boardColor = COLOR; send(colorLine(COLOR), true); }
1025
+ try { CFG = (await api('/config', { color: COLOR })).config; } catch (e) {}
1026
+ }
1027
+ // the board and the config disagree: a board left at the factory orange takes the chosen colour, any other colour on
1028
+ // the board is the robot's own (printed and set at the factory) and wins
1029
+ function reconcileColor() {
1030
+ if (!CFG || !boardColor || boardColor === 'other' || boardColor === CFG.color) return;
1031
+ if (boardColor === 'orange') { if (connected && canColor()) send(colorLine(CFG.color), true); boardColor = CFG.color; }
1032
+ else pickColor(boardColor, true);
1033
+ }
1034
+ function swatches(host) {
1035
+ host.innerHTML = '';
1036
+ for (const [k, c] of Object.entries(PALETTE)) {
1037
+ const b = document.createElement('button'); b.type = 'button'; b.className = 'swatch'; b.dataset.color = k;
1038
+ b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', String(k === COLOR));
1039
+ b.innerHTML = `<span class="chip" style="--c:${c.body};--e:${c.eye}"></span><span>${c.name}${k === 'orange' ? '<small>основний</small>' : ''}</span>`;
1040
+ b.onclick = () => pickColor(k);
1041
+ host.appendChild(b);
1042
+ }
1043
+ return host;
1044
+ }
1045
+ swatches($('cfgSwatches'));
1046
+
1047
+ // ---------------------------------------------------------------- what the board prints back (firmware text, Russian)
1048
+ const CAL = [{ dir: 1, trim: 0 }, { dir: 1, trim: 0 }, { dir: 1, trim: 0 }, { dir: -1, trim: 0 }];
1049
+ let SWAP = null, FLIP = null;
1050
+ const touched = [0, 0, 0, 0]; // when this window last moved a joint's trim: ignore echoes then
1051
+ function onLine(line) {
1052
+ const ok = line.match(/^ok (\S+)/);
1053
+ if (ok) { const w = waiters.find(x => x.word === ok[1]); if (w) w.done(true); }
1054
+ else if (/^(Нельзя|err )/.test(line) && waiters.length) waiters[0].done(false);
1055
+ if (/^Серво отпущены/i.test(line)) $('limpbox').hidden = false;
1056
+ if (/^Нельзя:/.test(line)) toast('Desky так не стане: зачепить стіл або ноутбук', true);
1057
+ let m = line.match(/поза: J1 ([+-]?\d+)\s+J2 ([+-]?\d+)\s+J3 (-?\d+)\s+J4 (-?\d+)/);
1058
+ if (m && !dragging) setFaders([+m[1], +m[2], +m[3], +m[4]]);
1059
+ m = line.match(/J([1-4]) [^:]+: направление ([+-]\d)/);
1060
+ if (m) { CAL[+m[1] - 1].dir = +m[2]; calChanged(+m[1] - 1); }
1061
+ m = line.match(/J([1-4]) [^:]+:.*подстройка ([+-]\d+) us/);
1062
+ if (m && Date.now() - touched[+m[1] - 1] > 900) { CAL[+m[1] - 1].trim = +m[2]; calChanged(+m[1] - 1); }
1063
+ // firmware's cal: "поворот на GPIO1, наклон на GPIO2; экран как есть" as wired in docs/pinout.html
1064
+ m = line.match(/поворот на GPIO(\d+), наклон на GPIO(\d+)(?:; экран (.+))?/);
1065
+ if (m) {
1066
+ SWAP = +m[1] > +m[2]; $('swapV').textContent = SWAP ? 'Зараз: поміняні місцями.' : 'Зараз: як на схемі.';
1067
+ if (m[3]) { FLIP = /перев/.test(m[3]); $('flipV').textContent = FLIP ? 'Зараз: перевернутий.' : 'Зараз: як є.'; }
1068
+ }
1069
+ m = line.match(/правая рука на GPIO(\d+), левая рука на GPIO(\d+)/);
1070
+ if (m) $('armsV').textContent = +m[1] > +m[2] ? 'Зараз: поміняні місцями.' : 'Зараз: як на схемі.';
1071
+ if (/^сохранено/.test(line)) { calDirty(false); }
1072
+ m = line.match(/^цвет ([0-9a-f]{6}) ([0-9a-f]{6})/i);
1073
+ // only fresh answers: the first poll replays the monitor's history, old colours included (each one sent ours back)
1074
+ if (m && primed) { boardColor = Object.keys(PALETTE).find(k => PALETTE[k].body.slice(1).toLowerCase() === m[1].toLowerCase()) || 'other'; reconcileColor(); }
1075
+ if (/^err (trim|inv|here|save|swap|aswap|flip|face)/.test(line)) toast('Плата не прийняла команду: ' + line.slice(4), true);
1076
+ wizLine(line);
1077
+ }
1078
+
1079
+ // ---------------------------------------------------------------- faders
1080
+ const F = [0, 1, 2, 3].map(i => $('f' + i)), O = [0, 1, 2, 3].map(i => $('o' + i));
1081
+ const fill = f => f.style.setProperty('--p', (f.value - f.min) / (f.max - f.min) * 100 + '%');
1082
+ const pose = () => F.map(f => +f.value);
1083
+ let dragging = false, lastSent = 0, timer = null;
1084
+ function setFaders(P) { P.forEach((v, i) => { F[i].value = v; }); refresh(); }
1085
+ function refresh() {
1086
+ const P = pose();
1087
+ P.forEach((v, i) => { O[i].textContent = (i < 2 && v > 0 ? '+' : '') + v + '°'; fill(F[i]); });
1088
+ drawSide($('side'), P); drawTop($('topv'), P[0], true);
1089
+ if (C3 && curTab === 'move' && $('wiz').hidden) C3.pose(P);
1090
+ }
1091
+ const sendPose = () => send('pose ' + pose().join(' '));
1092
+ function queueLive() {
1093
+ if (!$('live').checked || !connected) return;
1094
+ clearTimeout(timer);
1095
+ const wt = Math.max(0, 180 - (Date.now() - lastSent));
1096
+ timer = setTimeout(() => { lastSent = Date.now(); sendPose(); }, wt);
1097
+ }
1098
+ F.forEach((f, i) => {
1099
+ f.addEventListener('pointerdown', () => { dragging = true; });
1100
+ f.addEventListener('pointerup', () => { dragging = false; });
1101
+ f.addEventListener('input', () => {
1102
+ if ($('mirror').getAttribute('aria-pressed') === 'true' && i >= 2) F[5 - i].value = f.value;
1103
+ refresh(); queueLive();
1104
+ });
1105
+ });
1106
+ $('mirror').onclick = () => {
1107
+ const on = $('mirror').getAttribute('aria-pressed') !== 'true';
1108
+ $('mirror').setAttribute('aria-pressed', String(on));
1109
+ if (on) { F[3].value = F[2].value; refresh(); queueLive(); }
1110
+ };
1111
+ $('live').onchange = () => { $('send').hidden = $('live').checked; };
1112
+ $('send').onclick = sendPose;
1113
+ $('home').onclick = () => { setFaders([0, 0, 65, 65]); send('home'); };
1114
+ $('stop').onclick = () => send('stop');
1115
+ document.querySelectorAll('[data-cmd]').forEach(b => b.onclick = () => send(b.dataset.cmd, ['where', 'cal'].includes(b.dataset.cmd)));
1116
+ const spd = $('spd');
1117
+ spd.oninput = () => { $('ospd').textContent = spd.value + '°/с'; fill(spd); };
1118
+ spd.onchange = () => send('speed ' + spd.value);
1119
+ fill(spd);
1120
+ $('rawf').onsubmit = e => { e.preventDefault(); const v = $('raw').value.trim(); if (v) { send(v, /^(where|cal|help|who|ping|sound )/.test(v)); $('raw').value = ''; } };
1121
+ $('helpBtn').onclick = () => send('help', true);
1122
+
1123
+ // ---------------------------------------------------------------- joints: what each one is and how to judge it
1124
+ // as factory/clawd_factory/calibrate.py: direction first, then the centre (an arm's trim counts along its direction)
1125
+ const US_PER_DEG = 1000 / 90; // MG90S, as the firmware: about 1000 us per 90 deg
1126
+ const J = [
1127
+ { n: 1, name: 'Поворот голови', short: 'Поворот', base: 0, plus: 25, ref: 0,
1128
+ plusText: 'Голова повернулася <b>праворуч</b>, якщо дивитися Desky в обличчя.',
1129
+ refText: 'голова дивиться <b>прямо вперед</b>, рівно на ноутбук', lo: 'ліворуч', hi: 'праворуч' },
1130
+ { n: 2, name: 'Нахил голови', short: 'Нахил', base: 0, plus: 15, ref: 0,
1131
+ plusText: 'Голова нахилилася <b>вперед</b>, до ноутбука.',
1132
+ refText: 'голова стоїть <b>рівно</b>: не нахилена ні вперед, ні назад', lo: 'назад', hi: 'вперед' },
1133
+ { n: 3, name: 'Права рука', short: 'Права рука', base: 65, plus: 40, ref: 65, pic: 0,
1134
+ plusText: 'Права рука Desky <b>піднялася вперед</b>. Це та, що в тебе <b>зліва</b>, коли дивишся йому в обличчя.',
1135
+ refText: 'права рука <b>висить рівно вниз</b>', lo: 'назад', hi: 'вперед' },
1136
+ { n: 4, name: 'Ліва рука', short: 'Ліва рука', base: 65, plus: 40, ref: 65, pic: 0,
1137
+ plusText: 'Ліва рука Desky <b>піднялася вперед</b>. Це та, що в тебе <b>справа</b>, коли дивишся йому в обличчя.',
1138
+ refText: 'ліва рука <b>висить рівно вниз</b>', lo: 'назад', hi: 'вперед' },
1139
+ ];
1140
+ const HOME = [0, 0, 65, 65];
1141
+ // ref: the angle the centre is set at (sent to the board). An arm hangs straight down at the servo centre, home's
1142
+ // 65 (the horn goes on hanging), so its centre is set there; pic: how the pictures draw that pose (0 = hanging).
1143
+ const refPic = j => poseWith(j, J[j].pic ?? J[j].ref);
1144
+ const FACTORY_DIR = [1, 1, 1, -1]; // play.cpp dirOf: the arms are mirror images
1145
+ const poseWith = (j, v) => { const p = HOME.slice(); p[j] = v; return p; };
1146
+ const trimToDeg = j => CAL[j].trim * CAL[j].dir / US_PER_DEG;
1147
+ const degToTrim = (j, d) => Math.max(-500, Math.min(500, Math.round(d * US_PER_DEG * CAL[j].dir)));
1148
+ const fmtDeg = d => (d > 0.04 ? '+' : d < -0.04 ? '−' : '') + Math.abs(d).toFixed(1).replace('.', ',') + '°';
1149
+
1150
+ // a live trim: the firmware moves the servo at once (play.cpp, "trim"); at most one line per 110 ms, the last one always
1151
+ const trimQ = [null, null, null, null], trimT = [0, 0, 0, 0], trimTimer = [];
1152
+ function sendTrim(j, us) {
1153
+ CAL[j].trim = us; touched[j] = Date.now(); calDirty(true);
1154
+ trimQ[j] = us;
1155
+ if (trimTimer[j]) return;
1156
+ const go = () => {
1157
+ trimTimer[j] = null;
1158
+ if (trimQ[j] === null) return;
1159
+ const v = trimQ[j]; trimQ[j] = null; trimT[j] = Date.now();
1160
+ send('trim j' + (j + 1) + ' ' + (v >= 0 ? '+' : '') + v);
1161
+ trimTimer[j] = setTimeout(go, 110);
1162
+ };
1163
+ const wt = Math.max(0, 110 - (Date.now() - trimT[j]));
1164
+ trimTimer[j] = setTimeout(go, wt);
1165
+ }
1166
+
1167
+ // the centre dial in degrees (±45° = ±500 us), filled from the middle; fine steps of 0.5° and the arrow keys
1168
+ function toRef(j) {
1169
+ const line = 'pose ' + poseWith(j, J[j].ref).join(' ');
1170
+ if (atRef === line && manual) return Promise.resolve();
1171
+ clearTimeout(trimTimer[j]); trimTimer[j] = null;
1172
+ trimT[j] = Date.now() + 1500; // an arm from 65 to 0 at 60 deg/s; a trim sent sooner stops the move
1173
+ const sent = send(line);
1174
+ atRef = line;
1175
+ return sent;
1176
+ }
1177
+
1178
+ function makeDial(j, onMove) {
1179
+ const d = document.createElement('div'); d.className = 'dial';
1180
+ d.innerHTML = `<div class="ends"><span>← ${J[j].lo}</span><b></b><span>${J[j].hi} →</span></div>
1181
+ <div class="track"><input type="range" min="-45" max="45" step="0.1" aria-label="центр: ${J[j].short}"></div>
1182
+ <div class="fine"><button type="button" class="sm" data-d="-2">−2°</button><button type="button" class="sm" data-d="-0.5">−½°</button>
1183
+ <button type="button" class="sm ghost" data-z>у нуль</button>
1184
+ <button type="button" class="sm" data-d="0.5">+½°</button><button type="button" class="sm" data-d="2">+2°</button></div>
1185
+ <div class="hint"></div>`;
1186
+ const r = d.querySelector('input'), b = d.querySelector('.ends b'), hint = d.querySelector('.hint');
1187
+ const paint = () => {
1188
+ const v = +r.value, p = (v + 45) / 90 * 100;
1189
+ r.style.setProperty('--a', Math.min(50, p) + '%'); r.style.setProperty('--b', Math.max(50, p) + '%');
1190
+ b.textContent = fmtDeg(v);
1191
+ const us = Math.abs(degToTrim(j, v)), big = us > 200;
1192
+ d.classList.toggle('warn', big);
1193
+ hint.className = 'hint' + (big ? ' warn' : '');
1194
+ hint.innerHTML = big ? 'Зсув понад 18°: ходу в один бік стане менше. Краще переставити качалку серво на сусідній зубець і почати з нуля.'
1195
+ : 'Стрілки ← → на клавіатурі рухають на 0,1°. Зсув ' + (us ? '≈ ' + us + ' мкс' : 'нульовий') + '.';
1196
+ };
1197
+ const set = (v, push) => { r.value = Math.max(-45, Math.min(45, Math.round(v * 10) / 10)); paint(); if (push) { toRef(j); sendTrim(j, degToTrim(j, +r.value)); onMove && onMove(); } };
1198
+ r.addEventListener('input', () => set(+r.value, true));
1199
+ d.querySelectorAll('[data-d]').forEach(x => x.onclick = () => set(+r.value + +x.dataset.d, true));
1200
+ d.querySelector('[data-z]').onclick = () => set(0, true);
1201
+ d.sync = () => { if (Date.now() - touched[j] > 900 && document.activeElement !== r) set(trimToDeg(j), false); };
1202
+ set(trimToDeg(j), false);
1203
+ return d;
1204
+ }
1205
+
1206
+ // ---------------------------------------------------------------- calibration page
1207
+ const dials = [];
1208
+ function buildJoints() {
1209
+ const host = $('joints'); host.innerHTML = '';
1210
+ J.forEach((jj, j) => {
1211
+ const c = document.createElement('div'); c.className = 'card joint';
1212
+ c.innerHTML = `<div class="hd"><div><h2>${jj.name}</h2><small>J${jj.n}</small></div><button type="button" class="sm ghost" data-goref>Поставити в нуль</button></div>
1213
+ <div class="pic"><figure class="fig"><svg viewBox="0 0 160 120"></svg><figcaption>в обличчя</figcaption></figure>
1214
+ <figure class="fig"><svg viewBox="0 0 240 170"></svg><figcaption>${j === 0 ? 'згори' : 'збоку'}</figcaption></figure></div>
1215
+ <p class="hint">Центр: ${jj.refText}.</p>`;
1216
+ const dial = makeDial(j); dials[j] = dial; c.appendChild(dial);
1217
+ const dir = document.createElement('div'); dir.className = 'dir';
1218
+ dir.innerHTML = '<span>Напрямок: <b></b></span><button type="button" class="sm" data-test>Перевірити</button><button type="button" class="sm ghost" data-inv>Розвернути</button>';
1219
+ c.appendChild(dir);
1220
+ const [front, other] = c.querySelectorAll('svg');
1221
+ c.draw = () => {
1222
+ const P = refPic(j);
1223
+ drawFront(front, P, j);
1224
+ if (j === 0) { other.setAttribute('viewBox', '0 0 160 170'); drawTop(other, 0); } else drawSide(other, P, j);
1225
+ dir.querySelector('b').textContent = CAL[j].dir === FACTORY_DIR[j] ? 'як із заводу' : 'розвернутий';
1226
+ };
1227
+ c.querySelector('[data-goref]').onclick = () => { atRef = null; toRef(j); };
1228
+ dir.querySelector('[data-test]').onclick = async () => {
1229
+ await servosOn(); await demoMove('j' + jj.n + ' ' + (jj.base + jj.plus));
1230
+ toast(jj.plusText.replace(/<[^>]+>/g, '') + ' Якщо ні — «Розвернути».');
1231
+ };
1232
+ dir.querySelector('[data-inv]').onclick = async () => { await send('inv j' + jj.n); calDirty(true); await send('cal', true); };
1233
+ c.draw();
1234
+ host.appendChild(c);
1235
+ });
1236
+ }
1237
+ function calChanged(j) {
1238
+ const c = $('joints').children[j]; if (c && c.draw) c.draw();
1239
+ if (dials[j]) dials[j].sync();
1240
+ wizCal(j);
1241
+ }
1242
+ let dirty = false;
1243
+ function calDirty(on) {
1244
+ dirty = on; $('calbar').classList.toggle('dirty', on);
1245
+ $('calMsg').textContent = on ? 'Є незбережені зміни. Desky уже рухається з ними, але після перезапуску плати вони зникнуть.'
1246
+ : 'Усе збережено в платі.';
1247
+ }
1248
+ $('calSave').onclick = async () => { await send('save'); toast('Збережено в платі'); };
1249
+ $('swapYP').onclick = async () => { await send('swap'); await send('cal', true); };
1250
+ $('swapArms').onclick = async () => { await send('aswap'); await send('cal', true); };
1251
+ $('flipScr').onclick = async () => { await send('flip'); await send('face happy'); await send('cal', true); };
1252
+ $('faceTest').onclick = async () => { await send('face happy'); await wait(2500); await send('face eyes'); };
1253
+ $('calWiz').onclick = () => wizOpen('wires');
1254
+
1255
+ // ---------------------------------------------------------------- sketches (as firmware/panel.html)
1256
+ const NS = 'http://www.w3.org/2000/svg';
1257
+ function el(svg, tag, a) { const e = document.createElementNS(NS, tag); for (const k in a) e.setAttribute(k, a[k]); svg.appendChild(e); return e; }
1258
+ // side view, desk to the right. hl: the joint to pick out (1: the head, 2/3: an arm), the rest fades
1259
+ function drawSide(side, P, hl) {
1260
+ const [, pitch, aR, aL] = P;
1261
+ side.innerHTML = '';
1262
+ const ink = css('--ink'), cl = css('--clawd'), desk = css('--desk');
1263
+ const ox = 70, oy = 150, J2 = [0, 46.5];
1264
+ const pt = (y, z) => [ox + y * 1.1, oy - z * 1.1];
1265
+ const pp = (y, z) => { const r = -pitch * Math.PI / 180, dy = y - J2[0], dz = z - J2[1];
1266
+ return pt(J2[0] + dy * Math.cos(r) - dz * Math.sin(r), J2[1] + dy * Math.sin(r) + dz * Math.cos(r)); };
1267
+ const poly = (pts, fill, op = 1) => el(side, 'polygon', { points: pts.map(p => p.join(',')).join(' '), fill, opacity: op });
1268
+ poly([pt(29, 57), pt(79, 57), pt(79, 61), pt(29, 61)], desk);
1269
+ poly([pt(33, 61), pt(71, 61), pt(71, 67), pt(33, 67)], desk, .7);
1270
+ poly([pt(-22, 0), pt(30, 0), pt(30, 29), pt(-22, 29)], desk, .5);
1271
+ poly([pt(-26, 29.5), pt(26, 29.5), pt(26, 33.5), pt(-26, 33.5)], desk, .8);
1272
+ poly([pp(-18, 64.5), pp(18, 64.5), pp(18, 116.5), pp(-18, 116.5)], cl, hl >= 2 ? .45 : 1);
1273
+ poly([pp(-18, 35.5), pp(11, 35.5), pp(11, 64.5), pp(-18, 64.5)], cl, hl >= 2 ? .35 : .7);
1274
+ const sh = [-2.2, 90];
1275
+ [[aR, 2], [aL, 3]].forEach(([a, k]) => {
1276
+ const op = hl >= 2 ? (hl === k ? 1 : .18) : k === 2 ? 1 : .55;
1277
+ const r = a * Math.PI / 180, tip = [sh[0] + 26 * Math.sin(r), sh[1] - 26 * Math.cos(r)];
1278
+ const p0 = pp(...sh), p1 = pp(...tip);
1279
+ el(side, 'line', { x1: p0[0], y1: p0[1], x2: p1[0], y2: p1[1], stroke: hl === k ? cl : ink, 'stroke-width': 7, 'stroke-linecap': 'round', opacity: op,
1280
+ ...(hl === k ? { filter: 'drop-shadow(0 0 2px rgba(0,0,0,.35))' } : {}) });
1281
+ });
1282
+ if (hl === 1) { // the arc the head travels
1283
+ const c = pt(...J2);
1284
+ el(side, 'path', { d: `M ${c[0] + 6} ${c[1] - 82} A 82 82 0 0 1 ${c[0] + 50} ${c[1] - 66}`, fill: 'none', stroke: cl, 'stroke-width': 2, 'stroke-dasharray': '4 4', opacity: .8 });
1285
+ }
1286
+ }
1287
+ // top view, desk at the top; + yaw turns the head to Desky's left, which is your right when you face him
1288
+ function drawTop(top, yaw, label) {
1289
+ top.innerHTML = '';
1290
+ const ink = css('--ink'), cl = css('--clawd'), desk = css('--desk'), mut = css('--muted');
1291
+ const tx = 80, ty = 115;
1292
+ el(top, 'rect', { x: 14, y: 8, width: 132, height: 52, rx: 3, fill: desk, opacity: .6 });
1293
+ const g = el(top, 'g', { transform: `rotate(${-yaw} ${tx} ${ty})` });
1294
+ el(g, 'rect', { x: tx - 32, y: ty - 18, width: 64, height: 34, rx: 2, fill: cl });
1295
+ el(g, 'polygon', { points: `${tx - 8},${ty - 18} ${tx + 8},${ty - 18} ${tx},${ty - 30}`, fill: ink });
1296
+ if (label) el(top, 'text', { x: 80, y: 162, 'text-anchor': 'middle', fill: mut, 'font-size': 11, 'font-family': 'JetBrains Mono, monospace' }).textContent = (yaw > 0 ? '+' : '') + Math.round(yaw) + '°';
1297
+ }
1298
+ // front view: you face Desky, so his right arm is on your left. Yaw slides the eyes, pitch shrinks the head, an arm
1299
+ // raised forward looks shorter (cos), and past 90° it points up
1300
+ function drawFront(svg, P, hl) {
1301
+ const [yaw, pitch, aR, aL] = P;
1302
+ svg.innerHTML = '';
1303
+ const ink = css('--ink'), cl = css('--clawd'), desk = css('--desk');
1304
+ const cx = 80;
1305
+ el(svg, 'rect', { x: 20, y: 104, width: 120, height: 10, rx: 2, fill: desk, opacity: .55 });
1306
+ el(svg, 'rect', { x: cx - 26, y: 72, width: 52, height: 32, rx: 4, fill: cl, opacity: hl >= 2 ? .5 : .75 });
1307
+ const hh = 46 * Math.cos(pitch * Math.PI / 180) - 4 * Math.sin(pitch * Math.PI / 180);
1308
+ const shift = Math.sin(yaw * Math.PI / 180) * 14, sq = Math.cos(yaw * Math.PI / 180);
1309
+ const hw = 60 * (0.82 + 0.18 * sq);
1310
+ el(svg, 'rect', { x: cx - hw / 2, y: 72 - hh, width: hw, height: hh, rx: 5, fill: cl, opacity: hl >= 2 ? .5 : 1 });
1311
+ for (const ex of [-13, 13]) el(svg, 'rect', { x: cx + ex * sq + shift - 3.5, y: 72 - hh / 2 - 7 + pitch * .25, width: 7, height: 14, fill: '#000', opacity: hl >= 2 ? .5 : 1 });
1312
+ [[aR, 2, -1], [aL, 3, 1]].forEach(([a, k, side]) => {
1313
+ const sx = cx + side * 31, sy = 80, L = 26 * Math.cos(a * Math.PI / 180);
1314
+ const on = hl === k, op = hl >= 2 ? (on ? 1 : .2) : .8;
1315
+ el(svg, 'line', { x1: sx, y1: sy, x2: sx + side * 3, y2: sy + L, stroke: on ? cl : ink, 'stroke-width': 7, 'stroke-linecap': 'round', opacity: op });
1316
+ el(svg, 'circle', { cx: sx + side * 3, cy: sy + L, r: 4.5, fill: on ? cl : ink, opacity: op });
1317
+ });
1318
+ }
1319
+
1320
+ // a pose moving on a loop between two poses, for pictures that show what is about to happen
1321
+ function animate(draws, A, B) {
1322
+ let t0 = performance.now(), id = 0, alive = true;
1323
+ const ease = u => u < .5 ? 2 * u * u : 1 - Math.pow(-2 * u + 2, 2) / 2;
1324
+ const frame = now => {
1325
+ if (!alive) return;
1326
+ const T = 3000, u = ((now - t0) % T) / T;
1327
+ const k = u < .15 ? 0 : u < .45 ? ease((u - .15) / .3) : u < .7 ? 1 : u < 1 ? 1 - ease((u - .7) / .3) : 0;
1328
+ const P = A.map((a, i) => a + (B[i] - a) * k);
1329
+ draws.forEach(f => f(P));
1330
+ id = requestAnimationFrame(frame);
1331
+ };
1332
+ // drawn at once, so the picture is there before the first animation frame; without motion: the end pose, still
1333
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) { draws.forEach(f => f(B)); return () => {}; }
1334
+ t0 -= 3000 * .55; // start on the moved pose: what to look for comes first
1335
+ frame(performance.now());
1336
+ return () => { alive = false; cancelAnimationFrame(id); };
1337
+ }
1338
+
1339
+ // ---------------------------------------------------------------- setup wizard
1340
+ const STEPS = ['hello', 'connect', 'color', 'check', 'wires', 'arms', 'screen', 'j0', 'j1', 'j2', 'j3', 'done'];
1341
+ const STEP_NAMES = { hello: 'Привіт', connect: 'Підключення', color: 'Колір', check: 'Перевірка', wires: 'Проводи', arms: 'Руки', screen: 'Екран',
1342
+ j0: 'Поворот', j1: 'Нахил', j2: 'Права рука', j3: 'Ліва рука', done: 'Готово' };
1343
+ const W = { step: null, sub: null, stop: null, retried: false, orig: null, onTick: null, onLine: null, onCal: null };
1344
+ const IC_OK = '<svg viewBox="0 0 16 16"><path d="M3.5 8.5l3 3 6-7"/></svg>', IC_BAD = '<svg viewBox="0 0 16 16"><path d="M4.5 4.5l7 7M11.5 4.5l-7 7"/></svg>';
1345
+
1346
+ function wizOpen(from) {
1347
+ $('wiz').hidden = false; showMode();
1348
+ drawFace($('wizLogo'), 'done');
1349
+ go(from || 'hello');
1350
+ setTimeout(() => { const b = $('wizBody').querySelector('button.pri'); b && b.focus(); }, 50);
1351
+ }
1352
+ async function wizClose(finished) {
1353
+ if (W.stop) W.stop();
1354
+ revertCentre();
1355
+ W.step = null; W.onTick = W.onLine = W.onCal = null;
1356
+ $('wiz').hidden = true; showMode();
1357
+ place3d();
1358
+ try { localStorage.setItem('clawd.onboarded', '1'); } catch (e) {}
1359
+ if (connected) send('home');
1360
+ if (finished) showTab('home');
1361
+ }
1362
+ $('openWiz').onclick = () => wizOpen();
1363
+ $('wizClose').onclick = () => wizClose(false);
1364
+ document.addEventListener('keydown', e => { if (e.key === 'Escape' && !$('wiz').hidden) wizClose(false); });
1365
+
1366
+ function progress(name) {
1367
+ const i = STEPS.indexOf(name);
1368
+ $('wizBars').innerHTML = STEPS.map((s, k) => `<i class="${k < i || name === 'done' ? 'done' : k === i ? 'now' : ''}" title="${STEP_NAMES[s]}"></i>`).join('');
1369
+ $('wizLbl').innerHTML = `Крок ${i + 1} з ${STEPS.length} · <b>${STEP_NAMES[name]}</b>`;
1370
+ }
1371
+
1372
+ // one step: a stage on the left (pictures), the words and buttons on the right
1373
+ const SHOT3 = ['yaw', 'side', 'armR', 'armL'];
1374
+ function frame({ kick, title, lead, stage, scene, cap, body, foot }) {
1375
+ if (W.stop) { W.stop(); W.stop = null; }
1376
+ W.onTick = W.onLine = W.onCal = null;
1377
+ const s = document.createElement('div'); s.className = 'step';
1378
+ s.innerHTML = `<div class="stage"></div><div class="content"><div class="kick"></div><h2 id="wizTitle"></h2><p class="lead"></p><div class="slot"></div><div class="foot"></div></div>`;
1379
+ s.querySelector('.kick').textContent = kick || '';
1380
+ s.querySelector('h2').textContent = title;
1381
+ s.querySelector('.lead').innerHTML = lead || '';
1382
+ const stg = s.querySelector('.stage');
1383
+ let host = null;
1384
+ if (C3 && scene) {
1385
+ host = h('<div class="scene3d"><div class="tip3d"><svg viewBox="0 0 16 16"><path d="M13 8a5 5 0 1 1-1.5-3.5M13 2.5V5h-2.5"/></svg>потягни, щоб покрутити</div></div>');
1386
+ stg.classList.add('s3'); stg.appendChild(host);
1387
+ if (cap) { const c = h('<div class="cap3"><i></i></div>'); c.append(cap); stg.appendChild(c); }
1388
+ } else if (stage) stg.append(...[].concat(stage));
1389
+ if (body) s.querySelector('.slot').append(...[].concat(body));
1390
+ const f = s.querySelector('.foot');
1391
+ (foot || []).forEach(b => f.appendChild(b));
1392
+ $('wizBody').innerHTML = ''; $('wizBody').appendChild(s); $('wizBody').scrollTop = 0;
1393
+ if (C3) C3.glow(null);
1394
+ if (host) { C3.mount(host, scene.shot); if (scene.glow != null) C3.glow(scene.glow); if (scene.run) scene.run(C3); }
1395
+ return s;
1396
+ }
1397
+ function btn(text, cls, onclick) { const b = document.createElement('button'); b.type = 'button'; b.className = cls || ''; b.innerHTML = text; b.onclick = onclick; return b; }
1398
+ function spacer() { const s = document.createElement('span'); s.className = 'sp'; return s; }
1399
+ function h(html) { const d = document.createElement('div'); d.innerHTML = html.trim(); return d.firstElementChild; }
1400
+ function bigFace(state) { const s = document.createElementNS(NS, 'svg'); s.setAttribute('viewBox', '0 0 64 48'); s.setAttribute('class', 'big alive'); drawFace(s, state); return s; }
1401
+ function fig(viewBox, caption) {
1402
+ const f = document.createElement('figure'); f.className = 'fig';
1403
+ const s = document.createElementNS(NS, 'svg'); s.setAttribute('viewBox', viewBox); f.appendChild(s);
1404
+ if (caption) { const c = document.createElement('figcaption'); c.textContent = caption; f.appendChild(c); }
1405
+ return [f, s];
1406
+ }
1407
+ function views(...figs) { const v = document.createElement('div'); v.className = 'views' + (figs.length > 1 ? ' two' : ''); figs.forEach(f => v.appendChild(f)); return v; }
1408
+ function back(to) { return btn('Назад', 'ghost', () => go(to)); }
1409
+ const busy = async (b, fn) => { const all = [...$('wizBody').querySelectorAll('button')]; all.forEach(x => x.disabled = true); try { await fn(); } finally { all.forEach(x => x.disabled = false); W.onTick && W.onTick(); } };
1410
+
1411
+ // a centre the user moved but did not confirm ("Назад", closing): give the joint back what it had
1412
+ function revertCentre() {
1413
+ if (W.orig !== null && W.step && W.step[0] === 'j' && W.sub === 'centre') sendTrim(+W.step[1], W.orig);
1414
+ W.orig = null;
1415
+ }
1416
+ function go(name, sub) {
1417
+ revertCentre();
1418
+ W.step = name; W.sub = sub || null; W.retried = false;
1419
+ progress(name);
1420
+ const fixed = { hello: stHello, connect: stConnect, color: stColor, check: stCheck, wires: stWires, arms: stArms, screen: stScreen, done: stDone }[name];
1421
+ if (fixed) fixed(); else if (sub === 'centre') stCentre(+name[1]); else stDir(+name[1]);
1422
+ }
1423
+ function wizTick() { if (!$('wiz').hidden && W.onTick) W.onTick(); }
1424
+ function wizLine(line) { if (!$('wiz').hidden && W.onLine) W.onLine(line); }
1425
+ function wizCal(j) { if (!$('wiz').hidden && W.onCal) W.onCal(j); }
1426
+
1427
+ // ---- 1. hello
1428
+ function stHello() {
1429
+ frame({
1430
+ kick: 'Ласкаво просимо до Desky Agent', title: 'Привіт! Я Desky',
1431
+ lead: 'Я сиджу біля ноутбука й показую, що зараз робить <b>Claude Code</b> або <b>Codex</b>: пише код, читає файли, чекає на твою відповідь або вже закінчив.<br><br>Налаштуймо мене разом: під\'єднаємо плату, перевіримо рухи й за потреби відкалібруємо. Це займе кілька хвилин.',
1432
+ stage: [bigFace('idle'), h('<div class="cap">Desky · робот, який живе поруч із Claude Code і Codex</div>')],
1433
+ scene: { shot: 'hero', run: c => c.state('idle', true) }, cap: 'Desky за роботою',
1434
+ foot: [btn('Пропустити', 'ghost', () => wizClose(false)), spacer(), btn('Почнімо', 'pri lg', () => go('connect'))],
1435
+ });
1436
+ }
1437
+
1438
+ // ---- 2. the cable
1439
+ function stConnect() {
1440
+ const rows = h(`<div class="checks">
1441
+ <div class="ck" data-k="app"><span class="ic"></span><div><b>Програма Desky Agent</b><small></small></div></div>
1442
+ <div class="ck" data-k="board"><span class="ic"></span><div><b>Плата</b><small></small></div></div>
1443
+ <div class="ck" data-k="servo"><span class="ic"></span><div><b>Серво</b><small></small></div></div></div>`);
1444
+ const next = btn('Далі', 'pri lg', () => go('color'));
1445
+ const face = bigFace('sleep');
1446
+ frame({
1447
+ kick: 'Підключення', title: 'Під\'єднай Desky',
1448
+ lead: 'Встав кабель <b>USB-C</b> у Desky і в комп\'ютер. Програма знайде плату сама, нічого обирати не треба.',
1449
+ stage: [face, h('<div class="cap">Чекаю на плату…</div>')], body: rows,
1450
+ scene: { shot: 'front', run: c => c.state(connected ? 'wake' : 'sleep', true) }, cap: 'Чекаю на плату…',
1451
+ foot: [back('hello'), spacer(), next],
1452
+ });
1453
+ const cap = $('wizBody').querySelector('.cap') || $('wizBody').querySelector('.cap3');
1454
+ let woke = false;
1455
+ W.onTick = () => {
1456
+ const set = (k, cls, text) => { const r = rows.querySelector(`[data-k="${k}"]`); r.className = 'ck ' + cls; r.querySelector('small').textContent = text;
1457
+ r.querySelector('.ic').innerHTML = cls === 'ok' ? IC_OK : cls === 'bad' ? IC_BAD : ''; };
1458
+ set('app', up ? 'ok' : 'bad', up ? 'працює на цьому комп\'ютері' : 'не відповідає: відкрий застосунок Desky ще раз');
1459
+ set('board', connected ? 'ok' : up ? 'wait' : '', connected ? 'на зв\'язку · ' + port : 'шукаю… перевір кабель (потрібен кабель з даними, не лише для заряджання)');
1460
+ const limp = beat && /отпущены/.test(beat);
1461
+ set('servo', beat ? 'ok' : connected ? 'wait' : '', beat ? (limp ? 'відпущені — натисну «тримати»' : 'тримають позу') : connected ? 'чекаю відповіді плати…' : '—');
1462
+ next.disabled = !connected;
1463
+ const say3 = t => { cap.lastChild.textContent = t; };
1464
+ if (connected && !woke) { woke = true; drawFace(face, 'idle'); say3('Плата на зв\'язку!'); C3 && C3.state('wake'); send('on'); }
1465
+ if (!connected && woke) { woke = false; drawFace(face, 'sleep'); say3('Чекаю на плату…'); C3 && C3.state('sleep'); }
1466
+ };
1467
+ W.onTick();
1468
+ }
1469
+
1470
+ // ---- 3. which Desky is this: his colour
1471
+ function stColor() {
1472
+ const sw = swatches(h('<div class="swatches" role="radiogroup" aria-label="Колір Desky"></div>'));
1473
+ frame({
1474
+ kick: 'Колір', title: 'Якого кольору твій Desky?',
1475
+ lead: 'Обери колір корпусу. Під нього підлаштується застосунок, а Desky одразу перефарбує обличчя на своєму екрані.',
1476
+ stage: [bigFace('idle')], scene: { shot: 'hero', run: c => c.state('wake', true) }, cap: 'покрути його мишкою',
1477
+ body: [sw, h('<p class="hint">Колір можна змінити будь-коли в «Налаштуваннях».</p>')],
1478
+ foot: [back('connect'), spacer(), btn('Далі', 'pri lg', () => go('check'))],
1479
+ });
1480
+ }
1481
+
1482
+ // ---- 4. is everything fine already? (Desky leaves the factory calibrated)
1483
+ function stCheck() {
1484
+ const [f1, s1] = fig('0 0 160 120', 'в обличчя');
1485
+ W.stop = animate([P => drawFront(s1, P)], HOME, [0, 0, 150, 65]);
1486
+ const watch = h('<div class="watch"><span class="pulse"></span><span>Подивись на Desky: він помахає й стане рівно.</span></div>');
1487
+ const replay = btn('Показати ще раз', 'ghost', () => busy(replay, demo));
1488
+ const ok = btn('Так, усе рівно', 'pri', () => go('done'));
1489
+ const fix = btn('Ні, налаштуймо', '', () => go('wires'));
1490
+ frame({
1491
+ kick: 'Перевірка', title: 'Усе на своїх місцях?',
1492
+ lead: 'Desky калібрують ще на виробництві, тож зазвичай усе вже гаразд. Перевір: <b>голова дивиться прямо</b>, не нахилена, <b>руки висять рівно</b>, а помах був плавний.',
1493
+ stage: views(f1), body: [watch, h('<div class="row"></div>')],
1494
+ scene: { shot: 'front' }, cap: 'так має бути',
1495
+ foot: [back('color'), spacer(), fix, ok],
1496
+ });
1497
+ $('wizBody').querySelector('.slot .row').appendChild(replay);
1498
+ async function demo() { C3 && C3.state('wave', true); await servosOn(); await move('home'); await move('wave', 8000); await move('home'); }
1499
+ busy(replay, demo);
1500
+ }
1501
+
1502
+ // ---- 4. yaw and pitch on each other's pins? (calibrate.py, check_swap)
1503
+ function stWires() {
1504
+ const [fa, sa] = fig('0 0 160 120'), [fb, sb] = fig('0 0 240 170');
1505
+ const ca = btn('', 'choice yes', () => answer(true)), cb = btn('', 'choice', () => answer(false));
1506
+ ca.append(fa.firstChild, document.createTextNode('Повернув голову вбік'));
1507
+ cb.append(fb.firstChild, document.createTextNode('Кивнув уперед'));
1508
+ const stopA = animate([P => drawFront(sa, P)], HOME, [22, 0, 65, 65]);
1509
+ const stopB = animate([P => drawSide(sb, P, 1)], HOME, [0, 14, 65, 65]);
1510
+ const [ft, st] = fig('0 0 160 170', 'згори: має бути так');
1511
+ const stopT = animate([P => drawTop(st, P[0])], HOME, [22, 0, 65, 65]);
1512
+ W.stop = () => { stopA(); stopB(); stopT(); };
1513
+ const note = h('<div class="note" hidden></div>');
1514
+ const replay = btn('Показати ще раз', 'ghost', () => busy(replay, show));
1515
+ frame({
1516
+ kick: 'Калібрування · проводи', title: 'Поворот чи кивок?',
1517
+ lead: 'Desky спробує <b>повернути голову вбік</b>. Якщо серво поворота й нахилу під\'єднані навпаки, замість цього він кивне. Що він зробив?',
1518
+ stage: views(ft), body: [h('<div class="choices"></div>'), note, replay],
1519
+ scene: { shot: 'yaw', glow: 0, run: c => c.loop(HOME, [22, 0, 65, 65]) }, cap: 'має бути так: поворот убік',
1520
+ foot: [back('check'), spacer(), btn('Пропустити крок', 'ghost', () => go('arms'))],
1521
+ });
1522
+ const ch = $('wizBody').querySelector('.choices'); ch.append(ca, cb);
1523
+ async function show() { await servosOn(); await demoMove('j1 25'); }
1524
+ async function answer(ok) {
1525
+ if (ok) { go('arms'); return; }
1526
+ if (W.retried) { note.hidden = false; note.className = 'note bad';
1527
+ note.textContent = 'Голова не повертається й після перестановки. Перевір серво J1 і J2 та їхні роз\'єми, потім пройди майстер ще раз.'; return; }
1528
+ W.retried = true;
1529
+ await busy(ca, async () => { await send('swap'); note.hidden = false; note.className = 'note'; note.textContent = 'Поміняв поворот і нахил місцями й зберіг. Дивись ще раз!'; await show(); });
1530
+ }
1531
+ busy(replay, show);
1532
+ }
1533
+
1534
+ // ---- 4b. the arms on each other's pins? Desky lifts his right arm; the other one rising means swapped plugs
1535
+ function stArms() {
1536
+ const [fa, sa] = fig('0 0 240 170', 'має піднятися ця рука');
1537
+ W.stop = animate([P => drawFront(sa, P)], HOME, [0, 0, 150, 65]);
1538
+ const note = h('<div class="note" hidden></div>');
1539
+ const replay = btn('Показати ще раз', 'ghost', () => busy(replay, show));
1540
+ const ca = btn('Так, ця', 'pri', () => answer(true));
1541
+ const cb = btn('Ні, інша', '', () => answer(false));
1542
+ frame({
1543
+ kick: 'Калібрування · руки', title: 'Яка рука піднялась?',
1544
+ lead: 'Desky підніме <b>праву руку</b>: свою праву, тобто ту, що <b>ліворуч від тебе</b>, коли він дивиться на тебе, як на малюнку. Якщо піднялась інша, серво рук під\'єднані навпаки.',
1545
+ stage: views(fa), body: [note, h('<div class="row"></div>')],
1546
+ scene: { shot: 'front', run: c => c.loop(HOME, [0, 0, 150, 65]) }, cap: 'має бути так',
1547
+ foot: [back('wires'), spacer(), btn('Пропустити крок', 'ghost', () => go('screen')), cb, ca],
1548
+ });
1549
+ $('wizBody').querySelector('.slot .row').appendChild(replay);
1550
+ async function show() { await servosOn(); await demoMove('j3 105'); }
1551
+ async function answer(ok) {
1552
+ if (ok) { go('screen'); return; }
1553
+ if (W.retried) { note.hidden = false; note.className = 'note bad';
1554
+ note.textContent = 'Знову не та рука. Перевір серво J3 і J4 та їхні роз\'єми, потім пройди майстер ще раз.'; return; }
1555
+ W.retried = true;
1556
+ await busy(cb, async () => { await send('aswap'); note.hidden = false; note.className = 'note'; note.textContent = 'Поміняв руки місцями й зберіг. Дивись ще раз!'; await show(); });
1557
+ }
1558
+ busy(replay, show);
1559
+ }
1560
+
1561
+ // ---- 5. the screen upside down? (calibrate.py, check_flip)
1562
+ function stScreen() {
1563
+ const P = PALETTE[COLOR];
1564
+ const up = (cls, d) => `<svg viewBox="0 0 64 40" class="${cls}"><rect width="64" height="40" rx="4" fill="${P.body}"/><g fill="${P.eye}">${
1565
+ [16, 48].map(x => [0, 1, 2, 3, 4, 5].map(i => `<rect x="${x - 6 + i}" y="${d ? 22 - i : 16 + i}" width="2" height="2"/><rect x="${x + i}" y="${d ? 17 + i : 21 - i}" width="2" height="2"/>`).join('')).join('')}</g></svg>`;
1566
+ const ca = btn(up('', true) + 'Кутиками вгору «^ ^»', 'choice yes', () => answer(true));
1567
+ const cb = btn(up('', false) + 'Кутиками вниз «v v»', 'choice', () => answer(false));
1568
+ const note = h('<div class="note" hidden></div>');
1569
+ frame({
1570
+ kick: 'Калібрування · екран', title: 'Подивись на екран',
1571
+ lead: 'Зараз на екрані Desky <b>усміхнені очі-галочки</b>. Якщо вони перевернуті, екран стоїть догори дриґом. Як вони виглядають?',
1572
+ stage: [bigFace('happy'), h('<div class="cap">так має бути</div>')], body: [h('<div class="choices"></div>'), note],
1573
+ scene: { shot: 'face', run: c => { c.pose(HOME); c.face('HAPPY'); } }, cap: 'так має бути',
1574
+ foot: [back('arms'), spacer(), btn('Пропустити крок', 'ghost', () => { send('face eyes'); go('j0'); })],
1575
+ });
1576
+ $('wizBody').querySelector('.choices').append(ca, cb);
1577
+ send('face happy');
1578
+ async function answer(ok) {
1579
+ if (ok) { await send('face eyes'); go('j0'); return; }
1580
+ if (W.retried) { note.hidden = false; note.className = 'note bad'; note.textContent = 'Екран і досі перевернутий? Перевір, чи на ньому взагалі щось видно, і спробуй ще раз.'; return; }
1581
+ W.retried = true;
1582
+ await busy(ca, async () => { await send('flip'); await send('face happy'); note.hidden = false; note.className = 'note'; note.textContent = 'Перевернув екран і зберіг. А тепер?'; });
1583
+ }
1584
+ }
1585
+
1586
+ // ---- 6. a joint's direction (calibrate.py, direction)
1587
+ function stDir(j) {
1588
+ const jj = J[j], A = HOME, B = poseWith(j, jj.base + jj.plus);
1589
+ const [f1, s1] = fig('0 0 160 120', 'в обличчя');
1590
+ const [f2, s2] = j === 0 ? fig('0 0 160 170', 'згори') : fig('0 0 240 170', 'збоку');
1591
+ W.stop = animate([P => drawFront(s1, P, j), P => j === 0 ? drawTop(s2, P[0]) : drawSide(s2, P, j)], A, B);
1592
+ const note = h('<div class="note" hidden></div>');
1593
+ const replay = btn('Показати ще раз', 'ghost', () => busy(replay, show));
1594
+ const yes = btn('Так, саме так', 'choice yes', () => answer(true)), no = btn('Ні, в інший бік', 'choice', () => answer(false));
1595
+ frame({
1596
+ kick: `Калібрування · ${jj.short} · напрямок`, title: `${jj.name}: куди рухається?`,
1597
+ lead: `Desky зробить невеликий рух, як на малюнку. ${jj.plusText}`,
1598
+ stage: views(f1, f2), body: [h('<div class="choices"></div>'), note, replay],
1599
+ scene: { shot: SHOT3[j], glow: j, run: c => c.loop(A, B) }, cap: 'має бути так',
1600
+ foot: [back(j === 0 ? 'screen' : 'j' + (j - 1)), spacer(), btn('Пропустити суглоб', 'ghost', () => go(j < 3 ? 'j' + (j + 1) : 'done'))],
1601
+ });
1602
+ $('wizBody').querySelector('.choices').append(yes, no);
1603
+ async function show() { await servosOn(); await demoMove('j' + jj.n + ' ' + (jj.base + jj.plus)); }
1604
+ async function answer(ok) {
1605
+ if (ok) { await send('home'); go('j' + j, 'centre'); return; }
1606
+ if (W.retried) { note.hidden = false; note.className = 'note bad';
1607
+ note.textContent = `${jj.name} і після розвороту рухається не туди. Можливо, рухається не той суглоб: перевір роз'єми серво.`; return; }
1608
+ W.retried = true;
1609
+ await busy(yes, async () => { await send('inv j' + jj.n); calDirty(true); note.hidden = false; note.className = 'note'; note.textContent = 'Розвернув напрямок. Дивись ще раз!'; await show(); });
1610
+ }
1611
+ busy(replay, show);
1612
+ }
1613
+
1614
+ // ---- 7. a joint's centre, live on a dial
1615
+ function stCentre(j) {
1616
+ const jj = J[j];
1617
+ const [f1, s1] = fig('0 0 160 120', 'в обличчя: має бути так');
1618
+ const [f2, s2] = j === 0 ? fig('0 0 160 170', 'згори') : fig('0 0 240 170', 'збоку');
1619
+ const ref = refPic(j);
1620
+ drawFront(s1, ref, j); j === 0 ? drawTop(s2, 0) : drawSide(s2, ref, j);
1621
+ W.orig = CAL[j].trim;
1622
+ const dial = makeDial(j);
1623
+ const done = btn('Рівно, далі', 'pri lg', async () => {
1624
+ await busy(done, async () => { await send('save'); calDirty(false); W.orig = null; await send('home'); });
1625
+ go(j < 3 ? 'j' + (j + 1) : 'done');
1626
+ });
1627
+ frame({
1628
+ kick: `Калібрування · ${jj.short} · центр`, title: 'Виставимо нуль',
1629
+ lead: `Desky став у нульове положення. Тягни повзунок, поки ${jj.refText}. Desky рухається разом із повзунком.`,
1630
+ stage: views(f1, f2), body: [dial],
1631
+ scene: { shot: j === 0 ? 'front' : SHOT3[j], glow: j, run: c => c.pose(ref) }, cap: 'нуль: має бути так',
1632
+ foot: [back('j' + j), spacer(), done],
1633
+ });
1634
+ W.onCal = k => { if (k === j) dial.sync(); };
1635
+ (async () => { await servosOn(); await toRef(j); await send('cal', true); })();
1636
+ setTimeout(() => dial.querySelector('input').focus(), 80);
1637
+ }
1638
+
1639
+ // ---- 8. done
1640
+ function stDone() {
1641
+ const face = bigFace('happy');
1642
+ const conf = document.createElement('div'); conf.className = 'confetti';
1643
+ const colors = [PALETTE[COLOR].body, css('--clawd'), '#F2B48F', '#3C8A55', '#9FC6F0', '#E6C15A'];
1644
+ for (let i = 0; i < 46; i++) { const c = document.createElement('i'); c.style.left = Math.random() * 100 + '%'; c.style.background = colors[i % colors.length];
1645
+ c.style.animationDelay = Math.random() * .8 + 's'; c.style.transform = `rotate(${Math.random() * 180}deg)`; conf.appendChild(c); }
1646
+ const s = frame({
1647
+ kick: 'Готово', title: 'Desky готовий до роботи!',
1648
+ lead: 'Усе збережено в платі. Тепер просто працюй у <b>Claude Code</b> або <b>Codex</b>, а Desky показуватиме, що відбувається: працює, читає, чекає на тебе.<br><br>Майстер завжди можна відкрити знову в боковій панелі.',
1649
+ stage: [face], scene: { shot: 'hero', run: c => c.state('done', true) }, cap: 'Desky радіє',
1650
+ foot: [spacer(), btn('Відкрити пульт', 'pri lg', () => wizClose(true))],
1651
+ });
1652
+ s.querySelector('.stage').style.position = 'relative'; s.querySelector('.stage').appendChild(conf);
1653
+ if (connected) (async () => { if (dirty) await send('save'); calDirty(false); await send('home'); await send('happy'); await send('sound done', true); })();
1654
+ }
1655
+
1656
+ let tab = 'home';
1657
+ try { tab = localStorage.getItem('clawd.tab') || 'home'; } catch (e) {}
1658
+ if (location.hash) tab = location.hash.slice(1);
1659
+ showTab(document.querySelector('[data-page="' + tab + '"]') ? tab : 'home');
1660
+ ['logo', 'bigface'].forEach(id => drawFace($(id), 'idle'));
1661
+ buildJoints(); calDirty(false); showMode(); refresh(); pollStatus(); pollLines();
1662
+ window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { applyColor(COLOR); refresh(); buildJoints(); });
1663
+ })();
1664
+ </script>
1665
+ </body>
1666
+ </html>