tensaku 0.1.0 → 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.
data/lib/tensaku/notes.rb CHANGED
@@ -1,340 +1,334 @@
1
1
  require "json"
2
2
  require "time"
3
- require "fileutils"
3
+ require "securerandom"
4
4
 
5
5
  module Tensaku
6
- # Notes are one JSON file each in tmp/tensaku/notes: local and ignored by git.
6
+ # The notes left on the pages of the app at Tensaku.root, in the database in Tensaku.home (see Store
7
+ # and Project). The dev server and `tensaku mcp` (a separate process without Rails) both read and
8
+ # write them. Markdown renders them for agents.
7
9
  #
8
- # Timestamps carry microseconds, so watch_notes can tell apart notes saved within one second. Every
9
- # change goes through FileWrite.locked, so the overlay and an agent changing the same note at once
10
- # don't lose either change.
10
+ # A note is open until an agent (or you) resolves it, an agent declines it, or an agent asks something
11
+ # back and sets it to `question`. An agent sets `working` when it picks a note up. What the agent and
12
+ # you say to each other is the note's thread. Closed notes move to the archive after
13
+ # Tensaku.config.archive_after, or when you archive them from the page.
11
14
  #
12
- # A note is open until an agent (or you) resolves it with a reply, or sets it to `question` with a
13
- # reply asking for more detail. An agent sets `working` when it picks a note up. Resolved notes are
14
- # deleted after Tensaku.config.prune_after.
15
+ # `sent_at` says when the note was last sent to an agent: when you saved it, or last edited, answered
16
+ # or reopened it.
15
17
  module Notes
16
- STATUSES = %w[open working question resolved].freeze
18
+ autoload :Markdown, "tensaku/notes/markdown"
19
+ autoload :Target, "tensaku/notes/target"
20
+
21
+ STATUSES = %w[open working question resolved declined].freeze
17
22
  # The statuses that still need something from an agent or from you.
18
23
  ACTIVE = %w[open working question].freeze
19
- # An agent counts as connected for this long after its last MCP call.
20
- AGENT_WINDOW = 20
24
+ SCREENSHOT_LIMIT = 4_000_000
21
25
  ID = /\A[a-z0-9]{4,12}\z/
22
- TARGET_KINDS = %w[element text translation markdown].freeze
23
26
  AUTHORS = %w[you agent].freeze
24
- SESSION = /\A[a-f0-9]{32}\z/
25
27
 
26
28
  class NotFound < Error; end
27
29
 
28
- module_function
30
+ # The note belongs to another agent session that is still running.
31
+ class Taken < Error; end
29
32
 
30
- def dir
31
- Tensaku.root.join(Tensaku.config.notes_path)
32
- end
33
+ module_function
33
34
 
34
- def all
35
- return [] unless dir.directory?
35
+ # The notes not in the archive.
36
+ def all = list
36
37
 
37
- dir.glob("*.json").filter_map { read_note(it) }.sort_by { it["created_at"] }
38
+ # url and status narrow the list; status "archived" lists the archive. session leaves out the notes
39
+ # another running agent session owns.
40
+ def list(url: nil, status: nil, session: nil)
41
+ statuses = Array(status).map(&:to_s)
42
+ archived = statuses.delete("archived")
43
+ where = [ "project = ?", "archived_at IS #{"NOT " if archived}NULL" ]
44
+ params = []
45
+ if url
46
+ where << "url = ?"
47
+ params << text(url)
48
+ end
49
+ if statuses.any? && !archived
50
+ where << "status IN (#{(%w[?] * statuses.size).join(", ")})"
51
+ params.concat(statuses)
52
+ end
53
+ notes = Project.read { |db, app| load_notes(db, "#{where.join(" AND ")} ORDER BY created_at", [ app, *params ]) }
54
+ session ? notes.select { available_to?(it, session) } : notes
38
55
  end
39
56
 
40
- def list(url: nil, status: nil)
41
- statuses = Array(status).map(&:to_s)
42
- all.select do |note|
43
- (url.nil? || note["url"] == url) && (statuses.empty? || statuses.include?(note["status"]))
57
+ # How many notes need something from an agent or from you.
58
+ def active_count
59
+ Project.read do |db, app|
60
+ db.get_first_value("SELECT COUNT(*) FROM notes WHERE project = ? AND archived_at IS NULL AND status IN (#{ACTIVE.map { "'#{it}'" }.join(", ")})", [ app ])
44
61
  end
45
62
  end
46
63
 
47
64
  def find(id)
48
- raise NotFound, "No note #{id.inspect}" unless id.to_s.match?(ID)
65
+ id = text(id)
66
+ raise NotFound, "No note #{id.inspect}" unless id.match?(ID)
67
+
68
+ Project.read { |db, app| load_notes(db, "project = ? AND id = ?", [ app, id ]).first } or raise NotFound, "No note #{id.inspect}"
69
+ end
70
+
71
+ # The note with id in one of several apps (root directories): [app, note].
72
+ def locate(apps, id)
73
+ apps.each do |app|
74
+ return [ app, Tensaku.with_root(app) { find(id) } ]
75
+ rescue NotFound
76
+ next
77
+ end
78
+ raise NotFound, "No note #{text(id).inspect}"
79
+ end
49
80
 
50
- read_note(dir.join("#{id}.json")) or raise NotFound, "No note #{id.inspect}"
81
+ # A string as SQLite should compare it. A binary string (a note id from a request path) would be
82
+ # bound as a blob and never equal the text in the table.
83
+ def text(value)
84
+ value.to_s.dup.force_encoding(Encoding::UTF_8)
51
85
  end
52
86
 
53
- # attributes come from the overlay: url, comment, targets, and for area notes rect and viewport.
87
+ # attributes come from the overlay: url, comment, targets, for area notes rect and viewport, and
88
+ # `to`, the handle of the agent session the note is for (see Agents.owner).
54
89
  def create(attributes)
55
90
  attributes = attributes.to_h.stringify_keys
56
91
  comment = attributes["comment"].to_s.strip
57
92
  raise Error, "A note needs a comment" if comment.empty?
58
93
 
59
- now = timestamp
60
94
  note = {
61
- "id" => new_id,
62
95
  "url" => attributes["url"].to_s,
63
96
  "comment" => comment,
64
- "targets" => Array(attributes["targets"]).map { target(it) },
65
- "rect" => rect(attributes["rect"]),
97
+ "targets" => Array(attributes["targets"]).map { Target.from(it) },
98
+ "rect" => Target.rect(attributes["rect"]),
66
99
  "viewport" => attributes["viewport"]&.to_s,
67
100
  "status" => "open",
68
- "created_at" => now,
69
- "updated_at" => now
70
- }.compact_blank.merge("reply" => nil, "thread" => [])
71
- FileWrite.locked { write(note) }
101
+ "commit" => Repo.head(Tensaku.root)
102
+ }
103
+ # The id and the time are taken in the write transaction, so sent_between never scans past a note
104
+ # that is about to be written with an earlier sent_at.
105
+ Project.write do |db, app|
106
+ now = Project.timestamp
107
+ note = note.merge("id" => new_id(db), "sent_at" => now, "created_at" => now, "updated_at" => now).compact_blank.merge("thread" => [])
108
+ save(db, app, note.merge(Agents.owner(db, app, attributes["to"])))
109
+ end
72
110
  end
73
111
 
74
- # message adds to the note's thread, from "you" or "agent". An agent's message is also the note's
75
- # reply, the line shown next to the pin. targets moves the note to other elements.
76
- def update(id, status: nil, reply: nil, comment: nil, message: nil, from: "agent", agent: nil, targets: nil)
77
- FileWrite.locked { apply(find(id), status:, reply:, comment:, message:, from:, agent:, targets:) }
112
+ # message adds to the note's thread, from "you" or "agent". send sends the note to an agent again.
113
+ # session is the agent session making the change; another running session's note is refused.
114
+ #
115
+ # to (from the page) gives an open note to the agent session with that handle, or to whichever
116
+ # agent takes it first when blank, and sends it again.
117
+ #
118
+ # started: true refuses a note nobody started, for resolve_note: an agent has to call start_note
119
+ # before changing anything, so two sessions can't work on one note unseen.
120
+ def update(id, status: nil, comment: nil, message: nil, from: "agent", agent: nil, session: nil, send: false, to: nil, started: false)
121
+ Project.write do |db, app|
122
+ note = find(id)
123
+ check_owner!(note, session) if session
124
+ raise Error, "Note #{note["id"]} isn't started. Call start_note before you change anything for a note, then resolve it." if started && note["status"] != "working"
125
+ # Assigning: to a session's handle, or blank for anyone. A note in progress can be taken back
126
+ # from its session this way, for an agent stopped mid-work whose process still runs: it is open
127
+ # again, and the old session's start_note and resolve_note are refused.
128
+ unless to.nil?
129
+ raise Error, "Only an open or in-progress note can be assigned" unless %w[open working].include?((status || note["status"]).to_s)
130
+
131
+ note = note.merge("session" => nil, "agent" => nil, "delivered_at" => nil, "delivered_to" => nil).merge(Agents.owner(db, app, to))
132
+ status = "open"
133
+ send = true
134
+ end
135
+ apply(db, app, note, status:, comment:, message:, from:, agent:, send:)
136
+ end
78
137
  end
79
138
 
80
- def apply(note, status:, reply:, comment:, message:, from:, agent:, targets:)
81
- if status
82
- raise Error, "Status must be one of #{STATUSES.join(", ")}" unless STATUSES.include?(status.to_s)
83
-
84
- note["status"] = status.to_s
85
- end
86
- note["reply"] = reply.to_s.strip.presence unless reply.nil?
87
- note["comment"] = comment.to_s.strip unless comment.to_s.strip.empty?
88
- if message.present?
89
- raise Error, "A message is from one of #{AUTHORS.join(", ")}" unless AUTHORS.include?(from.to_s)
139
+ # A PNG of what the note points at, taken by the page when the note was written. The page sends it
140
+ # as a data URL; screenshots larger than SCREENSHOT_LIMIT are refused.
141
+ def attach_screenshot(id, data_url)
142
+ match = data_url.to_s.match(%r{\Adata:image/png;base64,([A-Za-z0-9+/=]+)\z})
143
+ raise Error, "A screenshot is a PNG data URL" unless match
90
144
 
91
- entry = { "from" => from.to_s, "text" => message.to_s.strip, "agent" => agent.presence, "at" => timestamp }.compact
92
- note["thread"] = Array(note["thread"]) << entry
93
- note["reply"] = entry["text"] if from.to_s == "agent"
94
- end
95
- note["agent"] = agent if agent.present? && status.to_s == "working"
96
- if targets
97
- note["targets"] = Array(targets).map { target(it) }
98
- note.delete("rect")
99
- note.delete("viewport")
100
- end
101
- note["updated_at"] = timestamp
102
- write(note)
103
- end
145
+ png = match[1].unpack1("m0")
146
+ raise Error, "The screenshot is larger than #{SCREENSHOT_LIMIT / 1_000_000} MB" if png.bytesize > SCREENSHOT_LIMIT
147
+ raise Error, "The screenshot isn't a PNG" unless png.start_with?("\x89PNG\r\n\x1A\n".b) && png.bytesize > 24
104
148
 
105
- def delete(id)
106
- FileWrite.locked do
149
+ width, height = png.byteslice(16, 8).unpack("NN")
150
+ Project.write do |db, app|
107
151
  find(id)
108
- dir.join("#{id}.json").delete
152
+ db.execute("INSERT OR REPLACE INTO screenshots (note_id, png, width, height) VALUES (?, ?, ?, ?)", [ text(id), SQLite3::Blob.new(png), width, height ])
153
+ Project.changed!(db, app, "note", text(id))
109
154
  end
155
+ { "width" => width, "height" => height }
110
156
  end
111
157
 
112
- def prune!(now: Time.now)
113
- cutoff = now - Tensaku.config.prune_after
114
- all.each do |note|
115
- next unless note["status"] == "resolved" && Time.iso8601(note["updated_at"]) < cutoff
116
-
117
- dir.join("#{note["id"]}.json").delete if dir.join("#{note["id"]}.json").file?
158
+ # The note's screenshot: png (binary), width and height, or nil.
159
+ def screenshot(id)
160
+ find(id)
161
+ Project.read do |db|
162
+ row = db.get_first_row("SELECT png, width, height FROM screenshots WHERE note_id = ?", [ text(id) ])
163
+ row && { "png" => row["png"].to_s.b, "width" => row["width"], "height" => row["height"] }
118
164
  end
119
- agents_dir.glob("*.json").each { it.delete if now - it.mtime > 86_400 } if agents_dir.directory?
120
165
  end
121
166
 
122
- # Blocks until a note is created or changed after `since`, or the timeout passes. Returns the open
123
- # notes that are new or changed, and the time just before the last scan: pass it as the next
124
- # `since` and a note saved during the scan is still seen. Polls the directory, which is plenty for
125
- # one person and an agent.
126
- def watch(since:, timeout: 60, interval: 0.5)
127
- deadline = monotonic + timeout
128
- touched = monotonic
129
- loop do
130
- if monotonic - touched >= 5
131
- agent_seen!
132
- touched = monotonic
133
- end
134
- checked_at = Time.now.utc
135
- fresh = all.select { it["status"] == "open" && Time.iso8601(it["updated_at"]) > since }
136
- return [ fresh, checked_at ] if fresh.any? || monotonic >= deadline
137
-
138
- sleep interval
167
+ # Marks the note as being worked on by session, which then owns it. Refused, in any status, when
168
+ # another session that is still running owns it; a note whose session quit can be taken.
169
+ def start(id, agent: nil, session: nil)
170
+ Project.write do |db, app|
171
+ note = find(id)
172
+ check_owner!(note, session)
173
+ note["session"] = session if session
174
+ apply(db, app, note, status: "working", agent:)
139
175
  end
140
176
  end
141
177
 
142
- # What the overlay last selected, for the MCP `current_selection` tool. A file, so every server
143
- # process sees the same selection.
144
- def selection
145
- read(dir.join(".selection.json"))
146
- end
147
-
148
- def selection=(value)
149
- write_json(dir.join(".selection.json"), value)
150
- end
151
-
152
- # Every MCP call touches a file next to the notes, so the overlay can show that an agent is
153
- # connected, whichever server process it talks to.
154
- # An MCP client that keeps the session id from initialize gets a file of its own with its name, so
155
- # the page can say which agent is connected. Other clients share one nameless file.
156
- def agent_seen!(session = nil)
157
- return touch(dir.join(".agent")) unless session.to_s.match?(SESSION)
158
-
159
- path = agents_dir.join("#{session}.json")
160
- path.file? ? FileUtils.touch(path) : write_agent(path, nil)
161
- end
162
-
163
- def register_agent(session, name)
164
- write_agent(agents_dir.join("#{session}.json"), name.to_s.truncate(80).presence)
165
- end
166
-
167
- def agent_name(session)
168
- return nil unless session.to_s.match?(SESSION)
169
-
170
- read(agents_dir.join("#{session}.json"))&.dig("name")
178
+ # A note belongs to the agent session that was handed it (claim_sent) or started it. Other sessions
179
+ # leave it alone while that session runs, so two listeners never change the same thing, and a
180
+ # request for changes goes back to the session that made them.
181
+ def available_to?(note, session)
182
+ owner = note["session"]
183
+ owner.nil? || session.nil? || owner == session || !Agents.connected?(owner)
171
184
  end
172
185
 
173
- def agent
174
- files = [ dir.join(".agent"), *(agents_dir.directory? ? agents_dir.glob("*.json") : []) ].select(&:file?)
175
- return { "connected" => false, "seen_at" => nil, "names" => [] } if files.empty?
186
+ def check_owner!(note, session)
187
+ return if available_to?(note, session)
176
188
 
177
- recent = files.select { Time.now - it.mtime < AGENT_WINDOW }
178
- names = recent.filter_map { read(it)&.dig("name") if it.extname == ".json" }.uniq
179
- { "connected" => recent.any?, "seen_at" => files.map(&:mtime).max.utc.iso8601, "names" => names }
189
+ raise Taken, "Note #{note["id"]} belongs to #{note["agent"] || "another agent session"}, which is still running. Leave it, and take the next one."
180
190
  end
181
191
 
182
- def agents_dir
183
- dir.join(".agents")
184
- end
185
-
186
- def touch(path)
187
- path.dirname.mkpath
188
- FileUtils.touch(path)
189
- end
190
-
191
- def write_agent(path, name)
192
- path.dirname.mkpath
193
- path.write(JSON.generate({ "name" => name }.compact) + "\n")
194
- end
195
-
196
- # One line per note, for a chat where the detailed form is too long.
197
- def to_short_markdown(notes)
198
- notes = Array(notes)
199
- return "No notes." if notes.empty?
200
-
201
- notes.map do |note|
202
- where = Array(note["targets"]).filter_map { [ it["file"], it["range"]&.split("-")&.first ].compact.join(":").presence }.uniq.first(3)
203
- "- `#{note["id"]}` (#{note["status"]}) #{note["comment"].squish.truncate(160)}#{" at #{where.map { "`#{it}`" }.join(", ")}" if where.any?}"
204
- end.join("\n")
205
- end
206
-
207
- def to_markdown(notes)
208
- notes = Array(notes)
209
- return "No notes." if notes.empty?
210
-
211
- notes.map { note_markdown(it) }.join("\n\n")
212
- end
192
+ def apply(db, app, note, status: nil, comment: nil, message: nil, from: "agent", agent: nil, send: false)
193
+ if status
194
+ raise Error, "Status must be one of #{STATUSES.join(", ")}" unless STATUSES.include?(status.to_s)
213
195
 
214
- def note_markdown(note)
215
- lines = [ "## Tensaku note #{note["id"]} (#{note["status"]}) on #{note["url"]}", "", note["comment"] ]
216
- targets = Array(note["targets"])
217
- if targets.any?
218
- lines << ""
219
- targets.each { lines << "- #{target_markdown(it)}" }
220
- end
221
- if (rect = note["rect"])
222
- lines << "" << "Area: #{rect["width"]}x#{rect["height"]} at (#{rect["x"]}, #{rect["y"]}) in a #{note["viewport"] || "unknown"} viewport"
196
+ note["status"] = status.to_s
223
197
  end
224
- thread = Array(note["thread"])
225
- if thread.any?
226
- lines << ""
227
- thread.each { lines << "> **#{it["from"] == "you" ? "You" : (it["agent"] || "Agent")}:** #{it["text"].to_s.gsub("\n", "\n> ")}" }
228
- elsif note["reply"]
229
- lines << "" << "Reply: #{note["reply"]}"
198
+ note["comment"] = comment.to_s.strip unless comment.to_s.strip.empty?
199
+ if message.present?
200
+ raise Error, "A message is from one of #{AUTHORS.join(", ")}" unless AUTHORS.include?(from.to_s)
201
+
202
+ entry = { "from" => from.to_s, "text" => message.to_s.strip, "agent" => agent.presence, "at" => Project.timestamp }.compact
203
+ note["thread"] = Array(note["thread"]) << entry
230
204
  end
231
- lines.join("\n")
205
+ note["agent"] = agent if status.to_s == "working" && agent.present?
206
+ note["updated_at"] = Project.timestamp
207
+ note["sent_at"] = note["updated_at"] if send
208
+ # A note you reopen comes back from the archive.
209
+ note.delete("archived_at") if ACTIVE.include?(note["status"])
210
+ save(db, app, note)
232
211
  end
233
212
 
234
- def target_markdown(target)
235
- location = [ target["file"], target["range"] ].compact.join(":")
236
- parts = [ target["kind"] ]
237
- parts << "`#{target["tag"]}`" if target["tag"]
238
- parts << "`#{target["key"]}` (#{target["locale"]})" if target["key"]
239
- parts << "at `#{location}`" unless location.empty?
240
- parts << "\"#{target["text"].to_s.squish.truncate(120)}\"" if target["text"].present?
241
- context = target["context"].to_h.compact_blank
242
- parts << "(#{context.map { |key, value| "#{key}: #{Array(value).join(" < ")}" }.join(", ")})" if context.any?
243
- parts.join(" ")
213
+ def delete(id)
214
+ Project.write do |db, app|
215
+ find(id)
216
+ db.execute("DELETE FROM notes WHERE project = ? AND id = ?", [ app, text(id) ])
217
+ Project.changed!(db, app, "note", text(id))
218
+ end
244
219
  end
245
220
 
246
- # Fills in file positions from what the overlay saw: a Herb stamp, a translation key or a Markdown
247
- # range. A target whose source can't be read keeps what the page said about it.
248
- def target(raw)
249
- raise Error, "A note target must be a JSON object" unless raw.is_a?(Hash)
250
-
251
- raw = raw.stringify_keys
252
- kind = TARGET_KINDS.include?(raw["kind"]) ? raw["kind"] : "element"
253
- target = { "kind" => kind, "text" => raw["text"]&.to_s&.truncate(500), "tag" => raw["tag"]&.to_s }
254
-
255
- if raw["stamp"].present?
256
- target["stamp"] = raw["stamp"].to_s
257
- path, line, column = Source::Template.parse_stamp(raw["stamp"])
258
- target["file"] = path
259
- target["range"] = "#{line}:#{column}"
260
- begin
261
- target.merge!(Source::Template.new(path).element_range(line, column).stringify_keys)
262
- rescue Error
263
- nil
221
+ # Moves closed notes to the archive. They stay listable (status "archived") and come back when
222
+ # reopened.
223
+ def archive!(ids)
224
+ Project.write do |db, app|
225
+ now = Project.timestamp
226
+ ids = Array(ids).map { text(it) }.grep(ID)
227
+ archived = ids.select do |id|
228
+ db.execute("UPDATE notes SET archived_at = ? WHERE project = ? AND id = ? AND archived_at IS NULL AND status IN ('resolved', 'declined')", [ now, app, id ])
229
+ db.changes.positive?
264
230
  end
231
+ archived.each { Project.changed!(db, app, "note", it) }
232
+ archived
265
233
  end
234
+ end
266
235
 
267
- if kind == "translation"
268
- target["key"] = raw["key"].to_s
269
- target["locale"] = raw["locale"].to_s
270
- if (entry = Source::Locale.find(target["locale"], target["key"]))
271
- target["file"] = entry[:file]
272
- target["range"] = entry[:line].to_s
273
- end
236
+ # Archives closed notes older than archive_after, and lets the database forget old rows (Store.prune!).
237
+ def prune!(now: Time.now)
238
+ cutoff = (now - Tensaku.config.archive_after).utc.iso8601(6)
239
+ old = Project.read { |db, app| db.execute("SELECT id FROM notes WHERE project = ? AND archived_at IS NULL AND status IN ('resolved', 'declined') AND updated_at < ?", [ app, cutoff ]).map { it["id"] } }
240
+ archive!(old) if old.any?
241
+ Store.prune!(now:)
242
+ end
243
+
244
+ # The open notes sent after since and up to upto that session may take. The scan runs in a write
245
+ # transaction, and notes get their sent_at in one, so a caller that took upto before calling and
246
+ # passes it as the next since sees every note exactly once.
247
+ def sent_between(since, upto, session: nil)
248
+ Project.write do
249
+ list(status: "open", session:).select { it["sent_at"] && it["sent_at"] > Project.timestamp(since) && it["sent_at"] <= Project.timestamp(upto) }
274
250
  end
251
+ end
275
252
 
276
- if kind == "markdown" && raw["md"].present?
277
- target["md"] = raw["md"].to_s
278
- target["file"], target["range"] = raw["md"].to_s.split(/:(?=\d+:\d+-)/, 2)
253
+ # sent_between, and the notes found become session's in the same transaction: delivered_at and
254
+ # delivered_to say they arrived. Two sessions scanning at once can't both get a note. updated_at and
255
+ # sent_at stay: delivery isn't a change the person or the agent made.
256
+ #
257
+ # A session busy with a note leaves new ones to a listening session that has nothing to do, except
258
+ # the notes the person sent to it.
259
+ def claim_sent(since, upto, session:, agent:)
260
+ Project.write do |db, app|
261
+ own_only = Agents.busy?(db, app, session) && Agents.idle_listener?(db, app, except: session)
262
+
263
+ now = Project.timestamp
264
+ sent_between(since, upto, session:).filter_map do |note|
265
+ next if own_only && note["session"] != session
266
+ # Already handed to this session since it was last sent: by a watch running in the
267
+ # background, or with the answer of another call.
268
+ next if note["session"] == session && note["delivered_at"].to_s >= note["sent_at"].to_s
269
+
270
+ save(db, app, note.merge("session" => session, "agent" => note["session"] == session ? note["agent"] || agent : agent, "delivered_at" => now, "delivered_to" => agent))
271
+ end
279
272
  end
280
-
281
- target["context"] = raw["context"].to_h.slice("partials", "controller", "frame").transform_values { Array(it).map(&:to_s).first(10) }.compact_blank
282
- target.compact_blank
283
273
  end
284
274
 
285
- def rect(raw)
286
- return nil unless raw.is_a?(Hash)
287
-
288
- raw.to_h.stringify_keys.slice("x", "y", "width", "height").transform_values { it.to_f.round }
275
+ # When an agent last said something on a note in this app (a resolve, a question, a reply), which
276
+ # follows its changes to files. The page refreshes itself when this changes.
277
+ def last_agent_message_at
278
+ Project.read do |db, app|
279
+ db.get_first_value(<<~SQL, [ app ])
280
+ SELECT MAX(messages.at) FROM messages JOIN notes ON notes.id = messages.note_id
281
+ WHERE notes.project = ? AND messages.author = 'agent'
282
+ SQL
283
+ end
289
284
  end
290
285
 
291
- def new_id
286
+ def new_id(db)
292
287
  loop do
293
288
  id = SecureRandom.alphanumeric(4).downcase
294
- return id unless dir.join("#{id}.json").exist?
289
+ return id unless db.get_first_value("SELECT 1 FROM notes WHERE id = ?", [ id ])
295
290
  end
296
291
  end
297
292
 
298
- def read(path)
299
- JSON.parse(File.read(path))
300
- rescue Errno::ENOENT, JSON::ParserError
301
- nil
302
- end
303
-
304
- # A note file as written by Tensaku. Agents may edit note files by hand, so a file that isn't a
305
- # JSON object with an id and valid timestamps is skipped instead of breaking every list.
306
- def read_note(path)
307
- note = read(path)
308
- return nil unless note.is_a?(Hash) && note["id"].to_s.match?(ID)
293
+ COLUMNS = %w[id url comment status targets rect viewport commit session agent sent_at delivered_at delivered_to archived_at created_at updated_at].freeze
309
294
 
310
- Time.iso8601(note["created_at"].to_s)
311
- Time.iso8601(note["updated_at"].to_s)
312
- note
313
- rescue ArgumentError
314
- nil
315
- end
316
-
317
- def write(note)
318
- write_json(dir.join("#{note["id"]}.json"), note)
295
+ # Writes the whole note, thread included, and logs the change. Returns the note.
296
+ def save(db, app, note)
297
+ values = COLUMNS.map do |column|
298
+ value = note[column]
299
+ %w[targets rect].include?(column) ? (value.nil? ? (column == "targets" ? "[]" : nil) : JSON.generate(value)) : value
300
+ end
301
+ quoted = COLUMNS.map { %("#{it}") }
302
+ db.execute(<<~SQL, [ app, *values ])
303
+ INSERT INTO notes (project, #{quoted.join(", ")}) VALUES (?, #{("?, " * COLUMNS.size).chomp(", ")})
304
+ ON CONFLICT (id) DO UPDATE SET #{quoted.drop(1).map { "#{it} = excluded.#{it}" }.join(", ")}
305
+ SQL
306
+ db.execute("DELETE FROM messages WHERE note_id = ?", [ note["id"] ])
307
+ Array(note["thread"]).each do |entry|
308
+ db.execute("INSERT INTO messages (note_id, author, agent, text, at) VALUES (?, ?, ?, ?, ?)", [ note["id"], entry["from"], entry["agent"], entry["text"], entry["at"] ])
309
+ end
310
+ Project.changed!(db, app, "note", note["id"])
319
311
  note
320
312
  end
321
313
 
322
- # Through a temp file with a name of its own, so two writers never share one.
323
- def write_json(path, data)
324
- path.dirname.mkpath
325
- temp = path.dirname.join(".#{path.basename}.#{SecureRandom.hex(4)}.tmp")
326
- temp.write(JSON.pretty_generate(data) + "\n")
327
- File.rename(temp, path)
328
- ensure
329
- temp.delete if temp&.exist?
330
- end
331
-
332
- def timestamp
333
- Time.now.utc.iso8601(6)
334
- end
335
-
336
- def monotonic
337
- Process.clock_gettime(Process::CLOCK_MONOTONIC)
314
+ def load_notes(db, where, params)
315
+ rows = db.execute("SELECT * FROM notes WHERE #{where}", params)
316
+ return [] if rows.empty?
317
+
318
+ ids = rows.map { it["id"] }
319
+ marks = ("?, " * ids.size).chomp(", ")
320
+ threads = db.execute("SELECT * FROM messages WHERE note_id IN (#{marks}) ORDER BY id", ids).group_by { it["note_id"] }
321
+ shots = db.execute("SELECT note_id, width, height FROM screenshots WHERE note_id IN (#{marks})", ids).to_h { [ it["note_id"], it.slice("width", "height") ] }
322
+ # A note in progress whose session's process ended: anyone can take it (available_to?).
323
+ gone = rows.select { it["status"] == "working" && it["session"] }.map { it["session"] }.uniq.reject { Presence.alive?(it) }
324
+ rows.map do |row|
325
+ note = COLUMNS.to_h { [ it, row[it] ] }
326
+ note["stopped"] = true if note["status"] == "working" && gone.include?(note["session"])
327
+ note["targets"] = JSON.parse(note["targets"] || "[]")
328
+ note["rect"] = note["rect"] && JSON.parse(note["rect"])
329
+ note["screenshot"] = shots[row["id"]]
330
+ note.compact.merge("thread" => Array(threads[row["id"]]).map { { "from" => it["author"], "text" => it["text"], "agent" => it["agent"], "at" => it["at"] }.compact })
331
+ end
338
332
  end
339
333
  end
340
334
  end