-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignal-lm-runtime-fix.js
More file actions
216 lines (196 loc) · 10.6 KB
/
Copy pathsignal-lm-runtime-fix.js
File metadata and controls
216 lines (196 loc) · 10.6 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
// Signal-LM Android/WebView runtime fixes.
(function () {
if (window.__signalLmRuntimeFix) return;
window.__signalLmRuntimeFix = true;
function syncViewport() {
var vv = window.visualViewport;
var h = vv && vv.height ? vv.height : window.innerHeight;
var offsetTop = vv && typeof vv.offsetTop === 'number' ? vv.offsetTop : 0;
var inset = Math.max(0, Math.round((window.innerHeight || h || 0) - h - offsetTop));
if (h) document.documentElement.style.setProperty('--app-height', Math.round(h) + 'px');
document.documentElement.style.setProperty('--viewport-offset-top', Math.round(offsetTop) + 'px');
document.documentElement.style.setProperty('--keyboard-inset', inset + 'px');
if (document.body) document.body.classList.toggle('keyboard-open', inset > 80);
}
function installKeyboardCss() {
if (document.getElementById('signal-lm-keyboard-css')) return;
if (!document.querySelector('.main-chat, .main-app')) return;
var style = document.createElement('style');
style.id = 'signal-lm-keyboard-css';
style.textContent = ':root{--viewport-offset-top:0px;--keyboard-inset:0px}@media(max-width:880px){html,body{height:var(--app-height);overflow:hidden;overscroll-behavior:none}.main-chat,.main-app{height:var(--app-height);max-height:var(--app-height)}#messages{flex:1 1 auto;min-height:0;overflow-y:auto;overscroll-behavior:contain}.composer-stack{flex:0 0 auto;position:relative;z-index:35}.keyboard-open .composer-stack{padding-bottom:.55rem}}';
document.head.appendChild(style);
}
function rawBridge() {
return window.lmStudioLiteNative || window.NativeFileBridge || window.NativeInferenceBridge || window.AndroidInferenceBridge || null;
}
function parseMaybeJson(value) {
if (typeof value !== 'string') return value;
var text = value.trim();
if (!text || !/^[{[]/.test(text)) return value;
try { return JSON.parse(text); } catch (error) { return value; }
}
function bridgePromise(triggerName, resolveName, rejectName, argsBuilder) {
return function () {
var bridge = rawBridge();
var args = Array.prototype.slice.call(arguments);
if (!bridge || typeof bridge[triggerName] !== 'function') return Promise.reject(new Error('Native bridge method missing: ' + triggerName));
return new Promise(function (resolve, reject) {
window[resolveName] = function (value) { resolve(parseMaybeJson(value)); };
window[rejectName] = function (error) { reject(new Error(String(error || 'Native bridge request failed.'))); };
bridge[triggerName].apply(bridge, argsBuilder ? argsBuilder(args) : args);
});
};
}
function installBridge() {
var bridge = rawBridge();
if (!bridge) return null;
var normalized = window.SignalLMNativeBridge || {};
normalized.acceptsObjects = true;
normalized.objectBridge = true;
if (typeof bridge.triggerSelectFolder === 'function') normalized.selectFolder = bridgePromise('triggerSelectFolder', '__selectFolderResolve', '__selectFolderReject');
if (typeof bridge.triggerGetPersistedWorkspace === 'function') normalized.getPersistedWorkspace = bridgePromise('triggerGetPersistedWorkspace', '__getPersistedWorkspaceResolve', '__getPersistedWorkspaceReject');
if (typeof bridge.triggerReadFile === 'function') normalized.readFile = bridgePromise('triggerReadFile', '__readFileResolve', '__readFileReject');
if (typeof bridge.triggerWriteFile === 'function') normalized.writeFile = bridgePromise('triggerWriteFile', '__writeFileResolve', '__writeFileReject');
if (typeof bridge.triggerWriteFiles === 'function') {
normalized.writeFiles = bridgePromise('triggerWriteFiles', '__writeFilesResolve', '__writeFilesReject', function (args) {
return [typeof args[0] === 'string' ? args[0] : JSON.stringify(args[0] || { files: [] })];
});
}
if (typeof bridge.triggerClearPersistedWorkspace === 'function') normalized.clearPersistedWorkspace = bridgePromise('triggerClearPersistedWorkspace', '__clearPersistedWorkspaceResolve', '__clearPersistedWorkspaceReject');
if (typeof bridge.triggerHttpRequest === 'function') {
normalized.httpRequest = function (payload) {
var id = 'http_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2);
return new Promise(function (resolve, reject) {
window['__httpResolve_' + id] = resolve;
window['__httpReject_' + id] = function (error) { reject(new Error(String(error || 'Native HTTP bridge failed.'))); };
bridge.triggerHttpRequest(typeof payload === 'string' ? payload : JSON.stringify(payload || {}), id);
});
};
normalized.request = normalized.httpRequest;
normalized.fetchJson = normalized.httpRequest;
}
window.SignalLMNativeBridge = normalized;
window.SignalLMTools = window.SignalLMTools || {};
window.SignalLMTools.bridge = normalized;
return normalized;
}
function normalizePath(path) {
var clean = String(path || '').replace(/\\/g, '/').replace(/^\/+/, '').replace(/\/+/g, '/').trim();
if (!clean) return '';
var roots = [];
if (typeof window.__signalLmActiveWorkspacePath === 'string' && window.__signalLmActiveWorkspacePath) {
roots.push(window.__signalLmActiveWorkspacePath);
}
try {
var mcpSettings = JSON.parse(localStorage.getItem('lmStudioLite.settings.v1') || '{}') || {};
if (mcpSettings.mcpFilePath) {
roots.push(mcpSettings.mcpFilePath);
}
} catch (e) {}
for (var i = 0; i < roots.length; i++) {
var root = String(roots[i]).replace(/\\/g, '/').replace(/\/+$/, '').trim();
if (root && clean.toLowerCase().indexOf(root.toLowerCase()) === 0) {
clean = clean.slice(root.length).replace(/^\/+/, '').trim();
break;
}
}
if (!clean || clean.indexOf('../') !== -1 || clean === '..' || /^[a-z]+:/i.test(clean)) return '';
return clean;
}
function normalizeEdits(parsed) {
var list = Array.isArray(parsed) ? parsed : (parsed && (parsed.files || parsed.changes || parsed.edits)) || [];
if (!Array.isArray(list)) return [];
var edits = [];
var seen = {};
list.forEach(function (item) {
var path = normalizePath(item && (item.path || item.file || item.name || item.relativePath));
var content = item && (item.content !== undefined ? item.content : item.newContent !== undefined ? item.newContent : item.replacement);
if (path && typeof content === 'string' && !seen[path]) {
seen[path] = true;
edits.push({ path: path, content: content });
}
});
return edits;
}
function extractEdits(text, previous) {
var raw = String(text || '');
var candidates = [];
raw.replace(/```(?:json|lmstudio-edits|signal-lm-edits)?\s*([\s\S]*?)```/gi, function (_, body) { candidates.push(body.trim()); });
var obj = raw.match(/\{[\s\S]*"(?:files|changes|edits)"[\s\S]*\}/);
if (obj) candidates.push(obj[0]);
for (var i = 0; i < candidates.length; i++) {
try {
var edits = normalizeEdits(JSON.parse(candidates[i]));
if (edits.length) return edits;
} catch (error) {}
}
var codeEdits = [];
raw.replace(/```([^\n]*)\n([\s\S]*?)```/gi, function (_, langInfo, fullContent) {
langInfo = langInfo.trim();
fullContent = fullContent.trim();
var path = '';
if (langInfo.indexOf(':') !== -1) {
path = langInfo.substring(langInfo.indexOf(':') + 1).trim();
} else {
var firstLine = fullContent.split('\n')[0].trim();
var pathMatch = firstLine.match(/^(?:\/\/|#|\/\*|<!--)\s*([a-zA-Z0-9_\-\.\/\\]+\.[a-zA-Z0-9]+)\s*(?:\*\/|-->)?$/);
if (pathMatch) path = pathMatch[1].trim();
}
if (path) codeEdits.push({ path: path, content: fullContent });
});
var normalizedCodeEdits = normalizeEdits(codeEdits);
if (normalizedCodeEdits.length) return normalizedCodeEdits;
return typeof previous === 'function' ? previous(raw) : [];
}
function patchAppHooks() {
installBridge();
if (typeof window.getNativeFileBridge === 'function' && !window.__signalLmGetBridgePatched) {
var oldGet = window.getNativeFileBridge;
window.getNativeFileBridge = function () {
var normalized = installBridge();
return normalized || oldGet();
};
window.__signalLmGetBridgePatched = true;
}
if (typeof window.extractEditsFromAssistantText === 'function' && !window.__signalLmExtractPatched) {
var oldExtract = window.extractEditsFromAssistantText;
window.extractEditsFromAssistantText = function (text) { return extractEdits(text, oldExtract); };
window.__signalLmExtractPatched = true;
}
if (typeof window.buildWorkspaceEditInstruction === 'function' && !window.__signalLmInstructionPatched) {
var oldInstruction = window.buildWorkspaceEditInstruction;
window.buildWorkspaceEditInstruction = function (isEdit) {
if (isEdit) return oldInstruction(true);
return oldInstruction() + '\n\nSignal-LM edit tool contract: output file edits in standard markdown code blocks and include the file path either in the language tag or as a comment on the first line. Please output the complete replacement content immediately without truncating or asking for permission. The app will parse it and show Apply.';
};
window.__signalLmInstructionPatched = true;
}
}
async function restoreWorkspace() {
try {
var bridge = installBridge();
if (!bridge || !bridge.getPersistedWorkspace || typeof window.loadNativeWorkspace !== 'function') return;
var ws = await bridge.getPersistedWorkspace();
if (ws && Array.isArray(ws.files) && ws.files.length) await window.loadNativeWorkspace(ws);
} catch (error) {}
}
window.SignalLMInstallNativeBridge = installBridge;
installKeyboardCss();
syncViewport();
window.addEventListener('resize', syncViewport, { passive: true });
window.addEventListener('orientationchange', function () { setTimeout(syncViewport, 80); }, { passive: true });
window.addEventListener('focusin', function () { setTimeout(syncViewport, 60); }, { passive: true });
window.addEventListener('focusout', function () { setTimeout(syncViewport, 160); }, { passive: true });
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', syncViewport, { passive: true });
}
var attempts = 0;
var timer = setInterval(function () {
attempts += 1;
patchAppHooks();
if (attempts === 4 || attempts === 10) restoreWorkspace();
if (attempts > 20) clearInterval(timer);
}, 150);
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', patchAppHooks);
else patchAppHooks();
})();