markupr 2.1.8

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 (299) hide show
  1. package/.claude/commands/review-feedback.md +47 -0
  2. package/.eslintrc.json +35 -0
  3. package/.github/CODEOWNERS +16 -0
  4. package/.github/FUNDING.yml +1 -0
  5. package/.github/ISSUE_TEMPLATE/bug_report.md +56 -0
  6. package/.github/ISSUE_TEMPLATE/feature_request.md +54 -0
  7. package/.github/PULL_REQUEST_TEMPLATE.md +89 -0
  8. package/.github/dependabot.yml +70 -0
  9. package/.github/workflows/ci.yml +184 -0
  10. package/.github/workflows/deploy-landing.yml +134 -0
  11. package/.github/workflows/nightly.yml +288 -0
  12. package/.github/workflows/release.yml +318 -0
  13. package/CHANGELOG.md +127 -0
  14. package/CLAUDE.md +137 -0
  15. package/CODE_OF_CONDUCT.md +9 -0
  16. package/CONTRIBUTING.md +390 -0
  17. package/LICENSE +21 -0
  18. package/PRODUCT_VISION.md +277 -0
  19. package/README.md +517 -0
  20. package/SECURITY.md +51 -0
  21. package/SIGNING_INSTRUCTIONS.md +284 -0
  22. package/assets/DMG_BACKGROUND_INSTRUCTIONS.md +130 -0
  23. package/assets/svg-source/dmg-background.svg +70 -0
  24. package/assets/svg-source/icon.svg +20 -0
  25. package/assets/svg-source/tray-icon-processing.svg +7 -0
  26. package/assets/svg-source/tray-icon-recording.svg +7 -0
  27. package/assets/svg-source/tray-icon.svg +6 -0
  28. package/assets/tray-complete.png +0 -0
  29. package/assets/tray-complete@2x.png +0 -0
  30. package/assets/tray-completeTemplate.png +0 -0
  31. package/assets/tray-completeTemplate@2x.png +0 -0
  32. package/assets/tray-error.png +0 -0
  33. package/assets/tray-error@2x.png +0 -0
  34. package/assets/tray-errorTemplate.png +0 -0
  35. package/assets/tray-errorTemplate@2x.png +0 -0
  36. package/assets/tray-icon-processing.png +0 -0
  37. package/assets/tray-icon-processing@2x.png +0 -0
  38. package/assets/tray-icon-processingTemplate.png +0 -0
  39. package/assets/tray-icon-processingTemplate@2x.png +0 -0
  40. package/assets/tray-icon-recording.png +0 -0
  41. package/assets/tray-icon-recording@2x.png +0 -0
  42. package/assets/tray-icon-recordingTemplate.png +0 -0
  43. package/assets/tray-icon-recordingTemplate@2x.png +0 -0
  44. package/assets/tray-icon.png +0 -0
  45. package/assets/tray-icon@2x.png +0 -0
  46. package/assets/tray-iconTemplate.png +0 -0
  47. package/assets/tray-iconTemplate@2x.png +0 -0
  48. package/assets/tray-idle.png +0 -0
  49. package/assets/tray-idle@2x.png +0 -0
  50. package/assets/tray-idleTemplate.png +0 -0
  51. package/assets/tray-idleTemplate@2x.png +0 -0
  52. package/assets/tray-processing-0.png +0 -0
  53. package/assets/tray-processing-0@2x.png +0 -0
  54. package/assets/tray-processing-0Template.png +0 -0
  55. package/assets/tray-processing-0Template@2x.png +0 -0
  56. package/assets/tray-processing-1.png +0 -0
  57. package/assets/tray-processing-1@2x.png +0 -0
  58. package/assets/tray-processing-1Template.png +0 -0
  59. package/assets/tray-processing-1Template@2x.png +0 -0
  60. package/assets/tray-processing-2.png +0 -0
  61. package/assets/tray-processing-2@2x.png +0 -0
  62. package/assets/tray-processing-2Template.png +0 -0
  63. package/assets/tray-processing-2Template@2x.png +0 -0
  64. package/assets/tray-processing-3.png +0 -0
  65. package/assets/tray-processing-3@2x.png +0 -0
  66. package/assets/tray-processing-3Template.png +0 -0
  67. package/assets/tray-processing-3Template@2x.png +0 -0
  68. package/assets/tray-processing.png +0 -0
  69. package/assets/tray-processing@2x.png +0 -0
  70. package/assets/tray-processingTemplate.png +0 -0
  71. package/assets/tray-processingTemplate@2x.png +0 -0
  72. package/assets/tray-recording.png +0 -0
  73. package/assets/tray-recording@2x.png +0 -0
  74. package/assets/tray-recordingTemplate.png +0 -0
  75. package/assets/tray-recordingTemplate@2x.png +0 -0
  76. package/build/DMG_BACKGROUND_SPEC.md +50 -0
  77. package/build/dmg-background.png +0 -0
  78. package/build/dmg-background@2x.png +0 -0
  79. package/build/entitlements.mac.inherit.plist +27 -0
  80. package/build/entitlements.mac.plist +41 -0
  81. package/build/favicon-16.png +0 -0
  82. package/build/favicon-180.png +0 -0
  83. package/build/favicon-192.png +0 -0
  84. package/build/favicon-32.png +0 -0
  85. package/build/favicon-48.png +0 -0
  86. package/build/favicon-512.png +0 -0
  87. package/build/favicon-64.png +0 -0
  88. package/build/icon-128.png +0 -0
  89. package/build/icon-16.png +0 -0
  90. package/build/icon-24.png +0 -0
  91. package/build/icon-256.png +0 -0
  92. package/build/icon-32.png +0 -0
  93. package/build/icon-48.png +0 -0
  94. package/build/icon-64.png +0 -0
  95. package/build/icon.icns +0 -0
  96. package/build/icon.ico +0 -0
  97. package/build/icon.iconset/icon_128x128.png +0 -0
  98. package/build/icon.iconset/icon_128x128@2x.png +0 -0
  99. package/build/icon.iconset/icon_16x16.png +0 -0
  100. package/build/icon.iconset/icon_16x16@2x.png +0 -0
  101. package/build/icon.iconset/icon_256x256.png +0 -0
  102. package/build/icon.iconset/icon_256x256@2x.png +0 -0
  103. package/build/icon.iconset/icon_32x32.png +0 -0
  104. package/build/icon.iconset/icon_32x32@2x.png +0 -0
  105. package/build/icon.iconset/icon_512x512.png +0 -0
  106. package/build/icon.iconset/icon_512x512@2x.png +0 -0
  107. package/build/icon.png +0 -0
  108. package/build/installer-header.bmp +0 -0
  109. package/build/installer-header.png +0 -0
  110. package/build/installer-sidebar.bmp +0 -0
  111. package/build/installer-sidebar.png +0 -0
  112. package/build/installer.nsh +45 -0
  113. package/build/overlay-processing.png +0 -0
  114. package/build/overlay-recording.png +0 -0
  115. package/build/toolbar-record.png +0 -0
  116. package/build/toolbar-screenshot.png +0 -0
  117. package/build/toolbar-settings.png +0 -0
  118. package/build/toolbar-stop.png +0 -0
  119. package/dist/main/index.mjs +12612 -0
  120. package/dist/preload/index.mjs +907 -0
  121. package/dist/renderer/assets/index-CCmUjl9K.js +19495 -0
  122. package/dist/renderer/assets/index-CUqz_Gs6.css +2270 -0
  123. package/dist/renderer/index.html +27 -0
  124. package/docs/AI_AGENT_QUICKSTART.md +42 -0
  125. package/docs/AI_PIPELINE_DESIGN.md +595 -0
  126. package/docs/API.md +514 -0
  127. package/docs/ARCHITECTURE.md +460 -0
  128. package/docs/CONFIGURATION.md +336 -0
  129. package/docs/DEVELOPMENT.md +508 -0
  130. package/docs/EXPORT_FORMATS.md +451 -0
  131. package/docs/GETTING_STARTED.md +236 -0
  132. package/docs/KEYBOARD_SHORTCUTS.md +334 -0
  133. package/docs/TROUBLESHOOTING.md +418 -0
  134. package/docs/landing/index.html +672 -0
  135. package/docs/landing/script.js +342 -0
  136. package/docs/landing/styles.css +1543 -0
  137. package/electron-builder.yml +140 -0
  138. package/electron.vite.config.ts +63 -0
  139. package/package.json +108 -0
  140. package/railway.json +12 -0
  141. package/scripts/build.mjs +51 -0
  142. package/scripts/generate-icons.mjs +314 -0
  143. package/scripts/generate-installer-images.cjs +253 -0
  144. package/scripts/generate-tray-icons.mjs +258 -0
  145. package/scripts/notarize.cjs +180 -0
  146. package/scripts/one-click-clean-test.sh +147 -0
  147. package/scripts/postinstall.mjs +36 -0
  148. package/scripts/setup-markupr.sh +55 -0
  149. package/setup +17 -0
  150. package/site/index.html +1835 -0
  151. package/site/package.json +11 -0
  152. package/site/railway.json +12 -0
  153. package/site/server.js +31 -0
  154. package/src/main/AutoUpdater.ts +392 -0
  155. package/src/main/CrashRecovery.ts +655 -0
  156. package/src/main/ErrorHandler.ts +703 -0
  157. package/src/main/HotkeyManager.ts +399 -0
  158. package/src/main/MenuManager.ts +529 -0
  159. package/src/main/PermissionManager.ts +420 -0
  160. package/src/main/SessionController.ts +1465 -0
  161. package/src/main/TrayManager.ts +540 -0
  162. package/src/main/ai/AIPipelineManager.ts +199 -0
  163. package/src/main/ai/ClaudeAnalyzer.ts +339 -0
  164. package/src/main/ai/ImageOptimizer.ts +176 -0
  165. package/src/main/ai/StructuredMarkdownBuilder.ts +379 -0
  166. package/src/main/ai/index.ts +16 -0
  167. package/src/main/ai/types.ts +258 -0
  168. package/src/main/analysis/ClarificationGenerator.ts +385 -0
  169. package/src/main/analysis/FeedbackAnalyzer.ts +531 -0
  170. package/src/main/analysis/index.ts +19 -0
  171. package/src/main/audio/AudioCapture.ts +978 -0
  172. package/src/main/audio/audioUtils.ts +100 -0
  173. package/src/main/audio/index.ts +20 -0
  174. package/src/main/capture/index.ts +1 -0
  175. package/src/main/index.ts +1693 -0
  176. package/src/main/ipc/captureHandlers.ts +272 -0
  177. package/src/main/ipc/index.ts +45 -0
  178. package/src/main/ipc/outputHandlers.ts +302 -0
  179. package/src/main/ipc/sessionHandlers.ts +56 -0
  180. package/src/main/ipc/settingsHandlers.ts +471 -0
  181. package/src/main/ipc/types.ts +56 -0
  182. package/src/main/ipc/windowHandlers.ts +277 -0
  183. package/src/main/output/ClipboardService.ts +369 -0
  184. package/src/main/output/ExportService.ts +539 -0
  185. package/src/main/output/FileManager.ts +416 -0
  186. package/src/main/output/MarkdownGenerator.ts +791 -0
  187. package/src/main/output/MarkdownPatcher.ts +299 -0
  188. package/src/main/output/index.ts +186 -0
  189. package/src/main/output/sessionAdapter.ts +207 -0
  190. package/src/main/output/templates/html-template.ts +553 -0
  191. package/src/main/pipeline/FrameExtractor.ts +330 -0
  192. package/src/main/pipeline/PostProcessor.ts +399 -0
  193. package/src/main/pipeline/TranscriptAnalyzer.ts +226 -0
  194. package/src/main/pipeline/index.ts +36 -0
  195. package/src/main/platform/WindowsTaskbar.ts +600 -0
  196. package/src/main/platform/index.ts +16 -0
  197. package/src/main/settings/SettingsManager.ts +730 -0
  198. package/src/main/settings/index.ts +19 -0
  199. package/src/main/transcription/ModelDownloadManager.ts +494 -0
  200. package/src/main/transcription/TierManager.ts +219 -0
  201. package/src/main/transcription/TranscriptionRecoveryService.ts +340 -0
  202. package/src/main/transcription/WhisperService.ts +748 -0
  203. package/src/main/transcription/index.ts +56 -0
  204. package/src/main/transcription/types.ts +135 -0
  205. package/src/main/windows/PopoverManager.ts +284 -0
  206. package/src/main/windows/TaskbarIntegration.ts +452 -0
  207. package/src/main/windows/index.ts +23 -0
  208. package/src/preload/index.ts +1047 -0
  209. package/src/renderer/App.tsx +515 -0
  210. package/src/renderer/AppWrapper.tsx +28 -0
  211. package/src/renderer/assets/logo-dark.svg +7 -0
  212. package/src/renderer/assets/logo.svg +7 -0
  213. package/src/renderer/audio/AudioCaptureRenderer.ts +454 -0
  214. package/src/renderer/capture/ScreenRecordingRenderer.ts +492 -0
  215. package/src/renderer/components/AnnotationOverlay.tsx +836 -0
  216. package/src/renderer/components/AudioWaveform.tsx +811 -0
  217. package/src/renderer/components/ClarificationQuestions.tsx +656 -0
  218. package/src/renderer/components/CountdownTimer.tsx +495 -0
  219. package/src/renderer/components/CrashRecoveryDialog.tsx +632 -0
  220. package/src/renderer/components/DonateButton.tsx +127 -0
  221. package/src/renderer/components/ErrorBoundary.tsx +308 -0
  222. package/src/renderer/components/ExportDialog.tsx +872 -0
  223. package/src/renderer/components/HotkeyHint.tsx +261 -0
  224. package/src/renderer/components/KeyboardShortcuts.tsx +787 -0
  225. package/src/renderer/components/ModelDownloadDialog.tsx +844 -0
  226. package/src/renderer/components/Onboarding.tsx +1830 -0
  227. package/src/renderer/components/ProcessingOverlay.tsx +157 -0
  228. package/src/renderer/components/RecordingOverlay.tsx +423 -0
  229. package/src/renderer/components/SessionHistory.tsx +1746 -0
  230. package/src/renderer/components/SessionReview.tsx +1321 -0
  231. package/src/renderer/components/SettingsPanel.tsx +217 -0
  232. package/src/renderer/components/Skeleton.tsx +347 -0
  233. package/src/renderer/components/StatusIndicator.tsx +86 -0
  234. package/src/renderer/components/ThemeProvider.tsx +429 -0
  235. package/src/renderer/components/Tooltip.tsx +370 -0
  236. package/src/renderer/components/TranscriptionPreview.tsx +183 -0
  237. package/src/renderer/components/TranscriptionTierSelector.tsx +640 -0
  238. package/src/renderer/components/UpdateNotification.tsx +377 -0
  239. package/src/renderer/components/WindowSelector.tsx +947 -0
  240. package/src/renderer/components/index.ts +99 -0
  241. package/src/renderer/components/primitives/ApiKeyInput.tsx +98 -0
  242. package/src/renderer/components/primitives/ColorPicker.tsx +65 -0
  243. package/src/renderer/components/primitives/DangerButton.tsx +45 -0
  244. package/src/renderer/components/primitives/DirectoryPicker.tsx +41 -0
  245. package/src/renderer/components/primitives/Dropdown.tsx +34 -0
  246. package/src/renderer/components/primitives/KeyRecorder.tsx +117 -0
  247. package/src/renderer/components/primitives/SettingsSection.tsx +32 -0
  248. package/src/renderer/components/primitives/Slider.tsx +43 -0
  249. package/src/renderer/components/primitives/Toggle.tsx +36 -0
  250. package/src/renderer/components/primitives/index.ts +10 -0
  251. package/src/renderer/components/settings/AdvancedTab.tsx +174 -0
  252. package/src/renderer/components/settings/AppearanceTab.tsx +77 -0
  253. package/src/renderer/components/settings/GeneralTab.tsx +40 -0
  254. package/src/renderer/components/settings/HotkeysTab.tsx +79 -0
  255. package/src/renderer/components/settings/RecordingTab.tsx +84 -0
  256. package/src/renderer/components/settings/index.ts +9 -0
  257. package/src/renderer/components/settings/settingsStyles.ts +673 -0
  258. package/src/renderer/components/settings/tabConfig.tsx +85 -0
  259. package/src/renderer/components/settings/useSettingsPanel.ts +447 -0
  260. package/src/renderer/contexts/ProcessingContext.tsx +227 -0
  261. package/src/renderer/contexts/RecordingContext.tsx +683 -0
  262. package/src/renderer/contexts/UIContext.tsx +326 -0
  263. package/src/renderer/contexts/index.ts +24 -0
  264. package/src/renderer/donateMessages.ts +69 -0
  265. package/src/renderer/hooks/index.ts +75 -0
  266. package/src/renderer/hooks/useAnimation.tsx +544 -0
  267. package/src/renderer/hooks/useTheme.ts +313 -0
  268. package/src/renderer/index.html +26 -0
  269. package/src/renderer/main.tsx +52 -0
  270. package/src/renderer/styles/animations.css +1093 -0
  271. package/src/renderer/styles/app-shell.css +662 -0
  272. package/src/renderer/styles/globals.css +515 -0
  273. package/src/renderer/styles/theme.ts +578 -0
  274. package/src/renderer/types/electron.d.ts +385 -0
  275. package/src/shared/hotkeys.ts +283 -0
  276. package/src/shared/types.ts +809 -0
  277. package/tests/clipboard.test.ts +228 -0
  278. package/tests/e2e/criticalPaths.test.ts +594 -0
  279. package/tests/feedbackAnalyzer.test.ts +303 -0
  280. package/tests/integration/sessionFlow.test.ts +583 -0
  281. package/tests/markdownGenerator.test.ts +418 -0
  282. package/tests/output.test.ts +96 -0
  283. package/tests/setup.ts +486 -0
  284. package/tests/unit/appIntegration.test.ts +676 -0
  285. package/tests/unit/appViewState.test.ts +281 -0
  286. package/tests/unit/audioIpcChannels.test.ts +17 -0
  287. package/tests/unit/exportService.test.ts +492 -0
  288. package/tests/unit/hotkeys.test.ts +92 -0
  289. package/tests/unit/navigationPreload.test.ts +94 -0
  290. package/tests/unit/onboardingFlow.test.ts +345 -0
  291. package/tests/unit/permissionManager.test.ts +175 -0
  292. package/tests/unit/permissionManagerExpanded.test.ts +296 -0
  293. package/tests/unit/screenRecordingRenderer.test.ts +368 -0
  294. package/tests/unit/sessionController.test.ts +515 -0
  295. package/tests/unit/tierManager.test.ts +61 -0
  296. package/tests/unit/tierManagerExpanded.test.ts +142 -0
  297. package/tests/unit/transcriptAnalyzer.test.ts +64 -0
  298. package/tsconfig.json +25 -0
  299. package/vitest.config.ts +46 -0
@@ -0,0 +1,299 @@
1
+ /**
2
+ * MarkdownPatcher
3
+ *
4
+ * Post-processing utilities for patching generated markdown reports with
5
+ * extracted frame links, metadata sync, and processing traces. Extracted
6
+ * from index.ts for separation of concerns.
7
+ */
8
+
9
+ import * as fs from 'fs/promises';
10
+ import { join, basename } from 'path';
11
+ import type { TranscriptSegment, KeyMoment } from '../pipeline';
12
+
13
+ // =============================================================================
14
+ // Text Normalization Helpers
15
+ // =============================================================================
16
+
17
+ export function formatSecondsAsTimestamp(seconds: number): string {
18
+ const total = Math.max(0, Math.floor(seconds));
19
+ const mins = Math.floor(total / 60);
20
+ const secs = total % 60;
21
+ return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
22
+ }
23
+
24
+ function normalizeForMatch(value: string): string {
25
+ return value
26
+ .toLowerCase()
27
+ .replace(/[`*_~[\]().,!?;:'"\\/|-]+/g, ' ')
28
+ .replace(/\s+/g, ' ')
29
+ .trim();
30
+ }
31
+
32
+ function buildTokenSet(value: string): Set<string> {
33
+ const tokens = normalizeForMatch(value)
34
+ .split(' ')
35
+ .map((token) => token.trim())
36
+ .filter((token) => token.length >= 3);
37
+ return new Set(tokens);
38
+ }
39
+
40
+ function overlapScore(a: Set<string>, b: Set<string>): number {
41
+ if (a.size === 0 || b.size === 0) {
42
+ return 0;
43
+ }
44
+ let overlap = 0;
45
+ for (const token of a) {
46
+ if (b.has(token)) {
47
+ overlap += 1;
48
+ }
49
+ }
50
+ return overlap / Math.min(a.size, b.size);
51
+ }
52
+
53
+ // =============================================================================
54
+ // AI Frame Hint Extraction
55
+ // =============================================================================
56
+
57
+ /**
58
+ * Parse AI-generated markdown to extract frame extraction hints.
59
+ * Matches **Timestamp:** annotations and blockquote references back
60
+ * to transcript segments for accurate frame timing.
61
+ */
62
+ export function extractAiFrameHintsFromMarkdown(
63
+ markdown: string,
64
+ transcriptSegments: TranscriptSegment[]
65
+ ): KeyMoment[] {
66
+ if (!markdown) {
67
+ return [];
68
+ }
69
+
70
+ const parseTimestampToSeconds = (value: string): number | null => {
71
+ const trimmed = value.trim();
72
+ const parts = trimmed.split(':').map((part) => Number.parseInt(part, 10));
73
+ if (parts.some((part) => !Number.isFinite(part) || part < 0)) {
74
+ return null;
75
+ }
76
+ if (parts.length === 2) {
77
+ return parts[0] * 60 + parts[1];
78
+ }
79
+ if (parts.length === 3) {
80
+ return parts[0] * 3600 + parts[1] * 60 + parts[2];
81
+ }
82
+ return null;
83
+ };
84
+
85
+ const timestampHints = Array.from(markdown.matchAll(/\*\*Timestamp:\*\*\s*([0-9]{1,2}:[0-9]{2}(?::[0-9]{2})?)/g))
86
+ .map((match) => parseTimestampToSeconds(match[1]))
87
+ .filter((value): value is number => value !== null)
88
+ .map((seconds) => ({
89
+ timestamp: Math.max(0, seconds),
90
+ reason: 'AI-timestamped issue context',
91
+ confidence: 0.96,
92
+ }));
93
+
94
+ const quoteLines = Array.from(markdown.matchAll(/^\s*>\s+(.+)$/gm))
95
+ .map((match) => match[1].trim())
96
+ .filter((line) => line.length >= 10);
97
+ if (quoteLines.length === 0 && timestampHints.length === 0) {
98
+ return [];
99
+ }
100
+
101
+ const normalizedSegments = transcriptSegments.map((segment) => ({
102
+ segment,
103
+ normalized: normalizeForMatch(segment.text || ''),
104
+ tokens: buildTokenSet(segment.text || ''),
105
+ }));
106
+
107
+ const hints: KeyMoment[] = [...timestampHints];
108
+ const seenQuotes = new Set<string>();
109
+
110
+ for (const quote of quoteLines) {
111
+ const normalizedQuote = normalizeForMatch(quote);
112
+ if (!normalizedQuote || seenQuotes.has(normalizedQuote)) {
113
+ continue;
114
+ }
115
+ seenQuotes.add(normalizedQuote);
116
+
117
+ const quoteTokens = buildTokenSet(quote);
118
+ let bestMatch: { score: number; segment: TranscriptSegment } | null = null;
119
+
120
+ for (const candidate of normalizedSegments) {
121
+ if (!candidate.normalized) {
122
+ continue;
123
+ }
124
+
125
+ let score = overlapScore(quoteTokens, candidate.tokens);
126
+ if (
127
+ normalizedQuote.length >= 16 &&
128
+ (candidate.normalized.includes(normalizedQuote) || normalizedQuote.includes(candidate.normalized))
129
+ ) {
130
+ score = Math.max(score, 0.9);
131
+ }
132
+
133
+ if (!bestMatch || score > bestMatch.score) {
134
+ bestMatch = { score, segment: candidate.segment };
135
+ }
136
+ }
137
+
138
+ if (!bestMatch || bestMatch.score < 0.34) {
139
+ continue;
140
+ }
141
+
142
+ const midpoint =
143
+ bestMatch.segment.startTime +
144
+ Math.max(0, (bestMatch.segment.endTime - bestMatch.segment.startTime) / 2);
145
+ hints.push({
146
+ timestamp: Math.max(0, midpoint),
147
+ reason: 'AI-highlighted context',
148
+ confidence: Math.min(0.98, 0.58 + bestMatch.score * 0.35),
149
+ });
150
+ }
151
+
152
+ if (hints.length === 0) {
153
+ return [];
154
+ }
155
+
156
+ const sorted = hints.sort((a, b) => a.timestamp - b.timestamp);
157
+ const deduped: KeyMoment[] = [];
158
+ for (const hint of sorted) {
159
+ const previous = deduped[deduped.length - 1];
160
+ if (!previous || Math.abs(previous.timestamp - hint.timestamp) >= 1.0) {
161
+ deduped.push(hint);
162
+ continue;
163
+ }
164
+ if (hint.confidence > previous.confidence) {
165
+ deduped[deduped.length - 1] = hint;
166
+ }
167
+ }
168
+
169
+ return deduped.slice(0, 12);
170
+ }
171
+
172
+ // =============================================================================
173
+ // Report Patching
174
+ // =============================================================================
175
+
176
+ /**
177
+ * Append extracted video frames to the markdown report.
178
+ * Verifies each frame path exists before linking to avoid broken images.
179
+ */
180
+ export async function appendExtractedFramesToReport(
181
+ markdownPath: string,
182
+ extractedFrames: Array<{ path: string; timestamp: number; reason: string }>
183
+ ): Promise<void> {
184
+ if (!extractedFrames.length) {
185
+ return;
186
+ }
187
+
188
+ const verifiedFrames: Array<{ path: string; timestamp: number; reason: string }> = [];
189
+ for (const frame of extractedFrames) {
190
+ try {
191
+ await fs.access(frame.path);
192
+ verifiedFrames.push(frame);
193
+ } catch {
194
+ // Skip stale frame references so markdown never links missing files.
195
+ }
196
+ }
197
+ if (!verifiedFrames.length) {
198
+ return;
199
+ }
200
+
201
+ let markdown = await fs.readFile(markdownPath, 'utf-8');
202
+ if (markdown.includes('## Auto-Extracted Screenshots')) {
203
+ return;
204
+ }
205
+
206
+ const lines = verifiedFrames
207
+ .slice()
208
+ .sort((a, b) => a.timestamp - b.timestamp)
209
+ .map((frame, index) => {
210
+ const filename = basename(frame.path) || `frame-${String(index + 1).padStart(3, '0')}.png`;
211
+ const timestamp = formatSecondsAsTimestamp(frame.timestamp);
212
+ const reason = frame.reason?.trim() || 'Auto-extracted frame';
213
+ return `### [${timestamp}] ${reason}\n\n![${reason}](./screenshots/${filename})`;
214
+ })
215
+ .join('\n\n');
216
+
217
+ markdown += `\n## Auto-Extracted Screenshots\n\n${lines}\n`;
218
+
219
+ // Keep report header/session info counts aligned with the post-processed frame output.
220
+ const screenshotCount = verifiedFrames.length;
221
+ markdown = markdown.replace(
222
+ /(\|\s*Duration:\s*[^|]+\|\s*)\d+\s+screenshots(\s*\|\s*\d+\s+items identified\s*\n)/,
223
+ `$1${screenshotCount} screenshots$2`
224
+ );
225
+ markdown = markdown.replace(
226
+ /(-\s*\*\*Screenshots:\*\*\s*)\d+/,
227
+ `$1${screenshotCount}`
228
+ );
229
+
230
+ await fs.writeFile(markdownPath, markdown, 'utf-8');
231
+ }
232
+
233
+ /**
234
+ * Sync extracted frame count into session metadata.json.
235
+ */
236
+ export async function syncExtractedFrameMetadata(
237
+ sessionDir: string,
238
+ screenshotCount: number
239
+ ): Promise<void> {
240
+ const metadataPath = join(sessionDir, 'metadata.json');
241
+ try {
242
+ const raw = await fs.readFile(metadataPath, 'utf-8');
243
+ const metadata = JSON.parse(raw) as { screenshotCount?: number };
244
+ metadata.screenshotCount = Math.max(
245
+ Number.isFinite(metadata.screenshotCount) ? Number(metadata.screenshotCount) : 0,
246
+ screenshotCount
247
+ );
248
+ await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2), 'utf-8');
249
+ } catch (error) {
250
+ console.warn('[Main] Failed to sync extracted frame metadata:', error);
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Sync extracted frame count into feedback-summary.md.
256
+ */
257
+ export async function syncExtractedFrameSummary(
258
+ sessionDir: string,
259
+ screenshotCount: number
260
+ ): Promise<void> {
261
+ const summaryPath = join(sessionDir, 'feedback-summary.md');
262
+ try {
263
+ const raw = await fs.readFile(summaryPath, 'utf-8');
264
+ const updated = raw.replace(/(\*\*Screenshots:\*\*\s*)\d+/, `$1${screenshotCount}`);
265
+ if (updated !== raw) {
266
+ await fs.writeFile(summaryPath, updated, 'utf-8');
267
+ }
268
+ } catch (error) {
269
+ console.warn('[Main] Failed to sync extracted frame summary:', error);
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Write a processing trace JSON file for debugging/diagnostics.
275
+ */
276
+ export async function writeProcessingTrace(
277
+ sessionDir: string,
278
+ trace: {
279
+ reportPath: string;
280
+ totalMs: number;
281
+ aiMs: number;
282
+ saveMs: number;
283
+ postProcessMs: number;
284
+ audioBytes: number;
285
+ recordingBytes: number;
286
+ transcriptBufferEvents: number;
287
+ providedTranscriptSegments: number;
288
+ aiFrameHints: number;
289
+ postProcessSegments: number;
290
+ extractedFrames: number;
291
+ aiTier: 'free' | 'byok' | 'premium';
292
+ aiEnhanced: boolean;
293
+ aiFallbackReason?: string;
294
+ completedAt: string;
295
+ }
296
+ ): Promise<void> {
297
+ const tracePath = join(sessionDir, 'processing-trace.json');
298
+ await fs.writeFile(tracePath, JSON.stringify(trace, null, 2), 'utf-8');
299
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Output Module
3
+ *
4
+ * Handles:
5
+ * - Markdown document generation
6
+ * - Screenshot embedding (base64)
7
+ * - Timestamp formatting
8
+ * - Clipboard integration
9
+ * - File output management
10
+ */
11
+
12
+ import type { FeedbackSession, OutputDocument, Screenshot, TranscriptionSegment } from '../../shared/types';
13
+ import { clipboardService, type ClipboardService } from './ClipboardService';
14
+ import type { Session } from '../SessionController';
15
+
16
+ export class OutputManager {
17
+ private clipboard: ClipboardService;
18
+
19
+ constructor() {
20
+ this.clipboard = clipboardService;
21
+ }
22
+ /**
23
+ * Generate a Markdown document from a feedback session
24
+ */
25
+ generateMarkdown(session: FeedbackSession): OutputDocument {
26
+ const { id, screenshots, transcription, startedAt, endedAt } = session;
27
+
28
+ // Build markdown content
29
+ let markdown = '# Feedback Session\n\n';
30
+
31
+ // Session metadata
32
+ markdown += `**Session ID:** ${id}\n`;
33
+ markdown += `**Started:** ${new Date(startedAt).toISOString()}\n`;
34
+ if (endedAt) {
35
+ markdown += `**Ended:** ${new Date(endedAt).toISOString()}\n`;
36
+ markdown += `**Duration:** ${Math.round((endedAt - startedAt) / 1000)}s\n`;
37
+ }
38
+ markdown += '\n---\n\n';
39
+
40
+ // Interleave transcription and screenshots by timestamp
41
+ const timeline = this.buildTimeline(transcription, screenshots);
42
+
43
+ for (const item of timeline) {
44
+ if (item.type === 'text') {
45
+ markdown += `${item.content}\n\n`;
46
+ } else if (item.type === 'screenshot') {
47
+ markdown += `![Screenshot at ${this.formatTimestamp(item.timestamp)}](${item.content})\n\n`;
48
+ }
49
+ }
50
+
51
+ return {
52
+ sessionId: id,
53
+ generatedAt: Date.now(),
54
+ markdown,
55
+ screenshots,
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Build a timeline interleaving transcription and screenshots
61
+ */
62
+ private buildTimeline(
63
+ transcription: TranscriptionSegment[],
64
+ screenshots: Screenshot[]
65
+ ): Array<{ type: 'text' | 'screenshot'; content: string; timestamp: number }> {
66
+ const timeline: Array<{ type: 'text' | 'screenshot'; content: string; timestamp: number }> = [];
67
+
68
+ // Add transcription segments
69
+ for (const segment of transcription) {
70
+ timeline.push({
71
+ type: 'text',
72
+ content: segment.text,
73
+ timestamp: segment.startTime,
74
+ });
75
+ }
76
+
77
+ // Add screenshots
78
+ for (const screenshot of screenshots) {
79
+ timeline.push({
80
+ type: 'screenshot',
81
+ content: screenshot.base64 || screenshot.imagePath,
82
+ timestamp: screenshot.timestamp,
83
+ });
84
+ }
85
+
86
+ // Sort by timestamp
87
+ timeline.sort((a, b) => a.timestamp - b.timestamp);
88
+
89
+ return timeline;
90
+ }
91
+
92
+ /**
93
+ * Format a timestamp as a readable string
94
+ */
95
+ private formatTimestamp(timestamp: number): string {
96
+ const date = new Date(timestamp);
97
+ return date.toLocaleTimeString('en-US', {
98
+ hour: '2-digit',
99
+ minute: '2-digit',
100
+ second: '2-digit',
101
+ });
102
+ }
103
+
104
+ /**
105
+ * Copy a summary of the session to clipboard with notification
106
+ */
107
+ async copySessionSummary(
108
+ session: Session,
109
+ reportPath?: string
110
+ ): Promise<boolean> {
111
+ const summary = this.clipboard.generateClipboardSummary(session, {
112
+ mode: 'compact',
113
+ maxLength: 1500,
114
+ includeReportPath: !!reportPath,
115
+ reportPath,
116
+ });
117
+
118
+ return this.clipboard.copyWithNotification(
119
+ summary,
120
+ 'Feedback Captured!'
121
+ );
122
+ }
123
+
124
+ /**
125
+ * Copy custom content to clipboard with notification
126
+ */
127
+ async copyToClipboard(content: string, title?: string): Promise<boolean> {
128
+ return this.clipboard.copyWithNotification(content, title);
129
+ }
130
+
131
+ /**
132
+ * Get the clipboard service for direct access
133
+ */
134
+ getClipboardService(): ClipboardService {
135
+ return this.clipboard;
136
+ }
137
+ }
138
+
139
+ // Singleton instance
140
+ export const outputManager = new OutputManager();
141
+
142
+ export default OutputManager;
143
+
144
+ // Re-export clipboard service types and instance
145
+ export { clipboardService, type ClipboardService, type SummaryOptions } from './ClipboardService';
146
+
147
+ // Re-export file manager types and instance
148
+ export { FileManager, fileManager, type SaveResult, type MarkdownDocument } from './FileManager';
149
+
150
+ // Re-export new llms.txt-inspired markdown generator
151
+ export {
152
+ markdownGenerator,
153
+ MarkdownGenerator,
154
+ adaptFeedbackSession,
155
+ type IMarkdownGenerator,
156
+ type Session as MarkdownSession,
157
+ type FeedbackItem,
158
+ type FeedbackCategory,
159
+ type FeedbackSeverity,
160
+ type GenerateOptions,
161
+ type MarkdownDocument as EnhancedMarkdownDocument,
162
+ type SessionMetadata,
163
+ } from './MarkdownGenerator';
164
+
165
+ // Re-export session adapter for type conversion
166
+ export {
167
+ adaptSessionForMarkdown,
168
+ generateDocumentForFileManager,
169
+ generateClipboardSummary,
170
+ } from './sessionAdapter';
171
+
172
+ // Re-export export service for multi-format export
173
+ export {
174
+ exportService,
175
+ ExportService,
176
+ generateHtmlDocument,
177
+ type ExportFormat,
178
+ type ExportOptions,
179
+ type ExportResult,
180
+ type PdfOptions,
181
+ type HtmlOptions,
182
+ type JsonOptions,
183
+ type MarkdownOptions,
184
+ type JsonExportSchema,
185
+ type HtmlExportOptions,
186
+ } from './ExportService';
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Session Adapter
3
+ *
4
+ * Converts between different session types used across the codebase.
5
+ * This is needed because:
6
+ * - SessionController uses its own Session/FeedbackItem types
7
+ * - MarkdownGenerator uses enhanced Session/FeedbackItem types
8
+ * - FileManager uses its own MarkdownDocument type
9
+ */
10
+
11
+ import type { Session as ControllerSession, FeedbackItem as ControllerFeedbackItem } from '../SessionController';
12
+ import type { TranscriptEvent } from '../transcription/types';
13
+ import type {
14
+ Session as MarkdownSession,
15
+ FeedbackItem as MarkdownFeedbackItem,
16
+ FeedbackCategory,
17
+ FeedbackSeverity,
18
+ GenerateOptions,
19
+ } from './MarkdownGenerator';
20
+ import type { MarkdownDocument as FileManagerDocument } from './FileManager';
21
+ import { markdownGenerator } from './MarkdownGenerator';
22
+ import { feedbackAnalyzer } from '../analysis';
23
+
24
+ const NO_TRANSCRIPTION_PLACEHOLDER =
25
+ '[Narration was recorded but not transcribed. Add an OpenAI API key, or download a Tiny Whisper model for local fallback.]';
26
+
27
+ /**
28
+ * Map analyzer category labels to markdown report labels
29
+ */
30
+ function mapCategory(category: ReturnType<typeof feedbackAnalyzer.analyze>['category']): FeedbackCategory {
31
+ switch (category) {
32
+ case 'bug':
33
+ return 'Bug';
34
+ case 'ux-issue':
35
+ return 'UX Issue';
36
+ case 'suggestion':
37
+ return 'Suggestion';
38
+ case 'performance':
39
+ return 'Performance';
40
+ case 'question':
41
+ return 'Question';
42
+ default:
43
+ return 'General';
44
+ }
45
+ }
46
+
47
+ function mapSeverity(severity: ReturnType<typeof feedbackAnalyzer.analyze>['severity']): FeedbackSeverity {
48
+ switch (severity) {
49
+ case 'critical':
50
+ return 'Critical';
51
+ case 'high':
52
+ return 'High';
53
+ case 'medium':
54
+ return 'Medium';
55
+ default:
56
+ return 'Low';
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Convert SessionController.FeedbackItem to MarkdownGenerator.FeedbackItem
62
+ */
63
+ function adaptFeedbackItem(item: ControllerFeedbackItem, index: number): MarkdownFeedbackItem {
64
+ const transcription = item.text.trim() || NO_TRANSCRIPTION_PLACEHOLDER;
65
+ const analysis = feedbackAnalyzer.analyze(transcription);
66
+
67
+ return {
68
+ id: item.id || `item-${index + 1}`,
69
+ transcription,
70
+ timestamp: item.timestamp,
71
+ category: mapCategory(analysis.category),
72
+ severity: mapSeverity(analysis.severity),
73
+ title: analysis.suggestedTitle,
74
+ keywords: analysis.keywords,
75
+ screenshots: item.screenshot ? [{
76
+ id: item.screenshot.id,
77
+ timestamp: item.screenshot.timestamp,
78
+ width: item.screenshot.width,
79
+ height: item.screenshot.height,
80
+ imagePath: '', // Filled in by FileManager when saving
81
+ base64: item.screenshot.base64,
82
+ }] : [],
83
+ };
84
+ }
85
+
86
+ function buildTranscriptOnlyItems(session: ControllerSession): MarkdownFeedbackItem[] {
87
+ const finalTranscripts = session.transcriptBuffer
88
+ .filter((event) => event.isFinal && event.text.trim().length > 0)
89
+ .sort((a, b) => a.timestamp - b.timestamp);
90
+
91
+ const usableTranscripts = finalTranscripts.length > 0
92
+ ? finalTranscripts
93
+ : session.transcriptBuffer
94
+ .filter((event) => event.text.trim().length > 0)
95
+ .sort((a, b) => a.timestamp - b.timestamp);
96
+
97
+ if (usableTranscripts.length === 0) {
98
+ return [];
99
+ }
100
+
101
+ const grouped: Array<{ timestampMs: number; transcripts: TranscriptEvent[] }> = [];
102
+ const GROUP_GAP_MS = 2200;
103
+
104
+ for (const transcript of usableTranscripts) {
105
+ const timestampMs = Math.round(transcript.timestamp * 1000);
106
+ const previousGroup = grouped[grouped.length - 1];
107
+
108
+ if (!previousGroup || timestampMs - previousGroup.timestampMs > GROUP_GAP_MS) {
109
+ grouped.push({
110
+ timestampMs,
111
+ transcripts: [transcript],
112
+ });
113
+ continue;
114
+ }
115
+
116
+ previousGroup.transcripts.push(transcript);
117
+ previousGroup.timestampMs = timestampMs;
118
+ }
119
+
120
+ return grouped.map((group, index) => {
121
+ const transcription = group.transcripts
122
+ .map((transcript) => transcript.text.trim())
123
+ .join(' ')
124
+ .replace(/\s+/g, ' ')
125
+ .trim();
126
+
127
+ const analysis = feedbackAnalyzer.analyze(transcription);
128
+
129
+ return {
130
+ id: `transcript-only-${index + 1}`,
131
+ transcription,
132
+ timestamp: group.timestampMs,
133
+ category: mapCategory(analysis.category),
134
+ severity: mapSeverity(analysis.severity),
135
+ title: analysis.suggestedTitle,
136
+ keywords: analysis.keywords,
137
+ screenshots: [],
138
+ };
139
+ });
140
+ }
141
+
142
+ /**
143
+ * Convert SessionController.Session to MarkdownGenerator.Session
144
+ */
145
+ export function adaptSessionForMarkdown(session: ControllerSession): MarkdownSession {
146
+ const adaptedFromScreenshots = session.feedbackItems.map((item, index) => adaptFeedbackItem(item, index));
147
+ const transcriptOnlyItems = buildTranscriptOnlyItems(session);
148
+ const hasNarratedScreenshotItems = adaptedFromScreenshots.some(
149
+ (item) => item.transcription !== NO_TRANSCRIPTION_PLACEHOLDER
150
+ );
151
+
152
+ const adaptedItems =
153
+ adaptedFromScreenshots.length === 0
154
+ ? transcriptOnlyItems
155
+ : hasNarratedScreenshotItems || transcriptOnlyItems.length === 0
156
+ ? adaptedFromScreenshots
157
+ : [...adaptedFromScreenshots, ...transcriptOnlyItems];
158
+
159
+ return {
160
+ id: session.id,
161
+ startTime: session.startTime,
162
+ endTime: session.endTime,
163
+ feedbackItems: adaptedItems,
164
+ metadata: {
165
+ os: process.platform,
166
+ sourceName: session.metadata?.sourceName || 'Screen',
167
+ sourceType: session.sourceId.startsWith('screen') ? 'screen' : 'window',
168
+ },
169
+ };
170
+ }
171
+
172
+ /**
173
+ * Generate a FileManager-compatible MarkdownDocument from a SessionController session
174
+ */
175
+ export function generateDocumentForFileManager(
176
+ session: ControllerSession,
177
+ options?: Partial<GenerateOptions>
178
+ ): FileManagerDocument {
179
+ const adaptedSession = adaptSessionForMarkdown(session);
180
+ const fullOptions: GenerateOptions = {
181
+ projectName: options?.projectName || session.metadata?.sourceName || 'Feedback Session',
182
+ screenshotDir: options?.screenshotDir || './screenshots',
183
+ };
184
+
185
+ const generatedDoc = markdownGenerator.generateFullDocument(adaptedSession, fullOptions);
186
+
187
+ // Convert MarkdownGenerator.MarkdownDocument to FileManager.MarkdownDocument
188
+ return {
189
+ content: generatedDoc.content,
190
+ metadata: {
191
+ itemCount: generatedDoc.metadata.itemCount,
192
+ screenshotCount: generatedDoc.metadata.screenshotCount,
193
+ types: Object.keys(generatedDoc.metadata.types),
194
+ },
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Generate clipboard summary from a SessionController session
200
+ */
201
+ export function generateClipboardSummary(session: ControllerSession, projectName?: string): string {
202
+ const adaptedSession = adaptSessionForMarkdown(session);
203
+ return markdownGenerator.generateClipboardSummary(
204
+ adaptedSession,
205
+ projectName || session.metadata?.sourceName || 'Feedback Session'
206
+ );
207
+ }