@rvagg/marginalia 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ui/app.js CHANGED
@@ -1,10 +1,28 @@
1
1
  import { createAnchor, locateAnchor } from './anchor.js'
2
+ import { compareTreePaths, sortFileDiffs } from './file-order.js'
3
+ import { buildTree } from './file-tree.js'
2
4
 
3
5
  (function () {
4
6
  'use strict'
5
7
 
6
8
  // --- Icons ---
7
9
  const ICON_COMMENT = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M1 2.75C1 1.784 1.784 1 2.75 1h10.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 13.25 12H9.06l-2.573 2.573A1.458 1.458 0 0 1 4 13.543V12H2.75A1.75 1.75 0 0 1 1 10.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h4.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg>'
10
+ const ICON_CHEVRON = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"/></svg>'
11
+ const ICON_SQUARE = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M2.5 2.75C2.5 2.61193 2.61193 2.5 2.75 2.5H13.25C13.3881 2.5 13.5 2.61193 13.5 2.75V13.25C13.5 13.3881 13.3881 13.5 13.25 13.5H2.75C2.61193 13.5 2.5 13.3881 2.5 13.25V2.75ZM2.75 1C1.7835 1 1 1.7835 1 2.75V13.25C1 14.2165 1.7835 15 2.75 15H13.25C14.2165 15 15 14.2165 15 13.25V2.75C15 1.7835 14.2165 1 13.25 1H2.75Z"/></svg>'
12
+ const ICON_CHECKBOX = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M2.75 1h10.5c.967 0 1.75.783 1.75 1.75v10.5A1.75 1.75 0 0 1 13.25 15H2.75A1.75 1.75 0 0 1 1 13.25V2.75C1 1.783 1.783 1 2.75 1Zm9.03 5.28a.749.749 0 1 0-1.06-1.06L6.75 9.189 5.28 7.72a.749.749 0 1 0-1.06 1.06l2 2a.749.749 0 0 0 1.06 0Z"/></svg>'
13
+ const ICON_DISCUSSION = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M1.75 1h8.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 10.25 10H7.061l-2.574 2.573A1.458 1.458 0 0 1 2 11.543V10h-.25A1.75 1.75 0 0 1 0 8.25v-5.5C0 1.784.784 1 1.75 1ZM1.5 2.75v5.5c0 .138.112.25.25.25h1a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h3.5a.25.25 0 0 0 .25-.25v-5.5a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm13 2a.25.25 0 0 0-.25-.25h-.5a.75.75 0 0 1 0-1.5h.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 14.25 12H14v1.543a1.458 1.458 0 0 1-2.487 1.03L9.22 12.28a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l2.22 2.22v-2.19a.75.75 0 0 1 .75-.75h1a.25.25 0 0 0 .25-.25Z"/></svg>'
14
+ const ICON_FOLD = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M10.896 2H8.75V.75a.75.75 0 0 0-1.5 0V2H5.104a.25.25 0 0 0-.177.427l2.896 2.896a.25.25 0 0 0 .354 0l2.896-2.896A.25.25 0 0 0 10.896 2ZM8.75 15.25a.75.75 0 0 1-1.5 0V14H5.104a.25.25 0 0 1-.177-.427l2.896-2.896a.25.25 0 0 1 .354 0l2.896 2.896a.25.25 0 0 1-.177.427H8.75v1.25Zm-6.5-6.5a.75.75 0 0 0 0-1.5h-.5a.75.75 0 0 0 0 1.5h.5ZM6 8a.75.75 0 0 1-.75.75h-.5a.75.75 0 0 1 0-1.5h.5A.75.75 0 0 1 6 8Zm2.25.75a.75.75 0 0 0 0-1.5h-.5a.75.75 0 0 0 0 1.5h.5ZM12 8a.75.75 0 0 1-.75.75h-.5a.75.75 0 0 1 0-1.5h.5A.75.75 0 0 1 12 8Zm2.25.75a.75.75 0 0 0 0-1.5h-.5a.75.75 0 0 0 0 1.5h.5Z"/></svg>'
15
+ const ICON_X = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"/></svg>'
16
+ const ICON_DIR = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"/></svg>'
17
+ const ICON_DIR_OPEN = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M.513 1.513A1.75 1.75 0 0 1 1.75 1h3.5c.55 0 1.07.26 1.4.7l.9 1.2a.25.25 0 0 0 .2.1H13a1 1 0 0 1 1 1v.5H2.75a.75.75 0 0 0 0 1.5h11.978a1 1 0 0 1 .994 1.117L15 13.25A1.75 1.75 0 0 1 13.25 15H1.75A1.75 1.75 0 0 1 0 13.25V2.75c0-.464.184-.91.513-1.237Z"/></svg>'
18
+ const ICON_FILE = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"/></svg>'
19
+ const ICON_SIDEBAR = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="m4.177 7.823 2.396-2.396A.25.25 0 0 1 7 5.604v4.792a.25.25 0 0 1-.427.177L4.177 8.177a.25.25 0 0 1 0-.354Z"/><path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25H9.5v-13Zm12.5 13a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H11v13Z"/></svg>'
20
+ const ICON_SIDEBAR_CLOSE = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M6.823 7.823a.25.25 0 0 1 0 .354l-2.396 2.396A.25.25 0 0 1 4 10.396V5.604a.25.25 0 0 1 .427-.177Z"/><path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25H9.5v-13H1.75a.25.25 0 0 0-.25.25ZM11 14.5h3.25a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H11Z"/></svg>'
21
+ const ICON_ADDED = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M2.75 1h10.5c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0 1 13.25 15H2.75A1.75 1.75 0 0 1 1 13.25V2.75C1 1.784 1.784 1 2.75 1Zm10.5 1.5H2.75a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25V2.75a.25.25 0 0 0-.25-.25ZM8 4a.75.75 0 0 1 .75.75v2.5h2.5a.75.75 0 0 1 0 1.5h-2.5v2.5a.75.75 0 0 1-1.5 0v-2.5h-2.5a.75.75 0 0 1 0-1.5h2.5v-2.5A.75.75 0 0 1 8 4Z"/></svg>'
22
+ const ICON_MODIFIED = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M13.25 1c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0 1 13.25 15H2.75A1.75 1.75 0 0 1 1 13.25V2.75C1 1.784 1.784 1 2.75 1ZM2.75 2.5a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25V2.75a.25.25 0 0 0-.25-.25ZM8 10a2 2 0 1 1-.001-3.999A2 2 0 0 1 8 10Z"/></svg>'
23
+ const ICON_REMOVED = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M13.25 1c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0 1 13.25 15H2.75A1.75 1.75 0 0 1 1 13.25V2.75C1 1.784 1.784 1 2.75 1ZM2.75 2.5a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25V2.75a.25.25 0 0 0-.25-.25Zm8.5 6.25h-6.5a.75.75 0 0 1 0-1.5h6.5a.75.75 0 0 1 0 1.5Z"/></svg>'
24
+ const ICON_RENAMED = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M13.25 1c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0 1 13.25 15H2.75A1.75 1.75 0 0 1 1 13.25V2.75C1 1.784 1.784 1 2.75 1ZM2.75 2.5a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25V2.75a.25.25 0 0 0-.25-.25Zm9.03 6.03-3.25 3.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l1.97-1.97H4.75a.75.75 0 0 1 0-1.5h4.69L7.47 5.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018l3.25 3.25a.75.75 0 0 1 0 1.06Z"/></svg>'
25
+ const ICON_SEARCH = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"/></svg>'
8
26
  const ICON_COPY = '<svg aria-hidden="true" viewBox="0 0 16 16" width="16" height="16" fill="currentColor"><path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg>'
9
27
 
10
28
  // --- Theme ---
@@ -32,15 +50,18 @@ import { createAnchor, locateAnchor } from './anchor.js'
32
50
  })
33
51
 
34
52
  // --- State ---
35
- const threads = {} // thread_id -> { el, messages }
53
+ // thread_id -> { file, target, messages, el, outdated, resolved, collapsed, reply }
54
+ const threads = {}
36
55
  const viewedFiles = {} // filename -> diff hash (to detect changes)
56
+ const collapsedFiles = {}
37
57
  let pendingPermission = null
38
- let chatExpanded = false
39
58
  let agentName = 'agent'
40
59
 
41
60
  // --- Elements ---
42
- const filenav = document.getElementById('filenav')
43
- const fileCountEl = document.getElementById('file-count')
61
+ const fileTree = document.getElementById('file-tree')
62
+ const treeList = document.getElementById('tree-list')
63
+ const treeToggle = document.getElementById('tree-toggle')
64
+ const treeFilter = document.getElementById('tree-filter')
44
65
  const diffContainer = document.getElementById('diff-container')
45
66
  const loadingState = document.getElementById('loading-state')
46
67
  const emptyState = document.getElementById('empty-state')
@@ -50,9 +71,11 @@ import { createAnchor, locateAnchor } from './anchor.js'
50
71
  const permissionText = document.getElementById('permission-text')
51
72
  const permissionApprove = document.getElementById('permission-approve')
52
73
  const permissionDeny = document.getElementById('permission-deny')
53
- const chatToggle = document.getElementById('chat-toggle')
54
- const chatIndicator = document.getElementById('chat-indicator')
55
- const chatHistory = document.getElementById('chat-history')
74
+ const commentsPanel = document.getElementById('comments-panel')
75
+ const commentsList = document.getElementById('comments-list')
76
+ const commentsToggle = document.getElementById('comments-toggle')
77
+ const commentsCount = document.getElementById('comments-count')
78
+ const minimizeToggle = document.getElementById('minimize-toggle')
56
79
  const generalInput = document.getElementById('general-input')
57
80
  const generalSend = document.getElementById('general-send')
58
81
  const baseInput = document.getElementById('base-input')
@@ -63,7 +86,7 @@ import { createAnchor, locateAnchor } from './anchor.js'
63
86
 
64
87
  const contextContainer = document.createElement('div')
65
88
  contextContainer.id = 'context-snippets'
66
- diffContainer.parentNode.insertBefore(contextContainer, diffContainer)
89
+ document.getElementById('workspace').before(contextContainer)
67
90
 
68
91
  function addContextSnippet(msg) {
69
92
  const snippet = document.createElement('div')
@@ -83,50 +106,129 @@ import { createAnchor, locateAnchor } from './anchor.js'
83
106
  snippet.scrollIntoView({ block: 'nearest', behavior: 'instant' })
84
107
  }
85
108
 
86
- // --- File nav ---
109
+ // --- File tree ---
87
110
 
88
- function updateFileCount(n) {
89
- const expanded = fileCountEl.classList.contains('active')
90
- const chevron = expanded ? '\u25B4' : '\u25BE'
91
- fileCountEl.textContent = n + ' file' + (n !== 1 ? 's' : '') + ' ' + chevron
111
+ const STATUS_ICONS = {
112
+ added: [ICON_ADDED, 'Added'],
113
+ deleted: [ICON_REMOVED, 'Deleted'],
114
+ moved: [ICON_RENAMED, 'Renamed'],
115
+ changed: [ICON_MODIFIED, 'Modified']
92
116
  }
117
+ const collapsedDirs = new Set()
118
+ let activeFile = null
119
+ // GitHub's breakpoint for showing the tree beside the diff.
120
+ const wideLayout = window.matchMedia('(min-width: 1012px)')
121
+
122
+ fileTree.querySelector('.mg-tree-filter-icon').innerHTML = ICON_SEARCH
123
+
124
+ function renderTree() {
125
+ const files = [...diffIndex.keys()]
126
+ document.getElementById('tree-count').textContent = files.length
127
+ const query = treeFilter.value.trim().toLowerCase()
128
+ const shown = query ? files.filter(f => f.toLowerCase().includes(query)) : files
129
+ const comments = new Map()
130
+ for (const t of Object.values(threads)) {
131
+ if (t.file && !t.resolved) comments.set(t.file, (comments.get(t.file) ?? 0) + 1)
132
+ }
93
133
 
94
- fileCountEl.addEventListener('click', () => {
95
- filenav.classList.toggle('hidden')
96
- fileCountEl.classList.toggle('active')
97
- const n = filenav.children.length
98
- updateFileCount(n)
99
- })
100
-
101
- function updateFilenav(diffText) {
102
- filenav.innerHTML = ''
103
- if (!diffText) return
104
- const chunks = diffText.split(/(?=^diff --git )/m)
105
- for (const chunk of chunks) {
106
- const nameMatch = chunk.match(/^diff --git a\/(.+?) b\/(.+)$/m)
107
- if (!nameMatch) continue
108
- const file = nameMatch[2]
109
- const isNew = /^new file mode/m.test(chunk)
110
- const isDel = /^deleted file mode/m.test(chunk)
111
- const badge = isNew ? 'added' : isDel ? 'deleted' : 'changed'
112
- const label = isNew ? 'A' : isDel ? 'D' : 'M'
113
- const item = document.createElement('div')
114
- item.className = 'filenav-item' + (viewedFiles[file] ? ' filenav-viewed' : '')
115
- item.innerHTML = `<span class="filenav-badge filenav-badge-${badge}">${label}</span>${escapeHtml(file)}`
116
- item.addEventListener('click', () => {
117
- const wrappers = diffContainer.querySelectorAll('.d2h-file-wrapper')
118
- for (const w of wrappers) {
119
- const n = w.querySelector('.d2h-file-name')
120
- if (n && n.textContent.trim() === file) {
121
- w.scrollIntoView({ block: 'start', behavior: 'instant' })
122
- break
123
- }
134
+ const rows = []
135
+ const walk = (nodes, depth) => {
136
+ for (const node of nodes) {
137
+ const li = document.createElement('li')
138
+ li.setAttribute('role', 'treeitem')
139
+ li.style.setProperty('--depth', depth)
140
+ if (node.type === 'dir') {
141
+ // A filter shows every match, whatever was collapsed.
142
+ const open = Boolean(query) || !collapsedDirs.has(node.path)
143
+ li.className = 'mg-tree-row mg-tree-dir'
144
+ li.setAttribute('aria-expanded', String(open))
145
+ li.title = node.path
146
+ li.innerHTML = `<span class="mg-tree-chevron">${ICON_CHEVRON}</span>` +
147
+ `<span class="mg-tree-icon">${open ? ICON_DIR_OPEN : ICON_DIR}</span><span class="mg-tree-name">${escapeHtml(node.name)}</span>`
148
+ li.addEventListener('click', () => {
149
+ if (collapsedDirs.has(node.path)) collapsedDirs.delete(node.path)
150
+ else collapsedDirs.add(node.path)
151
+ renderTree()
152
+ })
153
+ rows.push(li)
154
+ if (open) walk(node.children, depth + 1)
155
+ continue
124
156
  }
125
- })
126
- filenav.appendChild(item)
157
+ const entry = diffIndex.get(node.path)
158
+ const status = entry?.wrapper.querySelector('.d2h-tag')?.className.match(/d2h-(added|deleted|moved|changed)/)?.[1] ?? 'changed'
159
+ const [statusIcon, statusLabel] = STATUS_ICONS[status]
160
+ const count = comments.get(node.path)
161
+ li.className = 'mg-tree-row mg-tree-file' + (node.path === activeFile ? ' active' : '')
162
+ li.setAttribute('aria-selected', String(node.path === activeFile))
163
+ li.title = node.path
164
+ li.dataset.path = node.path
165
+ li.innerHTML = `<span class="mg-tree-icon">${ICON_FILE}</span><span class="mg-tree-name">${escapeHtml(node.name)}</span>` +
166
+ (count ? `<span class="mg-tree-comments" title="${count} unresolved conversation${count === 1 ? '' : 's'}">${ICON_DISCUSSION}${count}</span>` : '') +
167
+ `<span class="mg-tree-status mg-tree-${status}" title="${statusLabel}">${statusIcon}</span>`
168
+ li.addEventListener('click', () => {
169
+ entry?.wrapper.scrollIntoView({ block: 'start', behavior: 'instant' })
170
+ setActiveFile(node.path)
171
+ if (!wideLayout.matches) setTreeOpen(false)
172
+ })
173
+ rows.push(li)
174
+ }
175
+ }
176
+ if (!diffIndex.has(activeFile)) activeFile = files[0] ?? null
177
+ walk(buildTree(shown), 0)
178
+ if (!rows.length && files.length) {
179
+ const empty = document.createElement('li')
180
+ empty.className = 'mg-tree-empty'
181
+ empty.textContent = 'No files match'
182
+ rows.push(empty)
183
+ }
184
+ treeList.replaceChildren(...rows)
185
+ }
186
+
187
+ function setActiveFile(file) {
188
+ if (file === activeFile) return
189
+ activeFile = file
190
+ for (const row of treeList.querySelectorAll('.mg-tree-file')) {
191
+ const active = row.dataset.path === file
192
+ row.classList.toggle('active', active)
193
+ row.setAttribute('aria-selected', String(active))
194
+ if (active) row.scrollIntoView({ block: 'nearest' })
127
195
  }
128
196
  }
129
197
 
198
+ // The active file is the one whose section holds the top of the view.
199
+ let scrollFrame = 0
200
+ diffContainer.addEventListener('scroll', () => {
201
+ if (scrollFrame) return
202
+ scrollFrame = requestAnimationFrame(() => {
203
+ scrollFrame = 0
204
+ const top = diffContainer.getBoundingClientRect().top + 1
205
+ let current = null
206
+ for (const [file, entry] of diffIndex) {
207
+ if (entry.wrapper.getBoundingClientRect().top > top) break
208
+ current = file
209
+ }
210
+ setActiveFile(current ?? diffIndex.keys().next().value ?? null)
211
+ })
212
+ })
213
+
214
+ function setTreeOpen(open, remember = false) {
215
+ fileTree.classList.toggle('hidden', !open)
216
+ treeToggle.setAttribute('aria-pressed', String(open))
217
+ treeToggle.innerHTML = open ? ICON_SIDEBAR_CLOSE : ICON_SIDEBAR
218
+ treeToggle.title = open ? 'Hide file tree' : 'Show file tree'
219
+ if (remember && wideLayout.matches) localStorage.setItem('marginalia-tree', open ? '1' : '0')
220
+ }
221
+
222
+ treeToggle.addEventListener('click', () => setTreeOpen(fileTree.classList.contains('hidden'), true))
223
+ treeFilter.addEventListener('input', renderTree)
224
+ treeFilter.addEventListener('keydown', (e) => {
225
+ if (e.key === 'Escape') { treeFilter.value = ''; renderTree() }
226
+ })
227
+ // Wide, the tree shows unless hidden there before; narrow, it starts closed.
228
+ const treeOnWide = () => wideLayout.matches && localStorage.getItem('marginalia-tree') !== '0'
229
+ wideLayout.addEventListener('change', () => setTreeOpen(treeOnWide()))
230
+ setTreeOpen(treeOnWide())
231
+
130
232
  // --- Diff base ---
131
233
 
132
234
  const BASE_TITLE = 'Branch, tag or commit to diff against, from its merge-base with HEAD. Enter to apply, empty for HEAD.'
@@ -201,10 +303,11 @@ import { createAnchor, locateAnchor } from './anchor.js'
201
303
  const msg = JSON.parse(e.data)
202
304
  switch (msg.type) {
203
305
  case 'init':
204
- projectDirEl.textContent = msg.projectDir
306
+ projectDirEl.innerHTML = `<bdi>${escapeHtml(msg.projectDir)}</bdi>`
205
307
  showBase(msg.base ?? null)
206
308
  agentName = typeof msg.agentName === 'string' && msg.agentName ? msg.agentName : 'agent'
207
309
  renderDiff(msg.diff)
310
+ loadThreads(msg.threads ?? [])
208
311
  break
209
312
  case 'diff':
210
313
  if ((msg.base ?? null) !== currentBase) showBase(msg.base ?? null)
@@ -226,21 +329,19 @@ import { createAnchor, locateAnchor } from './anchor.js'
226
329
  dismissPermission()
227
330
  break
228
331
  case 'reply':
229
- appendReply(msg.thread_id, msg.text, msg.ephemeral)
332
+ showReply(msg.thread_id, msg.text, msg.ephemeral)
230
333
  dismissPermission()
231
334
  break
335
+ case 'thread':
336
+ applyThread(msg.thread)
337
+ // The agent moving on means its prompt was answered elsewhere; the
338
+ // reviewer's own comments say nothing about it.
339
+ if (msg.thread.messages.at(-1)?.from === 'assistant') dismissPermission()
340
+ break
232
341
  case 'status':
233
342
  statusEl.textContent = msg.text
234
343
  dismissPermission()
235
344
  break
236
- case 'comment_ack':
237
- if (msg.file) {
238
- const target = msg.anchor ? { side: msg.side, anchor: msg.anchor } : null
239
- confirmInlineComment(msg.thread_id, msg.file, target, msg.text)
240
- } else {
241
- confirmGeneralComment(msg.thread_id, msg.text)
242
- }
243
- break
244
345
  case 'permission':
245
346
  showPermission(msg)
246
347
  break
@@ -271,11 +372,12 @@ import { createAnchor, locateAnchor } from './anchor.js'
271
372
  diffContainer.innerHTML = ''
272
373
  diffContainer.appendChild(emptyState)
273
374
  emptyState.classList.remove('hidden')
274
- updateFileCount(0)
375
+ reinjectThreads()
275
376
  return
276
377
  }
277
378
 
278
379
  emptyState.classList.add('hidden')
380
+ diffText = sortFileDiffs(diffText)
279
381
  const scrollTop = diffContainer.scrollTop
280
382
 
281
383
  // Split diff into per-file chunks to detect changes
@@ -290,13 +392,11 @@ import { createAnchor, locateAnchor } from './anchor.js'
290
392
  for (const file of Object.keys(viewedFiles)) {
291
393
  if (currentFileDiffs[file] && currentFileDiffs[file] !== lastFileDiffs[file]) {
292
394
  delete viewedFiles[file]
395
+ delete collapsedFiles[file]
293
396
  }
294
397
  }
295
398
  lastFileDiffs = currentFileDiffs
296
399
 
297
- const fileHeaders = Object.keys(currentFileDiffs).length
298
- updateFileCount(fileHeaders)
299
-
300
400
  // eslint-disable-next-line no-undef
301
401
  const diff2htmlUi = new Diff2HtmlUI(diffContainer, diffText, {
302
402
  outputFormat: 'line-by-line',
@@ -310,10 +410,10 @@ import { createAnchor, locateAnchor } from './anchor.js'
310
410
 
311
411
  diff2htmlUi.draw()
312
412
  diff2htmlUi.highlightCode()
413
+ groupChangeRuns()
313
414
  indexDiff()
314
415
 
315
- updateFilenav(diffText)
316
- injectViewedToggles()
416
+ buildFileHeaders()
317
417
  attachGutterHandlers()
318
418
  reinjectThreads()
319
419
  restoreOpenInputs(openInputs)
@@ -349,73 +449,122 @@ import { createAnchor, locateAnchor } from './anchor.js'
349
449
  }
350
450
  }
351
451
 
352
- // --- File header controls ---
452
+ // --- Change runs ---
453
+
454
+ // Line matching pairs deletions with additions and emits each pair in turn;
455
+ // GitHub lists a run's deletions before its additions, so reorder to match.
456
+ function groupChangeRuns() {
457
+ const kind = (row) => row.querySelector('td.d2h-del:not(.d2h-code-linenumber)') ? 'del'
458
+ : row.querySelector('td.d2h-ins:not(.d2h-code-linenumber)') ? 'ins' : null
459
+ for (const tbody of diffContainer.querySelectorAll('.d2h-diff-tbody')) {
460
+ let run = []
461
+ const flush = (before) => {
462
+ const ordered = [...run.filter(([k]) => k === 'del'), ...run.filter(([k]) => k === 'ins')]
463
+ if (ordered.some(([, row], i) => row !== run[i][1])) {
464
+ for (const [, row] of ordered) tbody.insertBefore(row, before)
465
+ }
466
+ run = []
467
+ }
468
+ for (const row of [...tbody.children]) {
469
+ const k = kind(row)
470
+ if (k) run.push([k, row])
471
+ else if (run.length) flush(row)
472
+ }
473
+ if (run.length) flush(null)
474
+ }
475
+ }
476
+
477
+ // --- File headers ---
478
+
479
+ function iconButton(className, icon, title, onClick) {
480
+ const btn = document.createElement('button')
481
+ btn.type = 'button'
482
+ btn.className = 'mg-icon-btn ' + className
483
+ btn.innerHTML = icon
484
+ btn.title = title
485
+ btn.setAttribute('aria-label', title)
486
+ btn.addEventListener('click', (e) => {
487
+ e.stopPropagation()
488
+ onClick()
489
+ })
490
+ return btn
491
+ }
353
492
 
354
- function injectViewedToggles() {
355
- const wrappers = diffContainer.querySelectorAll('.d2h-file-wrapper')
356
- wrappers.forEach((wrapper) => {
357
- const nameEl = wrapper.querySelector('.d2h-file-name')
358
- const fileName = nameEl?.textContent?.trim()
359
- if (!fileName) return
493
+ // GitHub's five-square summary: each colour gets its floor share of five.
494
+ function diffStat(wrapper) {
495
+ const adds = wrapper.querySelectorAll('td.d2h-ins:not(.d2h-code-linenumber)').length
496
+ const dels = wrapper.querySelectorAll('td.d2h-del:not(.d2h-code-linenumber)').length
497
+ const stat = document.createElement('span')
498
+ stat.className = 'mg-diffstat'
499
+ const total = adds + dels
500
+ if (total === 0) return stat
501
+ const green = Math.floor(5 * adds / total)
502
+ const red = Math.floor(5 * dels / total)
503
+ const squares = ['add', 'del', 'neutral'].flatMap((k, i) => Array([green, red, 5 - green - red][i]).fill(k))
504
+ stat.title = `${adds} addition${adds === 1 ? '' : 's'} & ${dels} deletion${dels === 1 ? '' : 's'}`
505
+ stat.innerHTML = `<span class="mg-diffstat-add">+${adds}</span><span class="mg-diffstat-del">-${dels}</span>` +
506
+ `<span class="mg-diffstat-bar">${squares.map((k) => `<span class="mg-diffstat-${k}-square"></span>`).join('')}</span>`
507
+ return stat
508
+ }
360
509
 
510
+ function buildFileHeaders() {
511
+ for (const wrapper of diffContainer.querySelectorAll('.d2h-file-wrapper')) {
512
+ const fileName = wrapper.querySelector('.d2h-file-name')?.textContent?.trim()
361
513
  const header = wrapper.querySelector('.d2h-file-name-wrapper')
362
- if (!header || header.querySelector('.mg-viewed-toggle')) return
514
+ if (!fileName || !header || header.querySelector('.mg-viewed-toggle')) continue
515
+
516
+ const setCollapsed = (collapsed) => {
517
+ wrapper.classList.toggle('mg-collapsed', collapsed)
518
+ chevron.setAttribute('aria-expanded', String(!collapsed))
519
+ collapsedFiles[fileName] = collapsed
520
+ }
521
+ const entry = diffIndex.get(fileName)
522
+ if (entry) entry.setCollapsed = setCollapsed
523
+
524
+ const chevron = iconButton('mg-chevron', ICON_CHEVRON, 'Collapse file', () => {
525
+ setCollapsed(!wrapper.classList.contains('mg-collapsed'))
526
+ })
527
+
528
+ const copyBtn = iconButton('mg-copy-path', ICON_COPY, 'Copy file path', () => {
529
+ copyToClipboard(fileName).then(() => {
530
+ copyBtn.classList.add('mg-copied')
531
+ setTimeout(() => copyBtn.classList.remove('mg-copied'), 1500)
532
+ })
533
+ })
363
534
 
364
535
  const viewedBtn = document.createElement('button')
365
- viewedBtn.className = 'mg-viewed-toggle'
366
- viewedBtn.textContent = 'Viewed'
367
536
  viewedBtn.type = 'button'
368
-
369
- if (viewedFiles[fileName]) {
370
- viewedBtn.classList.add('viewed')
371
- wrapper.classList.add('mg-collapsed')
537
+ viewedBtn.className = 'mg-viewed-toggle'
538
+ const showViewed = (viewed) => {
539
+ viewedBtn.classList.toggle('viewed', viewed)
540
+ viewedBtn.setAttribute('aria-pressed', String(viewed))
541
+ viewedBtn.innerHTML = (viewed ? ICON_CHECKBOX : ICON_SQUARE) + '<span>Viewed</span>'
372
542
  }
373
-
374
543
  viewedBtn.addEventListener('click', (e) => {
375
544
  e.stopPropagation()
376
- const isViewed = viewedBtn.classList.toggle('viewed')
377
- if (isViewed) {
378
- viewedFiles[fileName] = true
379
- wrapper.classList.add('mg-collapsed')
380
- wrapper.scrollIntoView({ block: 'start', behavior: 'instant' })
381
- } else {
382
- delete viewedFiles[fileName]
383
- wrapper.classList.remove('mg-collapsed')
384
- }
545
+ const viewed = !viewedFiles[fileName]
546
+ if (viewed) viewedFiles[fileName] = true
547
+ else delete viewedFiles[fileName]
548
+ showViewed(viewed)
549
+ setCollapsed(viewed)
550
+ if (viewed) wrapper.scrollIntoView({ block: 'start', behavior: 'instant' })
385
551
  })
386
552
 
387
- const commentBtn = document.createElement('button')
388
- commentBtn.className = 'mg-file-comment'
389
- commentBtn.innerHTML = ICON_COMMENT
390
- commentBtn.type = 'button'
391
- commentBtn.title = 'Comment on file'
392
- commentBtn.addEventListener('click', (e) => {
393
- e.stopPropagation()
553
+ const commentBtn = iconButton('mg-file-comment', ICON_COMMENT, 'Comment on file', () => {
394
554
  const diffBody = wrapper.querySelector('.d2h-diff-tbody')
395
- if (!diffBody) return
396
- const firstRow = diffBody.querySelector('tr')
555
+ const firstRow = diffBody?.querySelector('tr')
397
556
  if (!firstRow) return
398
557
  if (firstRow.previousElementSibling?.classList.contains('comment-input-row')) return
558
+ setCollapsed(false)
399
559
  openFileCommentInput(diffBody, firstRow, fileName)
400
560
  })
401
561
 
402
- const copyBtn = document.createElement('button')
403
- copyBtn.className = 'mg-copy-path'
404
- copyBtn.innerHTML = ICON_COPY
405
- copyBtn.type = 'button'
406
- copyBtn.title = 'Copy file path'
407
- copyBtn.addEventListener('click', (e) => {
408
- e.stopPropagation()
409
- copyToClipboard(fileName).then(() => {
410
- copyBtn.classList.add('mg-copied')
411
- setTimeout(() => copyBtn.classList.remove('mg-copied'), 1500)
412
- })
413
- })
414
-
415
- header.appendChild(copyBtn)
416
- header.appendChild(viewedBtn)
417
- header.appendChild(commentBtn)
418
- })
562
+ header.prepend(chevron)
563
+ header.querySelector('.d2h-file-name').after(copyBtn)
564
+ header.append(diffStat(wrapper), viewedBtn, commentBtn)
565
+ showViewed(Boolean(viewedFiles[fileName]))
566
+ setCollapsed(Boolean(collapsedFiles[fileName] ?? viewedFiles[fileName]))
567
+ }
419
568
  }
420
569
 
421
570
  // --- Comment input persistence across re-renders ---
@@ -446,7 +595,8 @@ import { createAnchor, locateAnchor } from './anchor.js'
446
595
  function restoreOpenInputs(inputs) {
447
596
  for (const draft of inputs) {
448
597
  const { file, target, text, focused, selection } = draft
449
- const row = target && placeTarget(file, target)
598
+ const rows = target && locateRange(file, target)
599
+ const row = rows?.at(-1)
450
600
  const top = row ? null : fileTopRow(file)
451
601
  if (!row && !top) {
452
602
  heldDrafts.push({ ...draft, focused: false })
@@ -454,9 +604,9 @@ import { createAnchor, locateAnchor } from './anchor.js'
454
604
  }
455
605
  const inputRow = createCommentInputRow(file, target)
456
606
  if (row) {
607
+ inputRow.tintFrom(row)
457
608
  row.after(inputRow.el)
458
- row.classList.add('mg-commenting')
459
- inputRow.onCleanup = () => row.classList.remove('mg-commenting')
609
+ inputRow.onCleanup = markCommenting(rows)
460
610
  } else {
461
611
  top.before(inputRow.el)
462
612
  if (target) inputRow.markChanged()
@@ -473,39 +623,126 @@ import { createAnchor, locateAnchor } from './anchor.js'
473
623
  inputRow.focus()
474
624
  }
475
625
 
476
- function openCommentInput(afterRow, file, line, side) {
477
- const existingInput = afterRow.nextElementSibling
478
- if (existingInput?.classList.contains('comment-input-row')) return
479
- const lines = diffIndex.get(file)?.[side]
480
- const anchor = lines && createAnchor(lines.texts, line)
481
- if (!anchor) return
626
+ // A line or a range of lines: target names the last line, and target.start
627
+ // the first when there is more than one. code holds the range's text.
628
+ function lineTarget(file, rows) {
629
+ const lines = diffIndex.get(file)
630
+ const point = (row) => {
631
+ const info = parseLineInfo(row.querySelector('.d2h-code-linenumber'))
632
+ const anchor = info && lines?.[info.side] && createAnchor(lines[info.side].texts, info.line)
633
+ return anchor ? { side: info.side, anchor } : null
634
+ }
635
+ const end = point(rows.at(-1))
636
+ if (!end) return null
637
+ if (rows.length === 1) return end
638
+ const start = point(rows[0])
639
+ if (!start) return null
640
+ return { ...end, start, code: rangeText(rows) }
641
+ }
642
+
643
+ function rangeText(rows) {
644
+ return rows.map(row => row.querySelector('.d2h-code-line-ctn')?.textContent ?? '').join('\n')
645
+ }
646
+
647
+ // Finds a line or range target in the current diff, refreshing its anchors.
648
+ // A range must still be whole: its ends in order within one hunk and the
649
+ // lines between unchanged. Returns its rows, or null when it's outdated.
650
+ function locateRange(file, target) {
651
+ const end = placeTarget(file, target)
652
+ if (!end) return null
653
+ if (!target.start) return [end]
654
+ const start = placeTarget(file, target.start)
655
+ const rows = start && rowsBetween(start, end)
656
+ if (!rows || rows[0] !== start || rows.at(-1) !== end) return null
657
+ if (target.code !== undefined && rangeText(rows) !== target.code) return null
658
+ return rows
659
+ }
660
+
661
+ function openCommentInput(file, rows) {
662
+ const afterRow = rows.at(-1)
663
+ if (afterRow.nextElementSibling?.classList.contains('comment-input-row')) return
664
+ const target = lineTarget(file, rows)
665
+ if (!target) return
482
666
 
483
- const inputRow = createCommentInputRow(file, { side, anchor })
484
- afterRow.parentNode.insertBefore(inputRow.el, afterRow.nextSibling)
485
- afterRow.classList.add('mg-commenting')
486
- inputRow.onCleanup = () => afterRow.classList.remove('mg-commenting')
667
+ const inputRow = createCommentInputRow(file, target)
668
+ inputRow.tintFrom(afterRow)
669
+ afterRow.after(inputRow.el)
670
+ inputRow.onCleanup = markCommenting(rows)
487
671
  inputRow.focus()
488
672
  }
489
673
 
490
- function createCommentInputRow(file, target) {
491
- const isFileLevel = !target
674
+ function markCommenting(rows, className = 'mg-commenting') {
675
+ for (const row of rows) row.classList.add(className)
676
+ return () => { for (const row of rows) row.classList.remove(className) }
677
+ }
678
+
679
+ // The rows a placed range thread covers, for showing its range on hover.
680
+ function threadRangeRows(thread) {
681
+ return thread.target?.start ? locateRange(thread.file, thread.target) ?? [] : []
682
+ }
683
+
684
+ // The diff lines from one row to another, in either order, within one hunk:
685
+ // as on GitHub, a range stops at a hunk boundary.
686
+ function rowsBetween(from, to) {
687
+ if (!from || !to) return to ? [to] : []
688
+ const forward = from.compareDocumentPosition(to) & Node.DOCUMENT_POSITION_FOLLOWING
689
+ const rows = [from]
690
+ for (let row = from; row !== to;) {
691
+ row = forward ? row.nextElementSibling : row.previousElementSibling
692
+ if (!row || row.classList.contains('d2h-info') || row.querySelector('td.d2h-info')) break
693
+ if (row.querySelector('.d2h-code-linenumber')) rows.push(row)
694
+ }
695
+ return forward ? rows : rows.reverse()
696
+ }
697
+
698
+ // A comment row spans the diff table: a gutter cell that keeps its line's
699
+ // tint, as GitHub does, and a cell holding the card.
700
+ function commentRow(className) {
492
701
  const tr = document.createElement('tr')
493
- tr.className = 'comment-input-row'
702
+ tr.className = 'mg-comment-row ' + className
703
+ const gutter = document.createElement('td')
704
+ gutter.className = 'mg-row-gutter'
494
705
  const cell = document.createElement('td')
495
- cell.colSpan = 3
706
+ tr.append(gutter, cell)
707
+ return { tr, gutter, cell }
708
+ }
709
+
710
+ function tintGutter(gutter, row) {
711
+ const kind = row?.querySelector('td.d2h-code-linenumber.d2h-del') ? 'del'
712
+ : row?.querySelector('td.d2h-code-linenumber.d2h-ins') ? 'ins' : null
713
+ gutter.className = 'mg-row-gutter' + (kind ? ' mg-row-gutter-' + kind : '')
714
+ }
715
+
716
+ function lineLabel(target) {
717
+ const label = (t) => (t.side === 'left' ? 'L' : 'R') + t.anchor.line
718
+ return target.start ? `lines <strong>${label(target.start)}</strong> to <strong>${label(target)}</strong>` : `line <strong>${label(target)}</strong>`
719
+ }
720
+
721
+ function createCommentInputRow(file, target) {
722
+ const isFileLevel = !target
723
+ const { tr, gutter, cell } = commentRow('comment-input-row')
496
724
  cell.innerHTML = `
497
- <div class="comment-input-box">
498
- <div class="comment-input-context">${escapeHtml(file)}${isFileLevel ? '' : ':' + target.anchor.line}</div>
499
- <textarea class="mg-textarea" rows="3" placeholder="${isFileLevel ? 'Comment on this file...' : 'Leave a comment...'}"></textarea>
500
- <div class="comment-input-actions">
501
- <button class="small" data-action="submit">Comment</button>
502
- <button class="small secondary" data-action="cancel">Cancel</button>
725
+ <div class="mg-thread mg-comment-form">
726
+ <div class="mg-thread-header">
727
+ <span class="mg-thread-title">${isFileLevel ? 'Comment on file' : `Add a comment on ${lineLabel(target)}`}</span>
728
+ </div>
729
+ <div class="mg-thread-body mg-form-body">
730
+ <div class="mg-tabs">
731
+ <button type="button" class="mg-tab selected" data-tab="write">Write</button>
732
+ <button type="button" class="mg-tab" data-tab="preview">Preview</button>
733
+ </div>
734
+ <textarea class="mg-textarea" rows="4" placeholder="${isFileLevel ? 'Comment on this file' : 'Leave a comment'}"></textarea>
735
+ <div class="mg-md mg-preview hidden"></div>
736
+ <div class="comment-input-actions">
737
+ <button type="button" class="mg-btn" data-action="cancel">Cancel</button>
738
+ <button type="button" class="mg-btn mg-btn-primary" data-action="submit">Comment</button>
739
+ </div>
503
740
  </div>
504
741
  </div>
505
742
  `
506
- tr.appendChild(cell)
507
743
 
508
744
  const textarea = cell.querySelector('textarea')
745
+ const preview = cell.querySelector('.mg-preview')
509
746
  commentInputs.set(tr, { file, target, textarea })
510
747
  let onCleanup = null
511
748
  // Set when the commented line changed or left the diff; its line number
@@ -523,14 +760,28 @@ import { createAnchor, locateAnchor } from './anchor.js'
523
760
  if (isFileLevel) {
524
761
  send({ type: 'comment', file, line: 0, side: 'right', text })
525
762
  } else if (changed) {
526
- const quoted = `On former line ${target.anchor.line}:\n\n\`\`\`\n${target.anchor.text}\n\`\`\`\n\n${text}`
763
+ const where = target.start ? `former lines ${target.start.anchor.line} to ${target.anchor.line}` : `former line ${target.anchor.line}`
764
+ const quoted = `On ${where}:\n\n\`\`\`\n${target.code ?? target.anchor.text}\n\`\`\`\n\n${text}`
527
765
  send({ type: 'comment', file, line: 0, side: 'right', text: quoted })
528
766
  } else {
529
- send({ type: 'comment', file, line: target.anchor.line, side: target.side, text, anchor: target.anchor })
767
+ send({
768
+ type: 'comment', file, line: target.anchor.line, side: target.side, text, anchor: target.anchor,
769
+ ...(target.start && { start_line: target.start.anchor.line, start_side: target.start.side, start: target.start, code: target.code })
770
+ })
530
771
  }
531
772
  cleanup()
532
773
  }
533
774
 
775
+ function showTab(tab) {
776
+ for (const t of cell.querySelectorAll('.mg-tab')) t.classList.toggle('selected', t.dataset.tab === tab)
777
+ textarea.classList.toggle('hidden', tab === 'preview')
778
+ preview.classList.toggle('hidden', tab !== 'preview')
779
+ if (tab === 'preview') preview.innerHTML = renderMarkdown(textarea.value.trim() || '_Nothing to preview_')
780
+ else textarea.focus()
781
+ }
782
+
783
+ for (const t of cell.querySelectorAll('.mg-tab')) t.addEventListener('click', () => showTab(t.dataset.tab))
784
+
534
785
  textarea.addEventListener('keydown', (e) => {
535
786
  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); submit() }
536
787
  if (e.key === 'Escape') cleanup()
@@ -542,12 +793,14 @@ import { createAnchor, locateAnchor } from './anchor.js'
542
793
  return {
543
794
  el: tr,
544
795
  focus: () => textarea.focus(),
796
+ tintFrom: (row) => tintGutter(gutter, row),
545
797
  markChanged() {
546
798
  changed = true
547
799
  const note = document.createElement('span')
548
- note.className = 'comment-outdated'
549
- note.textContent = 'line changed or left the diff; sends as a file comment'
550
- cell.querySelector('.comment-input-context').append(' ', note)
800
+ note.className = 'mg-label mg-label-outdated'
801
+ note.textContent = 'Outdated'
802
+ note.title = 'The line changed or left the diff; this sends as a file comment'
803
+ cell.querySelector('.mg-thread-header').append(note)
551
804
  },
552
805
  restore(text, focused, [start, end]) {
553
806
  textarea.value = text
@@ -561,20 +814,50 @@ import { createAnchor, locateAnchor } from './anchor.js'
561
814
 
562
815
  // --- Gutter click handlers ---
563
816
 
817
+ // Press on a line number and release on the same line to comment on it, or
818
+ // drag over more lines in the hunk to comment on the range.
564
819
  function attachGutterHandlers() {
565
820
  diffContainer.querySelectorAll('.d2h-code-linenumber').forEach((el) => {
566
- el.addEventListener('click', (e) => {
567
- e.stopPropagation()
568
- const row = el.closest('tr')
569
- if (!row || row.classList.contains('d2h-info')) return
570
-
571
- const fileWrapper = el.closest('.d2h-file-wrapper')
572
- const file = fileWrapper?.querySelector('.d2h-file-name')?.textContent?.trim() ?? ''
573
- const lineInfo = parseLineInfo(el)
574
- if (!lineInfo) return
575
-
576
- openCommentInput(row, file, lineInfo.line, lineInfo.side)
821
+ el.addEventListener('pointerdown', (e) => {
822
+ if (e.button !== 0) return
823
+ const startRow = el.closest('tr')
824
+ if (!startRow || startRow.querySelector('td.d2h-info') || !parseLineInfo(el)) return
825
+ e.preventDefault()
826
+ const file = el.closest('.d2h-file-wrapper')?.querySelector('.d2h-file-name')?.textContent?.trim() ?? ''
827
+ const tbody = startRow.parentElement
828
+ let rows = [startRow]
829
+ let overRow = startRow
830
+ // The range keeps its bar, and each end its +, until the comment box opens.
831
+ const mark = () => {
832
+ const unbar = markCommenting(rows)
833
+ const unedge = markCommenting([rows[0], rows.at(-1)], 'mg-range-edge')
834
+ return () => { unbar(); unedge() }
835
+ }
836
+ let unmark = mark()
837
+
838
+ const move = (ev) => {
839
+ const row = document.elementFromPoint(ev.clientX, ev.clientY)?.closest('tr')
840
+ if (!row || row === overRow || row.parentElement !== tbody || !row.querySelector('.d2h-code-linenumber')) return
841
+ overRow = row
842
+ unmark()
843
+ rows = rowsBetween(startRow, row)
844
+ unmark = mark()
845
+ }
846
+ // A touch scroll cancels the drag, and a re-render mid-drag discards it.
847
+ const end = (ev) => {
848
+ document.removeEventListener('pointermove', move)
849
+ document.removeEventListener('pointerup', end)
850
+ document.removeEventListener('pointercancel', end)
851
+ unmark()
852
+ if (ev.type === 'pointerup' && rows.every(row => row.isConnected)) openCommentInput(file, rows)
853
+ }
854
+ // Captured, a release outside the window still ends the drag.
855
+ el.setPointerCapture?.(e.pointerId)
856
+ document.addEventListener('pointermove', move)
857
+ document.addEventListener('pointerup', end)
858
+ document.addEventListener('pointercancel', end)
577
859
  })
860
+ el.addEventListener('click', (e) => e.stopPropagation())
578
861
  })
579
862
  }
580
863
 
@@ -606,127 +889,348 @@ import { createAnchor, locateAnchor } from './anchor.js'
606
889
 
607
890
  // --- Comment threads ---
608
891
 
609
- function confirmInlineComment(threadId, file, target, text) {
610
- threads[threadId] = { file, target, messages: [{ from: 'user', text }], el: null }
611
- injectThread(threadId)
892
+ // The server keeps each thread's record: its messages and whether it is
893
+ // resolved. Placement, collapse state and reply drafts stay in this page.
894
+ function applyThread(record, { quiet = false } = {}) {
895
+ const local = threads[record.id]
896
+ const thread = local ?? {
897
+ id: record.id,
898
+ target: record.anchor ? { side: record.side, anchor: record.anchor, ...(record.start && { start: record.start, code: record.code }) } : null,
899
+ el: null,
900
+ bubble: null,
901
+ collapsed: record.resolved,
902
+ panelCollapsed: record.resolved,
903
+ reply: null,
904
+ shown: false,
905
+ count: 0
906
+ }
907
+ const grew = record.messages.length > thread.count
908
+ if (local && local.resolved !== record.resolved) {
909
+ thread.collapsed = thread.panelCollapsed = record.resolved
910
+ } else if (local && grew && !record.resolved) {
911
+ thread.collapsed = thread.panelCollapsed = false
912
+ }
913
+ const agentReplied = local && grew && record.messages.at(-1).from === 'assistant'
914
+ thread.file = record.file
915
+ thread.messages = record.messages
916
+ thread.resolved = record.resolved
917
+ thread.count = record.messages.length
918
+ threads[record.id] = thread
919
+ if (local) renderThread(thread)
920
+ else placeThread(thread)
921
+ if (quiet) return
922
+ renderPanel()
923
+ if (agentReplied || (!local && !thread.file)) reveal(thread)
612
924
  }
613
925
 
614
- function confirmGeneralComment(threadId, text) {
615
- threads[threadId] = { file: null, target: null, messages: [{ from: 'user', text }], el: null }
616
- addChatMessage('you', text)
926
+ // A page load or reconnect brings the server's full set.
927
+ function loadThreads(records) {
928
+ const ids = new Set(records.map(r => r.id))
929
+ for (const [id, thread] of Object.entries(threads)) {
930
+ if (ids.has(id)) continue
931
+ thread.el?.remove()
932
+ thread.bubble?.remove()
933
+ delete threads[id]
934
+ }
935
+ for (const record of records) applyThread(record, { quiet: true })
936
+ renderPanel()
617
937
  }
618
938
 
619
- function appendReply(threadId, text, ephemeral) {
939
+ // An ephemeral reply shows until the agent's final reply replaces it.
940
+ function showReply(threadId, text, ephemeral) {
941
+ const message = { from: 'assistant', name: agentName, text, ephemeral, at: Date.now() }
620
942
  const thread = threads[threadId]
621
- if (thread) {
622
- thread.messages = thread.messages.filter(m => !m.ephemeral)
623
- thread.messages.push({ from: 'assistant', text, ephemeral })
624
- if (thread.file) {
625
- renderThreadEl(thread)
626
- } else {
627
- addChatMessage(agentName, text, ephemeral)
628
- }
629
- } else {
630
- addChatMessage(agentName, text, ephemeral)
943
+ if (!thread) {
944
+ // A thread the server has no record of, such as one from before a restart.
945
+ applyThread({ id: threadId, file: null, resolved: false, messages: [message] })
946
+ return
631
947
  }
948
+ thread.messages = [...thread.messages.filter(m => !m.ephemeral), message]
949
+ thread.collapsed = thread.panelCollapsed = false
950
+ renderThread(thread)
951
+ renderPanel()
952
+ reveal(thread)
632
953
  }
633
954
 
634
- function injectThread(threadId) {
635
- const thread = threads[threadId]
636
- if (!thread || !thread.file) return
637
-
638
- // A line comment follows its line; a file comment, or one whose line
639
- // changed, sits at the top of the file's diff.
640
- let anchor = thread.target && placeTarget(thread.file, thread.target)
641
- thread.outdated = Boolean(thread.target) && !anchor
642
- const insertBefore = !anchor
643
- if (!anchor) anchor = fileTopRow(thread.file)
644
- if (!anchor) return
955
+ // Bring a thread into view when the agent answers, wherever it lives.
956
+ function reveal(thread) {
957
+ if (thread.where === 'line' && minimized && !thread.shown) {
958
+ thread.shown = true
959
+ placeThread(thread)
960
+ }
961
+ if (thread.where === 'line' || thread.where === 'file') return
962
+ openPanel()
963
+ panelCards.get(thread.id)?.scrollIntoView({ block: 'nearest' })
964
+ }
645
965
 
966
+ // Puts a thread in the diff, or records why it can't go there: thread.where
967
+ // is line, file, outdated (its line changed), gone (its file left the diff)
968
+ // or general. As on GitHub, only the panel shows outdated threads.
969
+ function placeThread(thread) {
970
+ thread.el?.remove()
971
+ thread.bubble?.remove()
972
+ thread.bubble = null
973
+ if (!thread.file) {
974
+ thread.where = 'general'
975
+ return
976
+ }
977
+ const top = fileTopRow(thread.file)
978
+ if (!top) {
979
+ thread.where = 'gone'
980
+ return
981
+ }
982
+ const row = thread.target && locateRange(thread.file, thread.target)?.at(-1)
983
+ if (thread.target && !row) {
984
+ thread.where = 'outdated'
985
+ return
986
+ }
987
+ thread.where = row ? 'line' : 'file'
988
+ if (row && minimized) {
989
+ thread.bubble = bubble(thread)
990
+ row.querySelector('td:not(.d2h-code-linenumber) .d2h-code-line')?.append(thread.bubble)
991
+ if (!thread.shown) return
992
+ }
646
993
  if (!thread.el) {
647
- thread.el = document.createElement('tr')
648
- thread.el.className = 'comment-thread-row'
649
- thread.el.dataset.threadId = threadId
650
- const cell = document.createElement('td')
651
- cell.colSpan = 3
652
- thread.el.appendChild(cell)
994
+ const { tr } = commentRow('comment-thread-row')
995
+ tr.dataset.threadId = thread.id
996
+ let unmark = null
997
+ tr.addEventListener('mouseenter', () => { unmark = markCommenting(threadRangeRows(thread), 'mg-in-range') })
998
+ tr.addEventListener('mouseleave', () => { unmark?.() })
999
+ thread.el = tr
653
1000
  }
1001
+ tintGutter(thread.el.firstChild, row)
1002
+ // Attached first, so a reply box being typed in can take focus back.
1003
+ if (row) row.after(thread.el)
1004
+ else top.before(thread.el)
1005
+ renderThread(thread)
1006
+ }
654
1007
 
655
- renderThreadEl(thread)
656
-
657
- const existing = diffContainer.querySelector(`[data-thread-id="${threadId}"]`)
658
- if (existing) existing.remove()
659
- if (insertBefore) {
660
- anchor.parentNode.insertBefore(thread.el, anchor)
661
- } else {
662
- anchor.parentNode.insertBefore(thread.el, anchor.nextSibling)
663
- }
1008
+ // Minimized, a line's thread is a bubble at the end of the line; it opens
1009
+ // and closes the thread there.
1010
+ function bubble(thread) {
1011
+ const btn = document.createElement('button')
1012
+ btn.type = 'button'
1013
+ btn.className = 'mg-bubble' + (thread.shown ? ' pressed' : '')
1014
+ btn.title = thread.shown ? 'Hide conversation' : 'Show conversation'
1015
+ btn.innerHTML = avatar(thread.messages[0]) + `<span>${thread.messages.length}</span>`
1016
+ btn.addEventListener('click', (e) => {
1017
+ e.stopPropagation()
1018
+ thread.shown = !thread.shown
1019
+ placeThread(thread)
1020
+ })
1021
+ return btn
664
1022
  }
665
1023
 
1024
+ // Comments render as GitHub renders them: GFM with single newlines as line
1025
+ // breaks. Text from the agent may quote untrusted files, so raw HTML shows
1026
+ // as text and links or images may use only web and mail schemes.
1027
+ // Without the Markdown library, comments show as plain text.
1028
+ // eslint-disable-next-line no-undef
1029
+ const markdown = typeof marked === 'undefined' ? null : marked
1030
+ markdown?.use({ gfm: true, breaks: true, renderer: { html: ({ text }) => escapeHtml(text) } })
1031
+
1032
+ const SAFE_PROTOCOLS = new Set(['http:', 'https:', 'mailto:'])
1033
+
1034
+ // Checks each URL as the browser will read it, after entity decoding, in an
1035
+ // inert template where nothing loads or runs.
666
1036
  function renderMarkdown(text) {
667
- // eslint-disable-next-line no-undef
668
- try { return marked.parse(text, { breaks: true }) } catch { return escapeHtml(text) }
1037
+ const plain = () => escapeHtml(text).replaceAll('\n', '<br>')
1038
+ if (!markdown) return plain()
1039
+ let html
1040
+ try { html = markdown.parse(text) } catch { return plain() }
1041
+ const template = document.createElement('template')
1042
+ template.innerHTML = html
1043
+ const safe = (url) => {
1044
+ try { return SAFE_PROTOCOLS.has(new URL(url, location.href).protocol) } catch { return false }
1045
+ }
1046
+ for (const a of template.content.querySelectorAll('a[href]')) {
1047
+ if (!safe(a.getAttribute('href'))) a.replaceWith(...a.childNodes)
1048
+ }
1049
+ for (const img of template.content.querySelectorAll('img')) {
1050
+ if (!safe(img.getAttribute('src') ?? '')) img.replaceWith(img.getAttribute('alt') ?? '')
1051
+ }
1052
+ return template.innerHTML
669
1053
  }
670
1054
 
671
- function renderMarkdownInline(text) {
672
- // eslint-disable-next-line no-undef
673
- try { return marked.parseInline(text) } catch { return escapeHtml(text) }
1055
+ function relativeTime(at) {
1056
+ const s = Math.round((Date.now() - at) / 1000)
1057
+ if (s < 60) return 'just now'
1058
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`
1059
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`
1060
+ return new Date(at).toLocaleDateString()
674
1061
  }
675
1062
 
676
- function renderMessageContent(m) {
677
- const content = renderMarkdown(m.text)
678
- const ephClass = m.ephemeral ? ' comment-ephemeral' : ''
679
- return `<div class="comment-message comment-${m.from}${ephClass}">` +
680
- `<strong>${m.from === 'user' ? 'you' : escapeHtml(agentName)}</strong>` +
681
- `<div class="mg-md">${content}</div></div>`
1063
+ setInterval(() => {
1064
+ for (const el of document.querySelectorAll('.mg-time[data-at]')) el.textContent = relativeTime(Number(el.dataset.at))
1065
+ }, 30000)
1066
+
1067
+ function authorName(m) {
1068
+ return m.from === 'user' ? 'you' : (m.name ?? agentName)
682
1069
  }
683
1070
 
684
- function renderThreadEl(thread) {
685
- if (!thread.el) return
686
- const cell = thread.el.querySelector('td')
687
- const threadId = thread.el.dataset.threadId
1071
+ function avatar(m) {
1072
+ return `<span class="mg-avatar mg-avatar-${m.from}">${escapeHtml(authorName(m)[0].toUpperCase())}</span>`
1073
+ }
688
1074
 
689
- // Preserve in-progress reply text
690
- const prevInput = cell.querySelector('.thread-reply-input')
691
- const savedText = prevInput ? prevInput.value : ''
1075
+ function renderMessage(m) {
1076
+ const time = m.at ? `<span class="mg-time" data-at="${m.at}" title="${new Date(m.at).toLocaleString()}">${relativeTime(m.at)}</span>` : ''
1077
+ return `<div class="mg-comment${m.ephemeral ? ' mg-comment-ephemeral' : ''}">` +
1078
+ `<div class="mg-comment-header">${avatar(m)}<strong>${escapeHtml(authorName(m))}</strong>${time}</div>` +
1079
+ `<div class="mg-md mg-comment-body">${renderMarkdown(m.text)}</div></div>`
1080
+ }
692
1081
 
693
- cell.innerHTML = '<div class="comment-thread">' +
694
- '<button class="comment-dismiss" title="Dismiss">&times;</button>' +
695
- (thread.outdated ? `<div class="comment-outdated">Outdated: line ${thread.target.anchor.line} changed or left the diff</div>` : '') +
696
- thread.messages.map(renderMessageContent).join('') +
697
- '<div class="thread-reply-box">' +
698
- '<textarea rows="2" class="mg-textarea thread-reply-input" placeholder="Reply..."></textarea>' +
699
- '<div class="comment-input-actions"><button class="small thread-reply-send">Reply</button></div>' +
1082
+ // A thread as a GitHub-style card, inline in the diff or in the panel. Each
1083
+ // view collapses on its own; thread.reply holds an open reply's draft for both.
1084
+ function threadCard(thread, view) {
1085
+ const collapsedKey = view === 'panel' ? 'panelCollapsed' : 'collapsed'
1086
+ const collapsed = thread[collapsedKey]
1087
+ const card = document.createElement('div')
1088
+ card.className = 'mg-thread' + (collapsed ? ' mg-thread-collapsed' : '')
1089
+ let title
1090
+ if (view === 'inline') {
1091
+ title = thread.target ? `Comment on ${lineLabel(thread.target)}` : 'Comment on file'
1092
+ } else if (thread.file) {
1093
+ title = `<button type="button" class="mg-thread-file" data-action="jump" title="Show in diff">${escapeHtml(thread.file)}</button>` +
1094
+ `<span>${!thread.target ? 'File' : thread.target.start ? `Lines ${thread.target.start.anchor.line} to ${thread.target.anchor.line}` : 'Line ' + thread.target.anchor.line}</span>`
1095
+ } else {
1096
+ title = 'General comment'
1097
+ }
1098
+ const code = view !== 'panel' || !thread.target ? ''
1099
+ : thread.target.start ? `<pre class="mg-thread-code">${escapeHtml(thread.target.code ?? '')}</pre>`
1100
+ : `<pre class="mg-thread-code"><span>${thread.target.anchor.line}</span>${escapeHtml(thread.target.anchor.text)}</pre>`
1101
+ card.innerHTML =
1102
+ '<div class="mg-thread-header">' +
1103
+ `<button type="button" class="mg-icon-btn mg-chevron" aria-expanded="${!collapsed}" title="${collapsed ? 'Expand' : 'Collapse'}">${ICON_CHEVRON}</button>` +
1104
+ `<span class="mg-thread-title">${title}</span>` +
1105
+ (thread.where === 'outdated' ? '<span class="mg-label mg-label-outdated" title="The line changed or left the diff">Outdated</span>' : '') +
1106
+ (thread.where === 'gone' ? '<span class="mg-label" title="The file is no longer in the diff">Not in diff</span>' : '') +
1107
+ (thread.resolved ? '<span class="mg-label">Resolved</span>' : '') +
1108
+ (view === 'inline' && thread.bubble ? `<button type="button" class="mg-icon-btn mg-thread-minimize" data-action="minimize" title="Minimize to a bubble">${ICON_FOLD}</button>` : '') +
700
1109
  '</div>' +
701
- '</div>'
702
- cell.querySelector('.comment-dismiss').addEventListener('click', () => {
703
- thread.dismissed = true
704
- thread.el.remove()
705
- thread.el = null
1110
+ '<div class="mg-thread-body">' + code + thread.messages.map(renderMessage).join('') +
1111
+ '<div class="mg-thread-reply"></div>' +
1112
+ '</div>' +
1113
+ `<div class="mg-thread-footer"><button type="button" class="mg-btn" data-action="resolve">${thread.resolved ? 'Unresolve conversation' : 'Resolve conversation'}</button></div>`
1114
+
1115
+ const rerender = () => {
1116
+ renderThread(thread)
1117
+ renderPanel()
1118
+ }
1119
+ card.querySelector('.mg-chevron').addEventListener('click', () => {
1120
+ thread[collapsedKey] = !collapsed
1121
+ rerender()
1122
+ })
1123
+ card.querySelector('[data-action="resolve"]').addEventListener('click', () => {
1124
+ send({ type: 'resolve', thread_id: thread.id, resolved: !thread.resolved })
1125
+ })
1126
+ card.querySelector('[data-action="jump"]')?.addEventListener('click', () => showInDiff(thread))
1127
+ card.querySelector('[data-action="minimize"]')?.addEventListener('click', () => {
1128
+ thread.shown = false
1129
+ placeThread(thread)
706
1130
  })
707
- const input = cell.querySelector('.thread-reply-input')
708
- input.value = savedText
709
- if (savedText) input.focus()
710
- const sendBtn = cell.querySelector('.thread-reply-send')
711
- function sendReply() {
1131
+
1132
+ const replyEl = card.querySelector('.mg-thread-reply')
1133
+ if (thread.reply == null) {
1134
+ const trigger = document.createElement('button')
1135
+ trigger.type = 'button'
1136
+ trigger.className = 'mg-reply-trigger'
1137
+ trigger.textContent = 'Write a reply'
1138
+ trigger.addEventListener('click', () => {
1139
+ thread.reply = { text: '', view }
1140
+ rerender()
1141
+ })
1142
+ replyEl.append(trigger)
1143
+ return card
1144
+ }
1145
+
1146
+ // One reply box per thread, in the view it was opened in; the other view
1147
+ // offers to bring it over, text and caret intact.
1148
+ if (thread.reply.view !== view) {
1149
+ const move = document.createElement('button')
1150
+ move.type = 'button'
1151
+ move.className = 'mg-reply-trigger mg-reply-elsewhere'
1152
+ move.textContent = thread.reply.view === 'panel' ? 'Replying in the Comments panel. Continue here' : 'Replying in the diff. Continue here'
1153
+ move.addEventListener('click', () => {
1154
+ thread.reply.view = view
1155
+ rerender()
1156
+ })
1157
+ replyEl.append(move)
1158
+ return card
1159
+ }
1160
+
1161
+ replyEl.innerHTML = '<textarea rows="3" class="mg-textarea thread-reply-input" placeholder="Write a reply"></textarea>' +
1162
+ '<div class="comment-input-actions">' +
1163
+ '<button type="button" class="mg-btn" data-action="cancel">Cancel</button>' +
1164
+ '<button type="button" class="mg-btn mg-btn-primary" data-action="reply">Reply</button>' +
1165
+ '</div>'
1166
+ const input = replyEl.querySelector('textarea')
1167
+ input.value = thread.reply.text
1168
+ // A re-render rebuilds the box; the caret goes back where it was.
1169
+ const keep = () => {
1170
+ if (!thread.reply) return
1171
+ thread.reply.text = input.value
1172
+ thread.reply.caret = [input.selectionStart, input.selectionEnd]
1173
+ }
1174
+ for (const type of ['input', 'keyup', 'mouseup', 'select']) input.addEventListener(type, keep)
1175
+ const close = () => {
1176
+ thread.reply = null
1177
+ rerender()
1178
+ }
1179
+ const sendReply = () => {
712
1180
  const text = input.value.trim()
713
1181
  if (!text) return
714
- input.value = ''
715
- send({ type: 'thread_reply', thread_id: threadId, text })
716
- thread.messages.push({ from: 'user', text })
717
- renderThreadEl(thread)
1182
+ send({ type: 'thread_reply', thread_id: thread.id, text })
1183
+ close()
718
1184
  }
719
- sendBtn.addEventListener('click', sendReply)
1185
+ replyEl.querySelector('[data-action="reply"]').addEventListener('click', sendReply)
1186
+ replyEl.querySelector('[data-action="cancel"]').addEventListener('click', close)
720
1187
  input.addEventListener('keydown', (e) => {
721
1188
  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); sendReply() }
1189
+ if (e.key === 'Escape' && !input.value.trim()) close()
722
1190
  })
1191
+ return card
1192
+ }
1193
+
1194
+ // Replaces host's card, keeping the reply box focused if it was.
1195
+ function mountCard(thread, view, host) {
1196
+ const focused = document.activeElement?.classList.contains('thread-reply-input') && host.contains(document.activeElement)
1197
+ const card = threadCard(thread, view)
1198
+ host.replaceChildren(card)
1199
+ if (focused || thread.reply?.view === view) {
1200
+ const input = card.querySelector('.thread-reply-input')
1201
+ if (input && (focused || document.activeElement === document.body || !document.activeElement)) {
1202
+ input.focus()
1203
+ if (thread.reply.caret) input.setSelectionRange(...thread.reply.caret)
1204
+ }
1205
+ }
1206
+ }
1207
+
1208
+ function renderThread(thread) {
1209
+ if (thread.bubble) {
1210
+ const fresh = bubble(thread)
1211
+ thread.bubble.replaceWith(fresh)
1212
+ thread.bubble = fresh
1213
+ }
1214
+ if (thread.el) mountCard(thread, 'inline', thread.el.lastChild)
723
1215
  }
724
1216
 
725
1217
  function reinjectThreads() {
726
- for (const threadId of Object.keys(threads)) {
727
- const thread = threads[threadId]
728
- if (thread.file && !thread.dismissed) injectThread(threadId)
1218
+ for (const thread of Object.values(threads)) placeThread(thread)
1219
+ renderPanel()
1220
+ }
1221
+
1222
+ function showInDiff(thread) {
1223
+ if (thread.where !== 'line' && thread.where !== 'file') return
1224
+ if (minimized && !thread.shown) {
1225
+ thread.shown = true
1226
+ placeThread(thread)
729
1227
  }
1228
+ // Opening the file leaves its Viewed mark alone.
1229
+ diffIndex.get(thread.file)?.setCollapsed?.(false)
1230
+ thread.collapsed = false
1231
+ renderThread(thread)
1232
+ thread.el?.scrollIntoView({ block: 'center', behavior: 'instant' })
1233
+ if (window.matchMedia('(max-width: 1000px)').matches) closePanel()
730
1234
  }
731
1235
 
732
1236
  function fileTopRow(file) {
@@ -744,6 +1248,102 @@ import { createAnchor, locateAnchor } from './anchor.js'
744
1248
  return lines.rows.get(found.line)
745
1249
  }
746
1250
 
1251
+ // --- Comments panel ---
1252
+
1253
+ const panelCards = new Map()
1254
+ let panelFilter = 'unresolved'
1255
+ let minimized = localStorage.getItem('marginalia-minimize') === '1'
1256
+
1257
+ commentsToggle.insertAdjacentHTML('afterbegin', ICON_DISCUSSION)
1258
+ minimizeToggle.innerHTML = ICON_FOLD
1259
+ document.getElementById('comments-close').innerHTML = ICON_X
1260
+
1261
+ // General threads first, then threads in file tree and line order.
1262
+ function panelOrder(a, b) {
1263
+ if (!a.file || !b.file) return (a.file ? 1 : 0) - (b.file ? 1 : 0) || a.messages[0].at - b.messages[0].at
1264
+ return compareTreePaths(a.file, b.file) || ((a.target?.start ?? a.target)?.anchor.line ?? 0) - ((b.target?.start ?? b.target)?.anchor.line ?? 0)
1265
+ }
1266
+
1267
+ function renderPanel() {
1268
+ const all = Object.values(threads).sort(panelOrder)
1269
+ const unresolved = all.filter(t => !t.resolved)
1270
+ commentsCount.textContent = unresolved.length || ''
1271
+ renderTree()
1272
+ commentsToggle.title = `${unresolved.length} unresolved conversation${unresolved.length === 1 ? '' : 's'}`
1273
+ if (commentsPanel.classList.contains('hidden')) return
1274
+
1275
+ for (const seg of commentsPanel.querySelectorAll('.mg-segment')) {
1276
+ seg.classList.toggle('selected', seg.dataset.filter === panelFilter)
1277
+ seg.querySelector('.mg-counter').textContent = seg.dataset.filter === 'all' ? all.length : unresolved.length
1278
+ }
1279
+ const shown = panelFilter === 'all' ? all : unresolved
1280
+ commentsPanel.querySelector('.mg-panel-summary').textContent =
1281
+ all.length ? `Showing ${shown.length} of ${all.length} conversation${all.length === 1 ? '' : 's'}` : ''
1282
+
1283
+ const active = document.activeElement
1284
+ const focusId = active?.classList.contains('thread-reply-input') && commentsList.contains(active)
1285
+ ? active.closest('[data-thread-id]')?.dataset.threadId
1286
+ : null
1287
+ panelCards.clear()
1288
+ commentsList.replaceChildren()
1289
+ for (const thread of shown) {
1290
+ const wrap = document.createElement('div')
1291
+ wrap.dataset.threadId = thread.id
1292
+ commentsList.append(wrap)
1293
+ mountCard(thread, 'panel', wrap)
1294
+ panelCards.set(thread.id, wrap)
1295
+ }
1296
+ if (focusId) panelCards.get(focusId)?.querySelector('.thread-reply-input')?.focus()
1297
+ if (!shown.length) {
1298
+ const empty = document.createElement('p')
1299
+ empty.className = 'mg-panel-empty'
1300
+ empty.textContent = all.length ? 'No unresolved conversations' : 'No conversations yet'
1301
+ commentsList.append(empty)
1302
+ }
1303
+ }
1304
+
1305
+ function openPanel() {
1306
+ if (!commentsPanel.classList.contains('hidden')) return
1307
+ commentsPanel.classList.remove('hidden')
1308
+ commentsToggle.setAttribute('aria-pressed', 'true')
1309
+ localStorage.setItem('marginalia-panel', '1')
1310
+ renderPanel()
1311
+ }
1312
+
1313
+ function closePanel() {
1314
+ commentsPanel.classList.add('hidden')
1315
+ commentsToggle.setAttribute('aria-pressed', 'false')
1316
+ localStorage.removeItem('marginalia-panel')
1317
+ }
1318
+
1319
+ commentsToggle.addEventListener('click', () => {
1320
+ if (commentsPanel.classList.contains('hidden')) openPanel()
1321
+ else closePanel()
1322
+ })
1323
+ document.getElementById('comments-close').addEventListener('click', closePanel)
1324
+ for (const seg of commentsPanel.querySelectorAll('.mg-segment')) {
1325
+ seg.addEventListener('click', () => {
1326
+ panelFilter = seg.dataset.filter
1327
+ renderPanel()
1328
+ })
1329
+ }
1330
+ if (localStorage.getItem('marginalia-panel') === '1') openPanel()
1331
+
1332
+ function showMinimized() {
1333
+ minimizeToggle.setAttribute('aria-pressed', String(minimized))
1334
+ minimizeToggle.title = minimized ? 'Show comments in the diff' : 'Minimize comments'
1335
+ }
1336
+
1337
+ minimizeToggle.addEventListener('click', () => {
1338
+ minimized = !minimized
1339
+ if (minimized) localStorage.setItem('marginalia-minimize', '1')
1340
+ else localStorage.removeItem('marginalia-minimize')
1341
+ for (const thread of Object.values(threads)) thread.shown = false
1342
+ showMinimized()
1343
+ reinjectThreads()
1344
+ })
1345
+ showMinimized()
1346
+
747
1347
  // --- Permission relay ---
748
1348
 
749
1349
  function showPermission(msg) {
@@ -772,14 +1372,7 @@ import { createAnchor, locateAnchor } from './anchor.js'
772
1372
  pendingPermission = null
773
1373
  })
774
1374
 
775
- // --- Chat footer ---
776
-
777
- chatToggle.addEventListener('click', (e) => {
778
- if (e.target === generalInput || e.target === generalSend) return
779
- chatExpanded = !chatExpanded
780
- chatHistory.classList.toggle('hidden', !chatExpanded)
781
- chatIndicator.textContent = chatExpanded ? '-' : '+'
782
- })
1375
+ // --- General comments ---
783
1376
 
784
1377
  function sendGeneral() {
785
1378
  const text = generalInput.value.trim()
@@ -796,28 +1389,6 @@ import { createAnchor, locateAnchor } from './anchor.js'
796
1389
  }
797
1390
  })
798
1391
 
799
- const MAX_CHAT_MESSAGES = 50
800
-
801
- function addChatMessage(from, text, ephemeral) {
802
- if (!ephemeral) {
803
- chatHistory.querySelectorAll('.chat-ephemeral').forEach(el => el.remove())
804
- }
805
- const div = document.createElement('div')
806
- div.className = 'chat-message chat-' + (from === 'you' ? 'you' : 'assistant') + (ephemeral ? ' chat-ephemeral' : '')
807
- const content = renderMarkdown(text)
808
- div.innerHTML = `<strong>${escapeHtml(from)}</strong><div class="mg-md">${content}</div>`
809
- chatHistory.appendChild(div)
810
- while (chatHistory.children.length > MAX_CHAT_MESSAGES) {
811
- chatHistory.removeChild(chatHistory.firstChild)
812
- }
813
- chatHistory.scrollTop = chatHistory.scrollHeight
814
- if (!chatExpanded) {
815
- chatExpanded = true
816
- chatHistory.classList.remove('hidden')
817
- chatIndicator.textContent = '-'
818
- }
819
- }
820
-
821
1392
  // --- Util ---
822
1393
 
823
1394
  function escapeHtml(str) {