scripts / chat-image-import-smoke.cjs

const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const sharp = require('sharp');
const { Chat, ChatMessage, FileHandle } = require('@lmstudio/sdk');
const { preprocess } = require('../dist/promptPreprocessor');
const { toolsProvider } = require('../dist/toolsProvider');

(async () => {
  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'aia-import-working-'));
  const storage = await fs.mkdtemp(path.join(os.tmpdir(), 'aia-import-user-files-'));
  const red = await sharp({create: {width: 32, height: 32, channels: 3, background: 'red'}}).jpeg().toBuffer();
  const blue = await sharp({create: {width: 32, height: 32, channels: 3, background: 'blue'}}).webp().toBuffer();
  const displayName = '1794247420831-5.jpg';
  await fs.writeFile(path.join(storage, 'actual-upload'), red);
  await fs.writeFile(path.join(root, 'downloaded.webp'), blue);
  await fs.writeFile(path.join(root, 'downloaded.json'), JSON.stringify({source: 'download', sourcePageUrl: 'https://example.invalid/product'}));
  let modelCalls = 0;
  let neutralCalls = 0;
  const client = {files: {getLocalFileAbsolutePath: async id => ({path: path.join(storage, id)})}, llm: {model: async () => ({vision: true, identifier: 'test', respond: async messages => {
    modelCalls++;
    assert.equal(messages[0].images.length, 2);
    if (messages[0].content.includes('visual inventory check')) {
      neutralCalls++;
      assert(!messages[0].content.includes('chat-attachment'));
      assert(!messages[0].content.includes('https://example.invalid/product'));
      return {content: 'Image 1: red square. Image 2: blue square.'};
    }
    assert(messages[0].content.includes('chat-attachment'));
    assert(messages[0].content.includes('https://example.invalid/product'));
    return {content: 'Manual image and downloaded image compared together.'};
  }})}};
  const settings = {autoAttach: false, carryAnalyzed: true, maxImages: 2, startImage: 1, pageUrl: '', analysisBackend: 'local'};
  let history = Chat.empty();
  const ctl = {client, abortSignal: new AbortController().signal, guardAbort() {}, debug() {},
    getWorkingDirectory: () => root, getPluginConfig: () => ({get: key => settings[key]}),
    pullHistory: async () => history, createStatus: () => ({setState() {}, setText() {}})};
  const original = ChatMessage.from({role: 'user', content: 'Compare this uploaded image with the downloaded one.',
    images: [new FileHandle(client.files, 'local:actual-upload', 'image', red.length, displayName)]}).asImmutableCopy();
  const imported = await preprocess(ctl, original);
  assert.equal(imported.getFiles(client).length, 1);
  assert(!original.getText().includes('Images available'));
  const match = imported.getText().match(/-> (aia-attachments\/[^\n]+)/);
  assert(match, imported.getText());
  const ref = match[1];
  assert(ref.endsWith('/'+displayName));
  assert.deepEqual(await fs.readFile(path.join(root, ref)), red);
  assert.equal(JSON.parse(await fs.readFile(path.join(root, ref.replace(/\.jpg$/, '.json')))).source, 'chat-attachment');
  assert.equal(await fs.stat(path.join(root, displayName)).catch(() => null), null);
  const ctx = {status() {}, warn() {}, signal: ctl.abortSignal, callId: 1};
  const multi = (await toolsProvider(ctl))[3];
  assert.equal((await multi.implementation({imageNames: [displayName, 'downloaded.webp'], prompt: 'compare'}, ctx)).error, 'image_not_found');
  const checked = await multi.implementation({imageNames: [ref, 'downloaded.webp'], prompt: 'compare'}, ctx);
  assert.equal(checked.status, 'image_selection_check_required');
  assert.equal(checked.analysis, undefined);
  const compared = await multi.implementation({imageNames: [ref, 'downloaded.webp'], prompt: 'compare', verificationToken: checked.verificationToken}, ctx);
  assert.equal(compared.analysis, 'Manual image and downloaded image compared together.');
  assert.equal(compared.images[0].imageName, ref);
  assert.equal(compared.images[1].imageName, 'downloaded.webp');
  assert.equal(modelCalls, 2);
  assert.equal(neutralCalls, 1);
  assert.equal((await preprocess(ctl, imported)).getText(), imported.getText()); // Idempotent references.
  history.append(original);
  const followup = await preprocess(ctl, ChatMessage.from('Compare the image I attached earlier.'));
  assert(followup.getText().includes(ref));
  assert.equal(followup.getFiles(client).length, 0);
  history = Chat.empty();
  const unrelated = ChatMessage.from('Different chat, same working directory.');
  assert.equal(await preprocess(ctl, unrelated), unrelated);
  // Import the already-attached image even when its filename is unsafe or misleading.
  const inline = ChatMessage.from({role: 'user', content: [
    {type: 'text', text: 'Image'}, {type: 'file', name: '../unsafe.webp', identifier: 'base64:'+blue.toString('base64'), sizeBytes: blue.length, fileType: 'image'},
  ]});
  const safe = await preprocess(ctl, inline);
  const safeRef = safe.getText().match(/-> (aia-attachments\/[^\n]+)/)[1];
  assert(!safeRef.includes('..'));
  assert.deepEqual(await fs.readFile(path.join(root, safeRef)), blue);
  // A stale qualified path must not resolve a different directory's matching basename.
  assert.equal((await multi.implementation({imageNames: ['stale/downloaded.webp', ref], prompt: 'compare'}, ctx)).error, 'image_not_found');
  await fs.writeFile(path.join(root, ref), blue);
  const tampered = await preprocess(ctl, original);
  assert(!tampered.getText().includes('-> '));
  assert.deepEqual(await fs.readFile(path.join(root, ref)), blue, 'Never overwrite an altered cache file.');
  console.log('PASS: external LM Studio-style manual storage imported with sidecar, mixed manual/download comparison in one inference, current-chat history references, no cross-chat lookup, safe names, idempotence, stale-path refusal and tampered-cache protection.');
})().catch(error => {console.error(error); process.exitCode = 1;});