File size: 13,338 Bytes
b39afbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/**
 * Copyright (c) 2023 MERCENARIES.AI PTE. LTD.
 * All rights reserved.
 */

import {
  type ChatClientService,
  Client,
  ClientExtensionManager,
  type JobControllerClientService,
  type MessagingClientService
} from 'omni-client-services';
import { Workbench } from './workbench';
import { OmniSDKHost, MarkdownEngine } from 'omni-sdk';

import {
  OmniSSEMessages,
  Manager,
  type IOmniSSEMessageCustomExtensionEvent,
  type IOmniSSEMessageClientToast,
  type IOmniSSEMessageShowExtensionEvent,
  insane
} from 'omni-shared';
import CodeRenderer from './renderers/chat/CodeRenderer';
import MarkdownRenderer from './renderers/chat/MarkdownRenderer';
import OmniComponentRenderer from './renderers/chat/OmniComponentRenderer';
import OmniComponentMetaRenderer from './renderers/chat/OmniComponentMetaRenderer';
import OmniJobRenderer from './renderers/chat/OmniJobRenderer';
import OmniRestErrorRenderer from './renderers/chat/OmniRestErrorRenderer';
import PlainTextRenderer from './renderers/chat/PlainTextRenderer';
import OmniBillingTabRenderer from './renderers/chat/OmniBillingTabRenderer';
import OmniSettingsRenderer from './renderers/chat/OmniSettingsRenderer';
import OmniExtensionListRenderer from './renderers/chat/OmniExtensionListRenderer';

import { OAIComponent31, type OAIBaseComponent, type OmniComponentFormat } from 'omni-sockets';
//@ts-expect-error
import WinBox from '@winbox/src/js/winbox.js';
import '@winbox/src/css/winbox.css';

enum ReteCurveType {
  CurveBasis = 'curveBasis',
  CurveBasisClosed = 'curveBasisClosed',
  CurveBasisOpen = 'curveBasisOpen',
  CurveBump = 'curveBump',
  CurveBundle = 'curveBundle',
  CurveCardinal = 'curveCardinal',
  CurveCardinalClosed = 'curveCardinalClosed',
  CurveCardinalOpen = 'curveCardinalOpen',
  CurveCatmullRom = 'curveCatmullRom',
  CurveCatmullRomOpen = 'curveCatmullRomOpen',
  CurveLinear = 'curveLinear',
  CurveLinearClosed = 'curveLinearClosed',
  CurveMonotone = 'curveMonotone',
  CurveNatural = 'curveNatural',
  CurveRadial = 'curveRadial',
  CurveStep = 'curveStep'
}

enum ReteSettings {
  curve = 'curve'
}

class ClientBlockManager extends Manager {
  private readonly factories: Map<string, Function>;
  private readonly componentCache: Map<string, OAIBaseComponent>;

  constructor(app: OmnitoolClient) {
    super(app);

    this.factories = new Map();
    this.componentCache = new Map();

    this.registerType('OAIComponent31', OAIComponent31.fromJSON);
  }

  public registerType(key: string, Factory: Function): void {
    if (!key) throw new Error('registerType(): key cannot be undefined');
    if (!Factory || typeof Factory !== 'function') throw new Error(`Factory ${key} must be a function`);
    if (this.factories.has(key)) throw new Error(`Block type ${key} already registered`);
    this.factories.set(key, Factory);
  }

  get client(): OmnitoolClient {
    return this.app as OmnitoolClient;
  }

  private async _rpc(fName: string, args: any): Promise<any> {
    return await this.client.runScript('blockManager', { command: fName, args }, { fromChatWindow: false });
  }

  public async getInstance(key: string): Promise<OAIBaseComponent | undefined> {
    const ret = await this.getInstances([key]);
    return ret ? ret[0] : undefined;
  }

  // return a composed block. If the key responds to a patch, the patch is applied to the underlying block
  public async getInstances(keys: string[]): Promise<OAIBaseComponent[]> {
    if (!keys) throw new Error('getInstances(): key cannot be undefined');

    // Check the cache first
    let found = (keys.map((k) => this.componentCache.get(k)) as OAIBaseComponent[]) || [];
    const missing = keys.filter((k) => !this.componentCache.has(k));

    // Retrieve any missing
    if (missing.length > 0) {
      const userId = undefined;
      const blocks = (await this._rpc('getInstances', [missing, userId, 'missing_block'])) as OmniComponentFormat[];
      const results = await Promise.all(
        blocks.map(async (block: OmniComponentFormat) => {
          const Factory = this.factories.get(block.type || 'OAIComponent31');
          if (!Factory) {
            throw new Error(`Internal error, Block type ${block.type} not registered`);
          }
          const instance = Factory(block); // return the composed block
          this.componentCache.set(instance.name, instance);
          return instance;
        })
      );
      found.push(...results);
    }
    found = found.filter((r) => r !== undefined);
    return found;
  }
}

// Custom client
class OmnitoolClient extends Client {
  clipboard: any = {};
  workbench: Workbench;
  uiSettings: any = {};
  reteSettings: {
    curve: ReteCurveType;
    curvature: number;
    arrow: boolean;
  };

  windows: Map<string, WinBox>;
  sdkHost: OmniSDKHost<OmnitoolClient>;
  public readonly markdownEngine: MarkdownEngine;

  private readonly _blocks: ClientBlockManager;

  constructor(id: string, options: any) {
    super(id, options);
    this.markdownEngine = new MarkdownEngine();
    this.windows = new Map<string, WinBox>();
    this.sdkHost = new OmniSDKHost<OmnitoolClient>(this).init();

    // @ts-ignore
    this.workbench = new window.Alpine.reactive(new Workbench(this));
    const client = this;

    this._blocks = new ClientBlockManager(this);

    //@ts-expect-error
    this.reteSettings = new window.Alpine.reactive({
      curve: window.localStorage.getItem('settings.rete.curve') ?? ReteCurveType.CurveBasis,
      arrow: window.localStorage.getItem('settings.rete.arrow') === 'true',
      curvature: parseFloat(window.localStorage.getItem('settings.rete.curvature') ?? '0.3')
    });

    for (const key in ReteSettings) {
      const value = window.localStorage.getItem(`settings.rete.${key}`);
      if (value) {
        //@ts-ignore
        this.reteSettings[key] = value;
      }
    }

    // @ts-ignore
    this.uiSettings = new window.Alpine.reactive({
      minimalChat: window.localStorage.getItem('settings.minimalChat') === 'true',
      chatSide: window.localStorage.getItem('settings.chatSide') ?? 'left',
      tabBarStyle: window.localStorage.getItem('settings.tabBarStyle') ?? 'tabs',
      chatMinimized: window.localStorage.getItem('settings.chatMinimized') === 'true' ?? false,
      async toggleMinimal() {
        this.minimalChat = !this.minimalChat;
        window.localStorage.setItem('settings.minimalChat', this.minimalChat);
        await client.emit('request_editor_resize', {});
      },
      async toggleSide() {
        this.chatSide = this.chatSide === 'left' ? 'right' : 'left';
        window.localStorage.setItem('settings.chatSide', this.chatSide);
        await client.emit('request_editor_resize', {});
      },
      async toggleMinimized(val?: boolean) {
        this.chatMinimized = val !== undefined ? val : !this.chatMinimized;
        window.localStorage.setItem('settings.chatMinimized', this.chatMinimized ? 'true' : 'false');
        await client.emit('request_editor_resize', {});
      }
    });
    // @ts-ignore
    this.extensions = new window.Alpine.reactive(new ClientExtensionManager(this));
  }

  showToast(
    message: string,
    options: {
      description?: string;
      type?: 'default' | 'danger' | 'success' | 'warning' | 'info';
      position?: string;
      html?: string;
    } = { description: '', type: 'default', position: 'top-right', html: '' }
  ) {
    const description = options.description || '';
    const type = options.type || 'default';
    const position = options.position || 'top-right';
    const html = options.html || '';

    window.dispatchEvent(new CustomEvent('toast-show', { detail: { type, message, description, position, html } }));
  }

  showTopBanner(
    bannerTitle: string,
    bannerDescription: string,
    options: {
      link?: string;
    }
  ) {
    const link = options.link ?? '';
    window.dispatchEvent(new CustomEvent('top-banner-show', { detail: { bannerTitle, bannerDescription, link } }));
  }

  closeWindow(singletonHash?: string): boolean {
    const win = this.getWindow(singletonHash);
    if (win) {
      win.close();
    }
    return !!win;
  }

  public getWindow(singletonHash?: string): WinBox | undefined {
    return singletonHash ? this.windows.get(singletonHash) : undefined;
  }

  public toggleWindow(url: string, singletonHash: string | undefined, opts: any): WinBox | undefined {
    opts ??= {};
    opts.minwidth ??= '600px';
    opts.minheight ??= '500px';
    opts.x ??= 'center';
    opts.y ??= 'center';

    if (singletonHash)
    {
      this.closeWindow(singletonHash)
      url += `&omniHash=${singletonHash}`;
    }

    const template = document.createElement('div');
    template.innerHTML = `
        <div class="wb-header">
            <div class="wb-control">
                <span class="wb-custom"></span>
                <span class="wb-close"></span>
            </div>
            <div class="wb-drag">
                <div class="wb-title">
                </div>
            </div>
        </div>
        <div class="wb-body"></div>
    `;

    const window = new WinBox(
      Object.assign(
        {},
        {
          title: opts.title,
          url,
          class: [],
          autosize: true
        },
        opts,
        {
          onclose: () => {
            if (singletonHash) {
              this.windows.delete(singletonHash);
              this.sdkHost.deregister(singletonHash);
            }
            this.workbench.refreshUI();
          }
        }
      )
    );

    if (singletonHash) {
      this.windows.set(singletonHash, window);
    }

    this.workbench.refreshUI();
    return window;
  }

  get blocks(): ClientBlockManager {
    return this._blocks;
  }

  async onConfigure(): Promise<boolean> {
    this.success('onConfigure');
    return true;
  }

  async onLoad(): Promise<boolean> {
    this.success('onLoad');

    return true;
  }

  async onStart(): Promise<boolean> {
    const renderInitTasks: Promise<void>[] = [];

    renderInitTasks.push(this.chat.registerRenderer(new PlainTextRenderer()));
    renderInitTasks.push(this.chat.registerRenderer(new MarkdownRenderer()));
    renderInitTasks.push(this.chat.registerRenderer(new OmniJobRenderer()));
    renderInitTasks.push(this.chat.registerRenderer(new OmniComponentRenderer()));
    renderInitTasks.push(this.chat.registerRenderer(new OmniComponentMetaRenderer()));
    renderInitTasks.push(this.chat.registerRenderer(new OmniRestErrorRenderer()));
    renderInitTasks.push(this.chat.registerRenderer(new OmniBillingTabRenderer()));
    renderInitTasks.push(this.chat.registerRenderer(new OmniSettingsRenderer()));
    renderInitTasks.push(this.chat.registerRenderer(new OmniExtensionListRenderer()));
    renderInitTasks.push(this.chat.registerRenderer(new CodeRenderer()));

    await Promise.all(renderInitTasks);

    this.io.registerMessageHandler({ type: 'chat', handler: this.chat.onChatMessage.bind(this.chat) });
    this.io.registerMessageHandler({
      type: OmniSSEMessages.CLIENT_TOAST,
      handler: (message: IOmniSSEMessageClientToast): any => {
        this.showToast(message.body.message, message.body.options);
      }
    });
    this.io.registerMessageHandler({ type: 'chat:system', handler: this.chat.onChatMessage.bind(this.chat) });

    // Extension messages
    this.io.registerMessageHandler({
      type: OmniSSEMessages.SHOW_EXTENSION,
      handler: (message: IOmniSSEMessageShowExtensionEvent): any => {
        this.workbench.showExtension(message.body.extensionId, message.body.args, message.body.page, message.body.opts);
      }
    })
    this.io.registerMessageHandler({
      type: OmniSSEMessages.CUSTOM_EXTENSION_EVENT,
      handler: (message: IOmniSSEMessageCustomExtensionEvent) => {
        const { extensionId, eventId, eventArgs } = message.body;
        this.sdkHost.signalCustomEvent(extensionId, eventId, eventArgs);
      }
    });

    // Subscribe to messages from the server
    this.io.registerMessageHandler({ type: 'job:status', handler: this.jobs.handleMessages.bind(this.jobs) });
    this.io.registerMessageHandler({ type: 'job:error', handler: this.jobs.handleMessages.bind(this.jobs) });
    this.io.registerMessageHandler({ type: 'job:update', handler: this.jobs.handleMessages.bind(this.jobs) });

    this.events.on('chat_message_added', async (eventData: any) => {
      const [message] = eventData;
      console.log(message);
      this.sdkHost.signalChatMessageReceived(message);
    });

    await this.io.startSSE(''); // Start the SSE connection to receive real time messages from the server.
    await this.workbench.load(); // Initialize the workbench

    return true;
  }

  get io(): MessagingClientService {
    return this.services.get('messaging') as unknown as MessagingClientService;
  }

  get jobs(): JobControllerClientService {
    return this.services.get('jobs') as unknown as JobControllerClientService;
  }

  get chat(): ChatClientService {
    return this.services.get('chat') as unknown as ChatClientService;
  }

  addImageToClipboard(images: any) {
    if (!images) {
      return;
    }

    if (!Array.isArray(images)) {
      images = [images];
    }

    this.clipboard ??= {};
    this.clipboard.images ??= [];
    this.clipboard.images = this.clipboard.images.concat(images);
  }
}

export { OmnitoolClient };