@circuitwall/jarela 2.5.0 → 2.5.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.
Files changed (188) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/app-path-routes-manifest.json +5 -5
  3. package/.next/standalone/.next/build-manifest.json +2 -2
  4. package/.next/standalone/.next/prerender-manifest.json +3 -3
  5. package/.next/standalone/.next/react-loadable-manifest.json +2 -2
  6. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  7. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  12. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  13. package/.next/standalone/.next/server/app/_not-found.html +2 -2
  14. package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
  15. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  16. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  17. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  19. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/chats/route.js +8 -1
  20. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/chats/route.js.nft.json +1 -1
  21. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/lookup/route.js +8 -1
  22. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/lookup/route.js.nft.json +1 -1
  23. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/pair/route.js +8 -1
  24. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/pair/route.js.nft.json +1 -1
  25. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js +8 -1
  26. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/status/route.js +8 -1
  28. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/status/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +7 -0
  30. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/api/v1/credentials/[id]/route.js +7 -0
  32. package/.next/standalone/.next/server/app/api/v1/credentials/[id]/route.js.nft.json +1 -1
  33. package/.next/standalone/.next/server/app/api/v1/credentials/route.js +7 -0
  34. package/.next/standalone/.next/server/app/api/v1/credentials/route.js.nft.json +1 -1
  35. package/.next/standalone/.next/server/app/api/v1/dashboard/pricing-task/route.js +8 -1
  36. package/.next/standalone/.next/server/app/api/v1/dashboard/pricing-task/route.js.nft.json +1 -1
  37. package/.next/standalone/.next/server/app/api/v1/delegations/codex/[job_id]/route.js +7 -0
  38. package/.next/standalone/.next/server/app/api/v1/delegations/codex/[job_id]/route.js.nft.json +1 -1
  39. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/reindex/route.js +7 -0
  40. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/reindex/route.js.nft.json +1 -1
  41. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/route.js +8 -1
  42. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/route.js.nft.json +1 -1
  43. package/.next/standalone/.next/server/app/api/v1/documents/sources/route.js +8 -1
  44. package/.next/standalone/.next/server/app/api/v1/documents/sources/route.js.nft.json +1 -1
  45. package/.next/standalone/.next/server/app/api/v1/events/route.js +8 -1
  46. package/.next/standalone/.next/server/app/api/v1/events/route.js.nft.json +1 -1
  47. package/.next/standalone/.next/server/app/api/v1/extension/agents/route.js +8 -1
  48. package/.next/standalone/.next/server/app/api/v1/extension/agents/route.js.nft.json +1 -1
  49. package/.next/standalone/.next/server/app/api/v1/extension/fill/route.js +8 -1
  50. package/.next/standalone/.next/server/app/api/v1/extension/fill/route.js.nft.json +1 -1
  51. package/.next/standalone/.next/server/app/api/v1/extension/refine/route.js +8 -1
  52. package/.next/standalone/.next/server/app/api/v1/extension/refine/route.js.nft.json +1 -1
  53. package/.next/standalone/.next/server/app/api/v1/extension/turn/route.js +8 -1
  54. package/.next/standalone/.next/server/app/api/v1/extension/turn/route.js.nft.json +1 -1
  55. package/.next/standalone/.next/server/app/api/v1/extensions/route.js +8 -1
  56. package/.next/standalone/.next/server/app/api/v1/extensions/route.js.nft.json +1 -1
  57. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/config/route.js +8 -1
  58. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/config/route.js.nft.json +1 -1
  59. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/route.js +8 -1
  60. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/route.js.nft.json +1 -1
  61. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js +8 -1
  62. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js.nft.json +1 -1
  63. package/.next/standalone/.next/server/app/api/v1/health/probes/route.js +7 -0
  64. package/.next/standalone/.next/server/app/api/v1/health/probes/route.js.nft.json +1 -1
  65. package/.next/standalone/.next/server/app/api/v1/integrations/[name]/test/route.js +7 -0
  66. package/.next/standalone/.next/server/app/api/v1/integrations/[name]/test/route.js.nft.json +1 -1
  67. package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/callback/route.js +22 -1
  68. package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/start/route.js +22 -1
  69. package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/status/route.js +22 -1
  70. package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/callback/route.js +19 -2
  71. package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/start/route.js +19 -2
  72. package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/status/route.js +19 -2
  73. package/.next/standalone/.next/server/app/api/v1/packages/defaults/[id]/route.js +12 -2
  74. package/.next/standalone/.next/server/app/api/v1/packages/defaults/[id]/route.js.nft.json +1 -1
  75. package/.next/standalone/.next/server/app/api/v1/packages/install/[id]/route.js +7 -0
  76. package/.next/standalone/.next/server/app/api/v1/packages/install/[id]/route.js.nft.json +1 -1
  77. package/.next/standalone/.next/server/app/api/v1/packages/install/route.js +7 -0
  78. package/.next/standalone/.next/server/app/api/v1/packages/install/route.js.nft.json +1 -1
  79. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/enabled/route.js +7 -0
  80. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/enabled/route.js.nft.json +1 -1
  81. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/route.js +7 -0
  82. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/route.js.nft.json +1 -1
  83. package/.next/standalone/.next/server/app/api/v1/packages/manifests/route.js +7 -0
  84. package/.next/standalone/.next/server/app/api/v1/packages/manifests/route.js.nft.json +1 -1
  85. package/.next/standalone/.next/server/app/api/v1/packages/reload/route.js +12 -2
  86. package/.next/standalone/.next/server/app/api/v1/packages/reload/route.js.nft.json +1 -1
  87. package/.next/standalone/.next/server/app/api/v1/packages/route.js +12 -2
  88. package/.next/standalone/.next/server/app/api/v1/packages/route.js.nft.json +1 -1
  89. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +8 -1
  90. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.nft.json +1 -1
  91. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js +7 -0
  92. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js.nft.json +1 -1
  93. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/deny/route.js +7 -0
  94. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/deny/route.js.nft.json +1 -1
  95. package/.next/standalone/.next/server/app/api/v1/pending-actions/route.js +7 -0
  96. package/.next/standalone/.next/server/app/api/v1/pending-actions/route.js.nft.json +1 -1
  97. package/.next/standalone/.next/server/app/api/v1/scheduled-tasks/[id]/run/route.js +8 -1
  98. package/.next/standalone/.next/server/app/api/v1/scheduled-tasks/[id]/run/route.js.nft.json +1 -1
  99. package/.next/standalone/.next/server/app/api/v1/system/restart/route.js +7 -0
  100. package/.next/standalone/.next/server/app/api/v1/system/restart/route.js.nft.json +1 -1
  101. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +52 -45
  102. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.nft.json +1 -1
  103. package/.next/standalone/.next/server/app/api/v1/tools/route.js +8 -1
  104. package/.next/standalone/.next/server/app/api/v1/tools/route.js.nft.json +1 -1
  105. package/.next/standalone/.next/server/app/api/v1/update/apply/route.js.nft.json +1 -1
  106. package/.next/standalone/.next/server/app/api/v1/watchers/[id]/run/route.js +8 -1
  107. package/.next/standalone/.next/server/app/api/v1/watchers/[id]/run/route.js.nft.json +1 -1
  108. package/.next/standalone/.next/server/app/api/v1/watchers/route.js +8 -1
  109. package/.next/standalone/.next/server/app/api/v1/watchers/route.js.nft.json +1 -1
  110. package/.next/standalone/.next/server/app/page.js +73385 -73375
  111. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  112. package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
  113. package/.next/standalone/.next/server/app-paths-manifest.json +5 -5
  114. package/.next/standalone/.next/server/chunks/1433.js +1 -1
  115. package/.next/standalone/.next/server/chunks/210.js +6 -6
  116. package/.next/standalone/.next/server/chunks/3524.js +31 -15
  117. package/.next/standalone/.next/server/chunks/3566.js +1 -1
  118. package/.next/standalone/.next/server/chunks/4189.js +1 -1
  119. package/.next/standalone/.next/server/chunks/{9590.js → 423.js} +10 -3
  120. package/.next/standalone/.next/server/chunks/4596.js +5 -2
  121. package/.next/standalone/.next/server/chunks/46.js +7 -0
  122. package/.next/standalone/.next/server/chunks/540.js +29 -5
  123. package/.next/standalone/.next/server/chunks/5585.js +41 -3
  124. package/.next/standalone/.next/server/chunks/5908.js +10 -10
  125. package/.next/standalone/.next/server/chunks/{3399.js → 6058.js} +485 -3
  126. package/.next/standalone/.next/server/chunks/{9164.js → 6190.js} +13828 -13581
  127. package/.next/standalone/.next/server/chunks/{1388.js → 8842.js} +5961 -5793
  128. package/.next/standalone/.next/server/chunks/9032.js +5 -5
  129. package/.next/standalone/.next/server/chunks/{7547.js → 9217.js} +485 -3
  130. package/.next/standalone/.next/server/instrumentation.js +7 -0
  131. package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
  132. package/.next/standalone/.next/server/middleware-react-loadable-manifest.js +1 -1
  133. package/.next/standalone/.next/server/middleware.js +7 -0
  134. package/.next/standalone/.next/server/pages/404.html +2 -2
  135. package/.next/standalone/.next/server/pages/500.html +1 -1
  136. package/.next/standalone/.next/server/preview-props.json +3 -3
  137. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  138. package/.next/standalone/.next/static/chunks/app/{page-2ef8d75d40eb4311.js → page-4112e14360a9909e.js} +1291 -1281
  139. package/.next/standalone/.next/static/css/{c160ea862133acd2.css → 5b30046ba49144c5.css} +2 -2
  140. package/.next/standalone/docs/adoption/changesets.json +151 -0
  141. package/.next/standalone/package.json +2 -1
  142. package/CHANGELOG.md +46 -0
  143. package/browser-extension/background.js +5 -539
  144. package/browser-extension/lib/form-editing.mjs +541 -0
  145. package/components/chat/MessageBubble.tsx +4 -736
  146. package/components/chat/MessageContent.tsx +749 -0
  147. package/components/dashboard/DashboardPanel.test.tsx +34 -0
  148. package/components/dashboard/DashboardPanel.tsx +1 -1
  149. package/components/layout/MenuPanel.tsx +1 -1
  150. package/components/ui/BootScreen.test.tsx +1 -0
  151. package/components/ui/BootScreen.tsx +1 -0
  152. package/components/ui/ServerStatus.test.tsx +50 -0
  153. package/components/ui/ServerStatus.tsx +10 -8
  154. package/hooks/useSSE.test.ts +46 -0
  155. package/lib/agents/llm.ts +1 -1
  156. package/lib/agents/output-validator/validator.test.ts +4 -0
  157. package/lib/agents/output-validator/validator.ts +1 -1
  158. package/lib/agents/prompt-registry.test.ts +11 -0
  159. package/lib/agents/prompt-registry.ts +13 -0
  160. package/lib/agents/retry-prompts.ts +17 -0
  161. package/lib/agents/run-retry.ts +671 -0
  162. package/lib/agents/run-thread.retry.test.ts +176 -2
  163. package/lib/agents/run-thread.test.ts +6 -6
  164. package/lib/agents/run-thread.ts +9 -717
  165. package/lib/agents/stream-collector.test.ts +28 -4
  166. package/lib/agents/stream-collector.ts +5 -28
  167. package/lib/agents/tool-outcomes.ts +61 -0
  168. package/lib/documents/remote/confluence.test.ts +65 -0
  169. package/lib/documents/remote/confluence.ts +35 -9
  170. package/lib/documents/remote/jira.ts +1 -1
  171. package/lib/health/probes.test.ts +32 -0
  172. package/lib/health/probes.ts +29 -14
  173. package/lib/integrations/atlassian/manifest.ts +5 -3
  174. package/lib/integrations/github/manifest.ts +7 -4
  175. package/lib/integrations/gmail-oauth.ts +16 -1
  176. package/lib/integrations/microsoft-oauth.ts +17 -2
  177. package/lib/integrations/outlook/manifest.ts +10 -8
  178. package/lib/stores/integrations.ts +1 -0
  179. package/lib/tools/communications/calendar-aliases.test.ts +77 -1
  180. package/lib/tools/communications/gmail.test.ts +13 -0
  181. package/lib/tools/communications/ms-graph.test.ts +26 -3
  182. package/lib/tools/communications/ms-graph.ts +9 -11
  183. package/lib/tools/communications/outlook-calendar.ts +94 -17
  184. package/lib/tools/packages/default-packages/atlassian.ts +8 -2
  185. package/package.json +2 -1
  186. package/scripts/standalone-footprint.mjs +1 -1
  187. /package/.next/standalone/.next/static/{544OFJV-q0RC6Gjgje4LT → VZXMorlOmSmi3dUr7K5UX}/_buildManifest.js +0 -0
  188. /package/.next/standalone/.next/static/{544OFJV-q0RC6Gjgje4LT → VZXMorlOmSmi3dUr7K5UX}/_ssgManifest.js +0 -0
@@ -1,20 +1,13 @@
1
1
  "use client";
2
- import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
2
+ import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
3
3
  import type { ReactNode } from "react";
4
- import ReactMarkdown from "react-markdown";
5
- import remarkGfm from "remark-gfm";
6
- import rehypeRaw from "rehype-raw";
7
- import rehypeHighlight from "rehype-highlight";
8
- import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
9
- import "highlight.js/styles/github-dark.css";
10
- import { AlertTriangle, Bot, Brain, Check, Clock, Copy, CornerDownRight, Eye, EyeOff, ExternalLink, FileText, Link as LinkIcon, Link2, Loader2, MessageCircle, Paperclip, Pause, Play, RotateCcw, ShieldCheck, User, Users, X, Zap } from "lucide-react";
4
+ import { AlertTriangle, Bot, Brain, Check, Clock, Copy, CornerDownRight, Eye, EyeOff, ExternalLink, Link as LinkIcon, Link2, Loader2, MessageCircle, Paperclip, Pause, Play, RotateCcw, ShieldCheck, User, Users, Zap } from "lucide-react";
11
5
  import type { AgentConfig, AutomationActivityMetadata, Message, RouteDecisionMetadata, UserProfile } from "@/api/types";
12
6
  import type { ContentPart } from "@/api/types";
13
7
  import { ToolList } from "@/components/chat/ToolList";
14
8
  import { ContextUsageBar } from "@/components/chat/ContextUsageBar";
15
9
  import { StructuredTurnCard, CATEGORY_BADGE } from "@/components/chat/StructuredTurnCard";
16
10
  import { CollapseChevron } from "@/components/ui/CollapseChevron";
17
- import { Dialog } from "@/components/ui/Dialog";
18
11
  import { MetaRow } from "@/components/ui/MetaRow";
19
12
  import { useAppContext } from "@/contexts/AppContext";
20
13
  import { parseHref } from "@/lib/ui/navigate";
@@ -24,6 +17,8 @@ import { parseBridgePrompt, type BridgePromptContext } from "@/lib/bridges/messa
24
17
  import { parseExtensionTurn, type ExtensionTurnContext } from "@/lib/api/extension-turn-prompt";
25
18
  import { errorMessage } from "@/lib/utils/error";
26
19
  import { stripDeclaredReferencesFence } from "@/api/message-content";
20
+ import "highlight.js/styles/github-dark.css";
21
+ import { MarkdownContent, ContentPartView } from "./MessageContent";
27
22
 
28
23
  interface ExtractedRef {
29
24
  title: string;
@@ -83,32 +78,6 @@ function extractRefs(text: string): { body: string; refs: ExtractedRef[] } {
83
78
  return { body, refs };
84
79
  }
85
80
 
86
- // Tracks which TTS clips have started auto-playing this session so a clip
87
- // only autoplays once. Re-renders of the same <audio> (message refetched,
88
- // scroll into view, list re-render) won't trigger a replay. Keyed by the
89
- // full href (including any `?autoplay=1`). Cleared on hard refresh — exactly
90
- // the "session" semantics we want.
91
- const playedAutoplayHrefs = new Set<string>();
92
-
93
- function InlineAudio({ href }: { href: string }) {
94
- // Decide autoPlay at mount time: opt in only if the URL asked for it AND
95
- // we haven't already auto-played this exact clip in this session.
96
- const wantsAuto = /[?&]autoplay=1\b/.test(href);
97
- const [auto] = useState(() => wantsAuto && !playedAutoplayHrefs.has(href));
98
- return (
99
- <audio
100
- controls
101
- preload="metadata"
102
- autoPlay={auto}
103
- src={href}
104
- className="my-2 w-full max-w-md"
105
- onPlay={() => {
106
- if (wantsAuto) playedAutoplayHrefs.add(href);
107
- }}
108
- />
109
- );
110
- }
111
-
112
81
  // Detects messages produced by the page-capture endpoint (composeBody in
113
82
  // lib/api/page-capture.ts) so the chat UI can render them as a collapsed
114
83
  // card instead of dumping ~100KB of page text into the bubble. The format
@@ -465,172 +434,6 @@ function CollapsibleLong({
465
434
  );
466
435
  }
467
436
 
468
- // Sanitizer schema = GitHub default + extras the agent is told it can use.
469
- // Anything not listed here gets stripped (scripts, event handlers, javascript: URLs).
470
- const sanitizeSchema = {
471
- ...defaultSchema,
472
- tagNames: [
473
- ...(defaultSchema.tagNames ?? []),
474
- "details", "summary", "mark", "kbd", "sub", "sup", "abbr", "small",
475
- "aside", "figure", "figcaption", "dl", "dt", "dd",
476
- "audio", "source",
477
- ],
478
- attributes: {
479
- ...(defaultSchema.attributes ?? {}),
480
- "*": [...((defaultSchema.attributes ?? {})["*"] ?? []), "className", "title"],
481
- aside: ["className"],
482
- abbr: ["title"],
483
- details: ["open"],
484
- audio: ["src", "controls", "preload", "loop", "autoplay", "muted"],
485
- source: ["src", "type"],
486
- },
487
- };
488
-
489
- // Module-scope plugin arrays — passing fresh array literals to ReactMarkdown
490
- // on every render of MarkdownContent forced react-markdown's internal
491
- // useMemo() inputs to differ each time, defeating its plugin-pipeline
492
- // memoization. Hoisting these makes the references stable across renders.
493
- const MD_REMARK_PLUGINS = [remarkGfm];
494
- // rehype-highlight runs after rehype-raw (so any raw HTML <code> blocks are
495
- // also highlighted) and before rehype-sanitize (so the spans/classes it adds
496
- // pass through the sanitizer's allow-list rather than being stripped).
497
- const MD_REHYPE_PLUGINS: import("unified").PluggableList = [
498
- rehypeRaw,
499
- [rehypeHighlight, { detect: true, ignoreMissing: true }],
500
- [rehypeSanitize, sanitizeSchema],
501
- ];
502
-
503
- function isLikelyLocalFileHref(href: string): boolean {
504
- if (!href || href.startsWith("#")) return false;
505
- if (/^(mailto|tel|javascript|data|blob):/i.test(href)) return false;
506
- if (/^file:\/\//i.test(href)) return true;
507
- if (/^[A-Za-z]:[\\/]/.test(href) || href.startsWith("~/") || href.startsWith("~\\")) return true;
508
- if (/^https?:\/\//i.test(href)) {
509
- try {
510
- const url = new URL(href);
511
- if (!["localhost", "127.0.0.1", "[::1]", "::1"].includes(url.hostname)) return false;
512
- return !/^\/(api|_next)(\/|$)/.test(url.pathname);
513
- } catch {
514
- return false;
515
- }
516
- }
517
- if (href.startsWith("/")) return false;
518
- if (/^[a-z][a-z0-9+.-]*:/i.test(href)) return false;
519
- return /(^\.\.?[\\/]|[\\/]|\.[A-Za-z0-9]{1,12}(?:[?#]|$))/.test(href);
520
- }
521
-
522
- interface LocalFilePreview {
523
- path: string;
524
- name: string;
525
- size: number;
526
- renderable: boolean;
527
- snippet?: string;
528
- truncated?: boolean;
529
- error?: string;
530
- }
531
-
532
- function LocalFileLink({ href, threadId, children, className, title }: { href: string; threadId?: string | null; children: ReactNode; className?: string; title?: string }) {
533
- const [preview, setPreview] = useState<LocalFilePreview | null>(null);
534
- const [loading, setLoading] = useState(false);
535
- const [openError, setOpenError] = useState<string | null>(null);
536
-
537
- const openDefault = useCallback(async () => {
538
- setOpenError(null);
539
- const res = await fetch("/api/v1/local-file", {
540
- method: "POST",
541
- headers: { "Content-Type": "application/json" },
542
- body: JSON.stringify({ href, thread_id: threadId ?? undefined }),
543
- });
544
- const body = await res.json().catch(() => ({} as { error?: string }));
545
- if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`);
546
- pushToast({
547
- kind: "success",
548
- source: "system",
549
- sourceLabel: "Chat",
550
- title: "Opening file",
551
- body: "Sent the file to the operating system default app.",
552
- agent_id: null,
553
- thread_id: threadId ?? null,
554
- ttl: 1800,
555
- });
556
- }, [href, threadId]);
557
-
558
- const activate = useCallback(async () => {
559
- setLoading(true);
560
- setOpenError(null);
561
- try {
562
- const params = new URLSearchParams({ href });
563
- if (threadId) params.set("thread_id", threadId);
564
- const res = await fetch(`/api/v1/local-file?${params.toString()}`);
565
- const body = await res.json().catch(() => ({} as LocalFilePreview));
566
- if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`);
567
- const info = body as LocalFilePreview;
568
- setPreview(info);
569
- if (!info.renderable) await openDefault();
570
- } catch (err) {
571
- const msg = errorMessage(err);
572
- setOpenError(msg);
573
- pushToast({
574
- kind: "error",
575
- source: "system",
576
- sourceLabel: "Chat",
577
- title: "Could not open file",
578
- body: msg,
579
- agent_id: null,
580
- thread_id: threadId ?? null,
581
- ttl: 5000,
582
- });
583
- } finally {
584
- setLoading(false);
585
- }
586
- }, [href, openDefault, threadId]);
587
-
588
- return (
589
- <span className="inline-flex flex-col max-w-full align-baseline">
590
- <button
591
- type="button"
592
- className={`${className ?? ""} inline-flex items-baseline gap-1 text-left underline decoration-dotted hover:decoration-solid break-all`.trim()}
593
- title={title ?? href}
594
- onClick={activate}
595
- disabled={loading}
596
- >
597
- <FileText size={12} className="relative top-0.5 shrink-0" />
598
- <span>{children}</span>
599
- {loading && <Loader2 size={11} className="relative top-0.5 shrink-0 animate-spin" />}
600
- </button>
601
- {preview?.renderable && typeof preview.snippet === "string" && (
602
- <span className="not-prose my-2 block rounded-md border border-border/60 bg-surface-2 overflow-hidden">
603
- <span className="flex items-center justify-between gap-2 px-2 py-1 text-[10px] text-fg-faint bg-surface-3">
604
- <span className="truncate" title={preview.path}>{preview.path}</span>
605
- <button
606
- type="button"
607
- onClick={openDefault}
608
- className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-border/60 bg-surface-2 text-fg-muted hover:text-fg shrink-0"
609
- >
610
- <ExternalLink size={10} />
611
- Open
612
- </button>
613
- </span>
614
- <code className="block max-h-72 overflow-auto whitespace-pre-wrap break-words px-3 py-2 text-xs leading-relaxed text-fg-muted bg-[#0d1117]">
615
- {preview.snippet}{preview.truncated ? "\n..." : ""}
616
- </code>
617
- </span>
618
- )}
619
- {openError && <span className="text-[11px] text-rose-400 mt-1">{openError}</span>}
620
- </span>
621
- );
622
- }
623
-
624
- function reactChildrenToText(children: ReactNode): string {
625
- if (children == null || typeof children === "boolean") return "";
626
- if (typeof children === "string" || typeof children === "number") return String(children);
627
- if (Array.isArray(children)) return children.map(reactChildrenToText).join("");
628
- if (typeof children === "object" && "props" in (children as object)) {
629
- return reactChildrenToText((children as { props: { children?: ReactNode } }).props.children);
630
- }
631
- return "";
632
- }
633
-
634
437
  type Props = {
635
438
  message: Message | { role: "assistant"; content: string; streaming?: boolean };
636
439
  attachedActivity?: AutomationActivityMetadata;
@@ -907,313 +710,6 @@ function parseContent(raw: string): string | ContentPart[] {
907
710
  return raw;
908
711
  }
909
712
 
910
- // Markdown image renderer with a one-time automatic retry. If both attempts
911
- // fail (common on transient local-network/SW races), show a compact fallback
912
- // with explicit actions instead of a broken image icon.
913
- function ResilientMarkdownImage({ src, alt }: { src?: string | Blob; alt?: string }) {
914
- const [retryNonce, setRetryNonce] = useState(0);
915
- const [failed, setFailed] = useState(false);
916
- const [open, setOpen] = useState(false);
917
- const objectUrl = useMemo(() => (src instanceof Blob ? URL.createObjectURL(src) : null), [src]);
918
-
919
- useEffect(() => {
920
- return () => {
921
- if (objectUrl) URL.revokeObjectURL(objectUrl);
922
- };
923
- }, [objectUrl]);
924
-
925
- const normalizedSrc = typeof src === "string" ? src : objectUrl ?? "";
926
- const effectiveSrc = normalizedSrc
927
- ? `${normalizedSrc}${normalizedSrc.includes("?") ? "&" : "?"}retry=${retryNonce}`
928
- : "";
929
-
930
- if (!normalizedSrc) {
931
- return (
932
- <div className="my-2 px-3 py-2 rounded border border-rose-800/60 bg-rose-950/30 text-xs text-rose-700 dark:text-rose-300">
933
- Invalid image URL in markdown.
934
- </div>
935
- );
936
- }
937
-
938
- if (failed) {
939
- return (
940
- <div className="my-2 px-3 py-2 rounded border border-amber-700/50 bg-amber-900/20 text-xs text-amber-300">
941
- <div>Image failed to load.</div>
942
- <div className="mt-1 flex items-center gap-2">
943
- <button
944
- type="button"
945
- className="px-2 py-1 rounded border border-amber-500/60 hover:bg-amber-900/30"
946
- onClick={() => {
947
- setFailed(false);
948
- setRetryNonce((n) => n + 1);
949
- }}
950
- >
951
- Retry
952
- </button>
953
- <a
954
- href={normalizedSrc}
955
- target="_blank"
956
- rel="noopener noreferrer"
957
- className="underline decoration-dotted hover:decoration-solid break-all"
958
- >
959
- Open image
960
- </a>
961
- </div>
962
- </div>
963
- );
964
- }
965
-
966
- return (
967
- <>
968
- {/* eslint-disable-next-line @next/next/no-img-element */}
969
- <img
970
- src={effectiveSrc}
971
- alt={alt ?? "image"}
972
- loading="lazy"
973
- className="rounded-lg border border-border/50 cursor-zoom-in hover:border-fg-faint transition-colors"
974
- onClick={() => setOpen(true)}
975
- onError={() => {
976
- if (retryNonce === 0) {
977
- setRetryNonce(1);
978
- return;
979
- }
980
- setFailed(true);
981
- }}
982
- />
983
- <ImagePreviewDialog src={normalizedSrc} alt={alt ?? "image"} open={open} onClose={() => setOpen(false)} />
984
- </>
985
- );
986
- }
987
-
988
- // Renders a Google Maps Embed inside an iframe whose src points at our
989
- // server-side proxy (/api/v1/maps/embed). The proxy injects the API key so
990
- // it never appears in chat HTML. Triggered by ```map fenced blocks emitted
991
- // by the agent — see PRESENTATION_CTX in lib/agents/run-thread.ts.
992
- function MapEmbed({ payload }: { payload: string }) {
993
- const [retryNonce, setRetryNonce] = useState(0);
994
- const [failed, setFailed] = useState(false);
995
- let params: URLSearchParams | null = null;
996
- let parseError: string | null = null;
997
- try {
998
- const obj = JSON.parse(payload) as Record<string, unknown>;
999
- const sp = new URLSearchParams();
1000
- for (const k of ["q", "center", "zoom", "origin", "destination", "search", "mode"] as const) {
1001
- const v = obj[k];
1002
- if (typeof v === "string" && v.length > 0) sp.set(k, v);
1003
- else if (typeof v === "number") sp.set(k, String(v));
1004
- }
1005
- if ([...sp.keys()].length === 0) parseError = "no recognized fields (q / center / origin+destination / search)";
1006
- else params = sp;
1007
- } catch (e) {
1008
- parseError = errorMessage(e);
1009
- }
1010
-
1011
- if (!params) {
1012
- return (
1013
- <div className="my-2 px-3 py-2 rounded border border-rose-800/60 bg-rose-950/30 text-xs text-rose-700 dark:text-rose-300">
1014
- Invalid map block: {parseError}
1015
- </div>
1016
- );
1017
- }
1018
- const src = `/api/v1/maps/embed?${params.toString()}${retryNonce > 0 ? `&retry=${retryNonce}` : ""}`;
1019
-
1020
- if (failed) {
1021
- const q = params.get("q") ?? params.get("search") ?? params.get("center") ?? "";
1022
- const direct = q
1023
- ? `https://www.google.com/maps?q=${encodeURIComponent(q)}`
1024
- : "https://www.google.com/maps";
1025
- return (
1026
- <div className="my-2 px-3 py-2 rounded border border-amber-700/50 bg-amber-900/20 text-xs text-amber-300">
1027
- <div>Map failed to load.</div>
1028
- <div className="mt-1 flex items-center gap-2">
1029
- <button
1030
- type="button"
1031
- className="px-2 py-1 rounded border border-amber-500/60 hover:bg-amber-900/30"
1032
- onClick={() => {
1033
- setFailed(false);
1034
- setRetryNonce((n) => n + 1);
1035
- }}
1036
- >
1037
- Retry
1038
- </button>
1039
- <a
1040
- href={direct}
1041
- target="_blank"
1042
- rel="noopener noreferrer"
1043
- className="underline decoration-dotted hover:decoration-solid"
1044
- >
1045
- Open in Google Maps
1046
- </a>
1047
- </div>
1048
- </div>
1049
- );
1050
- }
1051
-
1052
- return (
1053
- <div className="my-2 rounded overflow-hidden border border-border bg-surface-2">
1054
- <iframe
1055
- src={src}
1056
- title="Map"
1057
- width="100%"
1058
- height="320"
1059
- loading="lazy"
1060
- referrerPolicy="no-referrer-when-downgrade"
1061
- allowFullScreen
1062
- style={{ border: 0, display: "block" }}
1063
- onError={() => {
1064
- if (retryNonce === 0) {
1065
- setRetryNonce(1);
1066
- return;
1067
- }
1068
- setFailed(true);
1069
- }}
1070
- />
1071
- </div>
1072
- );
1073
- }
1074
-
1075
- // Memoized: this component appears under every assistant bubble and during
1076
- // streaming gets re-rendered on every rAF flush. The inner ReactMarkdown
1077
- // pipeline (remark + rehype passes, syntax highlighting via rehypeHighlight,
1078
- // custom <a> / <code> renderers) is the expensive part — re-running it
1079
- // against unchanged text on every parent render shows up as jank on long
1080
- // threads. With memo, only the in-flight bubble re-renders during streaming;
1081
- // persisted siblings sit idle.
1082
- const MarkdownContent = memo(function MarkdownContent({ text, streaming, onInAppLink, unverifiedLinks, sourceManifest, threadId }: { text: string; streaming?: boolean; onInAppLink?: (href: string) => void; unverifiedLinks?: ReadonlySet<string>; sourceManifest?: ReadonlyMap<number, { href: string; label: string }>; threadId?: string | null }) {
1083
- // Inline-citation pre-processor. The agent writes `[3]` markers in-prose;
1084
- // we resolve each to a markdown link `[3](href)` BEFORE react-markdown
1085
- // parses the string so the existing <a> renderer below picks it up with
1086
- // no special-casing. Markers whose number isn't in the manifest are
1087
- // left untouched (they'll show as plain `[3]` text) so an invented
1088
- // number is visibly un-linked rather than silently mis-routed.
1089
- const renderedText = useMemo(() => {
1090
- if (!sourceManifest || sourceManifest.size === 0) return text;
1091
- return text.replace(/(?<!\])\[(\d+)\]/g, (match, raw: string) => {
1092
- const entry = sourceManifest.get(parseInt(raw, 10));
1093
- return entry ? `[${raw}](${entry.href})` : match;
1094
- });
1095
- }, [text, sourceManifest]);
1096
- return (
1097
- <div className="prose prose-invert prose-sm max-w-none jarela-rich min-w-0">
1098
- <ReactMarkdown
1099
- remarkPlugins={MD_REMARK_PLUGINS}
1100
- rehypePlugins={MD_REHYPE_PLUGINS}
1101
- components={{
1102
- a({ href, children, ...rest }) {
1103
- const parsed = href ? parseHref(href) : undefined;
1104
- const isUnverified = !!(href && unverifiedLinks?.has(href));
1105
- // Detect citation markers: link text is literally `[N]` where N
1106
- // is a positive integer. These are rendered as small superscript
1107
- // chips (Wikipedia-style) so they're scannable as citations and
1108
- // distinct from ordinary inline links.
1109
- const isCitationMarker =
1110
- Array.isArray(children) && children.length === 1
1111
- ? typeof children[0] === "string" && /^\[\d+\]$/.test(children[0])
1112
- : typeof children === "string" && /^\[\d+\]$/.test(children);
1113
- const citationText = isCitationMarker
1114
- ? (Array.isArray(children) ? (children[0] as string) : (children as string))
1115
- : null;
1116
- // Inline audio: any link to a local /api/v1/files/*.{wav,mp3,ogg,webm,m4a}
1117
- // becomes a native <audio controls> player. The original anchor
1118
- // text is dropped — the player IS the answer. An `?autoplay=1`
1119
- // query string lets the agent (via generate_voice) ask the
1120
- // browser to start playback immediately.
1121
- if (href && /^\/api\/v1\/files\/[^?#]+\.(wav|mp3|ogg|webm|m4a)(\?|#|$)/i.test(href)) {
1122
- return <InlineAudio href={href} />;
1123
- }
1124
- const unverifiedCls = isUnverified ? "decoration-warn decoration-wavy underline-offset-2" : "";
1125
- const unverifiedTitle = isUnverified ? "Agent did not visit this source in this conversation — the citation may be invented." : undefined;
1126
- if (href && isLikelyLocalFileHref(href)) {
1127
- return (
1128
- <LocalFileLink href={href} threadId={threadId} title={unverifiedTitle ?? rest.title} className={`${rest.className ?? ""} ${unverifiedCls}`.trim()}>
1129
- {children}
1130
- {isUnverified && <sup className="text-warn ml-0.5" aria-label="unverified citation">⚠</sup>}
1131
- </LocalFileLink>
1132
- );
1133
- }
1134
- const inApp = !!parsed && !parsed.external && (!!parsed.tab || !!parsed.hash || (!!parsed.thread && !!parsed.agent));
1135
- // Citation-marker rendering: superscript chip with a tooltip
1136
- // showing the source label so the user can preview what the
1137
- // marker points to without clicking. The href is still active
1138
- // (jumps to anchor for #msg-… or opens external for URLs).
1139
- if (isCitationMarker && href) {
1140
- const markerNum = parseInt(citationText!.replace(/[\[\]]/g, ""), 10);
1141
- const entry = Number.isFinite(markerNum) ? sourceManifest?.get(markerNum) : undefined;
1142
- const title = entry?.label ?? unverifiedTitle ?? href;
1143
- const isAnchor = href.startsWith("#");
1144
- return (
1145
- <a
1146
- {...rest}
1147
- href={href}
1148
- target={isAnchor || inApp ? undefined : "_blank"}
1149
- rel={isAnchor || inApp ? undefined : "noopener noreferrer"}
1150
- title={title}
1151
- onClick={inApp && onInAppLink ? (e) => { e.preventDefault(); onInAppLink(href); } : undefined}
1152
- className="jarela-citation"
1153
- >
1154
- {citationText}
1155
- </a>
1156
- );
1157
- }
1158
- if (inApp && href && onInAppLink) {
1159
- return (
1160
- <a
1161
- {...rest}
1162
- href={href}
1163
- title={unverifiedTitle ?? rest.title}
1164
- className={`${rest.className ?? ""} ${unverifiedCls}`.trim()}
1165
- onClick={(e) => { e.preventDefault(); onInAppLink(href); }}
1166
- >
1167
- {children}
1168
- {isUnverified && <sup className="text-warn ml-0.5" aria-label="unverified citation">⚠</sup>}
1169
- </a>
1170
- );
1171
- }
1172
- return (
1173
- <a
1174
- {...rest}
1175
- href={href}
1176
- target="_blank"
1177
- rel="noopener noreferrer"
1178
- title={unverifiedTitle ?? rest.title}
1179
- className={`${rest.className ?? ""} ${unverifiedCls}`.trim()}
1180
- >
1181
- {children}
1182
- {isUnverified && <sup className="text-warn ml-0.5" aria-label="unverified citation">⚠</sup>}
1183
- </a>
1184
- );
1185
- },
1186
- pre({ children }) {
1187
- // CodeFence renders its own <pre>, so collapse react-markdown's
1188
- // outer wrapper to avoid <pre><pre>...</pre></pre>.
1189
- return <>{children}</>;
1190
- },
1191
- code({ className, children }) {
1192
- const match = /language-(\w+)/.exec(className ?? "");
1193
- if (match?.[1] === "map") {
1194
- return <MapEmbed payload={reactChildrenToText(children).replace(/\n$/, "")} />;
1195
- }
1196
- if (match?.[1] === "mermaid") {
1197
- return <MermaidFence source={reactChildrenToText(children).replace(/\n$/, "")} />;
1198
- }
1199
- return match ? (
1200
- <CodeFence language={match[1]} className={className ?? ""}>{children}</CodeFence>
1201
- ) : (
1202
- <code className="bg-surface-2 px-1 rounded text-fg-muted break-all">{children}</code>
1203
- );
1204
- },
1205
- img({ src, alt }) {
1206
- return <ResilientMarkdownImage src={src} alt={alt} />;
1207
- },
1208
- }}
1209
- >
1210
- {renderedText}
1211
- </ReactMarkdown>
1212
- {streaming && <span className="jarela-stream-caret" aria-hidden="true" />}
1213
- </div>
1214
- );
1215
- });
1216
-
1217
713
  function ReferencesPanel({ sources }: { sources: ReadonlyArray<{ n: number; label: string; href: string }> }) {
1218
714
  const [open, setOpen] = useState(false);
1219
715
  if (sources.length === 0) return null;
@@ -1506,238 +1002,10 @@ function RefsFooter({ refs }: { refs: ExtractedRef[] }) {
1506
1002
  );
1507
1003
  }
1508
1004
 
1509
- function CodeFence({ language, className, children }: { language: string; className: string; children: ReactNode }) {
1510
- const [copied, setCopied] = useState(false);
1511
- const codeText = useMemo(() => reactChildrenToText(children).replace(/\n$/, ""), [children]);
1512
-
1513
- const copyCode = useCallback(() => {
1514
- void navigator.clipboard.writeText(codeText).then(() => {
1515
- setCopied(true);
1516
- setTimeout(() => setCopied(false), 1200);
1517
- }).catch(console.error);
1518
- }, [codeText]);
1519
-
1520
- // rehype-highlight already populated `className` with `hljs language-X`
1521
- // plus per-token spans inside `children`. The `hljs` class drives styling
1522
- // from the imported github-dark theme.
1523
- return (
1524
- <div className="relative my-2 rounded-md overflow-hidden border border-border/60">
1525
- <div className="flex items-center justify-between px-2 py-1 text-[10px] bg-surface-3 text-fg-faint uppercase tracking-wide">
1526
- <span>{language}</span>
1527
- <button
1528
- onClick={copyCode}
1529
- className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-border/60 bg-surface-2 text-fg-muted hover:text-fg transition-colors"
1530
- title="Copy code"
1531
- aria-label="Copy code"
1532
- >
1533
- {copied ? <Check size={10} /> : <Copy size={10} />}
1534
- <span>{copied ? "Copied" : "Copy"}</span>
1535
- </button>
1536
- </div>
1537
- <pre className="m-0 p-3 text-xs leading-relaxed overflow-x-auto bg-[#0d1117]">
1538
- <code className={className}>{children}</code>
1539
- </pre>
1540
- </div>
1541
- );
1542
- }
1543
-
1544
- function MermaidFence({ source }: { source: string }) {
1545
- const renderId = `mermaid-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
1546
- const [svg, setSvg] = useState<string | null>(null);
1547
- const [error, setError] = useState<string | null>(null);
1548
-
1549
- useEffect(() => {
1550
- let cancelled = false;
1551
- setSvg(null);
1552
- setError(null);
1553
- void (async () => {
1554
- try {
1555
- const [{ default: mermaid }, { default: DOMPurify }] = await Promise.all([
1556
- import("mermaid"),
1557
- import("dompurify"),
1558
- ]);
1559
- mermaid.initialize({ startOnLoad: false, securityLevel: "strict", theme: "base" });
1560
- const result = await mermaid.render(renderId, source);
1561
- if (cancelled) return;
1562
- setSvg(DOMPurify.sanitize(result.svg, { USE_PROFILES: { svg: true } }));
1563
- } catch (err) {
1564
- if (!cancelled) setError(err instanceof Error ? err.message : String(err));
1565
- }
1566
- })();
1567
- return () => { cancelled = true; };
1568
- }, [renderId, source]);
1569
-
1570
- if (error) {
1571
- return (
1572
- <div className="my-2 rounded-md border border-warn/40 bg-warn/5 p-2">
1573
- <p className="mb-1 text-[10px] uppercase tracking-wide text-warn">Mermaid preview unavailable</p>
1574
- <CodeFence language="mermaid" className="language-mermaid"><>{source}</></CodeFence>
1575
- </div>
1576
- );
1577
- }
1578
- if (!svg) {
1579
- return <div className="my-2 rounded-md border border-border/60 bg-surface-3/40 p-3 text-xs text-fg-faint">Rendering diagram...</div>;
1580
- }
1581
- return (
1582
- <div
1583
- className="my-2 max-w-full overflow-x-auto rounded-md border border-border/60 bg-surface-2 p-3"
1584
- dangerouslySetInnerHTML={{ __html: svg }}
1585
- role="img"
1586
- aria-label="Mermaid diagram"
1587
- />
1588
- );
1589
- }
1590
-
1591
- function ContentPartView({ part, isUser, onInAppLink, unverifiedLinks, sourceManifest, threadId }: { part: ContentPart; isUser: boolean; onInAppLink?: (href: string) => void; unverifiedLinks?: ReadonlySet<string>; sourceManifest?: ReadonlyMap<number, { href: string; label: string }>; threadId?: string | null }) {
1592
- if (part.type === "text") {
1593
- return <MarkdownContent text={part.text} onInAppLink={onInAppLink} unverifiedLinks={unverifiedLinks} sourceManifest={sourceManifest} threadId={threadId} />;
1594
- }
1595
- if (part.type === "image") {
1596
- return <ClickableImage src={`data:${part.media_type};base64,${part.data}`} />;
1597
- }
1598
- if (part.type === "image_ref") {
1599
- // Ref-based image — server-hosted at /api/v1/files/[name]. See ADR-0065.
1600
- return <ClickableImage src={`/api/v1/files/${encodeURIComponent(part.name)}`} />;
1601
- }
1602
- if (part.type === "file_ref") {
1603
- return (
1604
- <a
1605
- href={`/api/v1/files/${encodeURIComponent(part.name)}`}
1606
- target="_blank"
1607
- rel="noopener noreferrer"
1608
- className="inline-flex items-center gap-1.5 px-2.5 py-1.5 mt-1 rounded-lg border border-border/60 bg-surface-3/60 hover:bg-surface-3 hover:border-border text-[11px] text-fg-muted transition-colors"
1609
- title="Open in new tab"
1610
- >
1611
- <Paperclip size={11} className="text-fg-faint shrink-0" />
1612
- <span className="truncate max-w-[200px]">{part.filename}</span>
1613
- </a>
1614
- );
1615
- }
1616
- // File attachment — render an inline player for audio/video so voice
1617
- // notes and short clips from the WhatsApp bridge are usable in-bubble.
1618
- // Other file types still fall through to a download/open-in-new-tab link.
1619
- const file = part as ContentPart & { type: "file"; name: string; media_type: string; data: string };
1620
- const dataUrl = `data:${file.media_type};base64,${file.data}`;
1621
- // For text files our data field is plain text, not base64. Detect and wrap.
1622
- const href = /^text\/|^application\/json$/.test(file.media_type)
1623
- ? `data:${file.media_type};charset=utf-8,${encodeURIComponent(file.data)}`
1624
- : dataUrl;
1625
- if (file.media_type.startsWith("audio/")) {
1626
- return (
1627
- <div className="mt-1 max-w-md">
1628
- {/* Native controls keep play/pause/seek consistent with the OS;
1629
- the filename hint below disambiguates voice-note vs file. */}
1630
- <audio controls className="w-full" src={dataUrl} />
1631
- <div className="mt-0.5 text-[10px] text-fg-faint truncate">{file.name}</div>
1632
- </div>
1633
- );
1634
- }
1635
- if (file.media_type.startsWith("video/")) {
1636
- return (
1637
- <div className="mt-1 max-w-md">
1638
- <video
1639
- controls
1640
- playsInline
1641
- className="w-full rounded-xl border border-border/40"
1642
- style={{ maxHeight: "400px" }}
1643
- src={dataUrl}
1644
- />
1645
- <div className="mt-0.5 text-[10px] text-fg-faint truncate">{file.name}</div>
1646
- </div>
1647
- );
1648
- }
1649
- return (
1650
- <a
1651
- href={href}
1652
- target="_blank"
1653
- rel="noopener noreferrer"
1654
- className="inline-flex items-center gap-1.5 px-2.5 py-1.5 mt-1 rounded-lg border border-border/60 bg-surface-3/60 hover:bg-surface-3 hover:border-border text-[11px] text-fg-muted transition-colors"
1655
- title="Open in new tab"
1656
- >
1657
- <Paperclip size={11} className="text-fg-faint shrink-0" />
1658
- <span className="truncate max-w-[200px]">{file.name}</span>
1659
- </a>
1660
- );
1661
- }
1662
-
1663
1005
  function hasImageAttachment(content: string | ContentPart[]): boolean {
1664
1006
  return Array.isArray(content) && content.some((part) => part.type === "image" || part.type === "image_ref");
1665
1007
  }
1666
1008
 
1667
- // Image attachment — thumbnail in the bubble, click for a full-screen lightbox.
1668
- // Accepts either a `data:` URL (inline base64) or a `/api/v1/files/[name]`
1669
- // URL (disk-hosted ref, see ADR-0065). Both render identically.
1670
- function ClickableImage({ src }: { src: string }) {
1671
- const [open, setOpen] = useState(false);
1672
- const [naturalSize, setNaturalSize] = useState<{ width: number; height: number } | null>(null);
1673
- return (
1674
- <>
1675
- {/* eslint-disable-next-line @next/next/no-img-element */}
1676
- <img
1677
- src={src}
1678
- alt="attached image"
1679
- onLoad={(e) => {
1680
- const img = e.currentTarget;
1681
- if (img.naturalWidth > 0 && img.naturalHeight > 0) {
1682
- setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight });
1683
- }
1684
- }}
1685
- onClick={() => setOpen(true)}
1686
- className="block w-full max-w-full rounded-xl mt-1 border border-border/40 cursor-zoom-in hover:border-fg-faint transition-colors"
1687
- style={{
1688
- width: naturalSize ? `min(100%, ${naturalSize.width}px)` : "100%",
1689
- maxHeight: naturalSize ? `min(82dvh, ${naturalSize.height}px)` : "82dvh",
1690
- objectFit: "contain",
1691
- }}
1692
- />
1693
- <ImagePreviewDialog src={src} alt="attached image" open={open} onClose={() => setOpen(false)} />
1694
- </>
1695
- );
1696
- }
1697
-
1698
- function ImagePreviewDialog({ src, alt, open, onClose }: { src: string; alt: string; open: boolean; onClose: () => void }) {
1699
- return (
1700
- <Dialog
1701
- open={open}
1702
- onClose={onClose}
1703
- title="Image preview"
1704
- size="full"
1705
- align="center"
1706
- level="elevated"
1707
- padded={false}
1708
- fitViewport
1709
- footer={(
1710
- <div className="flex items-center justify-end gap-2 px-4 pb-3">
1711
- <a
1712
- href={src}
1713
- target="_blank"
1714
- rel="noopener noreferrer"
1715
- className="px-2.5 py-1.5 rounded-md border border-border/70 bg-surface-3 text-xs text-fg-muted hover:text-fg hover:border-border"
1716
- >
1717
- Open in new tab
1718
- </a>
1719
- <button
1720
- type="button"
1721
- onClick={onClose}
1722
- className="px-2.5 py-1.5 rounded-md border border-border/70 bg-surface-3 text-xs text-fg-muted hover:text-fg hover:border-border"
1723
- >
1724
- Close
1725
- </button>
1726
- </div>
1727
- )}
1728
- >
1729
- <div className="h-full w-full min-w-0 bg-black/95 flex items-center justify-center">
1730
- {/* eslint-disable-next-line @next/next/no-img-element */}
1731
- <img
1732
- src={src}
1733
- alt={alt}
1734
- className="block max-h-full max-w-full h-auto w-auto object-contain"
1735
- />
1736
- </div>
1737
- </Dialog>
1738
- );
1739
- }
1740
-
1741
1009
  function messageTextForCopy(content: string | ContentPart[]): string {
1742
1010
  if (typeof content === "string") return content;
1743
1011
  return content.map((part) => {