dsh-gufa-code 1.3.6 → 1.3.7

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.
package/README.md CHANGED
@@ -73,6 +73,7 @@ dsh plugin add dsh-gufa-code
73
73
  - 把该 App 切到前台(主窗口自动被盖住,等于「隐藏主窗口」);
74
74
  - 以**无边框、半透明(0.55)、永远置顶**的独立悬浮窗出现,并**自动吸附**到该 App 当前窗口:位置、大小一致,窗口移动/缩放时实时跟随。
75
75
  - 读取窗口位置/大小走 macOS **「辅助功能」**权限(不是屏幕录制):系统设置 → 隐私与安全性 → 辅助功能 → 勾选 **DeepSeek Harness**;改完重启一次 DSH 生效。
76
+ - **状态延续**:进入摸鱼时会把主窗口的项目、已打开标签页、界面布局、当前会话一并带进悬浮层,悬浮窗里接着干活而不是从空白开始。
76
77
  - **悬浮层交互**:
77
78
  - 顶部 22px 拖动条移动窗口(右键 = 摸鱼菜单),窗口大小/位置会记住;
78
79
  - 全局快捷键 **⌃⌥⌘G**:切换点击穿透(穿透后鼠标直接操作下面的 App,再按一次切回来);
package/client.js CHANGED
@@ -46,6 +46,30 @@ G.portal = (function createPortalHelper() {
46
46
  })()
47
47
  G.hooks = { useState, useEffect, useRef, useMemo, useCallback, useLayoutEffect }
48
48
 
49
+ /* ── 悬浮层状态:helper 通过 URL 参数 ?gufa-state=<base64url(JSON)> 传主窗口快照 ── */
50
+ G.floatState = (function readFloatState() {
51
+ if (typeof window === 'undefined' || typeof document === 'undefined') return null
52
+ try {
53
+ const raw = new URLSearchParams(window.location.search).get('gufa-state')
54
+ if (raw === null || raw === '') {
55
+ try {
56
+ const stored = localStorage.getItem('gufa-code:float-state')
57
+ return stored === null ? null : JSON.parse(stored)
58
+ } catch {
59
+ return null
60
+ }
61
+ }
62
+ const base64 = raw.replace(/-/g, '+').replace(/_/g, '/')
63
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4)
64
+ const binary = atob(padded)
65
+ const bytes = Uint8Array.from(binary, (chunk) => chunk.charCodeAt(0))
66
+ const text = new TextDecoder().decode(bytes)
67
+ return JSON.parse(text)
68
+ } catch {
69
+ return null
70
+ }
71
+ })()
72
+
49
73
  /* ── 事件总线(零件之间解耦:SSH → 终端 发送命令等) ───────────────────── */
50
74
  G.bus = (function createBus() {
51
75
  const listeners = new Map()
@@ -9670,7 +9694,9 @@ G.GufaApp = function GufaApp(props) {
9670
9694
  bootedRef.current = true
9671
9695
  let cancelled = false
9672
9696
  void (async () => {
9673
- const saved = readJson(GUFA_LS.project)
9697
+ const saved = floatState !== null && floatState !== undefined && typeof floatState.projectRoot === 'string' && floatState.projectRoot !== ''
9698
+ ? floatState.projectRoot
9699
+ : readJson(GUFA_LS.project)
9674
9700
  if (typeof saved === 'string' && saved !== '') {
9675
9701
  try {
9676
9702
  const value = await G.api('project.open', { path: saved })
@@ -9680,6 +9706,7 @@ G.GufaApp = function GufaApp(props) {
9680
9706
  writeJson(GUFA_LS.project, null)
9681
9707
  }
9682
9708
  }
9709
+ if (G.floatState !== null && G.floatState !== undefined) return
9683
9710
  if (typeof sessionCwd === 'string' && sessionCwd !== '') {
9684
9711
  try {
9685
9712
  const value = await G.api('project.open', { path: sessionCwd })
@@ -10288,12 +10315,23 @@ G.GufaApp = function GufaApp(props) {
10288
10315
  if (floatBusy || target === null || target === undefined) return
10289
10316
  setFloatBusy(true)
10290
10317
  try {
10318
+ const floatState = {
10319
+ projectRoot: project !== null && typeof project.root === 'string' ? project.root : null,
10320
+ activePath: typeof activePath === 'string' ? activePath : null,
10321
+ tabs: tabs
10322
+ .filter((tab) => tab !== null && tab !== undefined && typeof tab.path === 'string' && tab.kind !== 'diff' && tab.kind !== 'graph')
10323
+ .map((tab) => tab.path)
10324
+ .slice(0, 10),
10325
+ ui: readJson(GUFA_LS.ui) ?? {},
10326
+ sessionId: typeof currentSessionId === 'string' ? currentSessionId : null,
10327
+ }
10291
10328
  const value = await G.api('float.start', {
10292
10329
  follow: {
10293
10330
  pid: Number(target.pid) || 0,
10294
10331
  bundleId: typeof target.bundleId === 'string' ? target.bundleId : '',
10295
10332
  title: '',
10296
10333
  },
10334
+ state: floatState,
10297
10335
  })
10298
10336
  setFloatRunning(value?.running === true)
10299
10337
  setFloatPicker(null)
@@ -10333,6 +10371,7 @@ G.GufaApp = function GufaApp(props) {
10333
10371
  const dockSyncRef = useRef('')
10334
10372
  useEffect(() => {
10335
10373
  if (sessionPinnedRef.current === true) return undefined
10374
+ if (G.floatState !== null && G.floatState !== undefined) return undefined
10336
10375
  if (project === null || typeof project.root !== 'string' || project.root === '') return undefined
10337
10376
  if (dockSyncRef.current === project.root) return undefined
10338
10377
  if (typeof sessionCwd === 'string' && sessionCwd !== '' && sessionCwd === project.root) {
@@ -10377,6 +10416,11 @@ G.GufaApp = function GufaApp(props) {
10377
10416
  const entryWorkspaceSyncedRef = useRef(false)
10378
10417
  useEffect(() => {
10379
10418
  if (entryWorkspaceSyncedRef.current) return
10419
+ /* 悬浮层:项目/会话由主窗口状态注入,不做「入口工作区」同步,避免被会话 cwd 覆盖 */
10420
+ if (G.floatState !== null && G.floatState !== undefined) {
10421
+ entryWorkspaceSyncedRef.current = true
10422
+ return
10423
+ }
10380
10424
  if (project === null) return
10381
10425
  const pending = G.pendingEntryWorkspace
10382
10426
  if (pending === null || pending === undefined || typeof pending.key !== 'string') {
@@ -10695,6 +10739,11 @@ G.GufaApp = function GufaApp(props) {
10695
10739
  const lastSessionCwdRef = useRef(null)
10696
10740
  useEffect(() => {
10697
10741
  if (sessionPinnedRef.current === true) return
10742
+ /* 悬浮层里项目由主窗口状态注入,不跟随(Web 版客户端自己的)会话 cwd 切换 */
10743
+ if (G.floatState !== null && G.floatState !== undefined) {
10744
+ lastSessionCwdRef.current = sessionCwd
10745
+ return
10746
+ }
10698
10747
  if (typeof sessionCwd !== 'string' || sessionCwd === '') return
10699
10748
  const previous = lastSessionCwdRef.current
10700
10749
  lastSessionCwdRef.current = sessionCwd
@@ -10889,6 +10938,38 @@ G.GufaApp = function GufaApp(props) {
10889
10938
  })()
10890
10939
  }, [project])
10891
10940
 
10941
+ /* 悬浮窗:恢复主窗口带过来的打开的标签页(只恢复普通文件,diff/graph 跳过) */
10942
+ const floatTabsRestoredRef = useRef(false)
10943
+ useEffect(() => {
10944
+ if (floatTabsRestoredRef.current) return
10945
+ if (project === null) return
10946
+ let state = null
10947
+ state = G.floatState
10948
+ if (state === null || typeof state !== 'object') return
10949
+ floatTabsRestoredRef.current = true
10950
+ const paths = Array.isArray(state.tabs) ? state.tabs.filter((path) => typeof path === 'string' && path !== '') : []
10951
+ const ordered = paths.filter((path) => path !== state.activePath).concat(
10952
+ typeof state.activePath === 'string' && state.activePath !== '' ? [state.activePath] : [],
10953
+ )
10954
+ void (async () => {
10955
+ for (const path of ordered.slice(0, 10)) {
10956
+ try {
10957
+ await openFile(path)
10958
+ } catch {
10959
+ /* 文件可能已被删除,忽略 */
10960
+ }
10961
+ }
10962
+ })()
10963
+ }, [project, openFile])
10964
+
10965
+ /* 悬浮层恢复入口:主窗口把状态带过来后,由 99-main 显式调用(不依赖 App 自己的启动时序) */
10966
+ useEffect(() => {
10967
+ G.floatRestoreRef = { applyProject, openFile }
10968
+ return () => {
10969
+ if (G.floatRestoreRef !== undefined && G.floatRestoreRef !== null && G.floatRestoreRef.applyProject === applyProject) G.floatRestoreRef = null
10970
+ }
10971
+ }, [applyProject, openFile])
10972
+
10892
10973
  const activeFileForChat = useMemo(() => {
10893
10974
  if (activeTab === null || activeTab.kind === 'diff' || activeTab.kind === 'graph') return null
10894
10975
  return { path: activeTab.path, content: activeTab.content ?? '', language: activeTab.language }
@@ -12247,6 +12328,67 @@ const GUFA_PLUGIN = {
12247
12328
  if (document.querySelector('.gufa-overlay-root') !== null || attempts > 40) {
12248
12329
  document.documentElement.removeAttribute('data-gufa-booting')
12249
12330
  window.clearInterval(timer)
12331
+ /* 显式恢复主窗口状态(项目 → 标签页 → 会话),避免依赖 Web 版 App 的启动时序 */
12332
+ try {
12333
+ if (window.__gufaFloatRestored !== true && G.floatState !== null && G.floatState !== undefined) {
12334
+ window.__gufaFloatRestored = true
12335
+ void (async () => {
12336
+ const state = G.floatState
12337
+ let projectValue = null
12338
+ if (typeof state.projectRoot === 'string' && state.projectRoot !== '') {
12339
+ try {
12340
+ projectValue = await G.api('project.open', { path: state.projectRoot })
12341
+ } catch {
12342
+ projectValue = null
12343
+ }
12344
+ }
12345
+ const restore = G.floatRestoreRef
12346
+ if (projectValue !== null && restore !== null && restore !== undefined && typeof restore.applyProject === 'function') {
12347
+ restore.applyProject(projectValue)
12348
+ }
12349
+ await new Promise((resolve) => setTimeout(resolve, 350))
12350
+ const paths = Array.isArray(state.tabs) ? state.tabs.filter((path) => typeof path === 'string' && path !== '') : []
12351
+ const ordered = typeof state.activePath === 'string' && state.activePath !== ''
12352
+ ? paths.filter((path) => path !== state.activePath).concat([state.activePath])
12353
+ : paths
12354
+ const openFile = restore !== null && restore !== undefined && typeof restore.openFile === 'function' ? restore.openFile : null
12355
+ if (openFile !== null) {
12356
+ for (const path of ordered.slice(0, 10)) {
12357
+ try {
12358
+ await openFile(path)
12359
+ } catch {
12360
+ /* ignore */
12361
+ }
12362
+ }
12363
+ }
12364
+ if (typeof state.sessionId === 'string' && state.sessionId !== '') {
12365
+ try {
12366
+ const workspace = G.ctx === null || G.ctx === undefined ? undefined : G.ctx.get('uiWorkspace')
12367
+ if (workspace !== undefined && workspace !== null && typeof workspace.openSession === 'function') workspace.openSession(state.sessionId)
12368
+ } catch {
12369
+ /* ignore */
12370
+ }
12371
+ }
12372
+ })()
12373
+ }
12374
+ } catch {
12375
+ /* ignore */
12376
+ }
12377
+ /* 恢复主窗口带过来的当前会话(悬浮窗是独立客户端实例,需要主动选中同一会话) */
12378
+ try {
12379
+ const parsedState = G.floatState
12380
+ const sessionId = parsedState !== null && typeof parsedState.sessionId === 'string' ? parsedState.sessionId : ''
12381
+ if (sessionId !== '') {
12382
+ const workspace = G.ctx === null || G.ctx === undefined ? undefined : G.ctx.get('uiWorkspace')
12383
+ if (workspace !== undefined && workspace !== null && typeof workspace.openSession === 'function') {
12384
+ window.setTimeout(() => {
12385
+ try { workspace.openSession(sessionId) } catch { /* ignore */ }
12386
+ }, 600)
12387
+ }
12388
+ }
12389
+ } catch {
12390
+ /* ignore */
12391
+ }
12250
12392
  }
12251
12393
  }, 250)
12252
12394
  ctx.effect(() => () => {
@@ -244,10 +244,12 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
244
244
  self.window.opaque = NO;
245
245
  self.window.backgroundColor = NSColor.clearColor;
246
246
  self.window.hasShadow = YES;
247
- self.window.level = NSFloatingWindowLevel + 1;
247
+ /* 高于普通浮动窗口(歌词、置顶小工具等),确保真正盖住被跟随的 App */
248
+ self.window.level = NSStatusWindowLevel;
248
249
  self.window.collectionBehavior = (NSWindowCollectionBehaviorCanJoinAllSpaces
249
250
  | NSWindowCollectionBehaviorFullScreenAuxiliary
250
- | NSWindowCollectionBehaviorStationary);
251
+ | NSWindowCollectionBehaviorStationary
252
+ | NSWindowCollectionBehaviorIgnoresCycle);
251
253
  self.window.minSize = NSMakeSize(520, 360);
252
254
  self.window.title = @"古法编程悬浮层";
253
255
 
@@ -257,8 +259,39 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
257
259
 
258
260
  WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
259
261
  config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
260
- /* URL query 可能被 DSH 的浏览器端路由吞掉,这里在文档开始前写一个标记,客户端据此进入悬浮模式 */
261
- WKUserScript *floatMarker = [[WKUserScript alloc] initWithSource:@"try{localStorage.setItem('gufa-code:float','1')}catch(e){}"
262
+ /* 文档开始前注入:悬浮模式标记 + 主窗口状态(项目/UI 布局/打开的标签页/会话),
263
+ 让悬浮窗里的古法编程「接着主窗口继续干活」,而不是一个空白的新实例。 */
264
+ NSMutableString *bootstrap = [NSMutableString stringWithString:@"try{localStorage.setItem('gufa-code:float','1');"];
265
+ NSDictionary *state = [self.options[@"state"] isKindOfClass:[NSDictionary class]] ? self.options[@"state"] : nil;
266
+ if (state != nil) {
267
+ NSData *stateJson = [NSJSONSerialization dataWithJSONObject:state options:0 error:NULL];
268
+ if (stateJson != nil) {
269
+ NSString *stateText = [[NSString alloc] initWithData:stateJson encoding:NSUTF8StringEncoding];
270
+ NSString *escaped = [stateText stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
271
+ escaped = [escaped stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
272
+ escaped = [escaped stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
273
+ escaped = [escaped stringByReplacingOccurrencesOfString:@"\r" withString:@""];
274
+ [bootstrap appendFormat:@"localStorage.setItem('gufa-code:float-state','%@');", escaped];
275
+ NSString *projectRoot = [state[@"projectRoot"] isKindOfClass:[NSString class]] ? state[@"projectRoot"] : @"";
276
+ if (projectRoot.length > 0) {
277
+ NSString *projectEscaped = [projectRoot stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
278
+ projectEscaped = [projectEscaped stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
279
+ [bootstrap appendFormat:@"localStorage.setItem('gufa-code:project','\"%@\"');", projectEscaped];
280
+ }
281
+ NSDictionary *ui = [state[@"ui"] isKindOfClass:[NSDictionary class]] ? state[@"ui"] : nil;
282
+ if (ui != nil) {
283
+ NSData *uiJson = [NSJSONSerialization dataWithJSONObject:ui options:0 error:NULL];
284
+ if (uiJson != nil) {
285
+ NSString *uiText = [[NSString alloc] initWithData:uiJson encoding:NSUTF8StringEncoding];
286
+ NSString *uiEscaped = [uiText stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
287
+ uiEscaped = [uiEscaped stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
288
+ [bootstrap appendFormat:@"localStorage.setItem('gufa-code:ui:v1','%@');", uiEscaped];
289
+ }
290
+ }
291
+ }
292
+ }
293
+ [bootstrap appendString:@"}catch(e){}"];
294
+ WKUserScript *floatMarker = [[WKUserScript alloc] initWithSource:bootstrap
262
295
  injectionTime:WKUserScriptInjectionTimeAtDocumentStart
263
296
  forMainFrameOnly:YES];
264
297
  [config.userContentController addUserScript:floatMarker];
@@ -317,14 +350,28 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
317
350
  self.navigation.pendingLoad = ^{
318
351
  __strong typeof(weakSelf) self = weakSelf;
319
352
  if (self == nil) return;
320
- NSURLComponents *components = [NSURLComponents componentsWithString:appUrl];
321
- components.queryItems = @[[NSURLQueryItem queryItemWithName:@"gufa-float" value:@"1"]];
322
- NSURL *clean = components.URL;
323
- if (clean != nil && ![clean.absoluteString isEqualToString:self.webView.URL.absoluteString]) {
324
- [self.webView loadRequest:[NSURLRequest requestWithURL:clean]];
353
+ /* 鉴权 cookie 已在 token URL 重定向时写入;这里用 JS 写 localStorage(避开 URL 长度/转义问题),
354
+ 再跳到带 gufa-float 标记的干净地址,客户端据此自动进入摸鱼模式并恢复状态。 */
355
+ NSMutableString *js = [NSMutableString stringWithString:@"try{"];
356
+ NSDictionary *state = [self.options[@"state"] isKindOfClass:[NSDictionary class]] ? self.options[@"state"] : nil;
357
+ if (state != nil) {
358
+ NSData *stateJson = [NSJSONSerialization dataWithJSONObject:state options:0 error:NULL];
359
+ NSString *stateText = stateJson != nil ? [[NSString alloc] initWithData:stateJson encoding:NSUTF8StringEncoding] : @"";
360
+ if (stateText.length > 0) {
361
+ NSData *quoted = [NSJSONSerialization dataWithJSONObject:@[stateText] options:0 error:NULL];
362
+ NSString *arrayLiteral = quoted != nil ? [[NSString alloc] initWithData:quoted encoding:NSUTF8StringEncoding] : @"[]";
363
+ /* arrayLiteral = ["{\"projectRoot\":...}"] */
364
+ if (arrayLiteral.length >= 2) {
365
+ NSString *stateLiteral = [arrayLiteral substringWithRange:NSMakeRange(1, arrayLiteral.length - 2)];
366
+ [js appendFormat:@"localStorage.setItem('gufa-code:float-state', %@);", stateLiteral];
367
+ }
368
+ }
325
369
  }
370
+ [js appendString:@"localStorage.setItem('gufa-code:float','1');location.href='/?gufa-float=1';}catch(e){}"];
371
+ [self.webView evaluateJavaScript:js completionHandler:nil];
326
372
  };
327
373
  [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:authUrl]]];
374
+
328
375
  }
329
376
 
330
377
  - (void)saveFrame {
@@ -386,8 +433,12 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
386
433
  self.statusItem.button.title = self.clickThrough ? @"古法·穿透" : @"古法";
387
434
  }
388
435
 
436
+ /* 只重启定时器,不动 following/窗口引用(stopFollowTimer 会清状态,不能在这里调) */
389
437
  - (void)startFollowTimer {
390
- [self stopFollowTimer];
438
+ if (self.followTimer != nil) {
439
+ [self.followTimer invalidate];
440
+ self.followTimer = nil;
441
+ }
391
442
  __weak typeof(self) weakSelf = self;
392
443
  self.followTimer = [NSTimer scheduledTimerWithTimeInterval:0.25 repeats:YES block:^(NSTimer *timer) {
393
444
  __strong typeof(weakSelf) self = weakSelf;
@@ -427,7 +478,18 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
427
478
  }
428
479
  CGFloat screenHeight = NSScreen.mainScreen.frame.size.height;
429
480
  NSRect frame = NSMakeRect(target.origin.x, screenHeight - target.origin.y - target.size.height, target.size.width, target.size.height);
481
+ static int applyLogCount = 0;
482
+ if (applyLogCount < 6) {
483
+ applyLogCount += 1;
484
+ GufaLog(@"follow-apply target=%.0f,%.0f %.0fx%.0f -> frame=%.0f,%.0f %.0fx%.0f", target.origin.x, target.origin.y, target.size.width, target.size.height, frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
485
+ }
430
486
  [self.window setFrame:frame display:YES animate:NO];
487
+ static int verifyLogCount = 0;
488
+ if (verifyLogCount < 3) {
489
+ verifyLogCount += 1;
490
+ NSRect actual = self.window.frame;
491
+ GufaLog(@"follow-applied actual=%.0f,%.0f %.0fx%.0f", actual.origin.x, actual.origin.y, actual.size.width, actual.size.height);
492
+ }
431
493
  }
432
494
 
433
495
  /* 全局快捷键 ⌃⌥⌘G(四键,避免冲突):穿透后窗口收不到鼠标事件,靠它切回来(Carbon 热键不需要辅助功能权限) */
package/host/dev.js CHANGED
@@ -45,6 +45,7 @@ export function register(router, env) {
45
45
  const startedAt = new Date().toISOString()
46
46
  const ctx = env?.ctx ?? router.ctx
47
47
 
48
+
48
49
  /* ── 桌面悬浮层 / 摸鱼模式(macOS) ────────────────────────────────
49
50
  * 通过 .app bundle 启动 helper:TCC(屏幕录制)按 bundle 身份授权,
50
51
  * 用户在「系统设置 → 隐私与安全性 → 屏幕录制」里添加「古法编程悬浮层.app」即可。
@@ -212,7 +213,13 @@ export function register(router, env) {
212
213
  }
213
214
  const base = `${webServer.protocol}//127.0.0.1:${String(webServer.port)}`
214
215
  const authUrl = connection.authenticatedUrl(`${base}/`)
215
- const payload = JSON.stringify({ authUrl, appUrl: `${base}/`, follow: follow !== null && follow.pid > 0 ? follow : undefined })
216
+ const state = body !== null && typeof body === 'object' && body.state !== null && typeof body.state === 'object' ? body.state : null
217
+ const payload = JSON.stringify({
218
+ authUrl,
219
+ appUrl: `${base}/`,
220
+ follow: follow !== null && follow.pid > 0 ? follow : undefined,
221
+ state: state ?? undefined,
222
+ })
216
223
  const binary = floatBinaryPath()
217
224
  if (binary === null) throw new ApiError('missing-helper', '悬浮层程序未构建', 500)
218
225
  const child = spawn(binary, [payload], { detached: true, stdio: 'ignore' })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.6",
3
+ "version": "1.3.7",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -38,6 +38,30 @@ G.portal = (function createPortalHelper() {
38
38
  })()
39
39
  G.hooks = { useState, useEffect, useRef, useMemo, useCallback, useLayoutEffect }
40
40
 
41
+ /* ── 悬浮层状态:helper 通过 URL 参数 ?gufa-state=<base64url(JSON)> 传主窗口快照 ── */
42
+ G.floatState = (function readFloatState() {
43
+ if (typeof window === 'undefined' || typeof document === 'undefined') return null
44
+ try {
45
+ const raw = new URLSearchParams(window.location.search).get('gufa-state')
46
+ if (raw === null || raw === '') {
47
+ try {
48
+ const stored = localStorage.getItem('gufa-code:float-state')
49
+ return stored === null ? null : JSON.parse(stored)
50
+ } catch {
51
+ return null
52
+ }
53
+ }
54
+ const base64 = raw.replace(/-/g, '+').replace(/_/g, '/')
55
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4)
56
+ const binary = atob(padded)
57
+ const bytes = Uint8Array.from(binary, (chunk) => chunk.charCodeAt(0))
58
+ const text = new TextDecoder().decode(bytes)
59
+ return JSON.parse(text)
60
+ } catch {
61
+ return null
62
+ }
63
+ })()
64
+
41
65
  /* ── 事件总线(零件之间解耦:SSH → 终端 发送命令等) ───────────────────── */
42
66
  G.bus = (function createBus() {
43
67
  const listeners = new Map()
@@ -253,7 +253,9 @@ G.GufaApp = function GufaApp(props) {
253
253
  bootedRef.current = true
254
254
  let cancelled = false
255
255
  void (async () => {
256
- const saved = readJson(GUFA_LS.project)
256
+ const saved = floatState !== null && floatState !== undefined && typeof floatState.projectRoot === 'string' && floatState.projectRoot !== ''
257
+ ? floatState.projectRoot
258
+ : readJson(GUFA_LS.project)
257
259
  if (typeof saved === 'string' && saved !== '') {
258
260
  try {
259
261
  const value = await G.api('project.open', { path: saved })
@@ -263,6 +265,7 @@ G.GufaApp = function GufaApp(props) {
263
265
  writeJson(GUFA_LS.project, null)
264
266
  }
265
267
  }
268
+ if (G.floatState !== null && G.floatState !== undefined) return
266
269
  if (typeof sessionCwd === 'string' && sessionCwd !== '') {
267
270
  try {
268
271
  const value = await G.api('project.open', { path: sessionCwd })
@@ -871,12 +874,23 @@ G.GufaApp = function GufaApp(props) {
871
874
  if (floatBusy || target === null || target === undefined) return
872
875
  setFloatBusy(true)
873
876
  try {
877
+ const floatState = {
878
+ projectRoot: project !== null && typeof project.root === 'string' ? project.root : null,
879
+ activePath: typeof activePath === 'string' ? activePath : null,
880
+ tabs: tabs
881
+ .filter((tab) => tab !== null && tab !== undefined && typeof tab.path === 'string' && tab.kind !== 'diff' && tab.kind !== 'graph')
882
+ .map((tab) => tab.path)
883
+ .slice(0, 10),
884
+ ui: readJson(GUFA_LS.ui) ?? {},
885
+ sessionId: typeof currentSessionId === 'string' ? currentSessionId : null,
886
+ }
874
887
  const value = await G.api('float.start', {
875
888
  follow: {
876
889
  pid: Number(target.pid) || 0,
877
890
  bundleId: typeof target.bundleId === 'string' ? target.bundleId : '',
878
891
  title: '',
879
892
  },
893
+ state: floatState,
880
894
  })
881
895
  setFloatRunning(value?.running === true)
882
896
  setFloatPicker(null)
@@ -916,6 +930,7 @@ G.GufaApp = function GufaApp(props) {
916
930
  const dockSyncRef = useRef('')
917
931
  useEffect(() => {
918
932
  if (sessionPinnedRef.current === true) return undefined
933
+ if (G.floatState !== null && G.floatState !== undefined) return undefined
919
934
  if (project === null || typeof project.root !== 'string' || project.root === '') return undefined
920
935
  if (dockSyncRef.current === project.root) return undefined
921
936
  if (typeof sessionCwd === 'string' && sessionCwd !== '' && sessionCwd === project.root) {
@@ -960,6 +975,11 @@ G.GufaApp = function GufaApp(props) {
960
975
  const entryWorkspaceSyncedRef = useRef(false)
961
976
  useEffect(() => {
962
977
  if (entryWorkspaceSyncedRef.current) return
978
+ /* 悬浮层:项目/会话由主窗口状态注入,不做「入口工作区」同步,避免被会话 cwd 覆盖 */
979
+ if (G.floatState !== null && G.floatState !== undefined) {
980
+ entryWorkspaceSyncedRef.current = true
981
+ return
982
+ }
963
983
  if (project === null) return
964
984
  const pending = G.pendingEntryWorkspace
965
985
  if (pending === null || pending === undefined || typeof pending.key !== 'string') {
@@ -1278,6 +1298,11 @@ G.GufaApp = function GufaApp(props) {
1278
1298
  const lastSessionCwdRef = useRef(null)
1279
1299
  useEffect(() => {
1280
1300
  if (sessionPinnedRef.current === true) return
1301
+ /* 悬浮层里项目由主窗口状态注入,不跟随(Web 版客户端自己的)会话 cwd 切换 */
1302
+ if (G.floatState !== null && G.floatState !== undefined) {
1303
+ lastSessionCwdRef.current = sessionCwd
1304
+ return
1305
+ }
1281
1306
  if (typeof sessionCwd !== 'string' || sessionCwd === '') return
1282
1307
  const previous = lastSessionCwdRef.current
1283
1308
  lastSessionCwdRef.current = sessionCwd
@@ -1472,6 +1497,38 @@ G.GufaApp = function GufaApp(props) {
1472
1497
  })()
1473
1498
  }, [project])
1474
1499
 
1500
+ /* 悬浮窗:恢复主窗口带过来的打开的标签页(只恢复普通文件,diff/graph 跳过) */
1501
+ const floatTabsRestoredRef = useRef(false)
1502
+ useEffect(() => {
1503
+ if (floatTabsRestoredRef.current) return
1504
+ if (project === null) return
1505
+ let state = null
1506
+ state = G.floatState
1507
+ if (state === null || typeof state !== 'object') return
1508
+ floatTabsRestoredRef.current = true
1509
+ const paths = Array.isArray(state.tabs) ? state.tabs.filter((path) => typeof path === 'string' && path !== '') : []
1510
+ const ordered = paths.filter((path) => path !== state.activePath).concat(
1511
+ typeof state.activePath === 'string' && state.activePath !== '' ? [state.activePath] : [],
1512
+ )
1513
+ void (async () => {
1514
+ for (const path of ordered.slice(0, 10)) {
1515
+ try {
1516
+ await openFile(path)
1517
+ } catch {
1518
+ /* 文件可能已被删除,忽略 */
1519
+ }
1520
+ }
1521
+ })()
1522
+ }, [project, openFile])
1523
+
1524
+ /* 悬浮层恢复入口:主窗口把状态带过来后,由 99-main 显式调用(不依赖 App 自己的启动时序) */
1525
+ useEffect(() => {
1526
+ G.floatRestoreRef = { applyProject, openFile }
1527
+ return () => {
1528
+ if (G.floatRestoreRef !== undefined && G.floatRestoreRef !== null && G.floatRestoreRef.applyProject === applyProject) G.floatRestoreRef = null
1529
+ }
1530
+ }, [applyProject, openFile])
1531
+
1475
1532
  const activeFileForChat = useMemo(() => {
1476
1533
  if (activeTab === null || activeTab.kind === 'diff' || activeTab.kind === 'graph') return null
1477
1534
  return { path: activeTab.path, content: activeTab.content ?? '', language: activeTab.language }
@@ -242,6 +242,67 @@ const GUFA_PLUGIN = {
242
242
  if (document.querySelector('.gufa-overlay-root') !== null || attempts > 40) {
243
243
  document.documentElement.removeAttribute('data-gufa-booting')
244
244
  window.clearInterval(timer)
245
+ /* 显式恢复主窗口状态(项目 → 标签页 → 会话),避免依赖 Web 版 App 的启动时序 */
246
+ try {
247
+ if (window.__gufaFloatRestored !== true && G.floatState !== null && G.floatState !== undefined) {
248
+ window.__gufaFloatRestored = true
249
+ void (async () => {
250
+ const state = G.floatState
251
+ let projectValue = null
252
+ if (typeof state.projectRoot === 'string' && state.projectRoot !== '') {
253
+ try {
254
+ projectValue = await G.api('project.open', { path: state.projectRoot })
255
+ } catch {
256
+ projectValue = null
257
+ }
258
+ }
259
+ const restore = G.floatRestoreRef
260
+ if (projectValue !== null && restore !== null && restore !== undefined && typeof restore.applyProject === 'function') {
261
+ restore.applyProject(projectValue)
262
+ }
263
+ await new Promise((resolve) => setTimeout(resolve, 350))
264
+ const paths = Array.isArray(state.tabs) ? state.tabs.filter((path) => typeof path === 'string' && path !== '') : []
265
+ const ordered = typeof state.activePath === 'string' && state.activePath !== ''
266
+ ? paths.filter((path) => path !== state.activePath).concat([state.activePath])
267
+ : paths
268
+ const openFile = restore !== null && restore !== undefined && typeof restore.openFile === 'function' ? restore.openFile : null
269
+ if (openFile !== null) {
270
+ for (const path of ordered.slice(0, 10)) {
271
+ try {
272
+ await openFile(path)
273
+ } catch {
274
+ /* ignore */
275
+ }
276
+ }
277
+ }
278
+ if (typeof state.sessionId === 'string' && state.sessionId !== '') {
279
+ try {
280
+ const workspace = G.ctx === null || G.ctx === undefined ? undefined : G.ctx.get('uiWorkspace')
281
+ if (workspace !== undefined && workspace !== null && typeof workspace.openSession === 'function') workspace.openSession(state.sessionId)
282
+ } catch {
283
+ /* ignore */
284
+ }
285
+ }
286
+ })()
287
+ }
288
+ } catch {
289
+ /* ignore */
290
+ }
291
+ /* 恢复主窗口带过来的当前会话(悬浮窗是独立客户端实例,需要主动选中同一会话) */
292
+ try {
293
+ const parsedState = G.floatState
294
+ const sessionId = parsedState !== null && typeof parsedState.sessionId === 'string' ? parsedState.sessionId : ''
295
+ if (sessionId !== '') {
296
+ const workspace = G.ctx === null || G.ctx === undefined ? undefined : G.ctx.get('uiWorkspace')
297
+ if (workspace !== undefined && workspace !== null && typeof workspace.openSession === 'function') {
298
+ window.setTimeout(() => {
299
+ try { workspace.openSession(sessionId) } catch { /* ignore */ }
300
+ }, 600)
301
+ }
302
+ }
303
+ } catch {
304
+ /* ignore */
305
+ }
245
306
  }
246
307
  }, 250)
247
308
  ctx.effect(() => () => {