@rvagg/marginalia 0.1.1 → 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,8 +1,28 @@
1
+ import { createAnchor, locateAnchor } from './anchor.js'
2
+ import { compareTreePaths, sortFileDiffs } from './file-order.js'
3
+ import { buildTree } from './file-tree.js'
4
+
1
5
  (function () {
2
6
  'use strict'
3
7
 
4
8
  // --- Icons ---
5
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>'
6
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>'
7
27
 
8
28
  // --- Theme ---
@@ -30,15 +50,18 @@
30
50
  })
31
51
 
32
52
  // --- State ---
33
- const threads = {} // thread_id -> { el, messages }
53
+ // thread_id -> { file, target, messages, el, outdated, resolved, collapsed, reply }
54
+ const threads = {}
34
55
  const viewedFiles = {} // filename -> diff hash (to detect changes)
56
+ const collapsedFiles = {}
35
57
  let pendingPermission = null
36
- let chatExpanded = false
37
58
  let agentName = 'agent'
38
59
 
39
60
  // --- Elements ---
40
- const filenav = document.getElementById('filenav')
41
- 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')
42
65
  const diffContainer = document.getElementById('diff-container')
43
66
  const loadingState = document.getElementById('loading-state')
44
67
  const emptyState = document.getElementById('empty-state')
@@ -48,9 +71,11 @@
48
71
  const permissionText = document.getElementById('permission-text')
49
72
  const permissionApprove = document.getElementById('permission-approve')
50
73
  const permissionDeny = document.getElementById('permission-deny')
51
- const chatToggle = document.getElementById('chat-toggle')
52
- const chatIndicator = document.getElementById('chat-indicator')
53
- 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')
54
79
  const generalInput = document.getElementById('general-input')
55
80
  const generalSend = document.getElementById('general-send')
56
81
  const baseInput = document.getElementById('base-input')
@@ -61,7 +86,7 @@
61
86
 
62
87
  const contextContainer = document.createElement('div')
63
88
  contextContainer.id = 'context-snippets'
64
- diffContainer.parentNode.insertBefore(contextContainer, diffContainer)
89
+ document.getElementById('workspace').before(contextContainer)
65
90
 
66
91
  function addContextSnippet(msg) {
67
92
  const snippet = document.createElement('div')
@@ -81,50 +106,129 @@
81
106
  snippet.scrollIntoView({ block: 'nearest', behavior: 'instant' })
82
107
  }
83
108
 
84
- // --- File nav ---
109
+ // --- File tree ---
85
110
 
86
- function updateFileCount(n) {
87
- const expanded = fileCountEl.classList.contains('active')
88
- const chevron = expanded ? '\u25B4' : '\u25BE'
89
- 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']
90
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
+ }
91
133
 
92
- fileCountEl.addEventListener('click', () => {
93
- filenav.classList.toggle('hidden')
94
- fileCountEl.classList.toggle('active')
95
- const n = filenav.children.length
96
- updateFileCount(n)
97
- })
98
-
99
- function updateFilenav(diffText) {
100
- filenav.innerHTML = ''
101
- if (!diffText) return
102
- const chunks = diffText.split(/(?=^diff --git )/m)
103
- for (const chunk of chunks) {
104
- const nameMatch = chunk.match(/^diff --git a\/(.+?) b\/(.+)$/m)
105
- if (!nameMatch) continue
106
- const file = nameMatch[2]
107
- const isNew = /^new file mode/m.test(chunk)
108
- const isDel = /^deleted file mode/m.test(chunk)
109
- const badge = isNew ? 'added' : isDel ? 'deleted' : 'changed'
110
- const label = isNew ? 'A' : isDel ? 'D' : 'M'
111
- const item = document.createElement('div')
112
- item.className = 'filenav-item' + (viewedFiles[file] ? ' filenav-viewed' : '')
113
- item.innerHTML = `<span class="filenav-badge filenav-badge-${badge}">${label}</span>${escapeHtml(file)}`
114
- item.addEventListener('click', () => {
115
- const wrappers = diffContainer.querySelectorAll('.d2h-file-wrapper')
116
- for (const w of wrappers) {
117
- const n = w.querySelector('.d2h-file-name')
118
- if (n && n.textContent.trim() === file) {
119
- w.scrollIntoView({ block: 'start', behavior: 'instant' })
120
- break
121
- }
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
122
156
  }
123
- })
124
- 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' })
125
195
  }
126
196
  }
127
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
+
128
232
  // --- Diff base ---
129
233
 
130
234
  const BASE_TITLE = 'Branch, tag or commit to diff against, from its merge-base with HEAD. Enter to apply, empty for HEAD.'
@@ -199,10 +303,11 @@
199
303
  const msg = JSON.parse(e.data)
200
304
  switch (msg.type) {
201
305
  case 'init':
202
- projectDirEl.textContent = msg.projectDir
306
+ projectDirEl.innerHTML = `<bdi>${escapeHtml(msg.projectDir)}</bdi>`
203
307
  showBase(msg.base ?? null)
204
308
  agentName = typeof msg.agentName === 'string' && msg.agentName ? msg.agentName : 'agent'
205
309
  renderDiff(msg.diff)
310
+ loadThreads(msg.threads ?? [])
206
311
  break
207
312
  case 'diff':
208
313
  if ((msg.base ?? null) !== currentBase) showBase(msg.base ?? null)
@@ -224,20 +329,19 @@
224
329
  dismissPermission()
225
330
  break
226
331
  case 'reply':
227
- appendReply(msg.thread_id, msg.text, msg.ephemeral)
332
+ showReply(msg.thread_id, msg.text, msg.ephemeral)
228
333
  dismissPermission()
229
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
230
341
  case 'status':
231
342
  statusEl.textContent = msg.text
232
343
  dismissPermission()
233
344
  break
234
- case 'comment_ack':
235
- if (msg.file) {
236
- confirmInlineComment(msg.thread_id, msg.file, parseInt(msg.line, 10), msg.side, msg.text)
237
- } else {
238
- confirmGeneralComment(msg.thread_id, msg.text)
239
- }
240
- break
241
345
  case 'permission':
242
346
  showPermission(msg)
243
347
  break
@@ -263,14 +367,17 @@
263
367
  loadingState.classList.add('hidden')
264
368
 
265
369
  if (!diffText || diffText.trim() === '') {
370
+ heldDrafts = saveOpenInputs().map((draft) => ({ ...draft, focused: false }))
371
+ diffIndex = new Map()
266
372
  diffContainer.innerHTML = ''
267
373
  diffContainer.appendChild(emptyState)
268
374
  emptyState.classList.remove('hidden')
269
- updateFileCount(0)
375
+ reinjectThreads()
270
376
  return
271
377
  }
272
378
 
273
379
  emptyState.classList.add('hidden')
380
+ diffText = sortFileDiffs(diffText)
274
381
  const scrollTop = diffContainer.scrollTop
275
382
 
276
383
  // Split diff into per-file chunks to detect changes
@@ -285,13 +392,11 @@
285
392
  for (const file of Object.keys(viewedFiles)) {
286
393
  if (currentFileDiffs[file] && currentFileDiffs[file] !== lastFileDiffs[file]) {
287
394
  delete viewedFiles[file]
395
+ delete collapsedFiles[file]
288
396
  }
289
397
  }
290
398
  lastFileDiffs = currentFileDiffs
291
399
 
292
- const fileHeaders = Object.keys(currentFileDiffs).length
293
- updateFileCount(fileHeaders)
294
-
295
400
  // eslint-disable-next-line no-undef
296
401
  const diff2htmlUi = new Diff2HtmlUI(diffContainer, diffText, {
297
402
  outputFormat: 'line-by-line',
@@ -305,128 +410,208 @@
305
410
 
306
411
  diff2htmlUi.draw()
307
412
  diff2htmlUi.highlightCode()
413
+ groupChangeRuns()
414
+ indexDiff()
308
415
 
309
- updateFilenav(diffText)
310
- injectViewedToggles()
416
+ buildFileHeaders()
311
417
  attachGutterHandlers()
312
418
  reinjectThreads()
313
419
  restoreOpenInputs(openInputs)
314
420
  diffContainer.scrollTop = scrollTop
315
421
  }
316
422
 
317
- // --- File header controls ---
423
+ // file -> { wrapper, left, right }; each side holds line -> text and line -> row.
424
+ let diffIndex = new Map()
425
+
426
+ function indexDiff() {
427
+ diffIndex = new Map()
428
+ for (const wrapper of diffContainer.querySelectorAll('.d2h-file-wrapper')) {
429
+ const file = wrapper.querySelector('.d2h-file-name')?.textContent.trim()
430
+ if (!file) continue
431
+ const entry = {
432
+ wrapper,
433
+ left: { texts: new Map(), rows: new Map() },
434
+ right: { texts: new Map(), rows: new Map() }
435
+ }
436
+ for (const row of wrapper.querySelectorAll('tr')) {
437
+ const numEl = row.querySelector('.d2h-code-linenumber')
438
+ if (!numEl) continue
439
+ const text = row.querySelector('.d2h-code-line-ctn')?.textContent ?? ''
440
+ const oldLine = parseInt(numEl.querySelector('.line-num1')?.textContent ?? '', 10)
441
+ const newLine = parseInt(numEl.querySelector('.line-num2')?.textContent ?? '', 10)
442
+ for (const [side, line] of [['left', oldLine], ['right', newLine]]) {
443
+ if (isNaN(line)) continue
444
+ entry[side].texts.set(line, text)
445
+ entry[side].rows.set(line, row)
446
+ }
447
+ }
448
+ diffIndex.set(file, entry)
449
+ }
450
+ }
318
451
 
319
- function injectViewedToggles() {
320
- const wrappers = diffContainer.querySelectorAll('.d2h-file-wrapper')
321
- wrappers.forEach((wrapper) => {
322
- const nameEl = wrapper.querySelector('.d2h-file-name')
323
- const fileName = nameEl?.textContent?.trim()
324
- if (!fileName) return
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
+ }
325
492
 
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
+ }
509
+
510
+ function buildFileHeaders() {
511
+ for (const wrapper of diffContainer.querySelectorAll('.d2h-file-wrapper')) {
512
+ const fileName = wrapper.querySelector('.d2h-file-name')?.textContent?.trim()
326
513
  const header = wrapper.querySelector('.d2h-file-name-wrapper')
327
- 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
+ })
328
534
 
329
535
  const viewedBtn = document.createElement('button')
330
- viewedBtn.className = 'mg-viewed-toggle'
331
- viewedBtn.textContent = 'Viewed'
332
536
  viewedBtn.type = 'button'
333
-
334
- if (viewedFiles[fileName]) {
335
- viewedBtn.classList.add('viewed')
336
- 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>'
337
542
  }
338
-
339
543
  viewedBtn.addEventListener('click', (e) => {
340
544
  e.stopPropagation()
341
- const isViewed = viewedBtn.classList.toggle('viewed')
342
- if (isViewed) {
343
- viewedFiles[fileName] = true
344
- wrapper.classList.add('mg-collapsed')
345
- wrapper.scrollIntoView({ block: 'start', behavior: 'instant' })
346
- } else {
347
- delete viewedFiles[fileName]
348
- wrapper.classList.remove('mg-collapsed')
349
- }
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' })
350
551
  })
351
552
 
352
- const commentBtn = document.createElement('button')
353
- commentBtn.className = 'mg-file-comment'
354
- commentBtn.innerHTML = ICON_COMMENT
355
- commentBtn.type = 'button'
356
- commentBtn.title = 'Comment on file'
357
- commentBtn.addEventListener('click', (e) => {
358
- e.stopPropagation()
553
+ const commentBtn = iconButton('mg-file-comment', ICON_COMMENT, 'Comment on file', () => {
359
554
  const diffBody = wrapper.querySelector('.d2h-diff-tbody')
360
- if (!diffBody) return
361
- const firstRow = diffBody.querySelector('tr')
555
+ const firstRow = diffBody?.querySelector('tr')
362
556
  if (!firstRow) return
363
557
  if (firstRow.previousElementSibling?.classList.contains('comment-input-row')) return
558
+ setCollapsed(false)
364
559
  openFileCommentInput(diffBody, firstRow, fileName)
365
560
  })
366
561
 
367
- const copyBtn = document.createElement('button')
368
- copyBtn.className = 'mg-copy-path'
369
- copyBtn.innerHTML = ICON_COPY
370
- copyBtn.type = 'button'
371
- copyBtn.title = 'Copy file path'
372
- copyBtn.addEventListener('click', (e) => {
373
- e.stopPropagation()
374
- copyToClipboard(fileName).then(() => {
375
- copyBtn.classList.add('mg-copied')
376
- setTimeout(() => copyBtn.classList.remove('mg-copied'), 1500)
377
- })
378
- })
379
-
380
- header.appendChild(copyBtn)
381
- header.appendChild(viewedBtn)
382
- header.appendChild(commentBtn)
383
- })
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
+ }
384
568
  }
385
569
 
386
570
  // --- Comment input persistence across re-renders ---
387
571
 
572
+ // Comment input rows -> { file, target, textarea }; target is null on a file comment.
573
+ const commentInputs = new WeakMap()
574
+ // Drafts whose file left the diff, restored when it returns.
575
+ let heldDrafts = []
576
+
388
577
  function saveOpenInputs() {
389
- const inputs = []
578
+ const inputs = heldDrafts
579
+ heldDrafts = []
390
580
  diffContainer.querySelectorAll('.comment-input-row').forEach((row) => {
391
- const textarea = row.querySelector('textarea')
392
- if (!textarea) return
393
- const context = row.querySelector('.comment-input-context')
394
- const contextText = context?.textContent ?? ''
395
- // Parse "file:line" or "file" from context label
396
- const match = contextText.match(/^(.+):(\d+)$/)
397
- const file = match ? match[1] : contextText
398
- const line = match ? parseInt(match[2], 10) : 0
399
- inputs.push({ file, line, text: textarea.value })
581
+ const input = commentInputs.get(row)
582
+ if (!input) return
583
+ const { textarea } = input
584
+ inputs.push({
585
+ file: input.file,
586
+ target: input.target,
587
+ text: textarea.value,
588
+ focused: document.activeElement === textarea,
589
+ selection: [textarea.selectionStart, textarea.selectionEnd]
590
+ })
400
591
  })
401
592
  return inputs
402
593
  }
403
594
 
404
595
  function restoreOpenInputs(inputs) {
405
- for (const { file, line, text } of inputs) {
406
- if (line === 0) {
407
- // File-level: find the file wrapper and re-open
408
- const wrappers = diffContainer.querySelectorAll('.d2h-file-wrapper')
409
- for (const wrapper of wrappers) {
410
- const nameEl = wrapper.querySelector('.d2h-file-name')
411
- if (nameEl?.textContent?.trim() !== file) continue
412
- const diffBody = wrapper.querySelector('.d2h-diff-tbody')
413
- const firstRow = diffBody?.querySelector('tr')
414
- if (!diffBody || !firstRow) continue
415
- const inputRow = createCommentInputRow(file, null)
416
- diffBody.insertBefore(inputRow.el, firstRow)
417
- inputRow.el.querySelector('textarea').value = text
418
- break
419
- }
596
+ for (const draft of inputs) {
597
+ const { file, target, text, focused, selection } = draft
598
+ const rows = target && locateRange(file, target)
599
+ const row = rows?.at(-1)
600
+ const top = row ? null : fileTopRow(file)
601
+ if (!row && !top) {
602
+ heldDrafts.push({ ...draft, focused: false })
603
+ continue
604
+ }
605
+ const inputRow = createCommentInputRow(file, target)
606
+ if (row) {
607
+ inputRow.tintFrom(row)
608
+ row.after(inputRow.el)
609
+ inputRow.onCleanup = markCommenting(rows)
420
610
  } else {
421
- // Line-level: find the row and re-open
422
- const row = findDiffRow(file, line, 'right') || findDiffRow(file, line, 'left')
423
- if (!row) continue
424
- const inputRow = createCommentInputRow(file, line)
425
- row.parentNode.insertBefore(inputRow.el, row.nextSibling)
426
- row.classList.add('mg-commenting')
427
- inputRow.onCleanup = () => row.classList.remove('mg-commenting')
428
- inputRow.el.querySelector('textarea').value = text
611
+ top.before(inputRow.el)
612
+ if (target) inputRow.markChanged()
429
613
  }
614
+ inputRow.restore(text, focused, selection)
430
615
  }
431
616
  }
432
617
 
@@ -438,37 +623,131 @@
438
623
  inputRow.focus()
439
624
  }
440
625
 
441
- function openCommentInput(afterRow, file, line, side) {
442
- const existingInput = afterRow.nextElementSibling
443
- if (existingInput?.classList.contains('comment-input-row')) 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
444
666
 
445
- const inputRow = createCommentInputRow(file, line)
446
- afterRow.parentNode.insertBefore(inputRow.el, afterRow.nextSibling)
447
- afterRow.classList.add('mg-commenting')
448
- 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)
449
671
  inputRow.focus()
450
672
  }
451
673
 
452
- function createCommentInputRow(file, line) {
453
- const isFileLevel = line === null || line === 0
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) {
454
701
  const tr = document.createElement('tr')
455
- tr.className = 'comment-input-row'
702
+ tr.className = 'mg-comment-row ' + className
703
+ const gutter = document.createElement('td')
704
+ gutter.className = 'mg-row-gutter'
456
705
  const cell = document.createElement('td')
457
- 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')
458
724
  cell.innerHTML = `
459
- <div class="comment-input-box">
460
- <div class="comment-input-context">${escapeHtml(file)}${isFileLevel ? '' : ':' + line}</div>
461
- <textarea class="mg-textarea" rows="3" placeholder="${isFileLevel ? 'Comment on this file...' : 'Leave a comment...'}"></textarea>
462
- <div class="comment-input-actions">
463
- <button class="small" data-action="submit">Comment</button>
464
- <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>
465
740
  </div>
466
741
  </div>
467
742
  `
468
- tr.appendChild(cell)
469
743
 
470
744
  const textarea = cell.querySelector('textarea')
745
+ const preview = cell.querySelector('.mg-preview')
746
+ commentInputs.set(tr, { file, target, textarea })
471
747
  let onCleanup = null
748
+ // Set when the commented line changed or left the diff; its line number
749
+ // no longer names that code, so the comment goes to the file instead.
750
+ let changed = false
472
751
 
473
752
  function cleanup() {
474
753
  tr.remove()
@@ -478,10 +757,31 @@
478
757
  function submit() {
479
758
  const text = textarea.value.trim()
480
759
  if (!text) return
481
- send({ type: 'comment', file, line: isFileLevel ? 0 : line, side: 'right', text })
760
+ if (isFileLevel) {
761
+ send({ type: 'comment', file, line: 0, side: 'right', text })
762
+ } else if (changed) {
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}`
765
+ send({ type: 'comment', file, line: 0, side: 'right', text: quoted })
766
+ } else {
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
+ })
771
+ }
482
772
  cleanup()
483
773
  }
484
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
+
485
785
  textarea.addEventListener('keydown', (e) => {
486
786
  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); submit() }
487
787
  if (e.key === 'Escape') cleanup()
@@ -493,26 +793,71 @@
493
793
  return {
494
794
  el: tr,
495
795
  focus: () => textarea.focus(),
796
+ tintFrom: (row) => tintGutter(gutter, row),
797
+ markChanged() {
798
+ changed = true
799
+ const note = document.createElement('span')
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)
804
+ },
805
+ restore(text, focused, [start, end]) {
806
+ textarea.value = text
807
+ if (!focused) return
808
+ textarea.focus()
809
+ textarea.setSelectionRange(start, end)
810
+ },
496
811
  set onCleanup(fn) { onCleanup = fn }
497
812
  }
498
813
  }
499
814
 
500
815
  // --- Gutter click handlers ---
501
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.
502
819
  function attachGutterHandlers() {
503
820
  diffContainer.querySelectorAll('.d2h-code-linenumber').forEach((el) => {
504
- el.addEventListener('click', (e) => {
505
- e.stopPropagation()
506
- const row = el.closest('tr')
507
- if (!row || row.classList.contains('d2h-info')) return
508
-
509
- const fileWrapper = el.closest('.d2h-file-wrapper')
510
- const file = fileWrapper?.querySelector('.d2h-file-name')?.textContent?.trim() ?? ''
511
- const lineInfo = parseLineInfo(el)
512
- if (!lineInfo) return
513
-
514
- 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)
515
859
  })
860
+ el.addEventListener('click', (e) => e.stopPropagation())
516
861
  })
517
862
  }
518
863
 
@@ -544,155 +889,461 @@
544
889
 
545
890
  // --- Comment threads ---
546
891
 
547
- function confirmInlineComment(threadId, file, line, side, text) {
548
- threads[threadId] = { file, line, side, messages: [{ from: 'user', text }], el: null }
549
- 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)
550
924
  }
551
925
 
552
- function confirmGeneralComment(threadId, text) {
553
- threads[threadId] = { file: null, line: null, side: null, messages: [{ from: 'user', text }], el: null }
554
- 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()
555
937
  }
556
938
 
557
- 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() }
558
942
  const thread = threads[threadId]
559
- if (thread) {
560
- thread.messages = thread.messages.filter(m => !m.ephemeral)
561
- thread.messages.push({ from: 'assistant', text, ephemeral })
562
- if (thread.file) {
563
- renderThreadEl(thread)
564
- } else {
565
- addChatMessage(agentName, text, ephemeral)
566
- }
567
- } else {
568
- 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
569
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)
570
953
  }
571
954
 
572
- function injectThread(threadId) {
573
- const thread = threads[threadId]
574
- if (!thread || !thread.file) return
575
-
576
- // Find the anchor point: a specific line, or the top of the file's diff
577
- let anchor = null
578
- let insertBefore = false
579
- if (thread.line) {
580
- anchor = findDiffRow(thread.file, thread.line, thread.side)
581
- } else {
582
- // File-level comment: insert before the first row in the file's tbody
583
- const wrappers = diffContainer.querySelectorAll('.d2h-file-wrapper')
584
- for (const wrapper of wrappers) {
585
- const nameEl = wrapper.querySelector('.d2h-file-name')
586
- if (nameEl?.textContent?.trim() !== thread.file) continue
587
- anchor = wrapper.querySelector('.d2h-diff-tbody tr')
588
- insertBefore = true
589
- break
590
- }
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)
591
960
  }
592
- if (!anchor) return
961
+ if (thread.where === 'line' || thread.where === 'file') return
962
+ openPanel()
963
+ panelCards.get(thread.id)?.scrollIntoView({ block: 'nearest' })
964
+ }
593
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
+ }
594
993
  if (!thread.el) {
595
- thread.el = document.createElement('tr')
596
- thread.el.className = 'comment-thread-row'
597
- thread.el.dataset.threadId = threadId
598
- const cell = document.createElement('td')
599
- cell.colSpan = 3
600
- 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
601
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
+ }
602
1007
 
603
- renderThreadEl(thread)
604
-
605
- const existing = diffContainer.querySelector(`[data-thread-id="${threadId}"]`)
606
- if (existing) existing.remove()
607
- if (insertBefore) {
608
- anchor.parentNode.insertBefore(thread.el, anchor)
609
- } else {
610
- anchor.parentNode.insertBefore(thread.el, anchor.nextSibling)
611
- }
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
612
1022
  }
613
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.
614
1036
  function renderMarkdown(text) {
615
- // eslint-disable-next-line no-undef
616
- 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
617
1053
  }
618
1054
 
619
- function renderMarkdownInline(text) {
620
- // eslint-disable-next-line no-undef
621
- 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()
622
1061
  }
623
1062
 
624
- function renderMessageContent(m) {
625
- const content = renderMarkdown(m.text)
626
- const ephClass = m.ephemeral ? ' comment-ephemeral' : ''
627
- return `<div class="comment-message comment-${m.from}${ephClass}">` +
628
- `<strong>${m.from === 'user' ? 'you' : escapeHtml(agentName)}</strong>` +
629
- `<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)
630
1069
  }
631
1070
 
632
- function renderThreadEl(thread) {
633
- if (!thread.el) return
634
- const cell = thread.el.querySelector('td')
635
- 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
+ }
636
1074
 
637
- // Preserve in-progress reply text
638
- const prevInput = cell.querySelector('.thread-reply-input')
639
- 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
+ }
640
1081
 
641
- cell.innerHTML = '<div class="comment-thread">' +
642
- '<button class="comment-dismiss" title="Dismiss">&times;</button>' +
643
- thread.messages.map(renderMessageContent).join('') +
644
- '<div class="thread-reply-box">' +
645
- '<textarea rows="2" class="mg-textarea thread-reply-input" placeholder="Reply..."></textarea>' +
646
- '<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>` : '') +
647
1109
  '</div>' +
648
- '</div>'
649
- cell.querySelector('.comment-dismiss').addEventListener('click', () => {
650
- thread.dismissed = true
651
- thread.el.remove()
652
- 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)
653
1130
  })
654
- const input = cell.querySelector('.thread-reply-input')
655
- input.value = savedText
656
- if (savedText) input.focus()
657
- const sendBtn = cell.querySelector('.thread-reply-send')
658
- 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 = () => {
659
1180
  const text = input.value.trim()
660
1181
  if (!text) return
661
- input.value = ''
662
- send({ type: 'thread_reply', thread_id: threadId, text })
663
- thread.messages.push({ from: 'user', text })
664
- renderThreadEl(thread)
1182
+ send({ type: 'thread_reply', thread_id: thread.id, text })
1183
+ close()
665
1184
  }
666
- sendBtn.addEventListener('click', sendReply)
1185
+ replyEl.querySelector('[data-action="reply"]').addEventListener('click', sendReply)
1186
+ replyEl.querySelector('[data-action="cancel"]').addEventListener('click', close)
667
1187
  input.addEventListener('keydown', (e) => {
668
1188
  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); sendReply() }
1189
+ if (e.key === 'Escape' && !input.value.trim()) close()
669
1190
  })
1191
+ return card
670
1192
  }
671
1193
 
672
- function reinjectThreads() {
673
- for (const threadId of Object.keys(threads)) {
674
- const thread = threads[threadId]
675
- if (thread.file && !thread.dismissed) injectThread(threadId)
676
- }
677
- }
678
-
679
- function findDiffRow(file, line, side) {
680
- const fileWrappers = diffContainer.querySelectorAll('.d2h-file-wrapper')
681
- for (const wrapper of fileWrappers) {
682
- const nameEl = wrapper.querySelector('.d2h-file-name')
683
- if (!nameEl || nameEl.textContent.trim() !== file) continue
684
- const rows = wrapper.querySelectorAll('tr')
685
- for (const row of rows) {
686
- const lineNumEl = row.querySelector('.d2h-code-linenumber')
687
- if (!lineNumEl) continue
688
- const info = parseLineInfo(lineNumEl)
689
- if (!info) continue
690
- if (info.line === line && info.side === side) return row
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)
691
1204
  }
692
1205
  }
693
- return null
694
1206
  }
695
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)
1215
+ }
1216
+
1217
+ function reinjectThreads() {
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)
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()
1234
+ }
1235
+
1236
+ function fileTopRow(file) {
1237
+ return diffIndex.get(file)?.wrapper.querySelector('.d2h-diff-tbody tr') ?? null
1238
+ }
1239
+
1240
+ // Find a line target in the current diff and refresh its anchor there.
1241
+ // Returns the row, or null when the line changed or left the diff.
1242
+ function placeTarget(file, target) {
1243
+ const lines = diffIndex.get(file)?.[target.side]
1244
+ if (!lines) return null
1245
+ const found = locateAnchor(target.anchor, lines.texts)
1246
+ if (!found) return null
1247
+ target.anchor = createAnchor(lines.texts, found.line)
1248
+ return lines.rows.get(found.line)
1249
+ }
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
+
696
1347
  // --- Permission relay ---
697
1348
 
698
1349
  function showPermission(msg) {
@@ -721,14 +1372,7 @@
721
1372
  pendingPermission = null
722
1373
  })
723
1374
 
724
- // --- Chat footer ---
725
-
726
- chatToggle.addEventListener('click', (e) => {
727
- if (e.target === generalInput || e.target === generalSend) return
728
- chatExpanded = !chatExpanded
729
- chatHistory.classList.toggle('hidden', !chatExpanded)
730
- chatIndicator.textContent = chatExpanded ? '-' : '+'
731
- })
1375
+ // --- General comments ---
732
1376
 
733
1377
  function sendGeneral() {
734
1378
  const text = generalInput.value.trim()
@@ -745,28 +1389,6 @@
745
1389
  }
746
1390
  })
747
1391
 
748
- const MAX_CHAT_MESSAGES = 50
749
-
750
- function addChatMessage(from, text, ephemeral) {
751
- if (!ephemeral) {
752
- chatHistory.querySelectorAll('.chat-ephemeral').forEach(el => el.remove())
753
- }
754
- const div = document.createElement('div')
755
- div.className = 'chat-message chat-' + (from === 'you' ? 'you' : 'assistant') + (ephemeral ? ' chat-ephemeral' : '')
756
- const content = renderMarkdown(text)
757
- div.innerHTML = `<strong>${escapeHtml(from)}</strong><div class="mg-md">${content}</div>`
758
- chatHistory.appendChild(div)
759
- while (chatHistory.children.length > MAX_CHAT_MESSAGES) {
760
- chatHistory.removeChild(chatHistory.firstChild)
761
- }
762
- chatHistory.scrollTop = chatHistory.scrollHeight
763
- if (!chatExpanded) {
764
- chatExpanded = true
765
- chatHistory.classList.remove('hidden')
766
- chatIndicator.textContent = '-'
767
- }
768
- }
769
-
770
1392
  // --- Util ---
771
1393
 
772
1394
  function escapeHtml(str) {