lazy-gravity 0.5.2 → 0.5.4

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.
@@ -97,13 +97,22 @@ class JoinCommandHandler {
97
97
  // Step 1: Check if a channel already exists for this session
98
98
  const existingSession = this.chatSessionRepo.findByDisplayName(projectName, selectedTitle);
99
99
  if (existingSession) {
100
- const embed = new discord_js_1.EmbedBuilder()
101
- .setTitle((0, i18n_1.t)('šŸ”— Session Already Connected'))
102
- .setDescription((0, i18n_1.t)(`This session already has a channel:\n→ <#${existingSession.channelId}>`))
103
- .setColor(0x3498DB)
104
- .setTimestamp();
105
- await interaction.editReply({ embeds: [embed], components: [] });
106
- return;
100
+ const channel = await guild.channels.fetch(existingSession.channelId).catch(() => null);
101
+ if (channel) {
102
+ const embed = new discord_js_1.EmbedBuilder()
103
+ .setTitle((0, i18n_1.t)('šŸ”— Session Already Connected'))
104
+ .setDescription((0, i18n_1.t)(`This session already has a channel:\n→ <#${existingSession.channelId}>`))
105
+ .setColor(0x3498DB)
106
+ .setTimestamp();
107
+ await interaction.editReply({ embeds: [embed], components: [] });
108
+ return;
109
+ }
110
+ else {
111
+ // Clean up stale bindings since the channel is gone
112
+ logger_1.logger.info(`[Cleanup] Removed stale session binding for deleted channel ${existingSession.channelId}`);
113
+ this.chatSessionRepo.deleteByChannelId(existingSession.channelId);
114
+ this.bindingRepo.deleteByChannelId(existingSession.channelId);
115
+ }
107
116
  }
108
117
  // Step 2: Connect to CDP
109
118
  let cdp;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.WorkspaceCommandHandler = exports.WORKSPACE_SELECT_ID = exports.PROJECT_SELECT_ID = void 0;
7
7
  const i18n_1 = require("../utils/i18n");
8
8
  const fs_1 = __importDefault(require("fs"));
9
+ const logger_1 = require("../utils/logger");
9
10
  const discord_js_1 = require("discord.js");
10
11
  const projectListUi_1 = require("../ui/projectListUi");
11
12
  // Re-export for backward compatibility
@@ -22,6 +23,41 @@ class WorkspaceCommandHandler {
22
23
  workspaceService;
23
24
  channelManager;
24
25
  processingWorkspaces = new Set();
26
+ /**
27
+ * Filters out stale bindings where the Discord channel no longer exists.
28
+ * Deletes stale bindings from the repository.
29
+ */
30
+ async getValidBindings(bindings, guild) {
31
+ const validBindings = [];
32
+ for (const b of bindings) {
33
+ try {
34
+ // Try fetching the channel from Discord API
35
+ try {
36
+ const channel = await guild.channels.fetch(b.channelId);
37
+ if (channel)
38
+ validBindings.push(b);
39
+ }
40
+ catch (error) {
41
+ // Only cleanup for confirmed deleted channels (code 10003)
42
+ if (error instanceof discord_js_1.DiscordAPIError && error.code === 10003) {
43
+ logger_1.logger.info(`[Cleanup] Removed stale binding for deleted channel ${b.channelId}`);
44
+ this.chatSessionRepo.deleteByChannelId(b.channelId);
45
+ this.bindingRepo.deleteByChannelId(b.channelId);
46
+ continue;
47
+ }
48
+ // Transient failures: preserve binding for next validation attempt
49
+ logger_1.logger.error(`[Cleanup] Failed to validate binding for channel ${b.channelId}`, error);
50
+ validBindings.push(b);
51
+ }
52
+ }
53
+ catch (error) {
54
+ logger_1.logger.error(`[Cleanup] Failed to remove stale binding for channel ${b.channelId}`, error);
55
+ this.chatSessionRepo.deleteByChannelId(b.channelId);
56
+ this.bindingRepo.deleteByChannelId(b.channelId);
57
+ }
58
+ }
59
+ return validBindings;
60
+ }
25
61
  constructor(bindingRepo, chatSessionRepo, workspaceService, channelManager) {
26
62
  this.bindingRepo = bindingRepo;
27
63
  this.chatSessionRepo = chatSessionRepo;
@@ -61,7 +97,8 @@ class WorkspaceCommandHandler {
61
97
  return;
62
98
  }
63
99
  // Check if the same project is already bound (prevent duplicates)
64
- const existingBindings = this.bindingRepo.findByWorkspacePathAndGuildId(workspacePath, guild.id);
100
+ let existingBindings = this.bindingRepo.findByWorkspacePathAndGuildId(workspacePath, guild.id);
101
+ existingBindings = await this.getValidBindings(existingBindings, guild);
65
102
  if (existingBindings.length > 0) {
66
103
  const channelLinks = existingBindings.map(b => `<#${b.channelId}>`).join(', ');
67
104
  const fullPath = this.workspaceService.getWorkspacePath(workspacePath);
@@ -148,7 +185,8 @@ class WorkspaceCommandHandler {
148
185
  }
149
186
  // Check for existing project
150
187
  if (this.workspaceService.exists(name)) {
151
- const existingBindings = this.bindingRepo.findByWorkspacePathAndGuildId(name, guild.id);
188
+ let existingBindings = this.bindingRepo.findByWorkspacePathAndGuildId(name, guild.id);
189
+ existingBindings = await this.getValidBindings(existingBindings, guild);
152
190
  if (existingBindings.length > 0) {
153
191
  const channelLinks = existingBindings.map(b => `<#${b.channelId}>`).join(', ');
154
192
  await interaction.editReply({
@@ -123,6 +123,18 @@ class CdpService extends events_1.EventEmitter {
123
123
  (t.url?.includes('workbench') || t.title?.includes('Antigravity') || t.title?.includes('Cascade')) &&
124
124
  !t.title?.includes('Launchpad'));
125
125
  }
126
+ // No workbench page found — try to open the chat panel automatically
127
+ // before falling back to Launchpad
128
+ if (!target) {
129
+ const anyPage = allPages.find(t => t.webSocketDebuggerUrl);
130
+ if (anyPage) {
131
+ logger_1.logger.debug('[CdpService] No workbench page found. Attempting to open chat panel via Cmd+L / Ctrl+L...');
132
+ await this.openChatPanelViaKeyboard(anyPage.webSocketDebuggerUrl);
133
+ // Re-scan after opening chat panel
134
+ target = await this.findWorkbenchTarget();
135
+ }
136
+ }
137
+ // Last resort: accept Launchpad as target
126
138
  if (!target) {
127
139
  target = allPages.find(t => t.webSocketDebuggerUrl &&
128
140
  (t.url?.includes('workbench') || t.title?.includes('Antigravity') || t.title?.includes('Cascade') || t.title?.includes('Launchpad')));
@@ -578,6 +590,94 @@ class CdpService extends events_1.EventEmitter {
578
590
  }
579
591
  throw new Error(`Workbench page for workspace "${projectName}" not found within ${maxWaitMs / 1000} seconds`);
580
592
  }
593
+ /**
594
+ * Scan all CDP ports and return the first workbench-like target page.
595
+ */
596
+ async findWorkbenchTarget() {
597
+ let allPages = [];
598
+ for (const port of this.ports) {
599
+ try {
600
+ const list = await this.getJson(`http://127.0.0.1:${port}/json/list`);
601
+ allPages.push(...list);
602
+ }
603
+ catch {
604
+ // port not responding
605
+ }
606
+ }
607
+ return (allPages.find(t => t.type === 'page' &&
608
+ t.webSocketDebuggerUrl &&
609
+ !t.title?.includes('Launchpad') &&
610
+ !t.url?.includes('workbench-jetski-agent') &&
611
+ (t.url?.includes('workbench') || t.title?.includes('Antigravity') || t.title?.includes('Cascade'))) ??
612
+ allPages.find(t => t.webSocketDebuggerUrl &&
613
+ (t.url?.includes('workbench') || t.title?.includes('Antigravity') || t.title?.includes('Cascade')) &&
614
+ !t.title?.includes('Launchpad')) ??
615
+ null);
616
+ }
617
+ /**
618
+ * Temporarily connect to a page and send Cmd+L / Ctrl+L to open the chat panel.
619
+ */
620
+ async openChatPanelViaKeyboard(wsUrl) {
621
+ const tempWs = new ws_1.default(wsUrl);
622
+ let idCounter = 1;
623
+ try {
624
+ await new Promise((resolve, reject) => {
625
+ tempWs.on('open', resolve);
626
+ tempWs.on('error', reject);
627
+ setTimeout(() => reject(new Error('Timeout')), 5000);
628
+ });
629
+ const send = (method, params = {}) => new Promise((resolve, reject) => {
630
+ const id = idCounter++;
631
+ tempWs.send(JSON.stringify({ id, method, params }));
632
+ const timeout = setTimeout(() => reject(new Error('Timeout')), 3000);
633
+ const onMsg = (raw) => {
634
+ try {
635
+ const data = JSON.parse(raw.toString());
636
+ if (data.id === id) {
637
+ clearTimeout(timeout);
638
+ tempWs.off('message', onMsg);
639
+ resolve();
640
+ }
641
+ }
642
+ catch { /* ignore */ }
643
+ };
644
+ tempWs.on('message', onMsg);
645
+ });
646
+ const modifiers = process.platform === 'darwin' ? 4 : 2; // Meta : Ctrl
647
+ await send('Input.dispatchKeyEvent', {
648
+ type: 'keyDown',
649
+ key: 'l',
650
+ code: 'KeyL',
651
+ modifiers,
652
+ windowsVirtualKeyCode: 76,
653
+ nativeVirtualKeyCode: 76,
654
+ });
655
+ await send('Input.dispatchKeyEvent', {
656
+ type: 'keyUp',
657
+ key: 'l',
658
+ code: 'KeyL',
659
+ modifiers,
660
+ windowsVirtualKeyCode: 76,
661
+ nativeVirtualKeyCode: 76,
662
+ });
663
+ // Wait until a workbench target appears, up to a bounded timeout
664
+ const deadline = Date.now() + 10000;
665
+ while (Date.now() < deadline) {
666
+ await new Promise(r => setTimeout(r, 500));
667
+ if (await this.findWorkbenchTarget()) {
668
+ break;
669
+ }
670
+ }
671
+ }
672
+ catch (e) {
673
+ logger_1.logger.debug(`[CdpService] Failed to open chat panel automatically: ${e}`);
674
+ }
675
+ finally {
676
+ if (tempWs.readyState === ws_1.default.OPEN) {
677
+ tempWs.close();
678
+ }
679
+ }
680
+ }
581
681
  async runCommand(command, args) {
582
682
  await new Promise((resolve, reject) => {
583
683
  const child = (0, child_process_1.spawn)(command, args, { stdio: 'ignore' });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lazy-gravity",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
4
4
  "description": "Control Antigravity from anywhere — a local, secure bot (Discord + Telegram) that lets you remotely operate Antigravity on your home PC from your smartphone.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {