@hachej/boring-ui-kit 0.2.0 → 0.2.2
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/dist/canvas-editor-native.js +2 -2
- package/dist/experience-document-viewer.js +1 -1
- package/dist/file-tree-view.d.ts +3 -1
- package/dist/file-tree-view.js +5 -5
- package/dist/html-viewer.js +1 -1
- package/dist/markdown-editor.js +2 -2
- package/package.json +32 -31
- package/r/button.json +29 -0
- package/r/feedback-preview.json +20 -0
- package/r/feedback.json +688 -0
- package/r/file-tree.json +26 -0
- package/r/html-viewer.json +94 -0
- package/r/markdown-editor.json +216 -0
- package/r/pi-ambient.json +66 -0
- package/r/pi-app.json +102 -0
- package/r/pi-chat.json +246 -0
- package/r/pi-workspace.json +29 -0
- package/r/provider-setup.json +24 -0
- package/r/registry.json +2274 -0
- package/r/task-list-viewer.json +71 -0
- package/r/theme.json +76 -0
- package/r/utils.json +19 -0
- package/r/viewers.json +653 -0
package/r/file-tree.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "file-tree",
|
|
4
|
+
"title": "File tree",
|
|
5
|
+
"description": "Browse, search, upload and inspect retained versions through one revisionProvider binding.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"@hachej/boring-ui-kit@^0.2.2",
|
|
8
|
+
"@hachej/boring-files@^0.2.2",
|
|
9
|
+
"react@^19.0.0",
|
|
10
|
+
"radix-ui@^1.8.0",
|
|
11
|
+
"lucide-react@^1.51.0"
|
|
12
|
+
],
|
|
13
|
+
"registryDependencies": [
|
|
14
|
+
"@boring-ui/theme"
|
|
15
|
+
],
|
|
16
|
+
"files": [
|
|
17
|
+
{
|
|
18
|
+
"path": "registry/file-tree/file-tree.tsx",
|
|
19
|
+
"content": "'use client';\n\nimport '@hachej/boring-ui-kit/file-tree.css';\n\nexport { FileTree, FileTreeView } from '@hachej/boring-ui-kit/file-tree-view';\nexport type { FileTreeProps, FileTreeViewProps } from '@hachej/boring-ui-kit/file-tree-view';\nexport { createFileTreeController } from '@hachej/boring-ui-kit/file-tree';\nexport type { FileTreeController } from '@hachej/boring-ui-kit/file-tree';\n",
|
|
20
|
+
"type": "registry:component",
|
|
21
|
+
"target": "components/file-tree/file-tree.tsx"
|
|
22
|
+
}
|
|
23
|
+
],
|
|
24
|
+
"css": {},
|
|
25
|
+
"type": "registry:component"
|
|
26
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "html-viewer",
|
|
4
|
+
"title": "HTML source and passive preview",
|
|
5
|
+
"description": "Exact HTML source editing with a reconstructed passive preview and borrowed controller. Browser security qualification remains separate.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"@hachej/boring-ui-kit@^0.2.2",
|
|
8
|
+
"@hachej/boring-files@^0.2.2",
|
|
9
|
+
"react@^19.0.0",
|
|
10
|
+
"react-dom@^19.0.0"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "registry/html-viewer/html-viewer.tsx",
|
|
15
|
+
"content": "'use client';\n\nimport { HtmlViewer as RuntimeHtmlViewer } from '@hachej/boring-ui-kit/html-viewer';\nimport type { HtmlViewerProps } from '@hachej/boring-ui-kit/html-viewer';\n\nexport type { HtmlViewerProps } from '@hachej/boring-ui-kit/html-viewer';\n\nexport function HtmlViewer({ className, ...props }: HtmlViewerProps) {\n return <RuntimeHtmlViewer {...props} className={['boring-html-recipe', className].filter(Boolean).join(' ')} />;\n}\n",
|
|
16
|
+
"type": "registry:component",
|
|
17
|
+
"target": "components/html-viewer/html-viewer.tsx"
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
"css": {
|
|
21
|
+
".boring-html-recipe[data-boring=\"html-viewer\"]": {
|
|
22
|
+
"background": "var(--boring-html-background, var(--background, #fff))",
|
|
23
|
+
"color": "var(--boring-html-foreground, var(--foreground, #111827))",
|
|
24
|
+
"border": "1px solid var(--boring-html-border, var(--border, #d1d5db))",
|
|
25
|
+
"border-radius": "var(--boring-html-radius, var(--radius, 0.75rem))",
|
|
26
|
+
"padding": "1rem",
|
|
27
|
+
"display": "grid",
|
|
28
|
+
"gap": "0.75rem",
|
|
29
|
+
"min-width": "0",
|
|
30
|
+
"font-family": "inherit"
|
|
31
|
+
},
|
|
32
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] > header": {
|
|
33
|
+
"display": "flex",
|
|
34
|
+
"justify-content": "space-between",
|
|
35
|
+
"align-items": "center",
|
|
36
|
+
"flex-wrap": "wrap",
|
|
37
|
+
"gap": "0.75rem"
|
|
38
|
+
},
|
|
39
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] [role=\"toolbar\"]": {
|
|
40
|
+
"display": "flex",
|
|
41
|
+
"flex-wrap": "wrap",
|
|
42
|
+
"gap": "0.375rem"
|
|
43
|
+
},
|
|
44
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] button": {
|
|
45
|
+
"font": "inherit",
|
|
46
|
+
"background": "var(--boring-html-background, var(--background, #fff))",
|
|
47
|
+
"color": "var(--boring-html-foreground, var(--foreground, #111827))",
|
|
48
|
+
"border": "1px solid var(--boring-html-border, var(--border, #d1d5db))",
|
|
49
|
+
"border-radius": "0.375rem",
|
|
50
|
+
"padding": "0.375rem 0.625rem",
|
|
51
|
+
"cursor": "pointer"
|
|
52
|
+
},
|
|
53
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] button[aria-pressed=\"true\"]": {
|
|
54
|
+
"font-weight": "700",
|
|
55
|
+
"text-decoration": "underline"
|
|
56
|
+
},
|
|
57
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] button:disabled": {
|
|
58
|
+
"opacity": "0.5",
|
|
59
|
+
"cursor": "not-allowed"
|
|
60
|
+
},
|
|
61
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] button:focus-visible, .boring-html-recipe[data-boring=\"html-viewer\"] textarea:focus-visible": {
|
|
62
|
+
"outline": "2px solid var(--boring-html-focus, var(--ring, #2563eb))",
|
|
63
|
+
"outline-offset": "2px"
|
|
64
|
+
},
|
|
65
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] .boring-html-viewer__source": {
|
|
66
|
+
"box-sizing": "border-box",
|
|
67
|
+
"width": "100%",
|
|
68
|
+
"min-height": "18rem",
|
|
69
|
+
"font-family": "monospace",
|
|
70
|
+
"line-height": "1.5",
|
|
71
|
+
"background": "var(--boring-html-background, var(--background, #fff))",
|
|
72
|
+
"color": "var(--boring-html-foreground, var(--foreground, #111827))",
|
|
73
|
+
"padding": "0.75rem",
|
|
74
|
+
"border": "1px solid var(--boring-html-border, var(--border, #d1d5db))",
|
|
75
|
+
"border-radius": "0.375rem",
|
|
76
|
+
"resize": "vertical"
|
|
77
|
+
},
|
|
78
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] .boring-html-viewer__frame": {
|
|
79
|
+
"box-sizing": "border-box",
|
|
80
|
+
"width": "100%",
|
|
81
|
+
"min-height": "18rem",
|
|
82
|
+
"border": "1px solid var(--boring-html-border, var(--border, #d1d5db))",
|
|
83
|
+
"border-radius": "0.375rem"
|
|
84
|
+
},
|
|
85
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] [role=\"status\"]": {
|
|
86
|
+
"font-size": "0.875rem"
|
|
87
|
+
},
|
|
88
|
+
".boring-html-recipe[data-boring=\"html-viewer\"] [role=\"alert\"]": {
|
|
89
|
+
"border-inline-start": "0.25rem solid currentColor",
|
|
90
|
+
"padding-inline-start": "0.75rem"
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
"type": "registry:component"
|
|
94
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "markdown-editor",
|
|
4
|
+
"title": "Markdown editor",
|
|
5
|
+
"description": "A host-owned styled wrapper over the concrete borrowed Markdown controller.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"@hachej/boring-ui-kit@^0.2.2",
|
|
8
|
+
"@hachej/boring-files@^0.2.2",
|
|
9
|
+
"react@^19.0.0",
|
|
10
|
+
"react-dom@^19.0.0",
|
|
11
|
+
"marked@^17.0.6",
|
|
12
|
+
"@tiptap/core@^3.31.4",
|
|
13
|
+
"@tiptap/react@^3.31.4",
|
|
14
|
+
"@tiptap/pm@^3.31.4",
|
|
15
|
+
"@tiptap/starter-kit@^3.31.4",
|
|
16
|
+
"@tiptap/markdown@^3.31.4",
|
|
17
|
+
"@tiptap/extensions@^3.31.4",
|
|
18
|
+
"@tiptap/extension-list@^3.31.4",
|
|
19
|
+
"@tiptap/extension-table@^3.31.4",
|
|
20
|
+
"@tiptap/extension-image@^3.31.4",
|
|
21
|
+
"@tiptap/extension-highlight@^3.31.4",
|
|
22
|
+
"@tiptap/extension-bubble-menu@^3.31.4",
|
|
23
|
+
"@tiptap/extension-floating-menu@^3.31.4"
|
|
24
|
+
],
|
|
25
|
+
"files": [
|
|
26
|
+
{
|
|
27
|
+
"path": "registry/markdown-editor/markdown-editor.tsx",
|
|
28
|
+
"content": "'use client';\n\nimport { MarkdownEditor as RuntimeMarkdownEditor } from '@hachej/boring-ui-kit/markdown-editor';\nimport type { MarkdownEditorProps } from '@hachej/boring-ui-kit/markdown-editor';\n\nexport type { MarkdownEditorProps } from '@hachej/boring-ui-kit/markdown-editor';\n\nexport function MarkdownEditor({ className, ...props }: MarkdownEditorProps) {\n return <RuntimeMarkdownEditor {...props} className={['boring-markdown-recipe', className].filter(Boolean).join(' ')} />;\n}\n",
|
|
29
|
+
"type": "registry:component",
|
|
30
|
+
"target": "components/markdown-editor/markdown-editor.tsx"
|
|
31
|
+
}
|
|
32
|
+
],
|
|
33
|
+
"css": {
|
|
34
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"]": {
|
|
35
|
+
"background": "var(--boring-editor-background, var(--background, #fff))",
|
|
36
|
+
"color": "var(--boring-editor-foreground, var(--foreground, #111827))",
|
|
37
|
+
"border": "1px solid var(--boring-editor-border, var(--border, #d1d5db))",
|
|
38
|
+
"border-radius": "var(--boring-editor-radius, var(--radius, 0.75rem))",
|
|
39
|
+
"padding": "1rem",
|
|
40
|
+
"display": "grid",
|
|
41
|
+
"gap": "1rem",
|
|
42
|
+
"min-width": "0",
|
|
43
|
+
"font-family": "inherit"
|
|
44
|
+
},
|
|
45
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] > header": {
|
|
46
|
+
"display": "flex",
|
|
47
|
+
"align-items": "center",
|
|
48
|
+
"justify-content": "space-between",
|
|
49
|
+
"flex-wrap": "wrap",
|
|
50
|
+
"gap": "0.75rem"
|
|
51
|
+
},
|
|
52
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] > header > strong": {
|
|
53
|
+
"margin": "0",
|
|
54
|
+
"font-size": "1.125rem",
|
|
55
|
+
"font-weight": "600"
|
|
56
|
+
},
|
|
57
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] [role=\"toolbar\"]": {
|
|
58
|
+
"display": "flex",
|
|
59
|
+
"flex-wrap": "wrap",
|
|
60
|
+
"gap": "0.375rem"
|
|
61
|
+
},
|
|
62
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] button": {
|
|
63
|
+
"appearance": "none",
|
|
64
|
+
"font": "inherit",
|
|
65
|
+
"font-size": "0.875rem",
|
|
66
|
+
"line-height": "1.4",
|
|
67
|
+
"background": "var(--boring-editor-control-background, var(--background, #fff))",
|
|
68
|
+
"color": "inherit",
|
|
69
|
+
"border": "1px solid var(--boring-editor-border, var(--border, #d1d5db))",
|
|
70
|
+
"border-radius": "0.375rem",
|
|
71
|
+
"padding": "0.375rem 0.625rem",
|
|
72
|
+
"cursor": "pointer"
|
|
73
|
+
},
|
|
74
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] button[aria-pressed=\"true\"]": {
|
|
75
|
+
"background": "var(--boring-editor-accent, var(--accent, #e5e7eb))",
|
|
76
|
+
"font-weight": "600"
|
|
77
|
+
},
|
|
78
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] button:disabled": {
|
|
79
|
+
"opacity": "0.5",
|
|
80
|
+
"cursor": "not-allowed"
|
|
81
|
+
},
|
|
82
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] button:focus-visible, .boring-markdown-recipe[data-boring=\"markdown-editor\"] textarea:focus-visible": {
|
|
83
|
+
"outline": "2px solid var(--boring-editor-focus, var(--ring, #2563eb))",
|
|
84
|
+
"outline-offset": "2px"
|
|
85
|
+
},
|
|
86
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] [role=\"status\"]": {
|
|
87
|
+
"font-size": "0.875rem",
|
|
88
|
+
"color": "var(--boring-editor-muted, var(--muted-foreground, #4b5563))"
|
|
89
|
+
},
|
|
90
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] nav[aria-label=\"Document outline\"]": {
|
|
91
|
+
"border-bottom": "1px solid var(--boring-editor-border, var(--border, #d1d5db))",
|
|
92
|
+
"padding-bottom": "0.75rem"
|
|
93
|
+
},
|
|
94
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] nav ol": {
|
|
95
|
+
"padding-left": "1.25rem",
|
|
96
|
+
"margin": "0",
|
|
97
|
+
"display": "grid",
|
|
98
|
+
"gap": "0.25rem"
|
|
99
|
+
},
|
|
100
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content": {
|
|
101
|
+
"min-height": "12rem",
|
|
102
|
+
"max-width": "75ch",
|
|
103
|
+
"width": "100%",
|
|
104
|
+
"margin-inline": "auto",
|
|
105
|
+
"line-height": "1.7",
|
|
106
|
+
"overflow-wrap": "anywhere"
|
|
107
|
+
},
|
|
108
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content p": {
|
|
109
|
+
"margin": "0.75rem 0"
|
|
110
|
+
},
|
|
111
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content h1": {
|
|
112
|
+
"font-size": "1.875rem",
|
|
113
|
+
"line-height": "1.2",
|
|
114
|
+
"margin": "1.25rem 0 0.75rem",
|
|
115
|
+
"font-weight": "700"
|
|
116
|
+
},
|
|
117
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content h2": {
|
|
118
|
+
"font-size": "1.5rem",
|
|
119
|
+
"line-height": "1.3",
|
|
120
|
+
"margin": "1.25rem 0 0.75rem",
|
|
121
|
+
"font-weight": "650"
|
|
122
|
+
},
|
|
123
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content h3": {
|
|
124
|
+
"font-size": "1.25rem",
|
|
125
|
+
"margin": "1rem 0 0.5rem",
|
|
126
|
+
"font-weight": "600"
|
|
127
|
+
},
|
|
128
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content ul": {
|
|
129
|
+
"list-style": "disc",
|
|
130
|
+
"padding-left": "1.5rem"
|
|
131
|
+
},
|
|
132
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content ol": {
|
|
133
|
+
"list-style": "decimal",
|
|
134
|
+
"padding-left": "1.5rem"
|
|
135
|
+
},
|
|
136
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content ul[data-type=\"taskList\"]": {
|
|
137
|
+
"list-style": "none",
|
|
138
|
+
"padding-left": "0"
|
|
139
|
+
},
|
|
140
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content li[data-type=\"taskItem\"]": {
|
|
141
|
+
"display": "flex",
|
|
142
|
+
"gap": "0.5rem",
|
|
143
|
+
"align-items": "baseline"
|
|
144
|
+
},
|
|
145
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content blockquote": {
|
|
146
|
+
"border-left": "3px solid var(--boring-editor-border, var(--border, #d1d5db))",
|
|
147
|
+
"padding-left": "1rem",
|
|
148
|
+
"margin-inline": "0",
|
|
149
|
+
"color": "var(--boring-editor-muted, var(--muted-foreground, #4b5563))"
|
|
150
|
+
},
|
|
151
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content pre, .boring-markdown-recipe[data-boring=\"markdown-editor\"] [data-boring=\"proposal\"] pre": {
|
|
152
|
+
"overflow-x": "auto",
|
|
153
|
+
"background": "var(--boring-editor-code-background, var(--muted, #f3f4f6))",
|
|
154
|
+
"border-radius": "0.375rem",
|
|
155
|
+
"padding": "0.75rem",
|
|
156
|
+
"font-family": "ui-monospace, monospace"
|
|
157
|
+
},
|
|
158
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content code": {
|
|
159
|
+
"font-family": "ui-monospace, monospace",
|
|
160
|
+
"font-size": "0.9em"
|
|
161
|
+
},
|
|
162
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] > textarea": {
|
|
163
|
+
"width": "100%",
|
|
164
|
+
"min-height": "16rem",
|
|
165
|
+
"resize": "vertical",
|
|
166
|
+
"font-family": "ui-monospace, monospace",
|
|
167
|
+
"font-size": "0.875rem",
|
|
168
|
+
"line-height": "1.6",
|
|
169
|
+
"padding": "0.75rem",
|
|
170
|
+
"background": "inherit",
|
|
171
|
+
"color": "inherit",
|
|
172
|
+
"border": "1px solid var(--boring-editor-border, var(--border, #d1d5db))",
|
|
173
|
+
"border-radius": "0.375rem",
|
|
174
|
+
"box-sizing": "border-box"
|
|
175
|
+
},
|
|
176
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] [role=\"alert\"]": {
|
|
177
|
+
"border-left": "3px solid var(--boring-editor-danger, var(--destructive, #b91c1c))",
|
|
178
|
+
"padding": "0.75rem",
|
|
179
|
+
"overflow-wrap": "anywhere"
|
|
180
|
+
},
|
|
181
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] [data-boring=\"proposal\"]": {
|
|
182
|
+
"border": "1px solid var(--boring-editor-border, var(--border, #d1d5db))",
|
|
183
|
+
"padding": "0.75rem",
|
|
184
|
+
"border-radius": "0.375rem"
|
|
185
|
+
},
|
|
186
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] [data-boring=\"proposal\"] summary": {
|
|
187
|
+
"cursor": "pointer",
|
|
188
|
+
"font-weight": "600"
|
|
189
|
+
},
|
|
190
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] .boring-markdown-content:focus-visible": {
|
|
191
|
+
"outline": "2px solid var(--boring-editor-focus, var(--ring, #2563eb))",
|
|
192
|
+
"outline-offset": "2px"
|
|
193
|
+
},
|
|
194
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] [data-boring=\"proposal-diff\"]": {
|
|
195
|
+
"font-family": "ui-monospace, monospace",
|
|
196
|
+
"font-size": "0.875rem",
|
|
197
|
+
"line-height": "1.5",
|
|
198
|
+
"overflow-x": "auto"
|
|
199
|
+
},
|
|
200
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] [data-diff]": {
|
|
201
|
+
"white-space": "pre-wrap",
|
|
202
|
+
"overflow-wrap": "anywhere",
|
|
203
|
+
"padding": "0.125rem 0.375rem"
|
|
204
|
+
},
|
|
205
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] [data-diff=\"add\"]": {
|
|
206
|
+
"background": "var(--boring-editor-diff-add-background, #ecfdf5)",
|
|
207
|
+
"color": "var(--boring-editor-diff-add-foreground, #065f46)"
|
|
208
|
+
},
|
|
209
|
+
".boring-markdown-recipe[data-boring=\"markdown-editor\"] [data-diff=\"remove\"]": {
|
|
210
|
+
"background": "var(--boring-editor-diff-remove-background, #fff1f2)",
|
|
211
|
+
"color": "var(--boring-editor-diff-remove-foreground, #9f1239)"
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
"docs": "Create and own a MarkdownController from @hachej/boring-ui-kit/markdown. Pass it to MarkdownEditor. The wrapper does not acquire resources or dispose the controller. Check the repository release notes for available npm versions; local tarball tests do not establish registry availability.",
|
|
215
|
+
"type": "registry:component"
|
|
216
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "pi-ambient",
|
|
4
|
+
"title": "Pi ambient agent",
|
|
5
|
+
"description": "AmbientChat, a compact floating agent bar that grows into a chat window over an existing page, and AgentNotifications, toasts for finished, failed and waiting tasks (with the one guarded browser Notification helper). A block over the pi-chat item; its in-window artifact panel uses the pi-workspace layout.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"@hachej/boring-ui-kit@^0.2.2",
|
|
8
|
+
"react@^19.0.0",
|
|
9
|
+
"react-dom@^19.0.0",
|
|
10
|
+
"@earendil-works/pi-durable@^1.1.0",
|
|
11
|
+
"@earendil-works/pi-ai@^1.1.0",
|
|
12
|
+
"lucide-react@^1.51.0"
|
|
13
|
+
],
|
|
14
|
+
"registryDependencies": [
|
|
15
|
+
"@boring-ui/pi-chat",
|
|
16
|
+
"@boring-ui/pi-workspace",
|
|
17
|
+
"@boring-ui/utils",
|
|
18
|
+
"@boring-ui/button"
|
|
19
|
+
],
|
|
20
|
+
"files": [
|
|
21
|
+
{
|
|
22
|
+
"path": "registry/pi-ambient/ambient.tsx",
|
|
23
|
+
"content": "'use client';\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { KeyboardEvent, PointerEvent, ReactNode } from 'react';\nimport type { EntryRecord } from '@earendil-works/pi-durable';\nimport type { ImageContent, ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { BellIcon, ChevronDownIcon, ExternalLinkIcon, GripVerticalIcon, Loader2Icon, MinusIcon, PanelLeftIcon, ThumbsDownIcon, ThumbsUpIcon } from 'lucide-react';\nimport { Button } from '../button/button';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction, BlockIcon } from '../button/actions';\nimport { CopyButton } from '../pi-chat/code-block';\nimport { Composer } from '../pi-chat/composer';\nimport type { ComposerFeedback } from '../pi-chat/composer';\nimport type { AttachmentsConfig, ConversationsConfig, EffortConfig, MentionsConfig, ModelConfig, SlashConfig } from '../pi-chat/config';\nimport { notifyPermission, requestNotifyPermission } from './browser-notify';\nimport type { NotifyPermission } from './browser-notify';\nimport { ConversationHistory } from '../pi-chat/history';\nimport type { CommandMentions } from '../pi-chat/markdown';\nimport { RowView } from '../pi-chat/message';\nimport type { RowContext } from '../pi-chat/message';\nimport { ChatNotices, Notice } from '../pi-chat/notice';\nimport { AgentNotifications, KindIcon, createNotificationStore, defaultNotificationLabels, finishNotice, pendingQuestion, useNotifications } from './notifications';\nimport type { AgentNotification, NotificationLabels, NotificationStore } from './notifications';\nimport { ChatTextProvider, defaultChatIcons, defaultChatLabels, useMergedText } from '../pi-chat/labels';\nimport type { ChatIcons, ChatLabels } from '../pi-chat/labels';\nimport { MessageQueue } from '../pi-chat/queue';\nimport { artifactKey, collectArtifacts } from '../pi-chat/artifact';\nimport type { ArtifactDescriptor, ArtifactsConfig } from '../pi-chat/artifact';\nimport type { ChatCard, Mode } from '../pi-chat/rows';\nimport { useChatSession, useTranscript } from '../pi-chat/session';\nimport type { ChatFeatureProps, ChatSession } from '../pi-chat/session';\nimport { ArtifactWorkspace } from '../pi-workspace/workspace';\nimport type { WorkspacePanelApi } from '../pi-workspace/workspace';\nimport { cn } from '../utils/utils';\n\nexport { AgentNotifications, createNotificationStore, defaultNotificationLabels, summaryOf, useNotifications, watchConversation } from './notifications';\nexport type { AgentNotification, AgentNotificationsProps, NewNotification, NotificationKind, NotificationLabels, NotificationStore } from './notifications';\n\nconst elapsedText = (seconds: number) => seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`;\n\n/** The floating window's own words, over the chat's (`defaultChatLabels`) and the toasts' (`defaultNotificationLabels`). */\nexport const defaultAmbientLabels = {\n ...defaultChatLabels,\n ...defaultNotificationLabels,\n /** Shown while the conversation has no title of its own (the active item of `conversations` provides one). */\n title: 'Agent',\n /** The input's placeholder while idle. */\n placeholder: 'Do anything',\n /** The input's placeholder while the agent works. */\n working: (seconds: number) => `Working for ${elapsedText(seconds)}`,\n region: (title: string) => `Agent: ${title}`,\n openAgent: (title: string, unread: boolean) => `Open agent: ${title}${unread ? ' (new activity)' : ''}`,\n openChat: (title: string) => `Open chat: ${title}`,\n minimize: 'Minimise',\n switchConversation: 'Switch conversation',\n statusWorking: 'Working',\n enableNotifications: 'Notify me when the page is in the background',\n dock: 'Dock chat',\n dockHint: 'Dock chat beside the panel',\n move: 'Move the agent window (arrow keys, Home resets)',\n moveHint: 'Drag to move',\n goodResponse: 'Good response',\n badResponse: 'Bad response',\n openFull: 'Open in full chat',\n empty: 'Ask the agent to do something.',\n loadFailedShort: 'Could not load the conversation.',\n disconnectedShort: 'Disconnected.',\n artifactPanel: 'Artifact panel',\n};\nexport type AmbientLabels = ChatLabels & NotificationLabels & typeof defaultAmbientLabels;\n\n/** The floating window's icons, over the chat's. */\nexport const defaultAmbientIcons = {\n ...defaultChatIcons,\n minimize: MinusIcon as BlockIcon,\n dock: PanelLeftIcon as BlockIcon,\n grip: GripVerticalIcon as BlockIcon,\n switchConversation: ChevronDownIcon as BlockIcon,\n notify: BellIcon as BlockIcon,\n openFull: ExternalLinkIcon as BlockIcon,\n goodResponse: ThumbsUpIcon as BlockIcon,\n badResponse: ThumbsDownIcon as BlockIcon,\n};\nexport type AmbientIcons = ChatIcons & typeof defaultAmbientIcons;\nconst AMBIENT_TEXT = { labels: defaultAmbientLabels as AmbientLabels, icons: defaultAmbientIcons as AmbientIcons };\n\n/** `bar` is the compact bar, `expanded` the same window grown into a chat, `minimized` a small pill. */\nexport type AmbientState = 'bar' | 'expanded' | 'minimized';\n\n/** What the artifact panel inside the window gets besides the full-screen and close controls: the versions of the open artifact and how to switch. */\nexport interface AmbientArtifactPanelApi extends WorkspacePanelApi {\n /** Every known version of the open artifact in this conversation, newest first. */\n readonly versions: readonly ArtifactDescriptor[];\n /** True while the panel follows the newest version; false when one older version is pinned. */\n readonly follow: boolean;\n /** `'latest'` follows the newest version; a descriptor from `versions` pins that one. */\n readonly select: (version: ArtifactDescriptor | 'latest') => void;\n}\n\nexport interface AmbientChatProps extends ChatFeatureProps {\n readonly controller: NativeChatController;\n /**\n * Every word the window shows, over `defaultAmbientLabels` (the chat's labels, the toasts' and its own): `title` while the conversation has\n * none of its own, `placeholder` while idle, `working(seconds)` while the agent works.\n */\n readonly labels?: Partial<AmbientLabels> | undefined;\n /** The window's icons (minimise, dock, grip, …) and the chat's, over `defaultAmbientIcons`. */\n readonly icons?: Partial<AmbientIcons> | undefined;\n /** The agent's avatar before the title in the bar. */\n readonly avatar?: ReactNode;\n /** Host actions in the bar, before Dock: `header` ones as buttons, `menu` ones in a \"…\" menu. Test ids `ambient-action-<id>`, the menu `ambient-action-more`. */\n readonly headerActions?: readonly BlockAction[] | undefined;\n /** `contrast` is a dark window on any page; `surface` follows the host's background. */\n readonly variant?: 'contrast' | 'surface';\n /** Controlled window state; otherwise `defaultState` starts it and the window keeps it. */\n readonly state?: AmbientState;\n readonly defaultState?: AmbientState;\n readonly onStateChange?: (state: AmbientState) => void;\n /** Where the bar was dragged is remembered under this key. */\n readonly storageKey?: string;\n /** `session` (default) remembers the position for this browser tab's session; `local` keeps it in `localStorage` across sessions. */\n readonly storage?: 'session' | 'local';\n /** Host controls in the composer row, between the effort picker and Send (for example a voice button the host guards itself). Absent: nothing is shown. */\n readonly tools?: ReactNode;\n /** Hand the conversation to a full `PiChat` or `ArtifactWorkspace`. Adds an \"Open in full chat\" action to replies. */\n readonly onOpenFull?: (conversationId: string) => void;\n /** Adds thumbs up and down to replies. `value` is `null` when the person takes the rating back. */\n readonly onFeedback?: (reply: { readonly key: string; readonly text: string }, value: 'up' | 'down' | null) => void;\n /** Toasts for finished, failed and waiting tasks. Pass a store to feed it for background conversations too; `false` turns them off. */\n readonly notifications?: NotificationStore | false;\n readonly autoDismissMs?: number;\n readonly maxToasts?: number;\n /** System notifications while the page is hidden. A bell in the header asks for permission when the person chooses to; nothing is asked on load. */\n readonly systemNotifications?: boolean;\n /**\n * The viewer shown inside the window when an artifact card is opened: the window widens into chat on the left and this panel on the right\n * (`ArtifactWorkspace`: draggable divider, full screen, a full-screen sheet on a phone). Build it from the viewer registry (`ViewerFrame`, ...),\n * wrapped in `ViewerWindowProvider` with `api.fullscreen` / `api.onFullscreenChange` so its bar shows the full screen button.\n */\n readonly artifactPanel?: (artifact: ArtifactDescriptor, api: AmbientArtifactPanelApi) => ReactNode;\n /** `window` (default when `artifactPanel` is given) opens artifacts inside the window; `host` calls `artifacts.open` instead, for hosts that show them in their own viewer. */\n readonly artifactTarget?: 'window' | 'host';\n /** The title's ⌄ opens this list to switch conversations or tasks. */\n readonly conversations?: ConversationsConfig;\n /** Adds a \"Dock chat\" action to the header, for a host that floats this window out of a docked chat (`ArtifactWorkspace` with `floatBelow`). It shares the controller with the docked `PiChat`, so nothing is lost. */\n readonly onDock?: () => void;\n /** The optional Feedback button in the composer (the registry `feedback` item's `useComposerFeedback`). Omit it and nothing changes. */\n readonly feedback?: ComposerFeedback;\n readonly className?: string;\n}\n\ninterface Position { readonly right: number; readonly bottom: number }\nconst MARGIN = 8, DEFAULT_POSITION: Position = { right: 16, bottom: 16 };\n\nfunction storageFor(persist: 'session' | 'local'): Storage | undefined { try { return persist === 'local' ? globalThis.localStorage : globalThis.sessionStorage; } catch { return undefined; } }\nfunction readPosition(key: string, persist: 'session' | 'local'): Position | undefined {\n try {\n const value: unknown = JSON.parse(storageFor(persist)?.getItem(key) ?? 'null');\n const { right, bottom } = (value ?? {}) as { right?: unknown; bottom?: unknown };\n return typeof right === 'number' && typeof bottom === 'number' && Number.isFinite(right) && Number.isFinite(bottom) ? { right, bottom } : undefined;\n } catch { return undefined; }\n}\nfunction writePosition(key: string, persist: 'session' | 'local', position: Position) {\n try { storageFor(persist)?.setItem(key, JSON.stringify(position)); } catch { /* the position is a convenience */ }\n}\nconst clamp = (position: Position, size: { w: number; h: number }, viewport: { w: number; h: number }): Position => ({\n right: Math.round(Math.min(Math.max(MARGIN, position.right), Math.max(MARGIN, viewport.w - size.w - MARGIN))),\n bottom: Math.round(Math.min(Math.max(MARGIN, position.bottom), Math.max(MARGIN, viewport.h - size.h - MARGIN))),\n});\n\n// The layout viewport that fixed positioning uses (without scrollbars), not the window's outer size.\nconst viewportSize = () => { const root = globalThis.document?.documentElement; return { w: root?.clientWidth || globalThis.innerWidth || 1024, h: root?.clientHeight || globalThis.innerHeight || 768 }; };\nfunction usePhone(): boolean {\n const query = '(max-width: 639px)';\n const [phone, setPhone] = useState(() => globalThis.matchMedia?.(query).matches === true);\n useEffect(() => {\n const list = globalThis.matchMedia?.(query);\n if (!list) return;\n const update = () => setPhone(list.matches);\n update();\n list.addEventListener('change', update);\n return () => list.removeEventListener('change', update);\n }, []);\n return phone;\n}\n\n/** Whole seconds since `active` became true; 0 while inactive. */\nfunction useElapsed(active: boolean): number {\n const [seconds, setSeconds] = useState(0);\n useEffect(() => {\n if (!active) { setSeconds(0); return; }\n const started = Date.now();\n setSeconds(0);\n const timer = setInterval(() => setSeconds(Math.floor((Date.now() - started) / 1000)), 1000);\n return () => clearInterval(timer);\n }, [active]);\n return seconds;\n}\n\n/** Pushes a toast when a run finishes or fails and when a question starts waiting; takes it back when the question is answered or a new run starts. */\nfunction useRunFeed({ enabled, store, conversationId, title, session, suppress, onOutcome, waiting }: {\n readonly enabled: boolean; readonly store: NotificationStore; readonly conversationId: string; readonly title: string; readonly session: ChatSession; readonly waiting: string;\n readonly suppress: () => boolean; readonly onOutcome: (outcome: 'done' | 'error' | null) => void;\n}) {\n const { working, waitingForAnswer, rows, connected } = session;\n const before = useRef({ working, waiting: waitingForAnswer });\n const latest = useRef({ rows, title, suppress, onOutcome, connected, waiting });\n latest.current = { rows, title, suppress, onOutcome, connected, waiting };\n useEffect(() => {\n const was = before.current;\n before.current = { working, waiting: waitingForAnswer };\n const now = latest.current;\n if (working && !was.working) { now.onOutcome(null); store.dismiss(`${conversationId}:done`); }\n if (!enabled) return;\n if (waitingForAnswer && !was.waiting && !now.suppress()) store.push({ id: `${conversationId}:input`, kind: 'input', title: now.title, summary: pendingQuestion(now.rows) ?? now.waiting, conversationId });\n if (!waitingForAnswer && was.waiting) store.dismiss(`${conversationId}:input`);\n if (was.working && !working && now.connected) {\n const finished = finishNotice(now.rows);\n if (!finished) return;\n now.onOutcome(finished.kind);\n if (!now.suppress()) store.push({ id: `${conversationId}:done`, kind: finished.kind, title: now.title, summary: finished.summary, conversationId });\n }\n }, [working, waitingForAnswer, enabled, store, conversationId]);\n}\n\n/** A compact floating agent bar over an existing page; it grows into a chat window in place. Borrows a concrete native controller like `PiChat`. */\nexport function AmbientChat(props: AmbientChatProps) {\n const active = useRef(props.controller); active.current = props.controller;\n const [mount, setMount] = useState({ controller: props.controller, sequence: 0 });\n if (mount.controller !== props.controller) setMount({ controller: props.controller, sequence: mount.sequence + 1 });\n // The window state and the toasts belong to the bar, not to one conversation: they survive switching conversations.\n const [local, setLocal] = useState<AmbientState>(props.defaultState ?? 'bar');\n const internalStore = useMemo(createNotificationStore, []);\n const text = useMergedText<AmbientLabels, AmbientIcons>(props.labels, props.icons, AMBIENT_TEXT);\n return <ChatTextProvider value={text}><AmbientSession key={mount.sequence} {...props} labels={text.labels} icons={text.icons} activeController={active} windowState={props.state ?? local} store={props.notifications || internalStore}\n onWindowState={next => { if (props.state === undefined) setLocal(next); props.onStateChange?.(next); }} /></ChatTextProvider>;\n}\n\nconst iconButton = 'inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 max-sm:size-11 pointer-coarse:size-11 motion-reduce:transition-none';\n\ntype SessionProps = Omit<AmbientChatProps, 'labels' | 'icons'> & { readonly labels: AmbientLabels; readonly icons: AmbientIcons; readonly activeController: { readonly current: NativeChatController }; readonly windowState: AmbientState; readonly store: NotificationStore; readonly onWindowState: (state: AmbientState) => void };\n\nfunction AmbientSession({ controller, labels, icons, avatar, headerActions, messageActions, variant = 'contrast', mode = 'expert', actions,\n windowState, onWindowState, store, storageKey = 'boring.ambient.position', storage = 'session', tools, onOpenFull, onFeedback, notifications, autoDismissMs, maxToasts, systemNotifications = false,\n renderEntry, renderTool, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, fileAccept = 'image/*', slash, mentions, attachments, model, effort, replyFooter, artifacts: hostArtifacts, artifactPanel, artifactTarget, conversations, onDock, feedback: composerFeedback, className,\n activeController }: SessionProps) {\n const { title } = labels;\n const stateRef = useRef(windowState); stateRef.current = windowState;\n // The artifact open inside the window, and whether it follows the newest version. It belongs to the expanded window: leaving that state closes it.\n const [opened, setOpened] = useState<{ readonly descriptor: ArtifactDescriptor; readonly follow: boolean } | null>(null);\n const [fullscreen, setFullscreen] = useState(false);\n const setWindowState = (next: AmbientState) => {\n if (next !== 'expanded') { setOpened(null); setFullscreen(false); }\n if (next !== stateRef.current) onWindowState(next);\n };\n const expanded = windowState === 'expanded', minimized = windowState === 'minimized';\n const phone = usePhone();\n const root = useRef<HTMLDivElement>(null), titleButton = useRef<HTMLButtonElement>(null), pill = useRef<HTMLButtonElement>(null);\n const [picking, setPicking] = useState(false);\n const [feedback, setFeedback] = useState<Readonly<Record<string, 'up' | 'down'>>>({});\n const [outcome, setOutcome] = useState<'done' | 'error' | null>(null);\n const [permission, setPermission] = useState<NotifyPermission>('unsupported');\n useEffect(() => { setPermission(notifyPermission()); }, []);\n useEffect(() => { if (!outcome) return; const timer = setTimeout(() => setOutcome(null), 8000); return () => clearTimeout(timer); }, [outcome]);\n\n // Replies get copy, optional feedback and the time; the host may hand the conversation to its full chat.\n const conversationRef = useRef('');\n const replyActions = useMemo<NonNullable<RowContext['replyActions']>>(() => (reply, host) => <div data-testid=\"reply-actions\" className=\"mt-2 -ml-2 flex items-center gap-0.5 text-muted-foreground\">\n <CopyButton text={reply.text} label={labels.copyResponse} iconOnly {...(onCopy ? { onCopy } : {})} className=\"size-8 p-0 text-muted-foreground max-sm:size-11\" />\n {onFeedback && <>\n {(['up', 'down'] as const).map(value => <button key={value} type=\"button\" data-testid={`feedback-${value}`} aria-pressed={feedback[reply.key] === value} aria-label={value === 'up' ? labels.goodResponse : labels.badResponse}\n title={value === 'up' ? labels.goodResponse : labels.badResponse}\n onClick={() => { const next = feedback[reply.key] === value ? null : value; setFeedback(current => { const { [reply.key]: _removed, ...rest } = current; return next ? { ...rest, [reply.key]: next } : rest; }); onFeedback({ key: reply.key, text: reply.text }, next); }}\n className={cn(iconButton, 'aria-pressed:text-foreground')}>{value === 'up' ? <icons.goodResponse className=\"size-3.5\" aria-hidden=\"true\" /> : <icons.badResponse className=\"size-3.5\" aria-hidden=\"true\" />}</button>)}\n </>}\n {onOpenFull && <button type=\"button\" data-testid=\"open-full\" aria-label={labels.openFull} title={labels.openFull} onClick={() => onOpenFull(conversationRef.current)} className={iconButton}><icons.openFull className=\"size-3.5\" aria-hidden=\"true\" /></button>}\n {host}\n {reply.timestamp !== undefined && <time dateTime={new Date(reply.timestamp).toISOString()} data-testid=\"reply-time\" className=\"ml-1.5 text-xs tabular-nums\">{new Date(reply.timestamp).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })}</time>}\n </div>, [onCopy, onFeedback, onOpenFull, feedback, labels, icons]);\n const scrollToBottom = useRef<() => void>(() => {});\n const rowExtras = useMemo(() => ({ replyActions }), [replyActions]);\n const inWindow = Boolean(artifactPanel) && artifactTarget !== 'host';\n const detect = hostArtifacts?.detect;\n const versionsRef = useRef<readonly ArtifactDescriptor[]>([]);\n const artifacts = useMemo<ArtifactsConfig | undefined>(() => !inWindow ? hostArtifacts : {\n open: descriptor => { const newest = versionsRef.current.filter(version => artifactKey(version) === artifactKey(descriptor)).reduce((top, version) => Math.max(top, version.ordinal ?? 0), 0); setOpened({ descriptor, follow: (descriptor.ordinal ?? 0) >= newest }); },\n isOpen: descriptor => opened !== null && artifactKey(opened.descriptor) === artifactKey(descriptor) && (opened.follow ? (descriptor.ordinal ?? 0) >= (versionsRef.current.find(version => artifactKey(version) === artifactKey(descriptor))?.ordinal ?? 0) : descriptor.revision === opened.descriptor.revision),\n ...(detect ? { detect } : {}),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [inWindow, hostArtifacts, opened, detect]);\n const session = useChatSession({ controller, activeController, mode, actions, renderEntry, renderTool, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, fileAccept,\n slash, mentions, attachments, model, effort, artifacts, messageActions, replyFooter, afterSend: () => scrollToBottom.current(), rowExtras, feedback: composerFeedback });\n const { state, derived, rows, queued, queueActions, working, waitingForAnswer, error, act, textarea, rowContext, composer, empty, loading } = session;\n const transcript = useTranscript(rows);\n const versions = useMemo(() => inWindow ? collectArtifacts(state.view, detect).sort((a, b) => (b.ordinal ?? 0) - (a.ordinal ?? 0)) : [], [inWindow, state.view, detect]);\n versionsRef.current = versions;\n const known = opened ? versions.filter(version => artifactKey(version) === artifactKey(opened.descriptor)) : [];\n const shownArtifact = opened ? (opened.follow ? known[0] ?? opened.descriptor : opened.descriptor) : undefined;\n const { stick, hidden } = transcript;\n scrollToBottom.current = () => { void stick.scrollToBottom('instant'); };\n const { barStart, barNote } = session.pickers();\n\n const conversationId = String(conversations?.activeId ?? state.conversationId);\n conversationRef.current = conversationId;\n const activeItem = conversations?.items.find(item => item.id === conversations.activeId);\n const shownTitle = activeItem?.title?.trim() || title;\n const toasts = useNotifications(store);\n useRunFeed({ enabled: notifications !== false, store, conversationId, title: shownTitle, session, onOutcome: setOutcome, waiting: labels.waitingForAnswer,\n suppress: () => stateRef.current === 'expanded' && globalThis.document?.visibilityState !== 'hidden' });\n const unread = !expanded && toasts.length > 0;\n const seconds = useElapsed(working);\n\n // Position: offsets from the bottom right corner, remembered for the session, clamped to the viewport at render so a smaller window restores them.\n const [position, setPosition] = useState<Position>(() => readPosition(storageKey, storage) ?? DEFAULT_POSITION);\n const [viewport, setViewport] = useState(viewportSize);\n const [size, setSize] = useState({ w: 0, h: 0 });\n useEffect(() => {\n const onResize = () => setViewport(viewportSize());\n globalThis.addEventListener('resize', onResize);\n return () => globalThis.removeEventListener('resize', onResize);\n }, []);\n useEffect(() => {\n const element = root.current;\n if (!element || typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(() => setSize({ w: element.offsetWidth, h: element.offsetHeight }));\n observer.observe(element);\n setSize({ w: element.offsetWidth, h: element.offsetHeight });\n return () => observer.disconnect();\n }, [minimized, expanded]);\n // The size and the viewport also follow every render, so the clamp below never works from a stale measurement (the title or status icon can change the pill's width; a scrollbar can appear without a resize event).\n useLayoutEffect(() => {\n const element = root.current;\n const fresh = viewportSize();\n setViewport(current => current.w === fresh.w && current.h === fresh.h ? current : fresh);\n if (element) setSize(current => current.w === element.offsetWidth && current.h === element.offsetHeight ? current : { w: element.offsetWidth, h: element.offsetHeight });\n });\n const placed = clamp(position, size, viewport);\n // Moves and the release are followed on the window, so a drag keeps working when the pointer leaves the handle (and when pointer capture is unavailable).\n // `threshold` is how far the pointer must travel before it is a drag: a click on the pill (threshold > 0) still restores it.\n const dragged = useRef(false);\n const beginDrag = (event: PointerEvent<HTMLElement>, threshold: number) => {\n if (phone || event.button !== 0) return;\n dragged.current = false;\n const origin = { pointer: event.pointerId, x: event.clientX, y: event.clientY, start: placed };\n let last = origin.start, moving = threshold === 0;\n const move = (next: globalThis.PointerEvent) => {\n if (next.pointerId !== origin.pointer) return;\n if (!moving) { if (Math.hypot(next.clientX - origin.x, next.clientY - origin.y) < threshold) return; moving = true; dragged.current = true; }\n last = clamp({ right: origin.start.right - (next.clientX - origin.x), bottom: origin.start.bottom - (next.clientY - origin.y) }, size, viewport);\n setPosition(last);\n };\n const end = (next: globalThis.PointerEvent) => {\n if (next.pointerId !== origin.pointer) return;\n globalThis.removeEventListener('pointermove', move); globalThis.removeEventListener('pointerup', end); globalThis.removeEventListener('pointercancel', end);\n if (moving) writePosition(storageKey, storage, last);\n };\n globalThis.addEventListener('pointermove', move); globalThis.addEventListener('pointerup', end); globalThis.addEventListener('pointercancel', end);\n };\n const onGripDown = (event: PointerEvent<HTMLButtonElement>) => { event.preventDefault(); beginDrag(event, 0); };\n // Arrow keys move the window (Shift for big steps); Home puts it back in the default corner.\n const onGripKey = (event: KeyboardEvent<HTMLElement>) => {\n if (phone) return;\n const step = event.shiftKey ? 64 : 16;\n const delta = event.key === 'ArrowLeft' ? { right: step, bottom: 0 } : event.key === 'ArrowRight' ? { right: -step, bottom: 0 } : event.key === 'ArrowUp' ? { right: 0, bottom: step } : event.key === 'ArrowDown' ? { right: 0, bottom: -step } : undefined;\n if (!delta && event.key !== 'Home') return;\n event.preventDefault();\n const next = delta ? clamp({ right: placed.right + delta.right, bottom: placed.bottom + delta.bottom }, size, viewport) : clamp(DEFAULT_POSITION, size, viewport);\n setPosition(next); writePosition(storageKey, storage, next);\n };\n const grip = (className?: string) => <button type=\"button\" data-testid=\"ambient-grip\" aria-label={labels.move} title={labels.moveHint} onPointerDown={onGripDown} onKeyDown={onGripKey}\n className={cn(iconButton, 'cursor-grab touch-none active:cursor-grabbing', className)}><icons.grip className=\"size-4\" aria-hidden=\"true\" /></button>;\n\n const expand = () => { setOutcome(null); store.dismissConversation(conversationId); setWindowState('expanded'); };\n useEffect(() => {\n if (expanded && !globalThis.matchMedia?.('(pointer: coarse)').matches) textarea.current?.focus();\n }, [expanded, textarea]);\n // The title is disabled while the window is open, so focus goes back to it once the bar is showing again.\n const refocusTitle = useRef(false);\n useEffect(() => { if (!expanded && refocusTitle.current) { refocusTitle.current = false; titleButton.current?.focus(); } }, [expanded]);\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.key !== 'Escape' || event.defaultPrevented || !expanded || picking) return;\n event.preventDefault();\n // Escape steps back: full screen, then the artifact, then the window.\n if (fullscreen) return setFullscreen(false);\n if (opened) return setOpened(null);\n refocusTitle.current = true;\n setWindowState('bar');\n };\n const onActivate = useCallback((item: AgentNotification) => {\n if (item.conversationId !== undefined && item.conversationId !== conversationId) conversations?.onSelect(item.conversationId);\n expand();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [conversationId, conversations]);\n\n const connectionKind = state.connection.kind;\n const status = waitingForAnswer ? 'input' : working ? 'working' : outcome;\n const label = waitingForAnswer ? labels.waitingForAnswer : labels.working(seconds);\n const panelOpen = expanded && shownArtifact !== undefined && artifactPanel !== undefined;\n const surface = cn('relative flex flex-col border border-border bg-background text-foreground shadow-2xl', phone && expanded ? 'h-dvh rounded-none border-0 pt-[env(safe-area-inset-top)]' : 'rounded-3xl',\n !phone && expanded && (panelOpen ? 'h-full overflow-hidden' : 'max-h-[70dvh]'));\n // With an artifact open the window widens (most of the viewport, at most 72rem) and takes a fixed height so the panel fills it.\n const rootClass = cn('pi-chat pi-ambient fixed z-50', phone ? (expanded ? 'inset-0' : 'inset-x-2 bottom-[max(0.5rem,env(safe-area-inset-bottom))]')\n : cn('transition-[width] duration-200 motion-reduce:transition-none', minimized ? 'w-auto' : panelOpen ? 'h-[min(46rem,calc(100dvh-1rem))] w-[min(72rem,calc(100vw-1rem))]' : expanded ? 'w-[min(35rem,calc(100vw-1rem))]' : 'w-[min(26rem,calc(100vw-1rem))]'), className);\n const rootStyle = phone ? undefined : { right: placed.right, bottom: placed.bottom };\n\n if (minimized) return <div ref={root} data-boring=\"ambient-chat\" data-state=\"minimized\" data-variant={variant} className={cn(rootClass, phone && 'flex justify-end')} style={rootStyle} onKeyDown={onKeyDown}>\n {notifications !== false && <AgentNotifications store={store} variant={variant} placement=\"inline\" systemNotifications={systemNotifications} onActivate={onActivate} labels={labels}\n {...(autoDismissMs !== undefined ? { autoDismissMs } : {})} {...(maxToasts !== undefined ? { max: maxToasts } : {})} className=\"absolute right-0 bottom-full mb-3 w-[min(26rem,calc(100vw-1rem))]\" />}\n {/* Feedback mode keeps its bar (Stop, Done, ✕) when the window is minimised; otherwise a recording could not be stopped. */}\n {composerFeedback?.active && composerFeedback.bar && <div data-testid=\"ambient-feedback-bar\" className=\"absolute right-0 bottom-full mb-2 w-[min(26rem,calc(100vw-1rem))] rounded-2xl border border-border bg-background pt-2.5 shadow-xl\">{composerFeedback.bar}</div>}\n <div data-testid=\"ambient-pill-box\" onPointerDown={event => beginDrag(event, 4)} onKeyDown={onGripKey} onClickCapture={event => { if (dragged.current) { dragged.current = false; event.stopPropagation(); event.preventDefault(); } }}\n className={cn('relative flex h-11 max-w-[min(20rem,calc(100vw-1rem))] items-center rounded-full border border-border bg-background text-foreground shadow-xl transition-colors hover:bg-popover motion-reduce:transition-none', !phone && 'cursor-grab touch-none select-none active:cursor-grabbing')}>\n {!phone && grip('ml-1.5 size-8 rounded-full')}\n <button ref={pill} type=\"button\" data-testid=\"ambient-pill\" onClick={() => setWindowState('bar')} aria-label={labels.openAgent(shownTitle, unread)}\n className={cn('relative flex h-full min-w-0 cursor-pointer items-center gap-2.5 rounded-full pr-4 text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/70', phone ? 'pl-3.5' : 'pl-1.5')}>\n {status === 'working' ? <Loader2Icon className=\"size-4 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none\" aria-hidden=\"true\" />\n : status ? <KindIcon kind={status === 'input' ? 'input' : status} className=\"size-4\" /> : null}\n <span className=\"min-w-0 truncate text-sm\">{shownTitle}</span>\n {unread && <span data-testid=\"ambient-unread\" aria-hidden=\"true\" className=\"absolute top-1.5 right-2 size-2.5 rounded-full border-2 border-background bg-primary\" />}\n </button>\n </div>\n </div>;\n\n const visibleRows = transcript.visible(rows);\n return <div ref={root} data-boring=\"ambient-chat\" data-state={windowState} data-variant={variant} data-phone={phone ? 'true' : undefined} role=\"region\" aria-label={labels.region(shownTitle)}\n className={rootClass} style={rootStyle} onKeyDown={onKeyDown}>\n {notifications !== false && !(phone && expanded) && <AgentNotifications store={store} variant={variant} placement=\"inline\" systemNotifications={systemNotifications} onActivate={onActivate} labels={labels}\n {...(autoDismissMs !== undefined ? { autoDismissMs } : {})} {...(maxToasts !== undefined ? { max: maxToasts } : {})} className=\"absolute right-0 bottom-full mb-3 w-full\" />}\n {picking && conversations && <ConversationHistory conversations={conversations} placement={expanded ? 'below' : 'above'} onClose={() => setPicking(false)} />}\n <div data-testid=\"ambient-surface\" className={surface}>\n <ArtifactWorkspace open={panelOpen} onClose={() => { setOpened(null); setFullscreen(false); }} fullscreen={fullscreen} onFullscreenChange={setFullscreen} storageKey=\"boring.ambient.panel-width\" panelLabel={labels.artifactPanel}\n defaultWidth={600} minPanel={320} minChat={300} sheetBelow={720}\n panel={api => shownArtifact && artifactPanel ? artifactPanel(shownArtifact, { ...api, versions: known, follow: opened?.follow ?? true,\n select: version => setOpened(current => current ? (version === 'latest' ? { descriptor: known[0] ?? current.descriptor, follow: true } : { descriptor: version, follow: false }) : current) }) : null}\n chat={<section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <header data-testid=\"ambient-header\" className={cn('flex h-12 shrink-0 items-center gap-0.5 px-2 max-sm:h-14', !expanded && 'border-b border-border')}>\n <button type=\"button\" data-testid=\"ambient-minimize\" aria-label={labels.minimize} title={labels.minimize} onClick={() => { setPicking(false); setWindowState(expanded ? 'bar' : 'minimized'); }} className={iconButton}><icons.minimize className=\"size-4\" aria-hidden=\"true\" /></button>\n <span data-testid=\"ambient-status\" data-status={status ?? 'idle'} role=\"img\" aria-label={status === 'working' ? labels.statusWorking : status === 'input' ? labels.needsInput : status === 'done' ? labels.finished : status === 'error' ? labels.failedRun : undefined}\n aria-hidden={status ? undefined : 'true'} className={cn('flex shrink-0 items-center justify-center', status ? 'mx-1.5 w-5' : 'w-1.5')}>\n {status === 'working' ? <Loader2Icon className=\"size-4 animate-spin text-muted-foreground motion-reduce:animate-none\" aria-hidden=\"true\" /> : status ? <KindIcon kind={status === 'input' ? 'input' : status} className=\"size-[1.125rem]\" /> : null}\n </span>\n {avatar && <span data-testid=\"ambient-avatar\" className=\"flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-full [&>img]:size-full [&>img]:object-cover [&>svg]:size-4\">{avatar}</span>}\n <button ref={titleButton} type=\"button\" data-testid=\"ambient-title\" onClick={expand} disabled={expanded} aria-label={expanded ? shownTitle : labels.openChat(shownTitle)}\n className=\"min-w-0 max-w-full cursor-pointer truncate rounded-md px-1 py-1 text-left text-[0.9375rem] text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/60 disabled:cursor-default max-sm:py-2.5\">{shownTitle}</button>\n {conversations && <button type=\"button\" data-testid=\"ambient-switch\" aria-label={labels.switchConversation} aria-haspopup=\"dialog\" aria-expanded={picking} title={labels.switchConversation} onClick={() => setPicking(open => !open)}\n className={cn(iconButton, 'size-7 max-sm:size-11')}><icons.switchConversation className=\"size-3.5\" aria-hidden=\"true\" /></button>}\n {expanded ? <span className=\"flex-1\" /> : <button type=\"button\" tabIndex={-1} aria-hidden=\"true\" data-testid=\"ambient-header-fill\" onClick={expand} className=\"h-full min-w-2 flex-1 cursor-pointer\" />}\n {systemNotifications && permission === 'default' && <button type=\"button\" data-testid=\"ambient-enable-notifications\" aria-label={labels.enableNotifications} title={labels.enableNotifications}\n onClick={() => { void requestNotifyPermission().then(setPermission); }} className={iconButton}><icons.notify className=\"size-4\" aria-hidden=\"true\" /></button>}\n <BlockActions actions={headerActions} testId=\"ambient-action\" menuLabel={labels.moreActions} className=\"[&_button]:max-sm:size-11 [&_button]:pointer-coarse:size-11\" />\n {onDock && !phone && <button type=\"button\" data-testid=\"ambient-dock\" aria-label={labels.dock} title={labels.dockHint} onClick={() => { setPicking(false); onDock(); }} className={iconButton}><icons.dock className=\"size-4\" aria-hidden=\"true\" /></button>}\n {!phone && grip()}\n </header>\n\n {expanded && <div className=\"flex min-h-0 flex-1 flex-col\">\n {(connectionKind === 'error' || connectionKind === 'closed') && <div className=\"px-4 pb-2\"><Notice tone={connectionKind === 'error' ? 'error' : 'info'} testid=\"connection-notice\">\n <span className=\"flex-1\">{connectionKind === 'error' ? labels.loadFailed : labels.disconnected}</span>\n {!state.disposed && <Button size=\"sm\" variant=\"outline\" onClick={() => act(controller.connect)}><icons.reconnect className=\"size-3.5\" aria-hidden=\"true\" />{labels.reconnect}</Button>}</Notice></div>}\n {derived.pinned.length > 0 && <aside aria-label={labels.requiredActions} className=\"shrink-0 space-y-2 px-4 pb-2\">{derived.pinned.map(card => <div key={card.key}>{card.content}</div>)}</aside>}\n <div className=\"relative flex min-h-0 flex-1 flex-col\">\n <div ref={stick.scrollRef} data-testid=\"transcript-scroll\" className=\"min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain\">\n <div ref={stick.contentRef} role=\"log\" aria-label={labels.messages} aria-live=\"polite\" data-testid=\"transcript\" className=\"flex min-h-28 flex-col gap-5 px-4 pt-1 pb-5\">\n {hidden > 0 && <div className=\"flex justify-center\"><Button size=\"sm\" variant=\"outline\" data-testid=\"show-earlier\" className=\"rounded-full text-muted-foreground\" onClick={transcript.reveal}>{labels.showEarlier}</Button></div>}\n {visibleRows.map(row => <RowView key={row.key} row={row} context={rowContext} />)}\n {loading && <p role=\"status\" data-testid=\"loading\" className=\"m-0 flex items-center gap-2 text-sm text-muted-foreground\"><Loader2Icon className=\"size-4 animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" />{labels.loading}</p>}\n {empty && !loading && <p data-testid=\"ambient-empty\" className=\"m-0 py-6 text-center text-sm text-muted-foreground\">{labels.empty}</p>}\n </div>\n </div>\n {!stick.isAtBottom && <Button variant=\"outline\" size=\"icon\" data-testid=\"jump-latest\" aria-label={labels.jumpToLatest} title={labels.jumpToLatest} onClick={() => { transcript.reset(); void stick.scrollToBottom(); }}\n className=\"absolute bottom-2 left-1/2 -translate-x-1/2 rounded-full bg-background/95 shadow-md backdrop-blur\"><icons.jumpToLatest className=\"size-4\" aria-hidden=\"true\" /></Button>}\n </div>\n </div>}\n\n <div className={cn('shrink-0', expanded && 'border-t border-border', phone && 'pb-[env(safe-area-inset-bottom)]')}>\n <div className=\"space-y-2 px-3 empty:hidden [&:has(*)]:pt-2\">\n <ChatNotices state={state} error={error} onReconcile={() => act(controller.reconcile)} onRetry={() => act(controller.retrySameRequest)} />\n {!expanded && (connectionKind === 'error' || connectionKind === 'closed') && <Notice tone=\"info\" testid=\"connection-notice\">\n <span className=\"flex-1\">{connectionKind === 'error' ? labels.loadFailedShort : labels.disconnectedShort}</span>\n {!state.disposed && <Button size=\"sm\" variant=\"outline\" onClick={() => act(controller.connect)}>{labels.reconnect}</Button>}</Notice>}\n </div>\n <MessageQueue items={queued} sending={state.outbox} withdraw={actions?.withdraw} actions={queueActions} />\n <Composer {...composer} layout=\"inline\" placeholder={working || waitingForAnswer ? label : labels.placeholder} barStart={barStart} barNote={barNote} barEnd={tools} />\n </div>\n </section>} />\n </div>\n </div>;\n}\n",
|
|
24
|
+
"type": "registry:component",
|
|
25
|
+
"target": "components/pi-ambient/ambient.tsx"
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"path": "registry/pi-ambient/browser-notify.ts",
|
|
29
|
+
"content": "// The one place this item touches the browser Notification API. It is secure-context and permission dependent, so every use\n// feature-detects first and nothing here is required: without it the toasts simply stay in the page. `npm run check` keeps it that way.\n\nexport type NotifyPermission = 'unsupported' | 'default' | 'granted' | 'denied';\n\ntype NotificationLike = {\n new (title: string, options?: { readonly body?: string; readonly tag?: string }): { onclick: (() => void) | null; close(): void };\n readonly permission: NotificationPermission;\n requestPermission(): Promise<NotificationPermission>;\n};\nconst api = (): NotificationLike | undefined => {\n const candidate = (globalThis as { Notification?: NotificationLike }).Notification;\n return typeof candidate === 'function' ? candidate : undefined;\n};\n\nexport function notifyPermission(): NotifyPermission {\n const Notify = api();\n return Notify ? Notify.permission : 'unsupported';\n}\n\n/** Ask for permission. Call this only from a person's own action (a click), never on load. */\nexport async function requestNotifyPermission(): Promise<NotifyPermission> {\n const Notify = api();\n if (!Notify) return 'unsupported';\n try { return await Notify.requestPermission(); } catch { return Notify.permission; }\n}\n\n/** A system notification, only while the page is hidden and permission was granted. Returns whether one was shown. */\nexport function notifyWhenHidden(title: string, body: string, tag: string, onClick: () => void): boolean {\n const Notify = api();\n if (!Notify || Notify.permission !== 'granted' || globalThis.document?.visibilityState !== 'hidden') return false;\n try {\n const shown = new Notify(title, { body, tag });\n shown.onclick = () => { shown.close(); onClick(); };\n return true;\n } catch { return false; }\n}\n",
|
|
30
|
+
"type": "registry:hook",
|
|
31
|
+
"target": "components/pi-ambient/browser-notify.ts"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"path": "registry/pi-ambient/notifications.tsx",
|
|
35
|
+
"content": "'use client';\n\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport type { KeyboardEvent } from 'react';\nimport { CircleCheckIcon, CircleAlertIcon, MessageCircleQuestionIcon, XIcon } from 'lucide-react';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { notifyWhenHidden } from './browser-notify';\nimport { parseQuestion } from '../pi-chat/question-card';\nimport { derive, object } from '../pi-chat/rows';\nimport type { Row } from '../pi-chat/rows';\nimport { cn, withDefaults } from '../utils/utils';\n\n/** `done`: a run finished. `input`: the agent waits for an answer (never auto-dismissed). `error`: a run failed. */\nexport type NotificationKind = 'done' | 'input' | 'error';\n\nexport interface AgentNotification {\n readonly id: string;\n readonly kind: NotificationKind;\n /** The task or conversation title. */\n readonly title: string;\n /** One line: the first line of the final reply, the question, or the failure. */\n readonly summary?: string | undefined;\n /** What a click opens. Hosts use their own ids for background tasks. */\n readonly conversationId?: string | undefined;\n readonly createdAt: number;\n}\nexport type NewNotification = Omit<AgentNotification, 'id' | 'createdAt'> & { readonly id?: string | undefined };\n\n/**\n * A small external store of notifications. `AmbientChat` feeds it for its own conversation; a host feeds it for background\n * conversations or tasks (`push` from any event), and may share one store between `AmbientChat` and `AgentNotifications`.\n */\nexport interface NotificationStore {\n readonly subscribe: (listener: () => void) => () => void;\n readonly getSnapshot: () => readonly AgentNotification[];\n /** Adds a notification (or replaces the one with the same `id`) and returns its id. */\n readonly push: (notification: NewNotification) => string;\n readonly dismiss: (id: string) => void;\n /** Dismisses every notification of a conversation, optionally of one kind. */\n readonly dismissConversation: (conversationId: string, kind?: NotificationKind) => void;\n readonly clear: () => void;\n}\n\nexport function createNotificationStore(): NotificationStore {\n let items: readonly AgentNotification[] = [];\n let sequence = 0;\n const listeners = new Set<() => void>();\n const set = (next: readonly AgentNotification[]) => { items = next; for (const listener of [...listeners]) listener(); };\n return {\n subscribe: listener => { listeners.add(listener); return () => { listeners.delete(listener); }; },\n getSnapshot: () => items,\n push: notification => {\n const id = notification.id ?? `notification-${++sequence}`;\n set([...items.filter(item => item.id !== id), { ...notification, id, createdAt: Date.now() }]);\n return id;\n },\n dismiss: id => { if (items.some(item => item.id === id)) set(items.filter(item => item.id !== id)); },\n dismissConversation: (conversationId, kind) => {\n if (items.some(item => item.conversationId === conversationId && (!kind || item.kind === kind))) set(items.filter(item => item.conversationId !== conversationId || (kind && item.kind !== kind)));\n },\n clear: () => { if (items.length) set([]); },\n };\n}\n\n/** The current notifications of a store. */\nexport function useNotifications(store: NotificationStore): readonly AgentNotification[] {\n return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n\n/** One line from a Markdown reply: its first non-empty line without Markdown marks, cut with an ellipsis. */\nexport function summaryOf(text: string, limit = 140): string {\n const line = text.split('\\n').map(item => item.trim()).find(item => item && !/^(```|---+$)/.test(item)) ?? '';\n const plain = line.replace(/^(#{1,6}\\s+|>\\s*|[-*+]\\s+|\\d+[.)]\\s+)/, '').replace(/!?\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1').replace(/[*_`~]+/g, '').replace(/\\s+/g, ' ').trim();\n return plain.length > limit ? `${plain.slice(0, limit - 1).trimEnd()}…` : plain;\n}\n\n/** What the newest pending `ask_user` question or approval asks, if one waits for the person. */\nexport function pendingQuestion(rows: readonly Row[]): string | undefined {\n for (const row of [...rows].reverse()) if (row.type === 'assistant') for (const part of row.parts) {\n if (part.kind === 'question' && !part.live && !part.result) return parseQuestion(part.call).question;\n if (part.kind === 'approval' && !part.live && !part.result && !part.decision) return `Approve: ${part.summary}`;\n }\n return undefined;\n}\n\n/** What a toast says about a run that just ended, from the conversation's rows; `undefined` when the person stopped it. */\nexport function finishNotice(rows: readonly Row[]): { readonly kind: 'done' | 'error'; readonly summary: string } | undefined {\n const last = [...rows].reverse().find((row): row is Extract<Row, { type: 'assistant' }> => row.type === 'assistant');\n if (last?.stopReason === 'aborted') return undefined;\n if (last?.stopReason === 'error') return { kind: 'error', summary: last.errorMessage ?? 'The run failed' };\n return { kind: 'done', summary: summaryOf(last?.text ?? '') || 'Finished' };\n}\n\n/**\n * Feeds a store from a conversation the host keeps connected in the background (a task, a subagent, another chat): a toast when its\n * run finishes or fails and while a question waits. Returns the unsubscribe. `AmbientChat` does the same for its own conversation.\n */\nexport function watchConversation(controller: NativeChatController, store: NotificationStore, options: { readonly conversationId: string; readonly title: string | (() => string) }): () => void {\n const { conversationId } = options;\n const title = () => typeof options.title === 'function' ? options.title() : options.title;\n const state = () => {\n const snapshot = controller.getSnapshot();\n const live = object(snapshot.view?.docs['pi.live']);\n return { working: Boolean(object(live?.['run'])), entries: snapshot.view?.entries.length ?? 0, connected: snapshot.connection.kind === 'connected' };\n };\n let before = state(), waiting = false;\n return controller.subscribe(() => {\n const now = state();\n const was = before;\n before = now;\n if (!now.connected || (now.working === was.working && now.entries === was.entries)) return;\n const rows = derive(controller.getSnapshot().view, { mode: 'expert', renderEntry: undefined, renderTool: undefined, groupTool: undefined }).rows;\n const question = now.working ? pendingQuestion(rows) : undefined;\n if (question !== undefined && !waiting) store.push({ id: `${conversationId}:input`, kind: 'input', title: title(), summary: question, conversationId });\n if (question === undefined && waiting) store.dismiss(`${conversationId}:input`);\n waiting = question !== undefined;\n if (now.working && !was.working) store.dismiss(`${conversationId}:done`);\n if (was.working && !now.working) {\n const finished = finishNotice(rows);\n if (finished) store.push({ id: `${conversationId}:done`, kind: finished.kind, title: title(), summary: finished.summary, conversationId });\n }\n });\n}\n\nconst ICONS = {\n done: { Icon: CircleCheckIcon, label: 'finished', tone: 'text-emerald-500' },\n input: { Icon: MessageCircleQuestionIcon, label: 'needsInput', tone: 'text-amber-400' },\n error: { Icon: CircleAlertIcon, label: 'failedRun', tone: 'text-destructive' },\n} as const;\n\n/** The toasts' words; `AmbientChat`'s `labels` carries them too. */\nexport const defaultNotificationLabels = {\n finished: 'Finished',\n needsInput: 'Needs your input',\n failedRun: 'Failed',\n notifications: 'Agent notifications',\n /** A toast's accessible name: its kind, title and summary, then what a press does. */\n openNotification: (kind: string, title: string, summary: string | undefined) => `${kind}: ${title}${summary ? `. ${summary}` : ''}. Open`,\n dismissNotification: (title: string) => `Dismiss: ${title}`,\n dismissShort: 'Dismiss',\n};\nexport type NotificationLabels = typeof defaultNotificationLabels;\n\n/** The status icon of a notification, also used by the ambient header. */\nexport function KindIcon({ kind, className }: { readonly kind: NotificationKind; readonly className?: string }) {\n const { Icon, tone } = ICONS[kind];\n return <Icon className={cn('size-5 shrink-0', tone, className)} aria-hidden=\"true\" />;\n}\n\nfunction Toast({ item, autoDismissMs, onActivate, onDismiss, labels }: {\n readonly item: AgentNotification; readonly autoDismissMs: number; readonly labels: NotificationLabels;\n readonly onActivate: (item: AgentNotification) => void; readonly onDismiss: (item: AgentNotification) => void;\n}) {\n const [paused, setPaused] = useState(false);\n const dismissible = item.kind !== 'input' && autoDismissMs > 0;\n useEffect(() => {\n if (!dismissible || paused) return;\n const timer = setTimeout(() => onDismiss(item), autoDismissMs);\n return () => clearTimeout(timer);\n }, [dismissible, paused, autoDismissMs, item, onDismiss]);\n const label = labels[ICONS[item.kind].label];\n return <li data-testid=\"agent-toast\" data-kind={item.kind} data-conversation-id={item.conversationId} className=\"pointer-events-auto relative list-none\"\n onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)} onFocus={() => setPaused(true)} onBlur={() => setPaused(false)}\n onKeyDown={(event: KeyboardEvent) => { if (event.key === 'Escape') { event.stopPropagation(); onDismiss(item); } }}>\n <button type=\"button\" data-testid=\"agent-toast-open\" onClick={() => onActivate(item)} aria-label={labels.openNotification(label, item.title, item.summary)}\n className=\"block w-full cursor-pointer rounded-[1.75rem] border border-border bg-background py-3.5 pr-6 pl-4 text-left text-foreground shadow-xl outline-none transition-colors hover:bg-popover focus-visible:ring-2 focus-visible:ring-ring/70 motion-reduce:transition-none\">\n <span className=\"flex items-center gap-2.5\"><KindIcon kind={item.kind} /><span className=\"min-w-0 flex-1 truncate text-[0.9375rem] font-medium\">{item.title}</span></span>\n {item.summary && <span data-testid=\"agent-toast-summary\" className=\"mt-1 block truncate text-sm text-muted-foreground\">{item.summary}</span>}\n </button>\n <button type=\"button\" data-testid=\"agent-toast-close\" aria-label={labels.dismissNotification(item.title)} title={labels.dismissShort} onClick={() => onDismiss(item)}\n className=\"absolute -top-2 -left-2 inline-flex size-6 cursor-pointer items-center justify-center rounded-full border border-border bg-background text-foreground shadow-md outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/70 max-sm:size-8 pointer-coarse:size-8 motion-reduce:transition-none\">\n <XIcon className=\"size-3.5\" aria-hidden=\"true\" /></button>\n </li>;\n}\n\nexport interface AgentNotificationsProps {\n readonly store: NotificationStore;\n /** Toasts shown at once; older ones appear when newer ones are closed. */\n readonly max?: number;\n /** Milliseconds before a toast closes itself; 0 keeps them. \"Needs input\" toasts never close themselves. Hovering or focusing a toast pauses the timer. */\n readonly autoDismissMs?: number;\n /** A click on a toast. It is dismissed afterwards. */\n readonly onActivate?: (notification: AgentNotification) => void;\n /** Also show a system notification while the page is hidden, when the person has allowed it (see `AmbientChat`'s bell). */\n readonly systemNotifications?: boolean;\n readonly variant?: 'contrast' | 'surface';\n /** `fixed` docks the stack at the bottom right of the page; `inline` leaves placement to `className`. */\n readonly placement?: 'fixed' | 'inline';\n /** The toasts' words, over `defaultNotificationLabels`. */\n readonly labels?: Partial<NotificationLabels> | undefined;\n readonly className?: string;\n}\n\n/**\n * A stack of toasts for finished, failed and waiting tasks, driven by a `NotificationStore`. It is a polite live region;\n * Escape closes the focused toast. `AmbientChat` renders one above its bar; use this directly for a host-placed stack.\n */\nexport function AgentNotifications({ store, max = 3, autoDismissMs = 8000, onActivate, systemNotifications = false, variant = 'contrast', placement = 'fixed', labels: given, className }: AgentNotificationsProps) {\n const labels = useMemo(() => withDefaults(defaultNotificationLabels, given), [given]);\n const items = useNotifications(store);\n const seen = useRef(new Set<string>());\n const dismiss = useCallback((item: AgentNotification) => store.dismiss(item.id), [store]);\n const activate = useCallback((item: AgentNotification) => { onActivate?.(item); store.dismiss(item.id); }, [onActivate, store]);\n useEffect(() => {\n for (const item of items) {\n if (seen.current.has(`${item.id}:${item.createdAt}`)) continue;\n seen.current.add(`${item.id}:${item.createdAt}`);\n if (systemNotifications) notifyWhenHidden(item.title, item.summary ?? labels[ICONS[item.kind].label], item.id, () => { globalThis.focus?.(); activate(item); });\n }\n }, [items, systemNotifications, activate, labels]);\n const shown = items.slice(-max);\n return <div data-boring=\"agent-notifications\" data-variant={variant} role=\"status\" aria-live=\"polite\" aria-relevant=\"additions\" aria-label={labels.notifications}\n className={cn('pi-chat pi-ambient pointer-events-none z-50', placement === 'fixed' && 'fixed right-4 bottom-4 w-[min(26rem,calc(100vw-2rem))]', className)}>\n <ul className=\"m-0 flex list-none flex-col gap-3 p-0\">\n {shown.map(item => <Toast key={`${item.id}:${item.createdAt}`} item={item} autoDismissMs={autoDismissMs} onActivate={activate} onDismiss={dismiss} labels={labels} />)}\n </ul>\n </div>;\n}\n",
|
|
36
|
+
"type": "registry:component",
|
|
37
|
+
"target": "components/pi-ambient/notifications.tsx"
|
|
38
|
+
}
|
|
39
|
+
],
|
|
40
|
+
"css": {
|
|
41
|
+
"@layer components": {
|
|
42
|
+
".pi-chat.pi-ambient[data-variant=\"contrast\"]": {
|
|
43
|
+
"color-scheme": "dark",
|
|
44
|
+
"--background": "oklch(0.262 0.004 285)",
|
|
45
|
+
"--foreground": "oklch(0.975 0.002 286)",
|
|
46
|
+
"--card": "oklch(0.262 0.004 285)",
|
|
47
|
+
"--card-foreground": "oklch(0.975 0.002 286)",
|
|
48
|
+
"--popover": "oklch(0.3 0.005 285)",
|
|
49
|
+
"--popover-foreground": "oklch(0.975 0.002 286)",
|
|
50
|
+
"--primary": "oklch(0.985 0 0)",
|
|
51
|
+
"--primary-foreground": "oklch(0.21 0.006 285.885)",
|
|
52
|
+
"--secondary": "oklch(0.33 0.006 286)",
|
|
53
|
+
"--secondary-foreground": "oklch(0.985 0 0)",
|
|
54
|
+
"--muted": "oklch(0.315 0.005 286)",
|
|
55
|
+
"--muted-foreground": "oklch(0.7 0.01 286)",
|
|
56
|
+
"--accent": "oklch(0.35 0.006 286)",
|
|
57
|
+
"--accent-foreground": "oklch(0.985 0 0)",
|
|
58
|
+
"--destructive": "oklch(0.704 0.191 22.216)",
|
|
59
|
+
"--border": "oklch(1 0 0 / 9%)",
|
|
60
|
+
"--input": "oklch(1 0 0 / 14%)",
|
|
61
|
+
"--ring": "oklch(0.75 0.02 286)"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"type": "registry:block"
|
|
66
|
+
}
|