@nan0web/communication.app 0.1.0 → 0.1.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nan0web/communication.app",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Sovereign Git-based messenger and co-creation space (7iOS.CoCreation)",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -28,7 +28,7 @@
28
28
  "build": "tsc",
29
29
  "test": "node --test \"src/**/*.{test,story}.js\"",
30
30
  "test:stories": "node --test \"src/**/*.story.js\"",
31
- "release:spec": "node --test \"releases/0/1/v0.1.0/task.spec.js\"",
31
+ "release:spec": "node --test \"releases/0/1/v0.1.1/task.spec.js\"",
32
32
  "release:validate": "nan0inspect release --non-interactive",
33
33
  "inspect": "nan0inspect domain --non-interactive",
34
34
  "knip": "knip --production",
@@ -1,4 +1,4 @@
1
- import { ModelAsApp, show, result } from '@nan0web/ui'
1
+ import { ModelAsApp, show, result, progress } from '@nan0web/ui'
2
2
  import { FractalContactBookModel } from './FractalContactBookModel.js'
3
3
  import { ChatRepoModel, parseMessageMarkdown, resolveChatShardUri } from './ChatRepoModel.js'
4
4
  import { CrystallizeModel } from './CrystallizeModel.js'
@@ -240,12 +240,20 @@ export class WatchCommand extends ModelAsApp {
240
240
  static alias = 'watch'
241
241
  static UI = {
242
242
  watching: 'Watching {repo} every {interval}s...',
243
- received: '[{author}] {text}',
243
+ fetching: 'Fetching {repo}...',
244
+ waiting: 'Waiting {interval}s (last check {time})...',
245
+ upToDate: 'Up to date ({time})',
246
+ received: '[{time}] {author}: {text}',
247
+ syncWarning: 'Sync warning: {message}',
244
248
  }
245
249
  static repo = { help: 'Explicit repository URI', default: '.' }
246
250
  static chatId = { help: 'Chat ID for prefix sharding', default: '' }
247
251
  static interval = { help: 'Polling interval in seconds (10-15 recommended)', default: 12 }
248
252
  static once = { help: 'Run a single poll tick and exit', default: false }
253
+ static maxTicks = { help: 'Maximum polling ticks (0 = unlimited)', default: 0 }
254
+ static limit = { help: 'Initial history messages count', default: 10 }
255
+ static author = { help: 'Current user author name for highlighting own messages', default: '' }
256
+ static color = { help: 'Colorize author names in terminal', default: true }
249
257
 
250
258
  /**
251
259
  * @param {Partial<WatchCommand>} [data]
@@ -269,43 +277,216 @@ export class WatchCommand extends ModelAsApp {
269
277
  /** @type {string} Chat ID for prefix sharding */ this.chatId
270
278
  /** @type {number} Polling interval in seconds */ this.interval
271
279
  /** @type {boolean} Run a single poll tick and exit */ this.once
280
+ /** @type {number} Maximum polling ticks */ this.maxTicks
281
+ /** @type {number} Initial history messages count */ this.limit
282
+ /** @type {string} Current user author name */ this.author
283
+ /** @type {boolean} Colorize author names in terminal */ this.color
272
284
  /** @type {any} Optional Git transport port */ this.$git = options.git || null
273
285
  /** @type {any} Optional Notifier port */ this.$notify = options.notify || null
274
286
  }
275
287
 
288
+ /**
289
+ * Formats a sync error into a concise, actionable warning message.
290
+ * @param {any} err
291
+ * @returns {string}
292
+ */
293
+ #formatSyncWarning(err) {
294
+ const msg = String(err?.message || 'Sync failed').split('\n')[0]
295
+ if (err?.hint && !msg.includes(err.hint)) {
296
+ return `${msg} (${err.hint})`
297
+ }
298
+ return msg
299
+ }
300
+
301
+ /**
302
+ * Formats ISO timestamp into HH:MM.
303
+ * @param {string} [timestamp]
304
+ * @returns {string}
305
+ */
306
+ #formatTime(timestamp) {
307
+ const match = String(timestamp || '').match(/T(\d{2}:\d{2})/)
308
+ if (match) return match[1]
309
+ return new Date().toTimeString().slice(0, 5)
310
+ }
311
+
312
+ /**
313
+ * Applies a deterministic ANSI color to an author name.
314
+ * @param {string} author
315
+ * @returns {string}
316
+ */
317
+ #colorizeAuthor(author) {
318
+ if (!this.color) return author
319
+ const palette = ['\x1b[36m', '\x1b[32m', '\x1b[33m', '\x1b[35m', '\x1b[34m', '\x1b[96m']
320
+ let hash = 0
321
+ for (let i = 0; i < author.length; i += 1) {
322
+ hash = (hash * 31 + author.charCodeAt(i)) >>> 0
323
+ }
324
+ const code = palette[hash % palette.length]
325
+ return `${code}${author}\x1b[0m`
326
+ }
327
+
328
+ /**
329
+ * Formats a message line with visual separation for own vs peer messages.
330
+ * @param {{ time: string, author: string, text: string }} msg
331
+ * @returns {{ line: string, level: 'info' | 'success' }}
332
+ */
333
+ #formatMessageLine({ time, author, text }) {
334
+ const isOwn = Boolean(this.author && author === this.author)
335
+ const prefix = isOwn ? ' → ' : '◀ '
336
+ const displayAuthor = this.#colorizeAuthor(author)
337
+ const body = this._.t(WatchCommand.UI.received, { time, author: displayAuthor, text })
338
+ return {
339
+ line: `\n${prefix}${body}`,
340
+ level: isOwn ? 'info' : 'success',
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Yields initial history messages for today without triggering OS notifications.
346
+ * @param {ChatRepoModel} chat
347
+ * @param {Set<string>} seen
348
+ */
349
+ async *#showInitialHistory(chat, seen) {
350
+ const today = new Date().toISOString().slice(0, 10)
351
+ const messages = await chat.listDay(today)
352
+ for (const msg of messages) {
353
+ seen.add(msg.uri)
354
+ }
355
+ const maxHistory = Math.max(0, Number(this.limit ?? 10))
356
+ const slice = maxHistory > 0 ? messages.slice(-maxHistory) : []
357
+ for (const msg of slice) {
358
+ const { line, level } = this.#formatMessageLine({
359
+ time: this.#formatTime(msg.timestamp),
360
+ author: msg.author || 'peer',
361
+ text: msg.text || msg.uri,
362
+ })
363
+ yield show(line, level)
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Loads, yields, and notifies newly pulled messages.
369
+ * @param {string[]} newFiles
370
+ * @param {any[]} received
371
+ * @param {Set<string>} seen
372
+ */
373
+ async *#deliverMessages(newFiles, received, seen) {
374
+ for (const uri of newFiles) {
375
+ if (seen.has(uri)) continue
376
+ seen.add(uri)
377
+ const raw = await this.$db.loadDocument(uri, '')
378
+ const parsed = parseMessageMarkdown(String(raw))
379
+ received.push({ uri, ...parsed })
380
+ const { line, level } = this.#formatMessageLine({
381
+ time: this.#formatTime(parsed.timestamp),
382
+ author: parsed.author || 'peer',
383
+ text: parsed.text || uri,
384
+ })
385
+ yield show(line, level)
386
+ if (this.$notify) {
387
+ await this.$notify.notify({
388
+ title: parsed.author || 'New message',
389
+ body: parsed.text || uri,
390
+ })
391
+ }
392
+ }
393
+ }
394
+
395
+ /**
396
+ * Yields any new local messages not yet seen in the stream.
397
+ * @param {ChatRepoModel} chat
398
+ * @param {any[]} received
399
+ * @param {Set<string>} seen
400
+ */
401
+ async *#deliverLocalMessages(chat, received, seen) {
402
+ const today = new Date().toISOString().slice(0, 10)
403
+ const messages = await chat.listDay(today)
404
+ for (const msg of messages) {
405
+ if (seen.has(msg.uri)) continue
406
+ seen.add(msg.uri)
407
+ received.push(msg)
408
+ const { line, level } = this.#formatMessageLine({
409
+ time: this.#formatTime(msg.timestamp),
410
+ author: msg.author || 'me',
411
+ text: msg.text || msg.uri,
412
+ })
413
+ yield show(line, level)
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Waits between poll ticks while updating spinner countdown every second.
419
+ * @param {string} now
420
+ */
421
+ async *#waitWithCountdown(now) {
422
+ let remainingMs = Math.max(0, Number(this.interval || 12) * 1000)
423
+ while (remainingMs > 0) {
424
+ const sec = Math.ceil(remainingMs / 1000)
425
+ yield progress(this._.t(WatchCommand.UI.waiting, { interval: sec, time: now }), 0, {
426
+ type: 'spinner',
427
+ id: 'watch',
428
+ })
429
+ const step = Math.min(1000, remainingMs)
430
+ await new Promise((r) => setTimeout(r, step))
431
+ remainingMs -= step
432
+ }
433
+ }
434
+
276
435
  /**
277
436
  * Polls remote Git repository and yields received messages.
278
437
  * @returns {AsyncGenerator<import('@nan0web/ui').Intent, any, any>}
279
438
  */
280
439
  async *run() {
281
440
  const targetRepo = resolveTargetRepo(this.repo, this.chatId)
441
+ const chat = new ChatRepoModel({ repo: targetRepo }, { db: this.$db })
282
442
  const sync = new PeerGitSyncModel({ repo: targetRepo }, { db: this.$db, git: this.$git })
283
443
  yield show(this._.t(WatchCommand.UI.watching, { repo: targetRepo, interval: this.interval }), 'info')
284
444
 
445
+ const seen = new Set()
446
+ yield* this.#showInitialHistory(chat, seen)
447
+ yield show('', 'info')
448
+
285
449
  const received = []
286
- do {
287
- const newFiles = await sync.pullUpdates()
288
- for (const uri of newFiles) {
289
- const raw = await this.$db.loadDocument(uri, '')
290
- const parsed = parseMessageMarkdown(String(raw))
291
- const item = { uri, ...parsed }
292
- received.push(item)
293
- yield show(this._.t(WatchCommand.UI.received, {
294
- author: parsed.author || 'peer',
295
- text: parsed.text || uri,
296
- }), 'success')
297
- if (this.$notify) {
298
- await this.$notify.notify({
299
- title: parsed.author || 'New message',
300
- body: parsed.text || uri,
301
- })
450
+ const limit = this.once ? 1 : Number(this.maxTicks || 0)
451
+ let ticks = 0
452
+ /** @type {any} */
453
+ let lastError = null
454
+
455
+ while (limit === 0 || ticks < limit) {
456
+ ticks += 1
457
+ const now = new Date().toTimeString().slice(0, 8)
458
+ yield progress(this._.t(WatchCommand.UI.fetching, { repo: targetRepo }), 0, { type: 'spinner', id: 'watch' })
459
+ try {
460
+ const newFiles = await sync.pullUpdates()
461
+ lastError = null
462
+ if (newFiles.length > 0) {
463
+ yield progress('', 0, { type: 'spinner', stop: 'success', id: 'watch' })
464
+ yield* this.#deliverMessages(newFiles, received, seen)
465
+ yield show('', 'info')
466
+ }
467
+ yield* this.#deliverLocalMessages(chat, received, seen)
468
+ if (newFiles.length === 0 && limit > 0 && ticks >= limit) {
469
+ yield progress(this._.t(WatchCommand.UI.upToDate, { time: now }), 0, { type: 'spinner', stop: 'success', id: 'watch' })
302
470
  }
471
+ } catch (err) {
472
+ lastError = err
473
+ yield progress('', 0, { type: 'spinner', stop: true, id: 'watch' })
474
+ yield show(this._.t(WatchCommand.UI.syncWarning, { message: this.#formatSyncWarning(err) }), 'warn')
303
475
  }
304
- if (!this.once) {
305
- await new Promise((r) => setTimeout(r, Number(this.interval || 12) * 1000))
476
+ if (limit === 0 || ticks < limit) {
477
+ yield* this.#waitWithCountdown(now)
306
478
  }
307
- } while (!this.once)
479
+ }
308
480
 
481
+ if (this.once && lastError) {
482
+ return result({
483
+ ok: false,
484
+ error: String(lastError?.message || 'Sync failed'),
485
+ code: lastError?.code || 'SYNC_ERROR',
486
+ hint: lastError?.hint || '',
487
+ received,
488
+ })
489
+ }
309
490
  return result({ ok: true, received })
310
491
  }
311
492
  }
@@ -3,6 +3,74 @@ import { promisify } from 'node:util'
3
3
 
4
4
  const execFileAsync = promisify(execFile)
5
5
 
6
+ /**
7
+ * Structured Git transport error with actionable hint.
8
+ */
9
+ export class GitTransportError extends Error {
10
+ /**
11
+ * @param {string} message
12
+ * @param {{ code: string, hint: string, command: string, cause?: unknown }} meta
13
+ */
14
+ constructor(message, meta) {
15
+ super(message, { cause: meta.cause })
16
+ this.name = 'GitTransportError'
17
+ /** @type {string} */ this.code = meta.code
18
+ /** @type {string} */ this.hint = meta.hint
19
+ /** @type {string} */ this.command = meta.command
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Extracts SSH target (user@host) from git stderr/message if present.
25
+ * @param {string} text
26
+ * @returns {string}
27
+ */
28
+ function extractSshTarget(text) {
29
+ const match = text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+):/)
30
+ return match ? match[1] : 'git@gitlab.com'
31
+ }
32
+
33
+ /**
34
+ * Classifies raw git CLI errors into structured GitTransportError instances.
35
+ * @param {any} err
36
+ * @param {string} command
37
+ * @returns {GitTransportError}
38
+ */
39
+ export function classifyGitError(err, command = 'git') {
40
+ if (err instanceof GitTransportError) return err
41
+ const raw = [err?.stderr, err?.message].filter(Boolean).join('\n')
42
+
43
+ if (/Permission denied \(publickey\)|Could not read from remote repository|Host key verification failed/i.test(raw)) {
44
+ const target = extractSshTarget(raw)
45
+ const hint = `Check SSH key with "ssh -T ${target}", run "ssh-add", and verify repository access rights.`
46
+ return new GitTransportError(`Git SSH authentication failed (${target}). ${hint}`, {
47
+ code: 'SSH_AUTH_FAILED',
48
+ hint,
49
+ command,
50
+ cause: err,
51
+ })
52
+ }
53
+
54
+ if (/Could not resolve host|Connection timed out|Operation timed out|Connection refused|Network is unreachable|unable to access|Temporary failure in name resolution|kex_exchange_identification/i.test(raw)) {
55
+ const hint = 'Check internet/VPN connection and remote server availability, then retry.'
56
+ return new GitTransportError(`Git network error during "${command}". ${hint}`, {
57
+ code: 'NETWORK_ERROR',
58
+ hint,
59
+ command,
60
+ cause: err,
61
+ })
62
+ }
63
+
64
+ const firstLine = String(err?.message || 'Git command failed').split('\n')[0]
65
+ const hint = 'Check repository state with "git status".'
66
+ return new GitTransportError(`${firstLine}. ${hint}`, {
67
+ code: 'GIT_ERROR',
68
+ hint,
69
+ command,
70
+ cause: err,
71
+ })
72
+ }
73
+
6
74
  /**
7
75
  * Runs a git command in the given working directory.
8
76
  * @param {string[]} args
@@ -33,15 +101,23 @@ export class GitTransport {
33
101
  * @returns {Promise<{ ok: boolean }>}
34
102
  */
35
103
  async commitAndPush(filePath, message) {
36
- await this.execGit(['add', filePath], this.cwd)
37
- await this.execGit(['commit', '-m', message], this.cwd)
38
104
  try {
39
- await this.execGit(['push'], this.cwd)
40
- } catch {
41
- await this.execGit(['pull', '--rebase'], this.cwd)
42
- await this.execGit(['push'], this.cwd)
105
+ await this.execGit(['add', filePath], this.cwd)
106
+ await this.execGit(['commit', '-m', message], this.cwd)
107
+ try {
108
+ await this.execGit(['push'], this.cwd)
109
+ } catch (pushErr) {
110
+ const classified = classifyGitError(pushErr, 'git push')
111
+ if (classified.code === 'SSH_AUTH_FAILED' || classified.code === 'NETWORK_ERROR') {
112
+ throw classified
113
+ }
114
+ await this.execGit(['pull', '--rebase', '--autostash'], this.cwd)
115
+ await this.execGit(['push'], this.cwd)
116
+ }
117
+ return { ok: true }
118
+ } catch (err) {
119
+ throw classifyGitError(err, 'git push')
43
120
  }
44
- return { ok: true }
45
121
  }
46
122
 
47
123
  /**
@@ -49,7 +125,11 @@ export class GitTransport {
49
125
  * @returns {Promise<string[]>} List of newly pulled .md file paths
50
126
  */
51
127
  async fetchAndPullRebase() {
52
- await this.execGit(['fetch'], this.cwd)
128
+ try {
129
+ await this.execGit(['fetch'], this.cwd)
130
+ } catch (err) {
131
+ throw classifyGitError(err, 'git fetch')
132
+ }
53
133
  let diffOutput = ''
54
134
  try {
55
135
  diffOutput = await this.execGit(
@@ -64,7 +144,11 @@ export class GitTransport {
64
144
  .map((s) => s.trim())
65
145
  .filter((s) => s.endsWith('.md'))
66
146
  if (newFiles.length > 0) {
67
- await this.execGit(['pull', '--rebase'], this.cwd)
147
+ try {
148
+ await this.execGit(['pull', '--rebase', '--autostash'], this.cwd)
149
+ } catch (err) {
150
+ throw classifyGitError(err, 'git pull --rebase')
151
+ }
68
152
  }
69
153
  return newFiles
70
154
  }
@@ -195,7 +195,11 @@ export class WatchCommand extends ModelAsApp {
195
195
  static alias: string;
196
196
  static UI: {
197
197
  watching: string;
198
+ fetching: string;
199
+ waiting: string;
200
+ upToDate: string;
198
201
  received: string;
202
+ syncWarning: string;
199
203
  };
200
204
  static repo: {
201
205
  help: string;
@@ -213,6 +217,22 @@ export class WatchCommand extends ModelAsApp {
213
217
  help: string;
214
218
  default: boolean;
215
219
  };
220
+ static maxTicks: {
221
+ help: string;
222
+ default: number;
223
+ };
224
+ static limit: {
225
+ help: string;
226
+ default: number;
227
+ };
228
+ static author: {
229
+ help: string;
230
+ default: string;
231
+ };
232
+ static color: {
233
+ help: string;
234
+ default: boolean;
235
+ };
216
236
  /**
217
237
  * @param {Partial<WatchCommand>} [data]
218
238
  * @param {Partial<import('@nan0web/ui').ModelAsAppOptions> & { git?: any, notify?: any }} [options]
@@ -234,6 +254,10 @@ export class WatchCommand extends ModelAsApp {
234
254
  /** @type {string} Chat ID for prefix sharding */ chatId: string;
235
255
  /** @type {number} Polling interval in seconds */ interval: number;
236
256
  /** @type {boolean} Run a single poll tick and exit */ once: boolean;
257
+ /** @type {number} Maximum polling ticks */ maxTicks: number;
258
+ /** @type {number} Initial history messages count */ limit: number;
259
+ /** @type {string} Current user author name */ author: string;
260
+ /** @type {boolean} Colorize author names in terminal */ color: boolean;
237
261
  /** @type {any} Optional Git transport port */ $git: any;
238
262
  /** @type {any} Optional Notifier port */ $notify: any;
239
263
  /**
@@ -241,6 +265,7 @@ export class WatchCommand extends ModelAsApp {
241
265
  * @returns {AsyncGenerator<import('@nan0web/ui').Intent, any, any>}
242
266
  */
243
267
  run(): AsyncGenerator<import("@nan0web/ui").Intent, any, any>;
268
+ #private;
244
269
  }
245
270
  /**
246
271
  * Main polymorphic OLMUI application controller for @nan0web/communication.app.
@@ -1,3 +1,28 @@
1
+ /**
2
+ * Classifies raw git CLI errors into structured GitTransportError instances.
3
+ * @param {any} err
4
+ * @param {string} command
5
+ * @returns {GitTransportError}
6
+ */
7
+ export function classifyGitError(err: any, command?: string): GitTransportError;
8
+ /**
9
+ * Structured Git transport error with actionable hint.
10
+ */
11
+ export class GitTransportError extends Error {
12
+ /**
13
+ * @param {string} message
14
+ * @param {{ code: string, hint: string, command: string, cause?: unknown }} meta
15
+ */
16
+ constructor(message: string, meta: {
17
+ code: string;
18
+ hint: string;
19
+ command: string;
20
+ cause?: unknown;
21
+ });
22
+ /** @type {string} */ code: string;
23
+ /** @type {string} */ hint: string;
24
+ /** @type {string} */ command: string;
25
+ }
1
26
  /**
2
27
  * Git CLI transport port for conflict-free message synchronization.
3
28
  */