~cytrogen/gstack

ref: 7450b5160b69d54eff1feb78e3e99a97e16fb4d5 gstack/browse/test/file-drop.test.ts -rw-r--r-- 10.0 KiB
7450b516 — Garry Tan fix: security audit remediation — 12 fixes, 20 tests (v0.13.1.0) (#595) 12 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/**
 * Tests for the inbox meta-command handler (file drop relay).
 *
 * Tests the inbox display, --clear flag, and edge cases by creating
 * temp directories with test JSON files and calling handleMetaCommand.
 */

import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { handleMetaCommand } from '../src/meta-commands';
import { BrowserManager } from '../src/browser-manager';

let tmpDir: string;
let bm: BrowserManager;

// We need a BrowserManager instance for handleMetaCommand, but inbox
// doesn't use it. We also need to mock git rev-parse to point to our
// temp directory. We'll test the inbox logic directly by manipulating
// the filesystem and using child_process.execSync override.

// ─── Direct filesystem tests (bypassing handleMetaCommand) ──────
// The inbox handler in meta-commands.ts calls `git rev-parse --show-toplevel`
// to find the inbox directory. Since we can't easily mock that in unit tests,
// we test the inbox parsing logic directly.

interface InboxMessage {
  timestamp: string;
  url: string;
  userMessage: string;
}

/** Replicate the inbox file reading logic from meta-commands.ts */
function readInbox(inboxDir: string): InboxMessage[] {
  if (!fs.existsSync(inboxDir)) return [];

  const files = fs.readdirSync(inboxDir)
    .filter(f => f.endsWith('.json') && !f.startsWith('.'))
    .sort()
    .reverse();

  if (files.length === 0) return [];

  const messages: InboxMessage[] = [];
  for (const file of files) {
    try {
      const data = JSON.parse(fs.readFileSync(path.join(inboxDir, file), 'utf-8'));
      messages.push({
        timestamp: data.timestamp || '',
        url: data.page?.url || 'unknown',
        userMessage: data.userMessage || '',
      });
    } catch {
      // Skip malformed files
    }
  }
  return messages;
}

/** Replicate the inbox formatting logic from meta-commands.ts */
function formatInbox(messages: InboxMessage[]): string {
  if (messages.length === 0) return 'Inbox empty.';

  const lines: string[] = [];
  lines.push(`SIDEBAR INBOX (${messages.length} message${messages.length === 1 ? '' : 's'})`);
  lines.push('────────────────────────────────');

  for (const msg of messages) {
    const ts = msg.timestamp ? `[${msg.timestamp}]` : '[unknown]';
    lines.push(`${ts} ${msg.url}`);
    lines.push(`  "${msg.userMessage}"`);
    lines.push('');
  }

  lines.push('────────────────────────────────');
  return lines.join('\n');
}

/** Replicate the --clear logic from meta-commands.ts */
function clearInbox(inboxDir: string): number {
  const files = fs.readdirSync(inboxDir)
    .filter(f => f.endsWith('.json') && !f.startsWith('.'));
  for (const file of files) {
    try { fs.unlinkSync(path.join(inboxDir, file)); } catch {}
  }
  return files.length;
}

function writeTestInboxFile(
  inboxDir: string,
  message: string,
  pageUrl: string,
  timestamp: string,
): string {
  fs.mkdirSync(inboxDir, { recursive: true });
  const filename = `${timestamp.replace(/:/g, '-')}-observation.json`;
  const filePath = path.join(inboxDir, filename);
  fs.writeFileSync(filePath, JSON.stringify({
    type: 'observation',
    timestamp,
    page: { url: pageUrl, title: '' },
    userMessage: message,
    sidebarSessionId: 'test-session',
  }, null, 2));
  return filePath;
}

beforeEach(() => {
  tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'file-drop-test-'));
});

afterEach(() => {
  fs.rmSync(tmpDir, { recursive: true, force: true });
});

// ─── Empty Inbox ─────────────────────────────────────────────────

describe('inbox — empty states', () => {
  test('no .context/sidebar-inbox directory returns empty', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    const messages = readInbox(inboxDir);
    expect(messages.length).toBe(0);
    expect(formatInbox(messages)).toBe('Inbox empty.');
  });

  test('empty inbox directory returns empty', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    fs.mkdirSync(inboxDir, { recursive: true });
    const messages = readInbox(inboxDir);
    expect(messages.length).toBe(0);
    expect(formatInbox(messages)).toBe('Inbox empty.');
  });

  test('directory with only dotfiles returns empty', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    fs.mkdirSync(inboxDir, { recursive: true });
    fs.writeFileSync(path.join(inboxDir, '.tmp-file.json'), '{}');
    const messages = readInbox(inboxDir);
    expect(messages.length).toBe(0);
  });
});

// ─── Valid Messages ──────────────────────────────────────────────

describe('inbox — valid messages', () => {
  test('displays formatted output with timestamps and URLs', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    writeTestInboxFile(inboxDir, 'This button is broken', 'https://example.com/page', '2024-06-15T10:30:00.000Z');
    writeTestInboxFile(inboxDir, 'Login form fails', 'https://example.com/login', '2024-06-15T10:31:00.000Z');

    const messages = readInbox(inboxDir);
    expect(messages.length).toBe(2);

    const output = formatInbox(messages);
    expect(output).toContain('SIDEBAR INBOX (2 messages)');
    expect(output).toContain('https://example.com/page');
    expect(output).toContain('https://example.com/login');
    expect(output).toContain('"This button is broken"');
    expect(output).toContain('"Login form fails"');
    expect(output).toContain('[2024-06-15T10:30:00.000Z]');
    expect(output).toContain('[2024-06-15T10:31:00.000Z]');
  });

  test('single message uses singular form', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    writeTestInboxFile(inboxDir, 'Just one', 'https://example.com', '2024-06-15T10:30:00.000Z');

    const messages = readInbox(inboxDir);
    const output = formatInbox(messages);
    expect(output).toContain('1 message)');
    expect(output).not.toContain('messages)');
  });

  test('messages sorted newest first', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    writeTestInboxFile(inboxDir, 'older', 'https://example.com', '2024-06-15T10:00:00.000Z');
    writeTestInboxFile(inboxDir, 'newer', 'https://example.com', '2024-06-15T11:00:00.000Z');

    const messages = readInbox(inboxDir);
    // Filenames sort lexicographically, reversed = newest first
    expect(messages[0].userMessage).toBe('newer');
    expect(messages[1].userMessage).toBe('older');
  });
});

// ─── Malformed Files ─────────────────────────────────────────────

describe('inbox — malformed files', () => {
  test('malformed JSON files are skipped gracefully', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    fs.mkdirSync(inboxDir, { recursive: true });

    // Write a valid message
    writeTestInboxFile(inboxDir, 'valid message', 'https://example.com', '2024-06-15T10:30:00.000Z');

    // Write a malformed JSON file
    fs.writeFileSync(
      path.join(inboxDir, '2024-06-15T10-35-00.000Z-observation.json'),
      'this is not valid json {{{',
    );

    const messages = readInbox(inboxDir);
    expect(messages.length).toBe(1);
    expect(messages[0].userMessage).toBe('valid message');
  });

  test('JSON file missing fields uses defaults', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    fs.mkdirSync(inboxDir, { recursive: true });

    // Write a JSON file with missing fields
    fs.writeFileSync(
      path.join(inboxDir, '2024-06-15T10-30-00.000Z-observation.json'),
      JSON.stringify({ type: 'observation' }),
    );

    const messages = readInbox(inboxDir);
    expect(messages.length).toBe(1);
    expect(messages[0].timestamp).toBe('');
    expect(messages[0].url).toBe('unknown');
    expect(messages[0].userMessage).toBe('');
  });
});

// ─── Clear Flag ──────────────────────────────────────────────────

describe('inbox — --clear flag', () => {
  test('files deleted after clear', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    writeTestInboxFile(inboxDir, 'message 1', 'https://example.com', '2024-06-15T10:30:00.000Z');
    writeTestInboxFile(inboxDir, 'message 2', 'https://example.com', '2024-06-15T10:31:00.000Z');

    // Verify files exist
    const filesBefore = fs.readdirSync(inboxDir).filter(f => f.endsWith('.json') && !f.startsWith('.'));
    expect(filesBefore.length).toBe(2);

    // Clear
    const cleared = clearInbox(inboxDir);
    expect(cleared).toBe(2);

    // Verify files deleted
    const filesAfter = fs.readdirSync(inboxDir).filter(f => f.endsWith('.json') && !f.startsWith('.'));
    expect(filesAfter.length).toBe(0);
  });

  test('clear on empty directory does nothing', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    fs.mkdirSync(inboxDir, { recursive: true });

    const cleared = clearInbox(inboxDir);
    expect(cleared).toBe(0);
  });

  test('clear preserves dotfiles', () => {
    const inboxDir = path.join(tmpDir, '.context', 'sidebar-inbox');
    fs.mkdirSync(inboxDir, { recursive: true });

    // Write a dotfile and a regular file
    fs.writeFileSync(path.join(inboxDir, '.keep'), '');
    writeTestInboxFile(inboxDir, 'to be cleared', 'https://example.com', '2024-06-15T10:30:00.000Z');

    clearInbox(inboxDir);

    // Dotfile should remain
    expect(fs.existsSync(path.join(inboxDir, '.keep'))).toBe(true);
    // Regular file should be gone
    const jsonFiles = fs.readdirSync(inboxDir).filter(f => f.endsWith('.json') && !f.startsWith('.'));
    expect(jsonFiles.length).toBe(0);
  });
});