dsh-gufa-code 1.3.5 → 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()
@@ -1071,6 +1095,9 @@ html[data-gufa-float] [data-gufa-dock]{
1071
1095
  }
1072
1096
  html[data-gufa-float] [data-gufa-dock] [data-conversation-scroll],
1073
1097
  html[data-gufa-float] [data-gufa-dock] [data-conversation-content]{background:transparent!important}
1098
+ /* 悬浮层启动瞬间:先隐藏经典界面,避免闪一下「另一个 DSH」 */
1099
+ html[data-gufa-booting] body{background:transparent!important}
1100
+ html[data-gufa-booting] #root{visibility:hidden!important}
1074
1101
  /* 经典 DSH 界面在悬浮窗里整体隐藏(保留古法覆盖层与右侧停靠会话),否则半透明下会透出「另一个 DSH」 */
1075
1102
  html[data-gufa-float] #root{visibility:hidden!important}
1076
1103
  html[data-gufa-float] #root .gufa-overlay-root,
@@ -9667,7 +9694,9 @@ G.GufaApp = function GufaApp(props) {
9667
9694
  bootedRef.current = true
9668
9695
  let cancelled = false
9669
9696
  void (async () => {
9670
- 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)
9671
9700
  if (typeof saved === 'string' && saved !== '') {
9672
9701
  try {
9673
9702
  const value = await G.api('project.open', { path: saved })
@@ -9677,6 +9706,7 @@ G.GufaApp = function GufaApp(props) {
9677
9706
  writeJson(GUFA_LS.project, null)
9678
9707
  }
9679
9708
  }
9709
+ if (G.floatState !== null && G.floatState !== undefined) return
9680
9710
  if (typeof sessionCwd === 'string' && sessionCwd !== '') {
9681
9711
  try {
9682
9712
  const value = await G.api('project.open', { path: sessionCwd })
@@ -10285,12 +10315,23 @@ G.GufaApp = function GufaApp(props) {
10285
10315
  if (floatBusy || target === null || target === undefined) return
10286
10316
  setFloatBusy(true)
10287
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
+ }
10288
10328
  const value = await G.api('float.start', {
10289
10329
  follow: {
10290
10330
  pid: Number(target.pid) || 0,
10291
10331
  bundleId: typeof target.bundleId === 'string' ? target.bundleId : '',
10292
10332
  title: '',
10293
10333
  },
10334
+ state: floatState,
10294
10335
  })
10295
10336
  setFloatRunning(value?.running === true)
10296
10337
  setFloatPicker(null)
@@ -10330,6 +10371,7 @@ G.GufaApp = function GufaApp(props) {
10330
10371
  const dockSyncRef = useRef('')
10331
10372
  useEffect(() => {
10332
10373
  if (sessionPinnedRef.current === true) return undefined
10374
+ if (G.floatState !== null && G.floatState !== undefined) return undefined
10333
10375
  if (project === null || typeof project.root !== 'string' || project.root === '') return undefined
10334
10376
  if (dockSyncRef.current === project.root) return undefined
10335
10377
  if (typeof sessionCwd === 'string' && sessionCwd !== '' && sessionCwd === project.root) {
@@ -10374,6 +10416,11 @@ G.GufaApp = function GufaApp(props) {
10374
10416
  const entryWorkspaceSyncedRef = useRef(false)
10375
10417
  useEffect(() => {
10376
10418
  if (entryWorkspaceSyncedRef.current) return
10419
+ /* 悬浮层:项目/会话由主窗口状态注入,不做「入口工作区」同步,避免被会话 cwd 覆盖 */
10420
+ if (G.floatState !== null && G.floatState !== undefined) {
10421
+ entryWorkspaceSyncedRef.current = true
10422
+ return
10423
+ }
10377
10424
  if (project === null) return
10378
10425
  const pending = G.pendingEntryWorkspace
10379
10426
  if (pending === null || pending === undefined || typeof pending.key !== 'string') {
@@ -10692,6 +10739,11 @@ G.GufaApp = function GufaApp(props) {
10692
10739
  const lastSessionCwdRef = useRef(null)
10693
10740
  useEffect(() => {
10694
10741
  if (sessionPinnedRef.current === true) return
10742
+ /* 悬浮层里项目由主窗口状态注入,不跟随(Web 版客户端自己的)会话 cwd 切换 */
10743
+ if (G.floatState !== null && G.floatState !== undefined) {
10744
+ lastSessionCwdRef.current = sessionCwd
10745
+ return
10746
+ }
10695
10747
  if (typeof sessionCwd !== 'string' || sessionCwd === '') return
10696
10748
  const previous = lastSessionCwdRef.current
10697
10749
  lastSessionCwdRef.current = sessionCwd
@@ -10886,6 +10938,38 @@ G.GufaApp = function GufaApp(props) {
10886
10938
  })()
10887
10939
  }, [project])
10888
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
+
10889
10973
  const activeFileForChat = useMemo(() => {
10890
10974
  if (activeTab === null || activeTab.kind === 'diff' || activeTab.kind === 'graph') return null
10891
10975
  return { path: activeTab.path, content: activeTab.content ?? '', language: activeTab.language }
@@ -12220,6 +12304,102 @@ const GUFA_PLUGIN = {
12220
12304
  apply(ctx) {
12221
12305
  G.ctx = ctx
12222
12306
 
12307
+ /* ── 悬浮层模式(?gufa-float=1 或 helper 注入的 localStorage 标记)──
12308
+ * 尽早打标记并隐藏经典 DSH 界面,避免先闪出一个「另一个 DSH」;
12309
+ * 同时重试进入 IDE 模式,直到覆盖层挂载完成。 */
12310
+ try {
12311
+ let floatMode = false
12312
+ try {
12313
+ floatMode = /[?&]gufa-float=1/.test(String(location.search || '')) || localStorage.getItem('gufa-code:float') === '1'
12314
+ } catch {
12315
+ floatMode = false
12316
+ }
12317
+ if (floatMode) {
12318
+ document.documentElement.setAttribute('data-gufa-float', '1')
12319
+ document.documentElement.setAttribute('data-gufa-booting', '1')
12320
+ let attempts = 0
12321
+ const timer = window.setInterval(() => {
12322
+ attempts += 1
12323
+ try {
12324
+ if (typeof G.mode?.get === 'function' && G.mode.get() !== true) G.mode.set(true)
12325
+ } catch {
12326
+ /* ignore */
12327
+ }
12328
+ if (document.querySelector('.gufa-overlay-root') !== null || attempts > 40) {
12329
+ document.documentElement.removeAttribute('data-gufa-booting')
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
+ }
12392
+ }
12393
+ }, 250)
12394
+ ctx.effect(() => () => {
12395
+ window.clearInterval(timer)
12396
+ document.documentElement.removeAttribute('data-gufa-booting')
12397
+ }, 'gufa-code: float boot')
12398
+ }
12399
+ } catch (error) {
12400
+ console.error('[gufa-code] 悬浮模式初始化失败', error)
12401
+ }
12402
+
12223
12403
  /* HMR 重载时如果仍处于 IDE 模式,重新打上标记(卸载清理会移除它) */
12224
12404
  try {
12225
12405
  if (typeof G.mode?.get === 'function' && G.mode.get() === true) document.documentElement.setAttribute('data-gufa-ide', '')
@@ -20,6 +20,23 @@ static const EventHotKeyID GufaToggleHotKey = {'gufa', 1};
20
20
 
21
21
  /* 前置声明(实现位于文件后半部分) */
22
22
  static NSString *GufaOutputPath = nil;
23
+ /** 悬浮层诊断日志(/tmp/gufa-float-debug.log)。 */
24
+ static void GufaLog(NSString *format, ...) {
25
+ va_list args;
26
+ va_start(args, format);
27
+ NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
28
+ va_end(args);
29
+ NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
30
+ NSString *line = [NSString stringWithFormat:@"[%@] %@\n", [formatter stringFromDate:[NSDate date]], message];
31
+ NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:@"/tmp/gufa-float-debug.log"];
32
+ if (handle == nil) {
33
+ [line writeToFile:@"/tmp/gufa-float-debug.log" atomically:YES encoding:NSUTF8StringEncoding error:NULL];
34
+ } else {
35
+ [handle seekToEndOfFile];
36
+ [handle writeData:[line dataUsingEncoding:NSUTF8StringEncoding]];
37
+ [handle closeFile];
38
+ }
39
+ }
23
40
  static void GufaEmitJSON(NSDictionary *out);
24
41
  static BOOL GufaTrustedForAX(void);
25
42
  static NSArray<NSDictionary *> *GufaAXWindows(void);
@@ -105,6 +122,7 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
105
122
  - (void)registerToggleHotKey;
106
123
  - (void)activateTargetApp;
107
124
  - (void)beginningFollowFromOptions;
125
+ - (void)findFollowWindowWithRetries:(NSInteger)attempt;
108
126
  - (void)exitMoyu:(id)sender;
109
127
  - (void)restoreMainWindow;
110
128
  - (void)toggleClickThrough:(id)sender;
@@ -163,15 +181,33 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
163
181
  if (![pid isKindOfClass:[NSNumber class]]) return;
164
182
  self.followPid = (pid_t)pid.intValue;
165
183
  self.followTitle = [follow[@"title"] isKindOfClass:[NSString class]] ? follow[@"title"] : @"";
166
- /* App 刚被激活,窗口可能还没切到当前 Space;稍等再抓窗口 */
167
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
168
- self.followWindowRef = GufaCopyAppWindow(self.followPid);
169
- if (self.followWindowRef == NULL) return;
170
- self.following = YES;
171
- [self startFollowTimer];
172
- [self applyFollowFrame];
173
- self.statusItem.button.title = @"古法·摸鱼";
174
- });
184
+ GufaLog(@"follow-start pid=%d bundle=%@ axTrusted=%d", self.followPid, follow[@"bundleId"] ?: @"", GufaTrustedForAX() ? 1 : 0);
185
+ [self findFollowWindowWithRetries:0];
186
+ }
187
+
188
+ /* 激活 App 后窗口可能还在切 Space,轮询最多 5 秒找它的窗口。 */
189
+ - (void)findFollowWindowWithRetries:(NSInteger)attempt {
190
+ AXUIElementRef window = GufaCopyAppWindow(self.followPid);
191
+ if (window == NULL) {
192
+ if (attempt >= 20) {
193
+ GufaLog(@"follow-window-not-found pid=%d attempts=%ld axTrusted=%d", self.followPid, (long)attempt, GufaTrustedForAX() ? 1 : 0);
194
+ return;
195
+ }
196
+ __weak typeof(self) weakSelf = self;
197
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
198
+ [weakSelf findFollowWindowWithRetries:attempt + 1];
199
+ });
200
+ return;
201
+ }
202
+ NSRect rect = NSZeroRect;
203
+ GufaRectFromAX(window, &rect);
204
+ GufaLog(@"follow-window-found pid=%d rect=%.0f,%.0f %.0fx%.0f attempt=%ld", self.followPid, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, (long)attempt);
205
+ if (self.followWindowRef != NULL) CFRelease(self.followWindowRef);
206
+ self.followWindowRef = window;
207
+ self.following = YES;
208
+ [self startFollowTimer];
209
+ [self applyFollowFrame];
210
+ self.statusItem.button.title = @"古法·摸鱼";
175
211
  }
176
212
 
177
213
  - (void)parseOptions {
@@ -208,10 +244,12 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
208
244
  self.window.opaque = NO;
209
245
  self.window.backgroundColor = NSColor.clearColor;
210
246
  self.window.hasShadow = YES;
211
- self.window.level = NSFloatingWindowLevel + 1;
247
+ /* 高于普通浮动窗口(歌词、置顶小工具等),确保真正盖住被跟随的 App */
248
+ self.window.level = NSStatusWindowLevel;
212
249
  self.window.collectionBehavior = (NSWindowCollectionBehaviorCanJoinAllSpaces
213
250
  | NSWindowCollectionBehaviorFullScreenAuxiliary
214
- | NSWindowCollectionBehaviorStationary);
251
+ | NSWindowCollectionBehaviorStationary
252
+ | NSWindowCollectionBehaviorIgnoresCycle);
215
253
  self.window.minSize = NSMakeSize(520, 360);
216
254
  self.window.title = @"古法编程悬浮层";
217
255
 
@@ -221,8 +259,39 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
221
259
 
222
260
  WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
223
261
  config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
224
- /* URL query 可能被 DSH 的浏览器端路由吞掉,这里在文档开始前写一个标记,客户端据此进入悬浮模式 */
225
- 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
226
295
  injectionTime:WKUserScriptInjectionTimeAtDocumentStart
227
296
  forMainFrameOnly:YES];
228
297
  [config.userContentController addUserScript:floatMarker];
@@ -281,14 +350,28 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
281
350
  self.navigation.pendingLoad = ^{
282
351
  __strong typeof(weakSelf) self = weakSelf;
283
352
  if (self == nil) return;
284
- NSURLComponents *components = [NSURLComponents componentsWithString:appUrl];
285
- components.queryItems = @[[NSURLQueryItem queryItemWithName:@"gufa-float" value:@"1"]];
286
- NSURL *clean = components.URL;
287
- if (clean != nil && ![clean.absoluteString isEqualToString:self.webView.URL.absoluteString]) {
288
- [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
+ }
289
369
  }
370
+ [js appendString:@"localStorage.setItem('gufa-code:float','1');location.href='/?gufa-float=1';}catch(e){}"];
371
+ [self.webView evaluateJavaScript:js completionHandler:nil];
290
372
  };
291
373
  [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:authUrl]]];
374
+
292
375
  }
293
376
 
294
377
  - (void)saveFrame {
@@ -350,8 +433,12 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
350
433
  self.statusItem.button.title = self.clickThrough ? @"古法·穿透" : @"古法";
351
434
  }
352
435
 
436
+ /* 只重启定时器,不动 following/窗口引用(stopFollowTimer 会清状态,不能在这里调) */
353
437
  - (void)startFollowTimer {
354
- [self stopFollowTimer];
438
+ if (self.followTimer != nil) {
439
+ [self.followTimer invalidate];
440
+ self.followTimer = nil;
441
+ }
355
442
  __weak typeof(self) weakSelf = self;
356
443
  self.followTimer = [NSTimer scheduledTimerWithTimeInterval:0.25 repeats:YES block:^(NSTimer *timer) {
357
444
  __strong typeof(weakSelf) self = weakSelf;
@@ -391,7 +478,18 @@ static OSStatus GufaHotKeyHandler(EventHandlerCallRef nextHandler, EventRef even
391
478
  }
392
479
  CGFloat screenHeight = NSScreen.mainScreen.frame.size.height;
393
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
+ }
394
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
+ }
395
493
  }
396
494
 
397
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」即可。
@@ -59,15 +60,22 @@ export function register(router, env) {
59
60
  }
60
61
  return null
61
62
  }
62
- const floatProcessPattern = '古法编程悬浮层.app/Contents/MacOS/gufa-float'
63
+ const floatProcessPatterns = ['gufa-float-macos-', '古法编程悬浮层.app/Contents/MacOS/gufa-float']
63
64
 
64
65
  const listFloatPids = async () => {
65
- try {
66
- const { stdout } = await runFile('pgrep', ['-f', floatProcessPattern], { timeout: 3000 })
67
- return String(stdout ?? '').split('\n').map((line) => Number(line.trim())).filter((pid) => Number.isFinite(pid) && pid > 0)
68
- } catch {
69
- return []
66
+ const pids = new Set()
67
+ for (const pattern of floatProcessPatterns) {
68
+ try {
69
+ const { stdout } = await runFile('pgrep', ['-f', pattern], { timeout: 3000 })
70
+ for (const line of String(stdout ?? '').split('\n')) {
71
+ const pid = Number(line.trim())
72
+ if (Number.isFinite(pid) && pid > 0) pids.add(pid)
73
+ }
74
+ } catch {
75
+ /* 没匹配到 */
76
+ }
70
77
  }
78
+ return [...pids]
71
79
  }
72
80
  const floatRunningAsync = async () => (await listFloatPids()).length > 0
73
81
 
@@ -205,12 +213,22 @@ export function register(router, env) {
205
213
  }
206
214
  const base = `${webServer.protocol}//127.0.0.1:${String(webServer.port)}`
207
215
  const authUrl = connection.authenticatedUrl(`${base}/`)
208
- const payload = JSON.stringify({ authUrl, appUrl: `${base}/`, follow: follow !== null && follow.pid > 0 ? follow : undefined })
209
- await openApp([payload])
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
+ })
223
+ const binary = floatBinaryPath()
224
+ if (binary === null) throw new ApiError('missing-helper', '悬浮层程序未构建', 500)
225
+ const child = spawn(binary, [payload], { detached: true, stdio: 'ignore' })
226
+ child.unref()
227
+ floatState.child = child
228
+ floatState.startedAt = Date.now()
210
229
  await new Promise((resolve) => setTimeout(resolve, 300))
211
230
  const pids = await listFloatPids()
212
- floatState.startedAt = Date.now()
213
- return { running: pids.length > 0, pid: pids[0] ?? null }
231
+ return { running: pids.length > 0 || child.exitCode === null, pid: child.pid ?? pids[0] ?? null }
214
232
  })
215
233
 
216
234
  router.method('float.stop', async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.5",
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()
@@ -1063,6 +1087,9 @@ html[data-gufa-float] [data-gufa-dock]{
1063
1087
  }
1064
1088
  html[data-gufa-float] [data-gufa-dock] [data-conversation-scroll],
1065
1089
  html[data-gufa-float] [data-gufa-dock] [data-conversation-content]{background:transparent!important}
1090
+ /* 悬浮层启动瞬间:先隐藏经典界面,避免闪一下「另一个 DSH」 */
1091
+ html[data-gufa-booting] body{background:transparent!important}
1092
+ html[data-gufa-booting] #root{visibility:hidden!important}
1066
1093
  /* 经典 DSH 界面在悬浮窗里整体隐藏(保留古法覆盖层与右侧停靠会话),否则半透明下会透出「另一个 DSH」 */
1067
1094
  html[data-gufa-float] #root{visibility:hidden!important}
1068
1095
  html[data-gufa-float] #root .gufa-overlay-root,
@@ -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 }
@@ -218,6 +218,102 @@ const GUFA_PLUGIN = {
218
218
  apply(ctx) {
219
219
  G.ctx = ctx
220
220
 
221
+ /* ── 悬浮层模式(?gufa-float=1 或 helper 注入的 localStorage 标记)──
222
+ * 尽早打标记并隐藏经典 DSH 界面,避免先闪出一个「另一个 DSH」;
223
+ * 同时重试进入 IDE 模式,直到覆盖层挂载完成。 */
224
+ try {
225
+ let floatMode = false
226
+ try {
227
+ floatMode = /[?&]gufa-float=1/.test(String(location.search || '')) || localStorage.getItem('gufa-code:float') === '1'
228
+ } catch {
229
+ floatMode = false
230
+ }
231
+ if (floatMode) {
232
+ document.documentElement.setAttribute('data-gufa-float', '1')
233
+ document.documentElement.setAttribute('data-gufa-booting', '1')
234
+ let attempts = 0
235
+ const timer = window.setInterval(() => {
236
+ attempts += 1
237
+ try {
238
+ if (typeof G.mode?.get === 'function' && G.mode.get() !== true) G.mode.set(true)
239
+ } catch {
240
+ /* ignore */
241
+ }
242
+ if (document.querySelector('.gufa-overlay-root') !== null || attempts > 40) {
243
+ document.documentElement.removeAttribute('data-gufa-booting')
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
+ }
306
+ }
307
+ }, 250)
308
+ ctx.effect(() => () => {
309
+ window.clearInterval(timer)
310
+ document.documentElement.removeAttribute('data-gufa-booting')
311
+ }, 'gufa-code: float boot')
312
+ }
313
+ } catch (error) {
314
+ console.error('[gufa-code] 悬浮模式初始化失败', error)
315
+ }
316
+
221
317
  /* HMR 重载时如果仍处于 IDE 模式,重新打上标记(卸载清理会移除它) */
222
318
  try {
223
319
  if (typeof G.mode?.get === 'function' && G.mode.get() === true) document.documentElement.setAttribute('data-gufa-ide', '')