-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
471 lines (420 loc) · 19.1 KB
/
Copy pathscript.js
File metadata and controls
471 lines (420 loc) · 19.1 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
const airlines = [
'American Airlines', 'Delta Air Lines', 'United Airlines', 'Southwest Airlines',
'JetBlue Airways', 'Alaska Airlines', 'Spirit Airlines', 'Frontier Airlines',
'Hawaiian Airlines', 'Allegiant Air'
];
const planes = [
'Boeing 737', 'Boeing 747', 'Boeing 777', 'Boeing 787',
'Airbus A320', 'Airbus A330', 'Airbus A350', 'Airbus A380'
];
let currentPage = 0;
const flightsPerPage = 6;
let allFlights = [];
let searchData = {};
let filteredFlights = []; // Tracks currently filtered flights
let activeToolNames = []; // TRACKS REGISTERED TOOLS FOR CLEANUP
// --- LATENCY SIMULATION & WORKAROUND LOGIC ---
let toolExecutionLatency = 0;
let enableToolBugWorkaround = true; // Default checked
document.getElementById('latencyInput').addEventListener('input', (e) => {
const val = parseInt(e.target.value);
toolExecutionLatency = isNaN(val) ? 0 : val;
console.log(`Tool latency set to ${toolExecutionLatency}ms`);
});
document.getElementById('toolBugWorkaround').addEventListener('change', (e) => {
enableToolBugWorkaround = e.target.checked;
console.log(`Tool bug workaround active: ${enableToolBugWorkaround}`);
updateModelContext(); // Immediate update when toggled
});
// Wrapper function to add delay
const withLatency = (fn) => async (...args) => {
if (toolExecutionLatency > 0) {
console.log(`Simulating tool latency: ${toolExecutionLatency}ms...`);
await new Promise(resolve => setTimeout(resolve, toolExecutionLatency));
}
return fn(...args);
};
// --------------------------------
// Search flights function
async function searchFlights({ origin, destination, departureDate, returnDate, passengers }) {
console.log('running searchFlights');
document.getElementById('origin').value = origin;
document.getElementById('destination').value = destination;
document.getElementById('departureDate').value = departureDate;
document.getElementById('passengers').value = passengers.toString();
if (returnDate) {
document.getElementById('oneWay').checked = false;
document.getElementById('returnDateGroup').classList.remove('hidden');
document.getElementById('returnDate').value = returnDate;
} else {
document.getElementById('oneWay').checked = true;
document.getElementById('returnDateGroup').classList.add('hidden');
document.getElementById('returnDate').value = '';
}
searchData = {
origin,
destination,
departureDate,
oneWay: !returnDate,
returnDate,
passengers
};
allFlights = generateFlights(origin, destination);
filteredFlights = [...allFlights];
currentPage = 0;
const dateOptions = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
timeZone: 'UTC'
};
const summaryHtml = `
<h2>${searchData.origin} → ${searchData.destination}</h2>
<p>${new Date(searchData.departureDate).toLocaleDateString('en-US', dateOptions)}
${searchData.returnDate ? ' - ' + new Date(searchData.returnDate).toLocaleDateString('en-US', dateOptions) : ' (One-way)'}
• ${searchData.passengers} passenger${searchData.passengers > 1 ? 's' : ''}</p>
`;
document.getElementById('searchSummary').innerHTML = summaryHtml;
document.getElementById('resultsCount').textContent = `${allFlights.length} flights found`;
document.getElementById('searchPage').classList.add('hidden');
document.getElementById('resultsPage').classList.remove('hidden');
renderFlights();
updateModelContext();
return JSON.stringify({
totalFlights: allFlights.length,
flights: allFlights.map(flight => ({
flightId: flight.flightId,
airline: flight.airline,
price: flight.price,
departure: { time: flight.departTime, airport: flight.origin },
arrival: { time: flight.arriveTime, airport: flight.destination },
duration: flight.duration,
stops: flight.stops,
details: {
aircraft: flight.plane,
legroom: flight.legroom,
inFlightEntertainment: flight.entertainment,
wifi: flight.wifi,
chargingPoints: flight.charging,
lieFlatUpgrade: flight.lieFlat
}
}))
});
}
async function getFlights({ scope = "visible" }) {
console.log('running getFlights');
let flightsToReturn;
if (scope === "visible") {
const start = currentPage * flightsPerPage;
const end = start + flightsPerPage;
flightsToReturn = filteredFlights.slice(start, end);
} else if (scope === "all") {
flightsToReturn = filteredFlights;
} else {
throw new Error("Invalid scope. Use 'visible' or 'all'");
}
return JSON.stringify({
scope: scope,
totalFlights: filteredFlights.length,
returnedFlights: flightsToReturn.length,
flights: flightsToReturn.map(flight => ({
flightId: flight.flightId,
airline: flight.airline,
price: flight.price,
departure: { time: flight.departTime, airport: flight.origin },
arrival: { time: flight.arriveTime, airport: flight.destination },
duration: flight.duration,
stops: flight.stops,
details: {
aircraft: flight.plane,
legroom: flight.legroom,
inFlightEntertainment: flight.entertainment,
wifi: flight.wifi,
chargingPoints: flight.charging,
lieFlatUpgrade: flight.lieFlat
}
}))
});
}
async function showFlights({ flightIds }) {
console.log('running showFlights');
filteredFlights = allFlights.filter(flight => flightIds.includes(flight.flightId));
currentPage = 0;
document.getElementById('resultsCount').textContent = `${filteredFlights.length} flights found`;
renderFlights();
return JSON.stringify({
displayedFlights: filteredFlights.length,
flightIds: filteredFlights.map(f => f.flightId)
});
}
async function resetFilters() {
console.log('running resetFilters');
filteredFlights = [...allFlights];
currentPage = 0;
document.getElementById('resultsCount').textContent = `${allFlights.length} flights found`;
renderFlights();
return JSON.stringify({
totalFlights: allFlights.length,
message: "All filters reset. Showing all flights."
});
}
// Expose to window for debugging
window.searchFlights = searchFlights;
window.getFlights = getFlights;
window.showFlights = showFlights;
window.resetFilters = resetFilters;
window.is_declarative_tool = window.is_declarative_tool === undefined ? false : window.is_declarative_tool;
// Update model context based on current page
function updateModelContext() {
const supportMessage = document.getElementById('webmcp-support-message');
if (!window.navigator.modelContext) {
supportMessage.innerHTML = 'WebMCP is not enabled in this browser.<br>For Chrome, enable chrome://flags/#enable-experimental-web-platform-features.';
return;
} else {
supportMessage.innerHTML = '';
}
// 1. UNREGISTER EXISTING TOOLS
activeToolNames.forEach(name => window.navigator.modelContext.unregisterTool(name));
activeToolNames = [];
const isResultsPage = !document.getElementById('resultsPage').classList.contains('hidden');
const searchTool = {
execute: withLatency(searchFlights),
name: "search_flights",
description: "Search for available flights between cities. Returns detailed flight information including airline, price, times, stops, duration, aircraft type, amenities, and seat details.",
inputSchema: {
type: "object",
properties: {
origin: { type: "string", description: "The origin city for the flight" },
destination: { type: "string", description: "The destination city for the flight" },
departureDate: { type: "string", description: "The departure date in YYYY-MM-DD format" },
returnDate: { type: "string", description: "The return date in YYYY-MM-DD format. Omit for one-way trips." },
passengers: { type: "number", description: "The number of passengers (1-8)" }
},
required: ["origin", "destination", "departureDate", "passengers"]
}
};
let toolsToRegister = [];
if (isResultsPage) {
toolsToRegister = [
{
execute: withLatency(getFlights),
name: "get_flights",
description: "Get the list of flights. Can return either currently visible flights on the page or all search results.",
inputSchema: {
type: "object",
properties: {
scope: {
type: "string",
enum: ["visible", "all"],
description: "Scope of flights to return.",
default: "visible"
}
}
}
},
{
execute: withLatency(showFlights),
name: "show_flights",
description: "Filter and display only specific flights by their IDs.",
inputSchema: {
type: "object",
properties: {
flightIds: {
type: "array",
items: { type: "string" },
description: "Array of flight IDs to display"
}
},
required: ["flightIds"]
}
},
{
execute: withLatency(resetFilters),
name: "reset_filters",
description: "Remove all filters and show all flights from the original search results.",
inputSchema: { type: "object", properties: {} }
}
];
if (enableToolBugWorkaround && !window.is_declarative_tool) {
toolsToRegister.push(searchTool);
}
} else if (!window.is_declarative_tool) {
toolsToRegister = [searchTool];
}
// 2. REGISTER NEW TOOLS
toolsToRegister.forEach(tool => {
window.navigator.modelContext.registerTool(tool);
activeToolNames.push(tool.name);
});
}
// Initialize
updateModelContext();
// Set minimum date to today
const today = new Date().toISOString().split('T')[0];
document.getElementById('departureDate').setAttribute('min', today);
document.getElementById('returnDate').setAttribute('min', today);
document.getElementById('departureDate').addEventListener('change', function() {
document.getElementById('returnDate').setAttribute('min', this.value);
});
document.getElementById('oneWay').addEventListener('change', function() {
const returnDateGroup = document.getElementById('returnDateGroup');
const returnDateInput = document.getElementById('returnDate');
if (this.checked) {
returnDateGroup.classList.add('hidden');
returnDateInput.value = '';
} else {
returnDateGroup.classList.remove('hidden');
}
});
function generateFlights(origin, destination) {
const flights = [];
for (let i = 0; i < 24; i++) {
const airline = airlines[Math.floor(Math.random() * airlines.length)];
const stops = Math.random() < 0.4 ? 0 : Math.random() < 0.7 ? 1 : 2;
let baseDuration;
if (stops === 0) baseDuration = 120 + Math.floor(Math.random() * 120);
else if (stops === 1) baseDuration = 240 + Math.floor(Math.random() * 120);
else baseDuration = 360 + Math.floor(Math.random() * 180);
const departHour = 6 + Math.floor(Math.random() * 16);
const departMinute = Math.floor(Math.random() * 4) * 15;
const arriveTime = new Date();
arriveTime.setHours(departHour);
arriveTime.setMinutes(departMinute + baseDuration);
const price = 150 + Math.floor(Math.random() * 450);
const hours = Math.floor(baseDuration / 60);
const minutes = baseDuration % 60;
const flightId = `FL${Date.now()}-${i}-${Math.random().toString(36).substr(2, 9)}`;
flights.push({
id: i,
flightId: flightId,
airline: airline,
origin: origin,
destination: destination,
departTime: `${departHour.toString().padStart(2, '0')}:${departMinute.toString().padStart(2, '0')}`,
arriveTime: `${arriveTime.getHours().toString().padStart(2, '0')}:${arriveTime.getMinutes().toString().padStart(2, '0')}`,
duration: hours + 'h ' + minutes + 'm',
stops: stops,
price: price,
plane: planes[Math.floor(Math.random() * planes.length)],
legroom: (28 + Math.floor(Math.random() * 8)) + ' inches',
entertainment: Math.random() < 0.7,
wifi: Math.random() < 0.6,
charging: Math.random() < 0.8,
lieFlat: Math.random() < 0.4
});
}
return flights.sort((a, b) => a.price - b.price);
}
function renderFlights() {
const container = document.getElementById('flightResults');
const start = currentPage * flightsPerPage;
const end = start + flightsPerPage;
const pageFlights = filteredFlights.slice(start, end);
container.innerHTML = pageFlights.map(flight => `
<div class="flight-card">
<div class="flight-header">
<div class="airline-info">
<div class="airline-logo">${flight.airline.substring(0, 2).toUpperCase()}</div>
<span class="airline-name">${flight.airline}</span>
</div>
<div class="price">$${flight.price}</div>
</div>
<div class="flight-details">
<div class="flight-time">
<div class="time">${flight.departTime}</div>
<div class="airport">${flight.origin}</div>
</div>
<div class="flight-path">
<div class="duration">${flight.duration}</div>
<div>————————</div>
<div class="stops">${flight.stops === 0 ? 'Nonstop' : flight.stops + ' stop' + (flight.stops > 1 ? 's' : '')}</div>
</div>
<div class="flight-time">
<div class="time">${flight.arriveTime}</div>
<div class="airport">${flight.destination}</div>
</div>
</div>
<button class="expand-button" onclick="toggleDetails(${flight.id})">
<span id="expand-text-${flight.id}">View Details</span>
</button>
<div class="expanded-details hidden" id="details-${flight.id}">
<div class="detail-grid">
<div class="detail-item"><div><div class="detail-label">Aircraft</div><div class="detail-value">${flight.plane}</div></div></div>
<div class="detail-item"><div><div class="detail-label">Legroom</div><div class="detail-value">${flight.legroom}</div></div></div>
<div class="detail-item"><div><div class="detail-label">IFE</div><div class="detail-value">${flight.entertainment ? '✓' : '✗'}</div></div></div>
<div class="detail-item"><div><div class="detail-label">WiFi</div><div class="detail-value">${flight.wifi ? '✓' : '✗'}</div></div></div>
<div class="detail-item"><div><div class="detail-label">Power</div><div class="detail-value">${flight.charging ? '✓' : '✗'}</div></div></div>
<div class="detail-item"><div><div class="detail-label">Lie-Flat</div><div class="detail-value">${flight.lieFlat ? '✓' : '✗'}</div></div></div>
</div>
</div>
</div>
`).join('');
updatePagination();
}
function toggleDetails(flightId) {
const details = document.getElementById(`details-${flightId}`);
const text = document.getElementById(`expand-text-${flightId}`);
details.classList.toggle('hidden');
text.textContent = details.classList.contains('hidden') ? 'View Details' : 'Hide Details';
}
function updatePagination() {
const totalPages = Math.ceil(filteredFlights.length / flightsPerPage);
document.getElementById('pageInfo').textContent = `Page ${currentPage + 1} of ${totalPages}`;
document.getElementById('prevButton').disabled = currentPage === 0;
document.getElementById('nextButton').disabled = currentPage >= totalPages - 1;
}
document.getElementById('prevButton').addEventListener('click', () => {
if (currentPage > 0) { currentPage--; renderFlights(); window.scrollTo({ top: 0, behavior: 'smooth' }); }
});
document.getElementById('nextButton').addEventListener('click', () => {
const totalPages = Math.ceil(filteredFlights.length / flightsPerPage);
if (currentPage < totalPages - 1) { currentPage++; renderFlights(); window.scrollTo({ top: 0, behavior: 'smooth' }); }
});
document.getElementById('backButton').addEventListener('click', () => history.back());
if (!window.is_declarative_tool) {
document.getElementById('flightForm').addEventListener('submit', function(e) {
e.preventDefault();
searchData = {
origin: document.getElementById('origin').value,
destination: document.getElementById('destination').value,
departureDate: document.getElementById('departureDate').value,
oneWay: document.getElementById('oneWay').checked,
returnDate: document.getElementById('oneWay').checked ? null : document.getElementById('returnDate').value,
passengers: document.getElementById('passengers').value
};
allFlights = generateFlights(searchData.origin, searchData.destination);
filteredFlights = [...allFlights];
currentPage = 0;
document.getElementById('searchPage').classList.add('hidden');
document.getElementById('resultsPage').classList.remove('hidden');
history.pushState({ page: 'results' }, '', '#results');
renderFlights();
updateModelContext();
});
}
window.addEventListener('popstate', (event) => {
if (!window.is_declarative_tool) {
if (event.state && event.state.page === 'results') {
document.getElementById('searchPage').classList.add('hidden');
document.getElementById('resultsPage').classList.remove('hidden');
} else {
document.getElementById('resultsPage').classList.add('hidden');
document.getElementById('searchPage').classList.remove('hidden');
}
updateModelContext();
}
});
function handleUrlParams() {
if (!window.is_declarative_tool) return;
const params = new URLSearchParams(window.location.search);
if (!params.has('origin') || !params.has('destination')) return;
searchFlights({
origin: params.get('origin'),
destination: params.get('destination'),
departureDate: params.get('departureDate'),
returnDate: params.get('returnDate'),
passengers: parseInt(params.get('passengers'))
});
}
handleUrlParams();