-
-
Notifications
You must be signed in to change notification settings - Fork 972
feat: tab templates and geolocation polyfill for webviews #3263
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dp-pcs
wants to merge
6
commits into
wavetermdev:main
Choose a base branch
from
dp-pcs:feat/tab-templates-and-geolocation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
82dc0a9
feat: tab templates and geolocation polyfill for webviews
dp-pcs 792c790
fix: remove geolocation (didn't work), address CodeRabbit review
dp-pcs d94ec6c
refactor: extract applyTabTransition helper, surface template errors
dp-pcs 9921300
fix: always show tab menu so Manage Templates is always accessible
dp-pcs 1117c9a
fix: surface template errors through MessageModal instead of console …
dp-pcs 7dd9e6c
fix: defer scroll update until tabIds state reflects new tab
dp-pcs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| DROP TABLE IF EXISTS db_tabtemplate; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| CREATE TABLE IF NOT EXISTS db_tabtemplate ( | ||
| oid varchar(36) PRIMARY KEY, | ||
| version int NOT NULL, | ||
| data json NOT NULL | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,270 @@ | ||
| // Copyright 2025, Command Line Inc. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import * as electron from "electron"; | ||
| import { spawn } from "child_process"; | ||
| import * as os from "os"; | ||
| import * as path from "path"; | ||
| import * as fs from "fs"; | ||
|
|
||
| interface GeolocationPosition { | ||
| latitude: number; | ||
| longitude: number; | ||
| accuracy: number; | ||
| altitude?: number; | ||
| altitudeAccuracy?: number; | ||
| heading?: number; | ||
| speed?: number; | ||
| } | ||
|
|
||
| interface GeolocationResult { | ||
| success: boolean; | ||
| position?: GeolocationPosition; | ||
| error?: string; | ||
| } | ||
|
|
||
| // Cache for location data (avoid hitting location services too often) | ||
| let cachedLocation: GeolocationPosition | null = null; | ||
| let cacheTimestamp: number = 0; | ||
| const CACHE_DURATION_MS = 60000; // 1 minute cache | ||
|
|
||
| /** | ||
| * Swift helper script for macOS CoreLocation | ||
| * This script requests location authorization and returns current location | ||
| */ | ||
| const SWIFT_LOCATION_SCRIPT = ` | ||
| import CoreLocation | ||
| import Foundation | ||
|
|
||
| class LocationHelper: NSObject, CLLocationManagerDelegate { | ||
| let manager = CLLocationManager() | ||
| let semaphore = DispatchSemaphore(value: 0) | ||
| var result: [String: Any] = ["success": false, "error": "Timeout"] | ||
|
|
||
| override init() { | ||
| super.init() | ||
| manager.delegate = self | ||
| manager.desiredAccuracy = kCLLocationAccuracyBest | ||
| } | ||
|
|
||
| func requestLocation() { | ||
| let status = manager.authorizationStatus | ||
|
|
||
| if status == .notDetermined { | ||
| manager.requestWhenInUseAuthorization() | ||
| // Wait a bit for authorization | ||
| Thread.sleep(forTimeInterval: 0.5) | ||
| } | ||
|
|
||
| let newStatus = manager.authorizationStatus | ||
| if newStatus == .denied || newStatus == .restricted { | ||
| result = ["success": false, "error": "Location access denied"] | ||
| return | ||
| } | ||
|
|
||
| manager.requestLocation() | ||
| _ = semaphore.wait(timeout: .now() + 10) | ||
| } | ||
|
|
||
| func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { | ||
| if let location = locations.last { | ||
| result = [ | ||
| "success": true, | ||
| "latitude": location.coordinate.latitude, | ||
| "longitude": location.coordinate.longitude, | ||
| "accuracy": location.horizontalAccuracy, | ||
| "altitude": location.altitude, | ||
| "altitudeAccuracy": location.verticalAccuracy, | ||
| "heading": location.course, | ||
| "speed": location.speed | ||
| ] | ||
| } | ||
| semaphore.signal() | ||
| } | ||
|
|
||
| func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { | ||
| result = ["success": false, "error": error.localizedDescription] | ||
| semaphore.signal() | ||
| } | ||
| } | ||
|
|
||
| let helper = LocationHelper() | ||
| helper.requestLocation() | ||
|
|
||
| if let jsonData = try? JSONSerialization.data(withJSONObject: helper.result), | ||
| let jsonString = String(data: jsonData, encoding: .utf8) { | ||
| print(jsonString) | ||
| } | ||
| `; | ||
|
|
||
| /** | ||
| * Get location using macOS CoreLocation via Swift | ||
| */ | ||
| async function getMacOSLocation(): Promise<GeolocationResult> { | ||
| return new Promise((resolve) => { | ||
| const tmpDir = os.tmpdir(); | ||
| const scriptPath = path.join(tmpDir, "wave-location-helper.swift"); | ||
|
|
||
| // Write the Swift script to temp | ||
| fs.writeFileSync(scriptPath, SWIFT_LOCATION_SCRIPT); | ||
|
|
||
| // Execute with swift | ||
| const proc = spawn("swift", [scriptPath], { | ||
| timeout: 15000, | ||
| }); | ||
|
|
||
| let stdout = ""; | ||
| let stderr = ""; | ||
|
|
||
| proc.stdout.on("data", (data) => { | ||
| stdout += data.toString(); | ||
| }); | ||
|
|
||
| proc.stderr.on("data", (data) => { | ||
| stderr += data.toString(); | ||
| }); | ||
|
|
||
| proc.on("close", (code) => { | ||
| // Clean up temp file | ||
| try { | ||
| fs.unlinkSync(scriptPath); | ||
| } catch (e) { | ||
| // Ignore cleanup errors | ||
| } | ||
|
|
||
| if (code !== 0) { | ||
| console.log("[geolocation] Swift helper failed:", stderr); | ||
| resolve({ success: false, error: `Swift execution failed: ${stderr}` }); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| const result = JSON.parse(stdout.trim()); | ||
| if (result.success) { | ||
| resolve({ | ||
| success: true, | ||
| position: { | ||
| latitude: result.latitude, | ||
| longitude: result.longitude, | ||
| accuracy: result.accuracy, | ||
| altitude: result.altitude, | ||
| altitudeAccuracy: result.altitudeAccuracy, | ||
| heading: result.heading >= 0 ? result.heading : undefined, | ||
| speed: result.speed >= 0 ? result.speed : undefined, | ||
| }, | ||
| }); | ||
| } else { | ||
| resolve({ success: false, error: result.error }); | ||
| } | ||
| } catch (e) { | ||
| console.log("[geolocation] Failed to parse Swift output:", stdout); | ||
| resolve({ success: false, error: "Failed to parse location data" }); | ||
| } | ||
| }); | ||
|
|
||
| proc.on("error", (err) => { | ||
| console.log("[geolocation] Failed to spawn Swift:", err); | ||
| resolve({ success: false, error: err.message }); | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Fallback: IP-based geolocation using free API | ||
| */ | ||
| async function getIPBasedLocation(): Promise<GeolocationResult> { | ||
| try { | ||
| // Use multiple free IP geolocation services as fallback | ||
| const response = await fetch("https://ipapi.co/json/", { | ||
| headers: { "User-Agent": "WaveTerm" }, | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error(`HTTP ${response.status}`); | ||
| } | ||
|
|
||
| const data = await response.json(); | ||
|
|
||
| if (data.latitude && data.longitude) { | ||
| return { | ||
| success: true, | ||
| position: { | ||
| latitude: data.latitude, | ||
| longitude: data.longitude, | ||
| accuracy: 10000, // IP-based is ~city level accuracy | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| return { success: false, error: "No location in response" }; | ||
| } catch (e) { | ||
| console.log("[geolocation] IP-based lookup failed:", e); | ||
| return { success: false, error: e.message }; | ||
| } | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. IP-based geolocation missing timeout and has privacy implications.
🛡️ Add timeout to fetch call async function getIPBasedLocation(): Promise<GeolocationResult> {
try {
// Use multiple free IP geolocation services as fallback
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 10000);
+
const response = await fetch("https://ipapi.co/json/", {
headers: { "User-Agent": "WaveTerm" },
+ signal: controller.signal,
});
+ clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}🤖 Prompt for AI Agents |
||
|
|
||
| /** | ||
| * Get current location with caching | ||
| */ | ||
| export async function getCurrentPosition(): Promise<GeolocationResult> { | ||
| // Check cache first | ||
| const now = Date.now(); | ||
| if (cachedLocation && (now - cacheTimestamp) < CACHE_DURATION_MS) { | ||
| console.log("[geolocation] Returning cached location"); | ||
| return { success: true, position: cachedLocation }; | ||
| } | ||
|
|
||
| let result: GeolocationResult; | ||
|
|
||
| // Try platform-specific location first | ||
| if (process.platform === "darwin") { | ||
| console.log("[geolocation] Attempting macOS CoreLocation..."); | ||
| result = await getMacOSLocation(); | ||
|
|
||
| if (result.success) { | ||
| console.log("[geolocation] CoreLocation succeeded"); | ||
| cachedLocation = result.position; | ||
| cacheTimestamp = now; | ||
| return result; | ||
| } | ||
| console.log("[geolocation] CoreLocation failed:", result.error); | ||
| } | ||
|
|
||
| // Fallback to IP-based geolocation | ||
| console.log("[geolocation] Falling back to IP-based geolocation..."); | ||
| result = await getIPBasedLocation(); | ||
|
|
||
| if (result.success) { | ||
| console.log("[geolocation] IP-based geolocation succeeded"); | ||
| cachedLocation = result.position; | ||
| cacheTimestamp = now; | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * Configure geolocation for webview sessions | ||
| * This injects a custom geolocation provider into webviews | ||
| */ | ||
| export function configureGeolocationForSession(session: electron.Session) { | ||
| // We'll inject a polyfill into webviews that calls back to the main process | ||
| // for geolocation data instead of relying on Chromium's built-in provider | ||
|
|
||
| session.webRequest.onBeforeRequest({ urls: ["*://*/*"] }, (details, callback) => { | ||
| callback({}); | ||
| }); | ||
|
|
||
| console.log("[geolocation] Session configured for geolocation support"); | ||
| } | ||
|
|
||
| /** | ||
| * IPC handler for geolocation requests from renderer/webview | ||
| */ | ||
| export function registerGeolocationIPC() { | ||
| electron.ipcMain.handle("get-geolocation", async () => { | ||
| return getCurrentPosition(); | ||
| }); | ||
|
|
||
| console.log("[geolocation] IPC handler registered"); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.